openpond 0.0.68 → 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 (206) hide show
  1. package/dist/chunks/{actions-command-DLOKFA34.js → actions-command-6N5XWMR6.js} +4 -4
  2. package/dist/chunks/{app-layer-K7NAOLDL.js → app-layer-XEYHFJHI.js} +7 -7
  3. package/dist/chunks/app-server-runtime-Y6MW4XCG.js +21 -0
  4. package/dist/chunks/{apps-5VSVJLM7.js → apps-GSXUDK6V.js} +7 -7
  5. package/dist/chunks/{chunk-HNY7OSDY.js → chunk-2JABRRNR.js} +1 -1
  6. package/dist/chunks/{chunk-N6FKRVAT.js → chunk-47EIAYI7.js} +2 -2
  7. package/dist/chunks/{chunk-7FW2CVYN.js → chunk-4L3ZJS2T.js} +426 -1
  8. package/dist/chunks/{chunk-OOJP442J.js → chunk-5TKZBMQM.js} +1 -1
  9. package/dist/chunks/{chunk-OQLYO7TA.js → chunk-6G6MDZLM.js} +1129 -200
  10. package/dist/chunks/{chunk-HFQHD35D.js → chunk-AN2EYCN3.js} +1 -1
  11. package/dist/chunks/{chunk-3KLQ52B2.js → chunk-BVY5JYM6.js} +4 -9
  12. package/dist/chunks/{chunk-KLD7NT5J.js → chunk-CNTM26OW.js} +3 -3
  13. package/dist/chunks/{chunk-DBHSOTYZ.js → chunk-D7BO5Y5J.js} +3 -24
  14. package/dist/chunks/chunk-DLQQIWN2.js +648 -0
  15. package/dist/chunks/{chunk-T55IL3GI.js → chunk-DNXBJZAU.js} +1 -1
  16. package/dist/chunks/{chunk-TSDVA7QP.js → chunk-EFET7LB7.js} +28 -13
  17. package/dist/chunks/{chunk-QETF6ILG.js → chunk-FQS2QL5F.js} +359 -841
  18. package/dist/chunks/{chunk-J2REM7LE.js → chunk-HFPUR4CQ.js} +5 -116
  19. package/dist/chunks/{chunk-JIEUB6OS.js → chunk-J3YDKJFD.js} +1 -1
  20. package/dist/chunks/{training-5CPTZRVC.js → chunk-J7PYGDRY.js} +251 -16
  21. package/dist/chunks/{chunk-JGOP4GCK.js → chunk-JTHL5XJ2.js} +5 -25
  22. package/dist/chunks/{chunk-NA4L2HQM.js → chunk-N3TGCM7J.js} +94 -36
  23. package/dist/chunks/{chunk-MUS7KPXK.js → chunk-NTK22KJD.js} +1979 -20
  24. package/dist/chunks/{chunk-PSGEH4FC.js → chunk-P6JLLWMI.js} +3 -3
  25. package/dist/chunks/chunk-R3C3MNSI.js +140 -0
  26. package/dist/chunks/{chunk-WEB37YVJ.js → chunk-TGM5IPYO.js} +31 -3
  27. package/dist/chunks/{chunk-IG72OKNB.js → chunk-TZWAUV2L.js} +3148 -16564
  28. package/dist/chunks/{chunk-TBEBLKCQ.js → chunk-WBAZFKC7.js} +3 -3
  29. package/dist/chunks/{chunk-Z2ZWHU7O.js → chunk-YVCYVDNP.js} +1 -1
  30. package/dist/chunks/{cli-6WFY2ULA.js → cli-L5VPOV6I.js} +9 -8
  31. package/dist/chunks/continual-FYDKLCO7.js +803 -0
  32. package/dist/chunks/{core-commands-HQ3HL34W.js → core-commands-MAN3CSJQ.js} +8 -8
  33. package/dist/chunks/{desktop-test-RU6SRARQ.js → desktop-test-OE5SST2W.js} +7 -7
  34. package/dist/chunks/{extension-4KFKWMC4.js → extension-J3CIEDP4.js} +1003 -105
  35. package/dist/chunks/{help-ZUCPOR22.js → help-JNGJJFU5.js} +1 -1
  36. package/dist/chunks/{opchat-AZX7SYM7.js → opchat-6HEQJFLL.js} +10 -18
  37. package/dist/chunks/{organizations-GV6Z7G4J.js → organizations-MWAPNOCK.js} +10 -9
  38. package/dist/chunks/{profile-TSLGZPUI.js → profile-P7HMONTZ.js} +11 -11
  39. package/dist/chunks/{project-agent-SHIQZWPY.js → project-agent-2RAK7GAZ.js} +10 -10
  40. package/dist/chunks/{sandbox-command-TRS66NUT.js → sandbox-command-G22CPFNK.js} +8 -8
  41. package/dist/chunks/{sandbox-template-RVWXD5O3.js → sandbox-template-S4WRUWJ6.js} +10 -10
  42. package/dist/chunks/{src-VUJ6EBOU.js → src-A6O6ZGIL.js} +18307 -10584
  43. package/dist/chunks/{src-Q3BOITLJ.js → src-BKBZ7WLO.js} +6 -5
  44. package/dist/chunks/taskset-BMI7KOWP.js +66 -0
  45. package/dist/chunks/{teams-bot-CLCMGBW5.js → teams-bot-5VBYEN7M.js} +7 -7
  46. package/dist/chunks/training-UPVSGDTB.js +17 -0
  47. package/dist/chunks/{workspaces-IIPITOCV.js → workspaces-XM5BY3MO.js} +4 -2
  48. package/dist/cli.js +13 -13
  49. package/dist/index.js +15 -56
  50. package/dist/web/assets/App-DfiCmBv6.js +173 -0
  51. package/dist/web/assets/{AppDialog-sLTPiFGX.js → AppDialog-CSXu5wRu.js} +1 -1
  52. package/dist/web/assets/{AppTerminalPanel-B0NCyY4L.js → AppTerminalPanel-y2bVL2RV.js} +2 -2
  53. package/dist/web/assets/{AppsView-DyDyktK2.js → AppsView-Bs9pwD2H.js} +1 -1
  54. package/dist/web/assets/{BrowserSidebar-C-PQxmQa.js → BrowserSidebar-CUgT5V1m.js} +1 -1
  55. package/dist/web/assets/{CartesianChart-CnerMhTr.js → CartesianChart-DA85hfrP.js} +1 -1
  56. package/dist/web/assets/{CollaborationTabs-DJEp6dux.js → CollaborationTabs-B8mlPhM3.js} +1 -1
  57. package/dist/web/assets/{CommandMenu-B5lGz8rG.js → CommandMenu-EwUGCeC_.js} +1 -1
  58. package/dist/web/assets/{CommunityView-DQJaHBa5.js → CommunityView-IHNq-YJz.js} +1 -1
  59. package/dist/web/assets/{ComposerCreateImproveStrip-7hBR2bdV.js → ComposerCreateImproveStrip-qOL2zA26.js} +1 -1
  60. package/dist/web/assets/{GetStartedView-l1Cz1e7g.js → GetStartedView-C2ypO0v7.js} +1 -1
  61. package/dist/web/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
  62. package/dist/web/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
  63. package/dist/web/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
  64. package/dist/web/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
  65. package/dist/web/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
  66. package/dist/web/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
  67. package/dist/web/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
  68. package/dist/web/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
  69. package/dist/web/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
  70. package/dist/web/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
  71. package/dist/web/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
  72. package/dist/web/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
  73. package/dist/web/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
  74. package/dist/web/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
  75. package/dist/web/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
  76. package/dist/web/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
  77. package/dist/web/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
  78. package/dist/web/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
  79. package/dist/web/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
  80. package/dist/web/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
  81. package/dist/web/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
  82. package/dist/web/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
  83. package/dist/web/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
  84. package/dist/web/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
  85. package/dist/web/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
  86. package/dist/web/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
  87. package/dist/web/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
  88. package/dist/web/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
  89. package/dist/web/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
  90. package/dist/web/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
  91. package/dist/web/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
  92. package/dist/web/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
  93. package/dist/web/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
  94. package/dist/web/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
  95. package/dist/web/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
  96. package/dist/web/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
  97. package/dist/web/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
  98. package/dist/web/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
  99. package/dist/web/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
  100. package/dist/web/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
  101. package/dist/web/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
  102. package/dist/web/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
  103. package/dist/web/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
  104. package/dist/web/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
  105. package/dist/web/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
  106. package/dist/web/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
  107. package/dist/web/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
  108. package/dist/web/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
  109. package/dist/web/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
  110. package/dist/web/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
  111. package/dist/web/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
  112. package/dist/web/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
  113. package/dist/web/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
  114. package/dist/web/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
  115. package/dist/web/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
  116. package/dist/web/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
  117. package/dist/web/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
  118. package/dist/web/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
  119. package/dist/web/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
  120. package/dist/web/assets/LabModelVersionDetailPage-BK0eoUlW.js +1 -0
  121. package/dist/web/assets/{LabSkillSidebar-jlX5I_D5.js → LabSkillSidebar-CRPb4qBn.js} +1 -1
  122. package/dist/web/assets/LabsRoute-Bw-HD6QC.js +2 -0
  123. package/dist/web/assets/LabsRoute-CGFgymTX.css +1 -0
  124. package/dist/web/assets/MainChatThread-Cu6_UnNE.js +2 -0
  125. package/dist/web/assets/MainPane-k1iII9e9.js +8 -0
  126. package/dist/web/assets/MarkdownText-N60tvLug.js +268 -0
  127. package/dist/web/assets/Messages-CYQFLElK.js +10 -0
  128. package/dist/web/assets/{NativeSkillSidebar-DaD52aW1.js → NativeSkillSidebar-zbx7WmOk.js} +1 -1
  129. package/dist/web/assets/{NewExperienceSwitcher-C7X_K5Xl.js → NewExperienceSwitcher-B0zev5Sx.js} +1 -1
  130. package/dist/web/assets/{NewProjectDialog-NuPVF2Y7.js → NewProjectDialog-lZlzrp-R.js} +1 -1
  131. package/dist/web/assets/{OutputsPage-Bmof4Tdv.js → OutputsPage-B4zYYUT5.js} +1 -1
  132. package/dist/web/assets/{ProjectsPage-D7opg6ff.js → ProjectsPage-97wgc84s.js} +1 -1
  133. package/dist/web/assets/RightChatPanelStack-I2znDCc7.js +1 -0
  134. package/dist/web/assets/{RightSidebarHomePanel-D8dAMHcp.js → RightSidebarHomePanel-BUcWVJi-.js} +1 -1
  135. package/dist/web/assets/ScheduledWorkPage-Bp-t0eVj.js +1 -0
  136. package/dist/web/assets/SettingsView-C1xyn1Y4.js +6 -0
  137. package/dist/web/assets/{TeamChatView-DIxvrgai.js → TeamChatView-Fj5_yjVE.js} +2 -2
  138. package/dist/web/assets/{TerminalOverlay-Cd0Sp9LD.js → TerminalOverlay-D2WBeJvp.js} +1 -1
  139. package/dist/web/assets/{TrainingCreationPanel-DACYaOny.js → TrainingCreationPanel-dYW_dh3M.js} +1 -1
  140. package/dist/web/assets/{TrainingDraftPanel-DBWJW8ZD.js → TrainingDraftPanel-zeJWmmW6.js} +1 -1
  141. package/dist/web/assets/{UsageSettingsSection-B3sbqaUV.js → UsageSettingsSection-B6SBqYuB.js} +2 -2
  142. package/dist/web/assets/WorkSidebarPanel-BwbWKpOZ.js +1 -0
  143. package/dist/web/assets/{WorkspaceDiffPanel-CBgPVF1P.js → WorkspaceDiffPanel-D9Kp0vFw.js} +6 -6
  144. package/dist/web/assets/WorkspaceEnvironmentMenu-D-3YGp06.js +32 -0
  145. package/dist/web/assets/WorkspaceGitDialogs-BUbzUN4m.js +1 -0
  146. package/dist/web/assets/{WorkspaceMonacoEditor-Db_sWYFt.js → WorkspaceMonacoEditor-CXPY7bBI.js} +3 -3
  147. package/dist/web/assets/{arrow-up-right-DaIxkG4K.js → arrow-up-right-C7VWgGQP.js} +1 -1
  148. package/dist/web/assets/{chat-file-links-wORSEipQ.js → chat-file-links-CqfMdhHQ.js} +1 -1
  149. package/dist/web/assets/chevron-up-DD9Tei-Q.js +1 -0
  150. package/dist/web/assets/{clipboard-BTRsPPaK.js → clipboard-B-8k7mlT.js} +1 -1
  151. package/dist/web/assets/{cloud-upload-BYXHJoKd.js → cloud-upload-CUVFzURz.js} +1 -1
  152. package/dist/web/assets/{cssMode-Be446Wgi.js → cssMode-DYvfmqoL.js} +1 -1
  153. package/dist/web/assets/{folder-open-KtKTXn4w.js → folder-open-CnbcQIy8.js} +1 -1
  154. package/dist/web/assets/{folder-plus-9-Xcli22.js → folder-plus-BOaLAKy4.js} +1 -1
  155. package/dist/web/assets/{git-commit-horizontal-CmVYsUnh.js → git-commit-horizontal-DQeHsooT.js} +1 -1
  156. package/dist/web/assets/{htmlMode-DTjTyBB_.js → htmlMode-BXEI-BVY.js} +1 -1
  157. package/dist/web/assets/index-CGMb_VXm.css +1 -0
  158. package/dist/web/assets/{index-DqWw2ymf.js → index-D-VK8mST.js} +1 -1
  159. package/dist/web/assets/index-D-WCyNdJ.js +1 -0
  160. package/dist/web/assets/{info-BLmP4K0e.js → info-DtzDuGLn.js} +1 -1
  161. package/dist/web/assets/{jsonMode-Z-2iim-u.js → jsonMode-Dosjh_hK.js} +1 -1
  162. package/dist/web/assets/{lspLanguageFeatures-Cr2iCfG2.js → lspLanguageFeatures-BNe-6FJA.js} +1 -1
  163. package/dist/web/assets/{minimize-2-CWA6iO3r.js → minimize-2-DnxKN5oK.js} +1 -1
  164. package/dist/web/assets/{monaco.contribution-NtjNqMdv.js → monaco.contribution-CfF-ajhi.js} +2 -2
  165. package/dist/web/assets/{monaco.contribution-YhqlKmCp.js → monaco.contribution-CnkROzNv.js} +2 -2
  166. package/dist/web/assets/{monaco.contribution-Cac9eBUk.js → monaco.contribution-Dyns81H2.js} +2 -2
  167. package/dist/web/assets/{monaco.contribution-BtMcDmCM.js → monaco.contribution-ytyanGyj.js} +2 -2
  168. package/dist/web/assets/{play-DYSQH2rx.js → play-B3o6IAQd.js} +1 -1
  169. package/dist/web/assets/{python-CNqOWXNv.js → python-B7zZ_9Z_.js} +1 -1
  170. package/dist/web/assets/{refresh-cw-DMysDKOA.js → refresh-cw-DSJZXa8S.js} +1 -1
  171. package/dist/web/assets/{save-HPZ4ZiDi.js → save-iC-AXHN6.js} +1 -1
  172. package/dist/web/assets/square-B2roZTxf.js +1 -0
  173. package/dist/web/assets/{toggleHighContrast-Bccdn3Qi.js → toggleHighContrast-CjlV4YHK.js} +1 -1
  174. package/dist/web/assets/{training-daZlCtKV.css → training-eg6uFi3M.css} +1 -1
  175. package/dist/web/assets/{tsMode-BhcKJxhG.js → tsMode-XmKmSq0B.js} +1 -1
  176. package/dist/web/assets/{upload-DE7xaWVj.js → upload-BgHXNjfJ.js} +1 -1
  177. package/dist/web/assets/{useLocalAgentSchedules-C0J--_MD.js → useLocalAgentSchedules-CVJz0AMr.js} +1 -1
  178. package/dist/web/assets/{wifi-off-CrCfhll9.js → wifi-off-CneL8bDZ.js} +1 -1
  179. package/dist/web/assets/{workers-DCaGzukk.js → workers-CT7VYBR5.js} +1 -1
  180. package/dist/web/assets/{yaml-CCfH63KB.js → yaml-CF8jchCz.js} +1 -1
  181. package/dist/web/index.html +2 -2
  182. package/docs/command-reference.md +58 -2
  183. package/package.json +3 -1
  184. package/dist/api/vercel-protection.d.ts +0 -1
  185. package/dist/chunks/app-server-runtime-OFZZIWAB.js +0 -20
  186. package/dist/chunks/chunk-MLWNI3WG.js +0 -15395
  187. package/dist/web/assets/App-D7vhbyMO.js +0 -171
  188. package/dist/web/assets/LabModelVersionDetailPage-D2PfI3-r.js +0 -1
  189. package/dist/web/assets/LabsRoute-D3w6nPSa.css +0 -1
  190. package/dist/web/assets/LabsRoute-VOgPrf94.js +0 -2
  191. package/dist/web/assets/MainChatThread-B1nXTMAf.js +0 -2
  192. package/dist/web/assets/MainPane-DxVcMBFo.js +0 -6
  193. package/dist/web/assets/MarkdownText-B3njGyZS.js +0 -9
  194. package/dist/web/assets/Messages-yBS4UHWl.js +0 -10
  195. package/dist/web/assets/RightChatPanelStack-BzsNeSwx.js +0 -1
  196. package/dist/web/assets/ScheduledWorkPage-Dkjhof6t.js +0 -1
  197. package/dist/web/assets/SettingsView-CWTAUy2b.js +0 -6
  198. package/dist/web/assets/WorkSidebarPanel-D4yXQ64j.js +0 -1
  199. package/dist/web/assets/WorkspaceEnvironmentMenu-Bp-9V7Jq.js +0 -32
  200. package/dist/web/assets/WorkspaceGitDialogs-BxU5Uhpz.js +0 -1
  201. package/dist/web/assets/activity-BzKyRXbd.js +0 -1
  202. package/dist/web/assets/chevron-up-C8-qSzck.js +0 -1
  203. package/dist/web/assets/git-branch-CLGxzDjJ.js +0 -1
  204. package/dist/web/assets/index-AzqEDIEY.css +0 -1
  205. package/dist/web/assets/index-C5uP_Gug.js +0 -1
  206. package/dist/web/assets/square-D-mpY1a-.js +0 -1
@@ -1,171 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CommandMenu-B5lGz8rG.js","./index-DqWw2ymf.js","./index-AzqEDIEY.css","./CommandMenu-hNQCm8mw.css","./SettingsView-CWTAUy2b.js","./chat-file-links-wORSEipQ.js","./refresh-cw-DMysDKOA.js","./save-HPZ4ZiDi.js","./folder-open-KtKTXn4w.js","./chevron-up-C8-qSzck.js","./play-DYSQH2rx.js","./wifi-off-CrCfhll9.js","./useLocalAgentSchedules-C0J--_MD.js","./cloud-upload-BYXHJoKd.js","./git-commit-horizontal-CmVYsUnh.js","./index-C5uP_Gug.js","./folder-plus-9-Xcli22.js","./AppDialog-sLTPiFGX.js","./WorkspaceDiffPanel-CBgPVF1P.js","./MarkdownText-B3njGyZS.js","./desktop-files-BQj1J-ob.js","./training-model-data-CKOkpBBL.js","./info-BLmP4K0e.js","./minimize-2-CWA6iO3r.js","./clipboard-BTRsPPaK.js","./SettingsView-BRPrJuP5.css","./git-dialogs-BZDqS1eT.css","./NewProjectDialog-NuPVF2Y7.js","./WorkspaceGitDialogs-BxU5Uhpz.js","./git-branch-CLGxzDjJ.js","./upload-DE7xaWVj.js","./WorkspaceEnvironmentMenu-Bp-9V7Jq.js","./square-D-mpY1a-.js","./activity-BzKyRXbd.js","./WorkspaceEnvironmentMenu-DGIFdG3o.css","./MainPane-DxVcMBFo.js","./arrow-up-right-DaIxkG4K.js"])))=>i.map(i=>d[i]);
2
- import{r as g,j as b,_ as Bo}from"./index-DqWw2ymf.js";var sf;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 o=n?.Parent??Object;class i extends o{}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 $r extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class hb extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(sf=globalThis).__zod_globalConfig??(sf.__zod_globalConfig={});const wm=globalThis.__zod_globalConfig;function Ba(e){return wm}function gb(e){const t=Object.values(e).filter(a=>typeof a=="number");return Object.entries(e).filter(([a,o])=>t.indexOf(+a)===-1).map(([a,o])=>o)}function Mu(e,t){return typeof t=="bigint"?t.toString():t}function zl(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function _m(e){return e==null}function Im(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function _k(e,t){const n=e/t,a=Math.round(n),o=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-a)<o?0:n-a}const lf=Symbol("evaluating");function At(e,t,n){let a;Object.defineProperty(e,t,{get(){if(a!==lf)return a===void 0&&(a=lf,a=n()),a},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function Fo(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function io(...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 Ik(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const bb="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Xi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Ck=zl(()=>{if(wm.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Lr(e){if(Xi(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Xi(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function vb(e){return Lr(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const Rk=new Set(["string","number","symbol"]);function zr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function so(e,t,n){const a=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(a._zod.parent=e),a}function tt(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 Ak(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const Pk={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 Tk(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=io(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 Fo(this,"shape",s),s},checks:[]});return so(e,i)}function Ek(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=io(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 Fo(this,"shape",s),s},checks:[]});return so(e,i)}function Mk(e,t){if(!Lr(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 o=io(e._zod.def,{get shape(){const i={...e._zod.def.shape,...t};return Fo(this,"shape",i),i}});return so(e,o)}function jk(e,t){if(!Lr(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=io(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t};return Fo(this,"shape",a),a}});return so(e,n)}function Ok(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=io(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t._zod.def.shape};return Fo(this,"shape",a),a},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return so(e,n)}function Nk(e,t,n){const o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const s=io(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 Fo(this,"shape",p),p},checks:[]});return so(t,s)}function $k(e,t,n){const a=io(t._zod.def,{get shape(){const o=t._zod.def.shape,i={...o};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:o[s]}))}else for(const s in o)i[s]=new e({type:"nonoptional",innerType:o[s]});return Fo(this,"shape",i),i}});return so(t,a)}function Ar(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 Dk(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 Pr(e,t){return t.map(n=>{var a;return(a=n).path??(a.path=[]),n.path.unshift(e),n})}function Ys(e){return typeof e=="string"?e:e?.message}function Fa(e,t,n){const a=e.message?e.message:Ys(e.inst?._zod.def?.error?.(e))??Ys(t?.error?.(e))??Ys(n.customError?.(e))??Ys(n.localeError?.(e))??"Invalid input",{inst:o,continue:i,input:s,...l}=e;return l.path??(l.path=[]),l.message=a,t?.reportInput&&(l.input=s),l}function Cm(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Qi(...e){const[t,n,a]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:a}:{...t}}const yb=(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,Mu,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Sb=ge("$ZodError",yb),xb=ge("$ZodError",yb,{Parent:Error});function Lk(e,t=n=>n.message){const n={},a=[];for(const o of e.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):a.push(t(o));return{formErrors:a,fieldErrors:n}}function zk(e,t=n=>n.message){const n={_errors:[]},a=(o,i=[])=>{for(const s of o.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 Rm=e=>(t,n,a,o)=>{const i=a?{...a,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw new $r;if(s.issues.length){const l=new(o?.Err??e)(s.issues.map(p=>Fa(p,i,Ba())));throw bb(l,o?.callee),l}return s.value},Am=e=>async(t,n,a,o)=>{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(o?.Err??e)(s.issues.map(p=>Fa(p,i,Ba())));throw bb(l,o?.callee),l}return s.value},Ul=e=>(t,n,a)=>{const o=a?{...a,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise)throw new $r;return i.issues.length?{success:!1,error:new(e??Sb)(i.issues.map(s=>Fa(s,o,Ba())))}:{success:!0,data:i.value}},Uk=Ul(xb),Hl=e=>async(t,n,a)=>{const o=a?{...a,async:!0}:{async:!0};let i=t._zod.run({value:n,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(s=>Fa(s,o,Ba())))}:{success:!0,data:i.value}},Hk=Hl(xb),qk=e=>(t,n,a)=>{const o=a?{...a,direction:"backward"}:{direction:"backward"};return Rm(e)(t,n,o)},Bk=e=>(t,n,a)=>Rm(e)(t,n,a),Fk=e=>async(t,n,a)=>{const o=a?{...a,direction:"backward"}:{direction:"backward"};return Am(e)(t,n,o)},Vk=e=>async(t,n,a)=>Am(e)(t,n,a),Wk=e=>(t,n,a)=>{const o=a?{...a,direction:"backward"}:{direction:"backward"};return Ul(e)(t,n,o)},Kk=e=>(t,n,a)=>Ul(e)(t,n,a),Gk=e=>async(t,n,a)=>{const o=a?{...a,direction:"backward"}:{direction:"backward"};return Hl(e)(t,n,o)},Zk=e=>async(t,n,a)=>Hl(e)(t,n,a),Jk=/^[cC][0-9a-z]{6,}$/,Yk=/^[0-9a-z]+$/,Xk=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Qk=/^[0-9a-vA-V]{20}$/,ew=/^[A-Za-z0-9]{27}$/,tw=/^[a-zA-Z0-9_-]{21}$/,nw=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,aw=/^([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})$/,df=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)$/,ow=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,rw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function iw(){return new RegExp(rw,"u")}const sw=/^(?:(?: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])$/,lw=/^(([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}|:))$/,cw=/^((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])$/,dw=/^(([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])$/,uw=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,kb=/^[A-Za-z0-9_-]*$/,mw=/^https?$/,pw=/^\+[1-9]\d{6,14}$/,wb="(?:(?:\\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])))",fw=new RegExp(`^${wb}$`);function _b(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 hw(e){return new RegExp(`^${_b(e)}$`)}function gw(e){const t=_b({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(`^${wb}T(?:${a})$`)}const bw=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},vw=/^-?\d+$/,Ib=/^-?\d+(?:\.\d+)?$/,yw=/^(?:true|false)$/i,Sw=/^null$/i,xw=/^[^A-Z]*$/,kw=/^[^a-z]*$/,Hn=ge("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Cb={number:"number",bigint:"bigint",object:"date"},Rb=ge("$ZodCheckLessThan",(e,t)=>{Hn.init(e,t);const n=Cb[typeof t.value];e._zod.onattach.push(a=>{const o=a._zod.bag,i=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?o.maximum=t.value:o.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})}}),Ab=ge("$ZodCheckGreaterThan",(e,t)=>{Hn.init(e,t);const n=Cb[typeof t.value];e._zod.onattach.push(a=>{const o=a._zod.bag,i=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?o.minimum=t.value:o.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})}}),ww=ge("$ZodCheckMultipleOf",(e,t)=>{Hn.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):_k(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})}}),_w=ge("$ZodCheckNumberFormat",(e,t)=>{Hn.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),a=n?"int":"number",[o,i]=Pk[t.format];e._zod.onattach.push(s=>{const l=s._zod.bag;l.format=t.format,l.minimum=o,l.maximum=i,n&&(l.pattern=vw)}),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<o&&s.issues.push({origin:"number",input:l,code:"too_small",minimum:o,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})}}),Iw=ge("$ZodCheckMaxLength",(e,t)=>{var n;Hn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const o=a.value;return!_m(o)&&o.length!==void 0}),e._zod.onattach.push(a=>{const o=a._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(a._zod.bag.maximum=t.maximum)}),e._zod.check=a=>{const o=a.value;if(o.length<=t.maximum)return;const s=Cm(o);a.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Cw=ge("$ZodCheckMinLength",(e,t)=>{var n;Hn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const o=a.value;return!_m(o)&&o.length!==void 0}),e._zod.onattach.push(a=>{const o=a._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(a._zod.bag.minimum=t.minimum)}),e._zod.check=a=>{const o=a.value;if(o.length>=t.minimum)return;const s=Cm(o);a.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Rw=ge("$ZodCheckLengthEquals",(e,t)=>{var n;Hn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const o=a.value;return!_m(o)&&o.length!==void 0}),e._zod.onattach.push(a=>{const o=a._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=a=>{const o=a.value,i=o.length;if(i===t.length)return;const s=Cm(o),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})}}),ql=ge("$ZodCheckStringFormat",(e,t)=>{var n,a;Hn.init(e,t),e._zod.onattach.push(o=>{const i=o._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=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(a=e._zod).check??(a.check=()=>{})}),Aw=ge("$ZodCheckRegex",(e,t)=>{ql.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})}}),Pw=ge("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=xw),ql.init(e,t)}),Tw=ge("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=kw),ql.init(e,t)}),Ew=ge("$ZodCheckIncludes",(e,t)=>{Hn.init(e,t);const n=zr(t.includes),a=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=a,e._zod.onattach.push(o=>{const i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(a)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),Mw=ge("$ZodCheckStartsWith",(e,t)=>{Hn.init(e,t);const n=new RegExp(`^${zr(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(a=>{const o=a._zod.bag;o.patterns??(o.patterns=new Set),o.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})}}),jw=ge("$ZodCheckEndsWith",(e,t)=>{Hn.init(e,t);const n=new RegExp(`.*${zr(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(a=>{const o=a._zod.bag;o.patterns??(o.patterns=new Set),o.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})}}),Ow=ge("$ZodCheckOverwrite",(e,t)=>{Hn.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class Nw{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),o=Math.min(...a.map(s=>s.length-s.trimStart().length)),i=a.map(s=>s.slice(o)).map(s=>" ".repeat(this.indent*2)+s);for(const s of i)this.content.push(s)}compile(){const t=Function,n=this?.args,o=[...(this?.content??[""]).map(i=>` ${i}`)];return new t(...n,o.join(`
4
- `))}}const $w={major:4,minor:4,patch:3},zt=ge("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=$w;const a=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&a.unshift(e);for(const o of a)for(const i of o._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 o=(s,l,p)=>{let m=Ar(s),f;for(const S of l){if(S._zod.def.when){if(Dk(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 $r;if(f||k instanceof Promise)f=(f??Promise.resolve()).then(async()=>{await k,s.issues.length!==y&&(m||(m=Ar(s,y)))});else{if(s.issues.length===y)continue;m||(m=Ar(s,y))}}return f?f.then(()=>s):s},i=(s,l,p)=>{if(Ar(s))return s.aborted=!0,s;const m=o(l,a,p);if(m instanceof Promise){if(p.async===!1)throw new $r;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 $r;return p.then(m=>o(m,a,l))}return o(p,a,l)}}At(e,"~standard",()=>({validate:o=>{try{const i=Uk(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return Hk(e,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),Pm=ge("$ZodString",(e,t)=>{zt.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??bw(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}}),Ut=ge("$ZodStringFormat",(e,t)=>{ql.init(e,t),Pm.init(e,t)}),Dw=ge("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=aw),Ut.init(e,t)}),Lw=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=df(a))}else t.pattern??(t.pattern=df());Ut.init(e,t)}),zw=ge("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=ow),Ut.init(e,t)}),Uw=ge("$ZodURL",(e,t)=>{Ut.init(e,t),e._zod.check=n=>{try{const a=n.value.trim();if(!t.normalize&&t.protocol?.source===mw.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 o=new URL(a);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.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(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.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=o.href:n.value=a;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Hw=ge("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=iw()),Ut.init(e,t)}),qw=ge("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=tw),Ut.init(e,t)}),Bw=ge("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Jk),Ut.init(e,t)}),Fw=ge("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Yk),Ut.init(e,t)}),Vw=ge("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Xk),Ut.init(e,t)}),Ww=ge("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Qk),Ut.init(e,t)}),Kw=ge("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=ew),Ut.init(e,t)}),Gw=ge("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=gw(t)),Ut.init(e,t)}),Zw=ge("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=fw),Ut.init(e,t)}),Jw=ge("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=hw(t)),Ut.init(e,t)}),Yw=ge("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=nw),Ut.init(e,t)}),Xw=ge("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=sw),Ut.init(e,t),e._zod.bag.format="ipv4"}),Qw=ge("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=lw),Ut.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})}}}),e_=ge("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=cw),Ut.init(e,t)}),t_=ge("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=dw),Ut.init(e,t),e._zod.check=n=>{const a=n.value.split("/");try{if(a.length!==2)throw new Error;const[o,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://[${o}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function Pb(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const n_=ge("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=uw),Ut.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{Pb(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function a_(e){if(!kb.test(e))return!1;const t=e.replace(/[-_]/g,a=>a==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return Pb(n)}const o_=ge("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=kb),Ut.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{a_(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),r_=ge("$ZodE164",(e,t)=>{t.pattern??(t.pattern=pw),Ut.init(e,t)});function i_(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[a]=n;if(!a)return!1;const o=JSON.parse(atob(a));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}const s_=ge("$ZodJWT",(e,t)=>{Ut.init(e,t),e._zod.check=n=>{i_(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Tb=ge("$ZodNumber",(e,t)=>{zt.init(e,t),e._zod.pattern=e._zod.bag.pattern??Ib,e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;const i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),n}}),l_=ge("$ZodNumberFormat",(e,t)=>{_w.init(e,t),Tb.init(e,t)}),c_=ge("$ZodBoolean",(e,t)=>{zt.init(e,t),e._zod.pattern=yw,e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=!!n.value}catch{}const o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}}),d_=ge("$ZodNull",(e,t)=>{zt.init(e,t),e._zod.pattern=Sw,e._zod.values=new Set([null]),e._zod.parse=(n,a)=>{const o=n.value;return o===null||n.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),n}}),u_=ge("$ZodUnknown",(e,t)=>{zt.init(e,t),e._zod.parse=n=>n}),m_=ge("$ZodNever",(e,t)=>{zt.init(e,t),e._zod.parse=(n,a)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function uf(e,t,n){e.issues.length&&t.issues.push(...Pr(n,e.issues)),t.value[n]=e.value}const p_=ge("$ZodArray",(e,t)=>{zt.init(e,t),e._zod.parse=(n,a)=>{const o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);const i=[];for(let s=0;s<o.length;s++){const l=o[s],p=t.element._zod.run({value:l,issues:[]},a);p instanceof Promise?i.push(p.then(m=>uf(m,n,s))):uf(p,n,s)}return i.length?Promise.all(i).then(()=>n):n}});function kl(e,t,n,a,o,i){const s=n in a;if(e.issues.length){if(o&&i&&!s)return;t.issues.push(...Pr(n,e.issues))}if(!s&&!o){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 Eb(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=Ak(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Mb(e,t,n,a,o,i){const s=[],l=o.keySet,p=o.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=>kl(R,n,y,t,f,S))):kl(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 f_=ge("$ZodObject",(e,t)=>{if(zt.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=zl(()=>Eb(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 o=Xi,i=t.catchall;let s;e._zod.parse=(l,p)=>{s??(s=a.value);const m=l.value;if(!o(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",$=k._zod.run({value:m[y],issues:[]},p);$ instanceof Promise?f.push($.then(z=>kl(z,l,y,m,R,A))):kl($,l,y,m,R,A)}return i?Mb(f,m,l,p,a.value,e):f.length?Promise.all(f).then(()=>l):l}}),h_=ge("$ZodObjectJIT",(e,t)=>{f_.init(e,t);const n=e._zod.parse,a=zl(()=>Eb(t)),o=y=>{const k=new Nw(["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 $=Object.create(null);let z=0;for(const x of R.keys)$[x]=`key_${z++}`;k.write("const newResult = {};");for(const x of R.keys){const I=$[x],P=cf(x),O=y[x],T=O?._zod?.optin==="optional",F=O?._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 D=k.compile();return(x,I)=>D(y,x,I)};let i;const s=Xi,l=!wm.jitless,m=l&&Ck.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=o(t.shape)),y=i(y,k),f?Mb([],R,y,k,S,e):y):n(y,k):(y.issues.push({expected:"object",code:"invalid_type",input:R,inst:e}),y)}});function mf(e,t,n,a){for(const i of e)if(i.issues.length===0)return t.value=i.value,t;const o=e.filter(i=>!Ar(i));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(i=>i.issues.map(s=>Fa(s,a,Ba())))}),t)}const jb=ge("$ZodUnion",(e,t)=>{zt.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(o=>o._zod.pattern);return new RegExp(`^(${a.map(o=>Im(o.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(a,o)=>{if(n)return n(a,o);let i=!1;const s=[];for(const l of t.options){const p=l._zod.run({value:a.value,issues:[]},o);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=>mf(l,a,e,o)):mf(s,a,e,o)}}),g_=ge("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,jb.init(e,t);const n=e._zod.parse;At(e._zod,"propValues",()=>{const o={};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)){o[l]||(o[l]=new Set);for(const m of p)o[l].add(m)}}return o});const a=zl(()=>{const o=t.options,i=new Map;for(const s of o){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=(o,i)=>{const s=o.value;if(!Xi(s))return o.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),o;const l=a.value.get(s?.[t.discriminator]);return l?l._zod.run(o,i):t.unionFallback||i.direction==="backward"?n(o,i):(o.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}),o)}}),b_=ge("$ZodIntersection",(e,t)=>{zt.init(e,t),e._zod.parse=(n,a)=>{const o=n.value,i=t.left._zod.run({value:o,issues:[]},a),s=t.right._zod.run({value:o,issues:[]},a);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([p,m])=>pf(n,p,m)):pf(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(Lr(e)&&Lr(t)){const n=Object.keys(t),a=Object.keys(e).filter(i=>n.indexOf(i)!==-1),o={...e,...t};for(const i of a){const s=ju(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};o[i]=s.data}return{valid:!0,data:o}}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 o=e[a],i=t[a],s=ju(o,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 pf(e,t,n){const a=new Map;let o;for(const l of t.issues)if(l.code==="unrecognized_keys"){o??(o=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&&o&&e.issues.push({...o,keys:i}),Ar(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 v_=ge("$ZodRecord",(e,t)=>{zt.init(e,t),e._zod.parse=(n,a)=>{const o=n.value;if(!Lr(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,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=>Fa(k,a,Ba())),input:m,path:[m],inst:e});continue}const S=f.value,y=t.valueType._zod.run({value:o[m],issues:[]},a);y instanceof Promise?i.push(y.then(k=>{k.issues.length&&n.issues.push(...Pr(m,k.issues)),n.value[S]=k.value})):(y.issues.length&&n.issues.push(...Pr(m,y.issues)),n.value[S]=y.value)}let p;for(const m in o)l.has(m)||(p=p??[],p.push(m));p&&p.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:p})}else{n.value={};for(const l of Reflect.ownKeys(o)){if(l==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,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"&&Ib.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]=o[l]:n.issues.push({code:"invalid_key",origin:"record",issues:p.issues.map(S=>Fa(S,a,Ba())),input:l,path:[l],inst:e});continue}const f=t.valueType._zod.run({value:o[l],issues:[]},a);f instanceof Promise?i.push(f.then(S=>{S.issues.length&&n.issues.push(...Pr(l,S.issues)),n.value[p.value]=S.value})):(f.issues.length&&n.issues.push(...Pr(l,f.issues)),n.value[p.value]=f.value)}}return i.length?Promise.all(i).then(()=>n):n}}),y_=ge("$ZodEnum",(e,t)=>{zt.init(e,t);const n=gb(t.entries),a=new Set(n);e._zod.values=a,e._zod.pattern=new RegExp(`^(${n.filter(o=>Rk.has(typeof o)).map(o=>typeof o=="string"?zr(o):o.toString()).join("|")})$`),e._zod.parse=(o,i)=>{const s=o.value;return a.has(s)||o.issues.push({code:"invalid_value",values:n,input:s,inst:e}),o}}),S_=ge("$ZodLiteral",(e,t)=>{if(zt.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"?zr(a):a?zr(a.toString()):String(a)).join("|")})$`),e._zod.parse=(a,o)=>{const i=a.value;return n.has(i)||a.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),a}}),x_=ge("$ZodTransform",(e,t)=>{zt.init(e,t),e._zod.optin="optional",e._zod.parse=(n,a)=>{if(a.direction==="backward")throw new hb(e.constructor.name);const o=t.transform(n.value,n);if(a.async)return(o instanceof Promise?o:Promise.resolve(o)).then(s=>(n.value=s,n.fallback=!0,n));if(o instanceof Promise)throw new $r;return n.value=o,n.fallback=!0,n}});function ff(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const Ob=ge("$ZodOptional",(e,t)=>{zt.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(`^(${Im(n.source)})?$`):void 0}),e._zod.parse=(n,a)=>{if(t.innerType._zod.optin==="optional"){const o=n.value,i=t.innerType._zod.run(n,a);return i instanceof Promise?i.then(s=>ff(s,o)):ff(i,o)}return n.value===void 0?n:t.innerType._zod.run(n,a)}}),k_=ge("$ZodExactOptional",(e,t)=>{Ob.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)}),w_=ge("$ZodNullable",(e,t)=>{zt.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(`^(${Im(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)}),__=ge("$ZodDefault",(e,t)=>{zt.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 o=t.innerType._zod.run(n,a);return o instanceof Promise?o.then(i=>hf(i,t)):hf(o,t)}});function hf(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const I_=ge("$ZodPrefault",(e,t)=>{zt.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))}),C_=ge("$ZodNonOptional",(e,t)=>{zt.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 o=t.innerType._zod.run(n,a);return o instanceof Promise?o.then(i=>gf(i,e)):gf(o,e)}});function gf(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 R_=ge("$ZodCatch",(e,t)=>{zt.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 o=t.innerType._zod.run(n,a);return o instanceof Promise?o.then(i=>(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(s=>Fa(s,a,Ba()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=o.value,o.issues.length&&(n.value=t.catchValue({...n,error:{issues:o.issues.map(i=>Fa(i,a,Ba()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),Nb=ge("$ZodPipe",(e,t)=>{zt.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=>Xs(s,t.in,a)):Xs(i,t.in,a)}const o=t.in._zod.run(n,a);return o instanceof Promise?o.then(i=>Xs(i,t.out,a)):Xs(o,t.out,a)}});function Xs(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 A_=ge("$ZodPreprocess",(e,t)=>{Nb.init(e,t)}),P_=ge("$ZodReadonly",(e,t)=>{zt.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 o=t.innerType._zod.run(n,a);return o instanceof Promise?o.then(bf):bf(o)}});function bf(e){return e.value=Object.freeze(e.value),e}const T_=ge("$ZodCustom",(e,t)=>{Hn.init(e,t),zt.init(e,t),e._zod.parse=(n,a)=>n,e._zod.check=n=>{const a=n.value,o=t.fn(a);if(o instanceof Promise)return o.then(i=>vf(i,n,a,e));vf(o,n,a,e)}});function vf(e,t,n,a){if(!e){const o={code:"custom",input:n,inst:a,path:[...a._zod.def.path??[]],continue:!a._zod.def.abort};a._zod.def.params&&(o.params=a._zod.def.params),t.issues.push(Qi(o))}}var yf;class E_{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 o={...a,...this._map.get(t)};return Object.keys(o).length?o:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function M_(){return new E_}(yf=globalThis).__zod_globalRegistry??(yf.__zod_globalRegistry=M_());const Wi=globalThis.__zod_globalRegistry;function j_(e,t){return new e({type:"string",...tt(t)})}function O_(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...tt(t)})}function Sf(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...tt(t)})}function N_(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...tt(t)})}function $_(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...tt(t)})}function D_(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...tt(t)})}function L_(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...tt(t)})}function z_(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...tt(t)})}function U_(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...tt(t)})}function H_(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...tt(t)})}function q_(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...tt(t)})}function B_(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...tt(t)})}function F_(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...tt(t)})}function V_(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...tt(t)})}function W_(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...tt(t)})}function K_(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...tt(t)})}function G_(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...tt(t)})}function Z_(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...tt(t)})}function J_(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...tt(t)})}function Y_(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...tt(t)})}function X_(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...tt(t)})}function Q_(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...tt(t)})}function eI(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...tt(t)})}function tI(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...tt(t)})}function nI(e,t){return new e({type:"string",format:"date",check:"string_format",...tt(t)})}function aI(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...tt(t)})}function oI(e,t){return new e({type:"string",format:"duration",check:"string_format",...tt(t)})}function rI(e,t){return new e({type:"number",checks:[],...tt(t)})}function iI(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...tt(t)})}function sI(e,t){return new e({type:"boolean",...tt(t)})}function lI(e,t){return new e({type:"null",...tt(t)})}function cI(e){return new e({type:"unknown"})}function dI(e,t){return new e({type:"never",...tt(t)})}function xf(e,t){return new Rb({check:"less_than",...tt(t),value:e,inclusive:!1})}function yd(e,t){return new Rb({check:"less_than",...tt(t),value:e,inclusive:!0})}function kf(e,t){return new Ab({check:"greater_than",...tt(t),value:e,inclusive:!1})}function Sd(e,t){return new Ab({check:"greater_than",...tt(t),value:e,inclusive:!0})}function wf(e,t){return new ww({check:"multiple_of",...tt(t),value:e})}function $b(e,t){return new Iw({check:"max_length",...tt(t),maximum:e})}function wl(e,t){return new Cw({check:"min_length",...tt(t),minimum:e})}function Db(e,t){return new Rw({check:"length_equals",...tt(t),length:e})}function uI(e,t){return new Aw({check:"string_format",format:"regex",...tt(t),pattern:e})}function mI(e){return new Pw({check:"string_format",format:"lowercase",...tt(e)})}function pI(e){return new Tw({check:"string_format",format:"uppercase",...tt(e)})}function fI(e,t){return new Ew({check:"string_format",format:"includes",...tt(t),includes:e})}function hI(e,t){return new Mw({check:"string_format",format:"starts_with",...tt(t),prefix:e})}function gI(e,t){return new jw({check:"string_format",format:"ends_with",...tt(t),suffix:e})}function Kr(e){return new Ow({check:"overwrite",tx:e})}function bI(e){return Kr(t=>t.normalize(e))}function vI(){return Kr(e=>e.trim())}function yI(){return Kr(e=>e.toLowerCase())}function SI(){return Kr(e=>e.toUpperCase())}function xI(){return Kr(e=>Ik(e))}function kI(e,t,n){return new e({type:"array",element:t,...tt(n)})}function wI(e,t,n){const a=tt(n);return a.abort??(a.abort=!0),new e({type:"custom",check:"custom",fn:t,...a})}function _I(e,t,n){return new e({type:"custom",check:"custom",fn:t,...tt(n)})}function II(e,t){const n=CI(a=>(a.addIssue=o=>{if(typeof o=="string")a.issues.push(Qi(o,a.value,n._zod.def));else{const i=o;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(Qi(i))}},e(a.value,a)),t);return n}function CI(e,t){const n=new Hn({check:"custom",...tt(t)});return n._zod.check=e,n}function Lb(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??Wi,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 nn(e,t,n={path:[],schemaPath:[]}){var a;const o=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[o.type];if(!k)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);k(e,t,y,f)}const S=e._zod.parent;S&&(s.ref||(s.ref=S),nn(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"&&In(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 zb(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 o=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}=o(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 Ub(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 $ in m)$==="$ref"||$==="allOf"||$ in f||delete m[$];if(R.$ref&&k.def)for(const $ in m)$==="$ref"||$==="allOf"||$ in k.def&&JSON.stringify(m[$])===JSON.stringify(k.def[$])&&delete m[$]}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 o={};if(e.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?o.$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");o.$id=e.external.uri(l)}Object.assign(o,n.def??n.schema);const i=e.metadataRegistry.get(t)?.id;i!==void 0&&o.id===i&&delete o.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"?o.$defs=s:o.definitions=s);try{const l=JSON.parse(JSON.stringify(o));return Object.defineProperty(l,"~standard",{value:{...t["~standard"],jsonSchema:{input:_l(t,"input",e.processors),output:_l(t,"output",e.processors)}},enumerable:!1,writable:!1}),l}catch{throw new Error("Error converting schema to JSON.")}}function In(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 In(a.element,n);if(a.type==="set")return In(a.valueType,n);if(a.type==="lazy")return In(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 In(a.innerType,n);if(a.type==="intersection")return In(a.left,n)||In(a.right,n);if(a.type==="record"||a.type==="map")return In(a.keyType,n)||In(a.valueType,n);if(a.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:In(a.in,n)||In(a.out,n);if(a.type==="object"){for(const o in a.shape)if(In(a.shape[o],n))return!0;return!1}if(a.type==="union"){for(const o of a.options)if(In(o,n))return!0;return!1}if(a.type==="tuple"){for(const o of a.items)if(In(o,n))return!0;return!!(a.rest&&In(a.rest,n))}return!1}const RI=(e,t={})=>n=>{const a=Lb({...n,processors:t});return nn(e,a),zb(a,e),Ub(a,e)},_l=(e,t,n={})=>a=>{const{libraryOptions:o,target:i}=a??{},s=Lb({...o??{},target:i,io:t,processors:n});return nn(e,s),zb(s,e),Ub(s,e)},AI={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},PI=(e,t,n,a)=>{const o=n;o.type="string";const{minimum:i,maximum:s,format:l,patterns:p,contentEncoding:m}=e._zod.bag;if(typeof i=="number"&&(o.minLength=i),typeof s=="number"&&(o.maxLength=s),l&&(o.format=AI[l]??l,o.format===""&&delete o.format,l==="time"&&delete o.format),m&&(o.contentEncoding=m),p&&p.size>0){const f=[...p];f.length===1?o.pattern=f[0].source:f.length>1&&(o.allOf=[...f.map(S=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:S.source}))])}},TI=(e,t,n,a)=>{const o=n,{minimum:i,maximum:s,format:l,multipleOf:p,exclusiveMaximum:m,exclusiveMinimum:f}=e._zod.bag;typeof l=="string"&&l.includes("int")?o.type="integer":o.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?(o.minimum=f,o.exclusiveMinimum=!0):o.exclusiveMinimum=f:typeof i=="number"&&(o.minimum=i),y?k?(o.maximum=m,o.exclusiveMaximum=!0):o.exclusiveMaximum=m:typeof s=="number"&&(o.maximum=s),typeof p=="number"&&(o.multipleOf=p)},EI=(e,t,n,a)=>{n.type="boolean"},MI=(e,t,n,a)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},jI=(e,t,n,a)=>{n.not={}},OI=(e,t,n,a)=>{},NI=(e,t,n,a)=>{const o=e._zod.def,i=gb(o.entries);i.every(s=>typeof s=="number")&&(n.type="number"),i.every(s=>typeof s=="string")&&(n.type="string"),n.enum=i},$I=(e,t,n,a)=>{const o=e._zod.def,i=[];for(const s of o.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},DI=(e,t,n,a)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},LI=(e,t,n,a)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},zI=(e,t,n,a)=>{const o=n,i=e._zod.def,{minimum:s,maximum:l}=e._zod.bag;typeof s=="number"&&(o.minItems=s),typeof l=="number"&&(o.maxItems=l),o.type="array",o.items=nn(i.element,t,{...a,path:[...a.path,"items"]})},UI=(e,t,n,a)=>{const o=n,i=e._zod.def;o.type="object",o.properties={};const s=i.shape;for(const m in s)o.properties[m]=nn(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&&(o.required=Array.from(p)),i.catchall?._zod.def.type==="never"?o.additionalProperties=!1:i.catchall?i.catchall&&(o.additionalProperties=nn(i.catchall,t,{...a,path:[...a.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},HI=(e,t,n,a)=>{const o=e._zod.def,i=o.inclusive===!1,s=o.options.map((l,p)=>nn(l,t,{...a,path:[...a.path,i?"oneOf":"anyOf",p]}));i?n.oneOf=s:n.anyOf=s},qI=(e,t,n,a)=>{const o=e._zod.def,i=nn(o.left,t,{...a,path:[...a.path,"allOf",0]}),s=nn(o.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},BI=(e,t,n,a)=>{const o=n,i=e._zod.def;o.type="object";const s=i.keyType,p=s._zod.bag?.patterns;if(i.mode==="loose"&&p&&p.size>0){const f=nn(i.valueType,t,{...a,path:[...a.path,"patternProperties","*"]});o.patternProperties={};for(const S of p)o.patternProperties[S.source]=f}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(o.propertyNames=nn(i.keyType,t,{...a,path:[...a.path,"propertyNames"]})),o.additionalProperties=nn(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&&(o.required=f)}},FI=(e,t,n,a)=>{const o=e._zod.def,i=nn(o.innerType,t,a),s=t.seen.get(e);t.target==="openapi-3.0"?(s.ref=o.innerType,n.nullable=!0):n.anyOf=[i,{type:"null"}]},VI=(e,t,n,a)=>{const o=e._zod.def;nn(o.innerType,t,a);const i=t.seen.get(e);i.ref=o.innerType},WI=(e,t,n,a)=>{const o=e._zod.def;nn(o.innerType,t,a);const i=t.seen.get(e);i.ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))},KI=(e,t,n,a)=>{const o=e._zod.def;nn(o.innerType,t,a);const i=t.seen.get(e);i.ref=o.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},GI=(e,t,n,a)=>{const o=e._zod.def;nn(o.innerType,t,a);const i=t.seen.get(e);i.ref=o.innerType;let s;try{s=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=s},ZI=(e,t,n,a)=>{const o=e._zod.def,i=o.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?i?o.out:o.in:o.out;nn(s,t,a);const l=t.seen.get(e);l.ref=s},JI=(e,t,n,a)=>{const o=e._zod.def;nn(o.innerType,t,a);const i=t.seen.get(e);i.ref=o.innerType,n.readOnly=!0},Hb=(e,t,n,a)=>{const o=e._zod.def;nn(o.innerType,t,a);const i=t.seen.get(e);i.ref=o.innerType},YI=ge("ZodISODateTime",(e,t)=>{Gw.init(e,t),Ft.init(e,t)});function XI(e){return tI(YI,e)}const QI=ge("ZodISODate",(e,t)=>{Zw.init(e,t),Ft.init(e,t)});function e1(e){return nI(QI,e)}const t1=ge("ZodISOTime",(e,t)=>{Jw.init(e,t),Ft.init(e,t)});function n1(e){return aI(t1,e)}const a1=ge("ZodISODuration",(e,t)=>{Yw.init(e,t),Ft.init(e,t)});function o1(e){return oI(a1,e)}const r1=(e,t)=>{Sb.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>zk(e,n)},flatten:{value:n=>Lk(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,Mu,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,Mu,2)}},isEmpty:{get(){return e.issues.length===0}}})},oa=ge("ZodError",r1,{Parent:Error}),i1=Rm(oa),s1=Am(oa),l1=Ul(oa),c1=Hl(oa),d1=qk(oa),u1=Bk(oa),m1=Fk(oa),p1=Vk(oa),f1=Wk(oa),h1=Kk(oa),g1=Gk(oa),b1=Zk(oa),_f=new WeakMap;function ms(e,t,n){const a=Object.getPrototypeOf(e);let o=_f.get(a);if(o||(o=new Set,_f.set(a,o)),!o.has(t)){o.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 Ht=ge("ZodType",(e,t)=>(zt.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:_l(e,"input"),output:_l(e,"output")}}),e.toJSONSchema=RI(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,a)=>i1(e,n,a,{callee:e.parse}),e.safeParse=(n,a)=>l1(e,n,a),e.parseAsync=async(n,a)=>s1(e,n,a,{callee:e.parseAsync}),e.safeParseAsync=async(n,a)=>c1(e,n,a),e.spa=e.safeParseAsync,e.encode=(n,a)=>d1(e,n,a),e.decode=(n,a)=>u1(e,n,a),e.encodeAsync=async(n,a)=>m1(e,n,a),e.decodeAsync=async(n,a)=>p1(e,n,a),e.safeEncode=(n,a)=>f1(e,n,a),e.safeDecode=(n,a)=>h1(e,n,a),e.safeEncodeAsync=async(n,a)=>g1(e,n,a),e.safeDecodeAsync=async(n,a)=>b1(e,n,a),ms(e,"ZodType",{check(...n){const a=this.def;return this.clone(io(a,{checks:[...a.checks??[],...n.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,a){return so(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(cC(n,a))},overwrite(n){return this.check(Kr(n))},optional(){return Af(this)},exactOptional(){return J1(this)},nullable(){return Pf(this)},nullish(){return Af(Pf(this))},nonoptional(n){return nC(this,n)},array(){return h(this)},or(n){return vn([this,n])},and(n){return W1(this,n)},transform(n){return Tf(this,Wb(n))},default(n){return Q1(this,n)},prefault(n){return tC(this,n)},catch(n){return oC(this,n)},pipe(n){return Tf(this,n)},readonly(){return sC(this)},describe(n){const a=this.clone();return Wi.add(a,{description:n}),a},meta(...n){if(n.length===0)return Wi.get(this);const a=this.clone();return Wi.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 Wi.get(e)?.description},configurable:!0}),e)),qb=ge("_ZodString",(e,t)=>{Pm.init(e,t),Ht.init(e,t),e._zod.processJSONSchema=(a,o,i)=>PI(e,a,o);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,ms(e,"_ZodString",{regex(...a){return this.check(uI(...a))},includes(...a){return this.check(fI(...a))},startsWith(...a){return this.check(hI(...a))},endsWith(...a){return this.check(gI(...a))},min(...a){return this.check(wl(...a))},max(...a){return this.check($b(...a))},length(...a){return this.check(Db(...a))},nonempty(...a){return this.check(wl(1,...a))},lowercase(a){return this.check(mI(a))},uppercase(a){return this.check(pI(a))},trim(){return this.check(vI())},normalize(...a){return this.check(bI(...a))},toLowerCase(){return this.check(yI())},toUpperCase(){return this.check(SI())},slugify(){return this.check(xI())}})}),v1=ge("ZodString",(e,t)=>{Pm.init(e,t),qb.init(e,t),e.email=n=>e.check(O_(y1,n)),e.url=n=>e.check(z_(S1,n)),e.jwt=n=>e.check(eI(N1,n)),e.emoji=n=>e.check(U_(x1,n)),e.guid=n=>e.check(Sf(If,n)),e.uuid=n=>e.check(N_(Qs,n)),e.uuidv4=n=>e.check($_(Qs,n)),e.uuidv6=n=>e.check(D_(Qs,n)),e.uuidv7=n=>e.check(L_(Qs,n)),e.nanoid=n=>e.check(H_(k1,n)),e.guid=n=>e.check(Sf(If,n)),e.cuid=n=>e.check(q_(w1,n)),e.cuid2=n=>e.check(B_(_1,n)),e.ulid=n=>e.check(F_(I1,n)),e.base64=n=>e.check(Y_(M1,n)),e.base64url=n=>e.check(X_(j1,n)),e.xid=n=>e.check(V_(C1,n)),e.ksuid=n=>e.check(W_(R1,n)),e.ipv4=n=>e.check(K_(A1,n)),e.ipv6=n=>e.check(G_(P1,n)),e.cidrv4=n=>e.check(Z_(T1,n)),e.cidrv6=n=>e.check(J_(E1,n)),e.e164=n=>e.check(Q_(O1,n)),e.datetime=n=>e.check(XI(n)),e.date=n=>e.check(e1(n)),e.time=n=>e.check(n1(n)),e.duration=n=>e.check(o1(n))});function r(e){return j_(v1,e)}const Ft=ge("ZodStringFormat",(e,t)=>{Ut.init(e,t),qb.init(e,t)}),y1=ge("ZodEmail",(e,t)=>{zw.init(e,t),Ft.init(e,t)}),If=ge("ZodGUID",(e,t)=>{Dw.init(e,t),Ft.init(e,t)}),Qs=ge("ZodUUID",(e,t)=>{Lw.init(e,t),Ft.init(e,t)}),S1=ge("ZodURL",(e,t)=>{Uw.init(e,t),Ft.init(e,t)}),x1=ge("ZodEmoji",(e,t)=>{Hw.init(e,t),Ft.init(e,t)}),k1=ge("ZodNanoID",(e,t)=>{qw.init(e,t),Ft.init(e,t)}),w1=ge("ZodCUID",(e,t)=>{Bw.init(e,t),Ft.init(e,t)}),_1=ge("ZodCUID2",(e,t)=>{Fw.init(e,t),Ft.init(e,t)}),I1=ge("ZodULID",(e,t)=>{Vw.init(e,t),Ft.init(e,t)}),C1=ge("ZodXID",(e,t)=>{Ww.init(e,t),Ft.init(e,t)}),R1=ge("ZodKSUID",(e,t)=>{Kw.init(e,t),Ft.init(e,t)}),A1=ge("ZodIPv4",(e,t)=>{Xw.init(e,t),Ft.init(e,t)}),P1=ge("ZodIPv6",(e,t)=>{Qw.init(e,t),Ft.init(e,t)}),T1=ge("ZodCIDRv4",(e,t)=>{e_.init(e,t),Ft.init(e,t)}),E1=ge("ZodCIDRv6",(e,t)=>{t_.init(e,t),Ft.init(e,t)}),M1=ge("ZodBase64",(e,t)=>{n_.init(e,t),Ft.init(e,t)}),j1=ge("ZodBase64URL",(e,t)=>{o_.init(e,t),Ft.init(e,t)}),O1=ge("ZodE164",(e,t)=>{r_.init(e,t),Ft.init(e,t)}),N1=ge("ZodJWT",(e,t)=>{s_.init(e,t),Ft.init(e,t)}),Bb=ge("ZodNumber",(e,t)=>{Tb.init(e,t),Ht.init(e,t),e._zod.processJSONSchema=(a,o,i)=>TI(e,a,o),ms(e,"ZodNumber",{gt(a,o){return this.check(kf(a,o))},gte(a,o){return this.check(Sd(a,o))},min(a,o){return this.check(Sd(a,o))},lt(a,o){return this.check(xf(a,o))},lte(a,o){return this.check(yd(a,o))},max(a,o){return this.check(yd(a,o))},int(a){return this.check(Cf(a))},safe(a){return this.check(Cf(a))},positive(a){return this.check(kf(0,a))},nonnegative(a){return this.check(Sd(0,a))},negative(a){return this.check(xf(0,a))},nonpositive(a){return this.check(yd(0,a))},multipleOf(a,o){return this.check(wf(a,o))},step(a,o){return this.check(wf(a,o))},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 u(e){return rI(Bb,e)}const $1=ge("ZodNumberFormat",(e,t)=>{l_.init(e,t),Bb.init(e,t)});function Cf(e){return iI($1,e)}const D1=ge("ZodBoolean",(e,t)=>{c_.init(e,t),Ht.init(e,t),e._zod.processJSONSchema=(n,a,o)=>EI(e,n,a)});function C(e){return sI(D1,e)}const L1=ge("ZodNull",(e,t)=>{d_.init(e,t),Ht.init(e,t),e._zod.processJSONSchema=(n,a,o)=>MI(e,n,a)});function Fb(e){return lI(L1,e)}const z1=ge("ZodUnknown",(e,t)=>{u_.init(e,t),Ht.init(e,t),e._zod.processJSONSchema=(n,a,o)=>OI()});function Re(){return cI(z1)}const U1=ge("ZodNever",(e,t)=>{m_.init(e,t),Ht.init(e,t),e._zod.processJSONSchema=(n,a,o)=>jI(e,n,a)});function H1(e){return dI(U1,e)}const q1=ge("ZodArray",(e,t)=>{p_.init(e,t),Ht.init(e,t),e._zod.processJSONSchema=(n,a,o)=>zI(e,n,a,o),e.element=t.element,ms(e,"ZodArray",{min(n,a){return this.check(wl(n,a))},nonempty(n){return this.check(wl(1,n))},max(n,a){return this.check($b(n,a))},length(n,a){return this.check(Db(n,a))},unwrap(){return this.element}})});function h(e,t){return kI(q1,e,t)}const B1=ge("ZodObject",(e,t)=>{h_.init(e,t),Ht.init(e,t),e._zod.processJSONSchema=(n,a,o)=>UI(e,n,a,o),At(e,"shape",()=>t.shape),ms(e,"ZodObject",{keyof(){return v(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:Re()})},loose(){return this.clone({...this._zod.def,catchall:Re()})},strict(){return this.clone({...this._zod.def,catchall:H1()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return Mk(this,n)},safeExtend(n){return jk(this,n)},merge(n){return Ok(this,n)},pick(n){return Tk(this,n)},omit(n){return Ek(this,n)},partial(...n){return Nk(Kb,this,n[0])},required(...n){return $k(Gb,this,n[0])}})});function c(e,t){const n={type:"object",shape:e??{},...tt(t)};return new B1(n)}const Vb=ge("ZodUnion",(e,t)=>{jb.init(e,t),Ht.init(e,t),e._zod.processJSONSchema=(n,a,o)=>HI(e,n,a,o),e.options=t.options});function vn(e,t){return new Vb({type:"union",options:e,...tt(t)})}const F1=ge("ZodDiscriminatedUnion",(e,t)=>{Vb.init(e,t),g_.init(e,t)});function fn(e,t,n){return new F1({type:"union",options:t,discriminator:e,...tt(n)})}const V1=ge("ZodIntersection",(e,t)=>{b_.init(e,t),Ht.init(e,t),e._zod.processJSONSchema=(n,a,o)=>qI(e,n,a,o)});function W1(e,t){return new V1({type:"intersection",left:e,right:t})}const Rf=ge("ZodRecord",(e,t)=>{v_.init(e,t),Ht.init(e,t),e._zod.processJSONSchema=(n,a,o)=>BI(e,n,a,o),e.keyType=t.keyType,e.valueType=t.valueType});function ve(e,t,n){return!t||!t._zod?new Rf({type:"record",keyType:r(),valueType:e,...tt(t)}):new Rf({type:"record",keyType:e,valueType:t,...tt(n)})}const Ou=ge("ZodEnum",(e,t)=>{y_.init(e,t),Ht.init(e,t),e._zod.processJSONSchema=(a,o,i)=>NI(e,a,o),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(a,o)=>{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 Ou({...t,checks:[],...tt(o),entries:i})},e.exclude=(a,o)=>{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 Ou({...t,checks:[],...tt(o),entries:i})}});function v(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(a=>[a,a])):e;return new Ou({type:"enum",entries:n,...tt(t)})}const K1=ge("ZodLiteral",(e,t)=>{S_.init(e,t),Ht.init(e,t),e._zod.processJSONSchema=(n,a,o)=>$I(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 _(e,t){return new K1({type:"literal",values:Array.isArray(e)?e:[e],...tt(t)})}const G1=ge("ZodTransform",(e,t)=>{x_.init(e,t),Ht.init(e,t),e._zod.processJSONSchema=(n,a,o)=>LI(e,n),e._zod.parse=(n,a)=>{if(a.direction==="backward")throw new hb(e.constructor.name);n.addIssue=i=>{if(typeof i=="string")n.issues.push(Qi(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(Qi(s))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(i=>(n.value=i,n.fallback=!0,n)):(n.value=o,n.fallback=!0,n)}});function Wb(e){return new G1({type:"transform",transform:e})}const Kb=ge("ZodOptional",(e,t)=>{Ob.init(e,t),Ht.init(e,t),e._zod.processJSONSchema=(n,a,o)=>Hb(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function Af(e){return new Kb({type:"optional",innerType:e})}const Z1=ge("ZodExactOptional",(e,t)=>{k_.init(e,t),Ht.init(e,t),e._zod.processJSONSchema=(n,a,o)=>Hb(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function J1(e){return new Z1({type:"optional",innerType:e})}const Y1=ge("ZodNullable",(e,t)=>{w_.init(e,t),Ht.init(e,t),e._zod.processJSONSchema=(n,a,o)=>FI(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function Pf(e){return new Y1({type:"nullable",innerType:e})}const X1=ge("ZodDefault",(e,t)=>{__.init(e,t),Ht.init(e,t),e._zod.processJSONSchema=(n,a,o)=>WI(e,n,a,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Q1(e,t){return new X1({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():vb(t)}})}const eC=ge("ZodPrefault",(e,t)=>{I_.init(e,t),Ht.init(e,t),e._zod.processJSONSchema=(n,a,o)=>KI(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function tC(e,t){return new eC({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():vb(t)}})}const Gb=ge("ZodNonOptional",(e,t)=>{C_.init(e,t),Ht.init(e,t),e._zod.processJSONSchema=(n,a,o)=>VI(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function nC(e,t){return new Gb({type:"nonoptional",innerType:e,...tt(t)})}const aC=ge("ZodCatch",(e,t)=>{R_.init(e,t),Ht.init(e,t),e._zod.processJSONSchema=(n,a,o)=>GI(e,n,a,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function oC(e,t){return new aC({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const Zb=ge("ZodPipe",(e,t)=>{Nb.init(e,t),Ht.init(e,t),e._zod.processJSONSchema=(n,a,o)=>ZI(e,n,a,o),e.in=t.in,e.out=t.out});function Tf(e,t){return new Zb({type:"pipe",in:e,out:t})}const rC=ge("ZodPreprocess",(e,t)=>{Zb.init(e,t),A_.init(e,t)}),iC=ge("ZodReadonly",(e,t)=>{P_.init(e,t),Ht.init(e,t),e._zod.processJSONSchema=(n,a,o)=>JI(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function sC(e){return new iC({type:"readonly",innerType:e})}const Jb=ge("ZodCustom",(e,t)=>{T_.init(e,t),Ht.init(e,t),e._zod.processJSONSchema=(n,a,o)=>DI(e,n)});function xd(e,t){return wI(Jb,(()=>!0),t)}function lC(e,t={}){return _I(Jb,e,t)}function cC(e,t){return II(e,t)}function dC(e,t){return new rC({type:"pipe",in:Wb(e),out:t})}const An={custom:"custom"},Tm=["openpond","codex","anthropic","openai","xai","google","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],Vo=v(Tm),Bl=v(["active","preview","planned","deprecated"]),Yb=v(["openpond-account","openpond-managed","codex-login","chatgpt-subscription","local-byok","hosted-byok","custom"]),uC=v(["none","local_secret","env","openpond_account","codex_login","chatgpt_subscription","hosted"]),Ef=c({connected:C().default(!1),source:uC.default("none"),redacted:r().nullable().default(null),lastValidatedAt:r().nullable().default(null),lastError:r().nullable().default(null)}),Nu=c({hostedOpChat:C().default(!1),localRuntime:C().default(!0),localByok:C().default(!1),hostedByok:C().default(!1)}),mC=v(["hosted","provider","manual","none"]),$u=c({chatCompletions:C().default(!0),streaming:C().default(!0),modelDiscovery:mC.default("none"),toolCalling:C().default(!1),reasoning:C().default(!1),imageInput:C().default(!1),structuredOutput:C().default(!1)}),pC=v(["hosted","provider","curated","manual","cache"]),Du=c({streaming:C().default(!0),toolCalling:C().default(!1),reasoning:C().default(!1),vision:C().default(!1),structuredOutput:C().default(!1)}),fC=c({id:r().trim().min(1).max(300),providerId:Vo,displayName:r().trim().min(1).max(300),contextWindow:u().int().positive().nullable().default(null),outputLimit:u().int().positive().nullable().default(null),lifecycleStatus:Bl.default("active"),source:pC,capabilities:Du.default(()=>Du.parse({})),raw:ve(r(),Re()).optional()}),hC=c({providerId:Vo,models:h(fC).default([]),fetchedAt:r().nullable().default(null),lastError:r().nullable().default(null),source:v(["none","hosted","provider","curated","manual"]).default("none")}),gC=c({enabled:C().default(!1),baseUrl:r().trim().min(1).max(2048).nullable().default(null),defaultModel:r().trim().min(1).max(300).nullable().default(null),modelOverrides:h(r().trim().min(1).max(300)).max(500).default([]),updatedAt:r().nullable().default(null)}),bC=c({enabled:C().optional(),baseUrl:r().trim().min(1).max(2048).nullable().optional(),defaultModel:r().trim().min(1).max(300).nullable().optional(),modelOverrides:h(r().trim().min(1).max(300)).max(500).optional()}),vC=c({id:r().trim().min(1).max(300),displayName:r().trim().min(1).max(300),contextWindow:u().int().positive().nullable().optional(),outputLimit:u().int().positive().nullable().optional(),lifecycleStatus:Bl.optional(),capabilities:Du.partial().optional()}),yC=c({id:Vo,displayName:r().trim().min(1).max(160),lifecycleStatus:Bl.default("active"),credentialModes:h(Yb).default([]),routing:Nu,capabilities:$u,defaultEnabled:C().optional(),defaultBaseUrl:r().trim().min(1).max(2048).nullable().optional(),defaultModel:r().trim().min(1).max(300).nullable().optional(),modelCacheSource:v(["none","hosted","provider","curated","manual"]),models:h(vC).default([])});c({version:_(1).default(1),generatedAt:r().datetime(),providers:h(yC)});const SC=c({id:Vo,displayName:r().trim().min(1).max(160),lifecycleStatus:Bl.default("active"),credentialModes:h(Yb).default([]),routing:Nu.default(()=>Nu.parse({})),capabilities:$u.default(()=>$u.parse({})),credential:Ef.default(()=>Ef.parse({})),enabled:C().default(!1),available:C().default(!1),defaultModel:r().trim().min(1).max(300).nullable().default(null),modelIds:h(r().trim().min(1).max(300)).max(1e3).default([]),lastError:r().nullable().default(null)}),Mf=c({version:_(1).default(1),providers:ve(r(),gC).default({}),statuses:ve(r(),SC).default({}),modelCaches:ve(r(),hC).default({}),updatedAt:r().nullable().default(null)}),sn=c({providerId:Vo,modelId:r().trim().min(1).max(300)});c({providers:ve(r(),bC).optional()});c({source:v(["local_secret","env"]).default("local_secret"),value:r().min(1).max(2e4).optional(),envVar:r().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:v(["local_secret","env","chatgpt_subscription"]).optional()});c({modelId:r().trim().min(1).max(300).optional(),baseUrl:r().trim().min(1).max(2048).optional()});c({query:r().trim().max(200).optional(),refresh:C().default(!1),limit:u().int().positive().max(500).default(100)});c({query:r().trim().max(200).optional(),force:C().default(!1)});const xC=["coding","research","review","test","docs","planner","summarizer"];v(xC);const Gr=r().trim().min(1).max(80).regex(/^[a-z][a-z0-9_-]*$/),Xb=v(["none","worktree","copy_on_write"]),Qb=v(["read_only","workspace_write","full_tools"]),ev=v(["disabled","parent_scoped"]),Fl=v(["manual","balanced","proactive"]),kC=v(["queued","running","completed","failed","cancelled","needs_resume"]),tv=["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"];v(tv);const wC=[{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"}],Em=c({id:Gr,enabled:C().default(!0),modelRef:sn.nullable().default(null),isolationMode:Xb.default("none"),maxConcurrentRuns:u().int().min(1).max(16).default(1),toolPolicy:Qb.default("read_only"),background:C().default(!0),peerMessages:ev.default("parent_scoped")}),es=c({enabled:C().default(!0),workspaceDefaultsVersion:_(1).default(1),toolDefaultsVersion:_(1).default(1),delegationMode:Fl.default("manual"),defaultModelRef:sn.nullable().default(null),roles:h(Em).max(64).default(()=>ov()),maxConcurrentRuns:u().int().min(1).max(32).default(4),maxConcurrentRunsPerProvider:u().int().min(1).max(32).nullable().default(2),maxConcurrentRunsPerWorkspaceTarget:u().int().min(1).max(32).nullable().default(1)}).transform(e=>({...e,roles:OC(e.roles)})),Zi=c({kind:v(["session","turn","file","diff","artifact"]),id:r().trim().min(1).max(500),label:r().trim().min(1).max(500)}),_C=c({kind:v(["retain_with_parent"]).default("retain_with_parent"),messageRetentionDays:u().int().min(1).max(3650).nullable().default(null),artifactRetentionDays:u().int().min(1).max(3650).nullable().default(null),cleanupAfterExpiry:C().default(!1)}).default(()=>({kind:"retain_with_parent",messageRetentionDays:null,artifactRetentionDays:null,cleanupAfterExpiry:!1})),IC=v(["orient","edit","validate","report"]),CC=c({command:r().trim().min(1).max(2e3),status:v(["passed","failed","unknown"]).default("unknown"),exitCode:u().int().nullable().default(null),outputSummary:r().trim().max(5e3).nullable().default(null),startedAt:r().nullable().default(null),completedAt:r().nullable().default(null)}),RC=c({phase:IC.default("orient"),inspectedFiles:h(r().trim().min(1).max(1e3)).max(500).default([]),inspectedResources:h(r().trim().min(1).max(1e3)).max(500).default([]),repeatedSearches:h(r().trim().min(1).max(1e3)).max(200).default([]),repeatedReads:h(r().trim().min(1).max(1e3)).max(200).default([]),repeatedCommands:h(r().trim().min(1).max(1e3)).max(200).default([]),changedFiles:h(r().trim().min(1).max(1e3)).max(500).default([]),patchRefs:h(Zi).max(100).default([]),validationAttempts:h(CC).max(100).default([]),latestMeaningfulActivity:r().trim().max(5e3).nullable().default(null),currentBlocker:r().trim().max(5e3).nullable().default(null),updatedAt:r().nullable().default(null)}).default(()=>({phase:"orient",inspectedFiles:[],inspectedResources:[],repeatedSearches:[],repeatedReads:[],repeatedCommands:[],changedFiles:[],patchRefs:[],validationAttempts:[],latestMeaningfulActivity:null,currentBlocker:null,updatedAt:null})),AC=c({summary:r().trim().max(2e4).default(""),findings:h(r().trim().min(1).max(5e3)).max(200).default([]),artifacts:h(Zi).max(200).default([]),patchRef:Zi.nullable().default(null),diffRef:Zi.nullable().default(null),testsRun:h(r().trim().min(1).max(2e3)).max(100).default([]),blockers:h(r().trim().min(1).max(5e3)).max(100).default([]),confidence:v(["low","medium","high"]).nullable().default(null),followUpNeeded:C().default(!1)}),nv=c({id:r().trim().min(1).max(200),parentSessionId:r().trim().min(1).max(200),parentTurnId:r().trim().min(1).max(200).nullable().default(null),childSessionId:r().trim().min(1).max(200).nullable().default(null),roleId:Gr,objective:r().trim().min(1).max(5e4),modelRef:sn.nullable().default(null),isolationMode:Xb.default("none"),toolPolicy:Qb.default("read_only"),background:C().default(!0),peerMessages:ev.default("parent_scoped"),status:kC.default("queued"),progress:RC,evidenceRetention:_C,createdAt:r(),startedAt:r().nullable().default(null),completedAt:r().nullable().default(null),updatedAt:r().nullable().default(null),error:r().nullable().default(null),report:AC.nullable().default(null),metadata:ve(r(),Re()).optional().default({})}),av=v(["cleanup","archive","cleanup_and_archive"]);c({action:av,reason:r().trim().min(1).max(2e3).nullable().default(null)});c({action:av,run:nv,workspaceCleanup:ve(r(),Re()).nullable().default(null),sessionArchive:ve(r(),Re()).nullable().default(null),nextStep:r()});const PC=v(["question","answer","handoff","artifact","status","blocker"]),TC=v(["normal","interrupt"]),EC=c({status:v(["pending","delivered","undelivered"]).default("pending"),deliveredRunIds:h(r().trim().min(1).max(200)).max(200).default([]),acknowledgedRunIds:h(r().trim().min(1).max(200)).max(200).default([]),deliveredParentSessionId:r().trim().min(1).max(200).nullable().default(null),acknowledgedParentSessionId:r().trim().min(1).max(200).nullable().default(null),wakeRequestedParentSessionId:r().trim().min(1).max(200).nullable().default(null),wakeQueuedParentSessionId:r().trim().min(1).max(200).nullable().default(null),wakeDeferredParentSessionId:r().trim().min(1).max(200).nullable().default(null),wakeParentReason:r().trim().min(1).max(1e3).nullable().default(null),wakeRequestedRunIds:h(r().trim().min(1).max(200)).max(200).default([]),wakeInterruptedRunIds:h(r().trim().min(1).max(200)).max(200).default([]),wakeDeferredRunIds:h(r().trim().min(1).max(200)).max(200).default([]),reason:r().trim().min(1).max(1e3).nullable().default(null)}),MC=c({id:r().trim().min(1).max(200),fromRunId:r().trim().min(1).max(200),toRunId:r().trim().min(1).max(200).nullable().default(null),toRole:Gr.nullable().default(null),kind:PC,priority:TC.optional(),body:r().trim().min(1).max(5e4),refs:h(Zi).max(100).default([]),delivery:EC.optional(),createdAt:r()});function ov(){return wC.map(e=>Em.parse({id:e.id,toolPolicy:e.defaultToolPolicy}))}function jC(){return es.parse({})}function OC(e){const t=ov(),n=new Map(t.map(o=>[o.id,o])),a=[];for(const o of e??[]){const i=Em.parse(o);n.has(i.id)?n.set(i.id,i):a.push(i)}return[...t.map(o=>n.get(o.id)??o),...a]}const NC=v(["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",...tv,"diagnostic"]),jf=c({id:r(),sequence:u().int().positive().optional(),sessionId:r().optional(),turnId:r().optional(),name:NC,timestamp:r(),source:v(["ui_button","chat_action","terminal_command","hook","provider","server"]).optional(),action:r().optional(),appId:r().nullable().optional(),args:ve(r(),Re()).optional(),status:v(["started","completed","failed","pending"]).optional(),output:r().optional(),error:r().optional(),relatedDeploymentId:r().optional(),data:Re().optional()}),$C=c({id:r().trim().min(1).max(80),label:r().trim().min(1).max(160),description:r().trim().max(500).nullable().optional().default(null)}),DC=c({id:r().trim().min(1),sessionId:r().trim().min(1),turnId:r().trim().min(1),toolCallId:r().trim().min(1),question:r().trim().min(1).max(2e3),reason:r().trim().max(1e3).nullable().optional().default(null),options:h($C).max(5).default([]),allowFreeform:C().default(!0),status:v(["pending","answered","dismissed"]),answer:c({optionId:r().trim().min(1).nullable(),text:r().max(4e3)}).nullable(),createdAt:r(),answeredAt:r().nullable()}),LC=c({questionId:r().trim().min(1),action:v(["answer","dismiss"]),optionId:r().trim().min(1).nullable().optional().default(null),text:r().trim().max(4e3).optional().default("")});c({kind:v(["session","project","draft"]),id:r().trim().min(1).max(300)});v(["unknown","idle","running","success","failed"]);v(["none","idle","running","success","failed","unknown"]);function zC(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var hn={},el={},Ja={},Of;function ps(){if(Of)return Ja;Of=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 o(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 Ja.isNothing=e,Ja.isObject=t,Ja.toArray=n,Ja.repeat=o,Ja.isNegativeZero=i,Ja.extend=a,Ja}var kd,Nf;function fs(){if(Nf)return kd;Nf=1;function e(n,a){let o="";const i=n.reason||"(unknown reason)";return n.mark?(n.mark.name&&(o+='in "'+n.mark.name+'" '),o+="("+(n.mark.line+1)+":"+(n.mark.column+1)+")",!a&&n.mark.snippet&&(o+=`
66
-
67
- `+n.mark.snippet),i+" "+o):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)},kd=t,kd}var wd,$f;function UC(){if($f)return wd;$f=1;const e=ps();function t(o,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+o.slice(i,s).replace(/\t/g,"→")+f,pos:l-i+m.length}}function n(o,i){return e.repeat(" ",i-o.length)+o}function a(o,i){if(i=Object.create(i||null),!o.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(o.buffer);)p.push(m.index),l.push(m.index+m[0].length),o.position<=m.index&&f<0&&(f=l.length-2);f<0&&(f=l.length-1);let S="";const y=Math.min(o.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 $=t(o.buffer,l[f-A],p[f-A],o.position-(l[f]-l[f-A]),k);S=e.repeat(" ",i.indent)+n((o.line-A+1).toString(),y)+" | "+$.str+`
68
- `+S}const R=t(o.buffer,l[f],p[f],o.position,k);S+=e.repeat(" ",i.indent)+n((o.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 $=t(o.buffer,l[f+A],p[f+A],o.position-(l[f]-l[f+A]),k);S+=e.repeat(" ",i.indent)+n((o.line+A+1).toString(),y)+" | "+$.str+`
71
- `}return S.replace(/\n$/,"")}return wd=a,wd}var _d,Df;function Tn(){if(Df)return _d;Df=1;const e=fs(),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 o(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 _d=o,_d}var Id,Lf;function rv(){if(Lf)return Id;Lf=1;const e=fs(),t=Tn();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 o(i){return this.extend(i)}return o.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(o.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},Id=o,Id}var Cd,zf;function iv(){if(zf)return Cd;zf=1;const e=Tn();return Cd=new e("tag:yaml.org,2002:str",{kind:"scalar",construct:function(t){return t!==null?t:""}}),Cd}var Rd,Uf;function sv(){if(Uf)return Rd;Uf=1;const e=Tn();return Rd=new e("tag:yaml.org,2002:seq",{kind:"sequence",construct:function(t){return t!==null?t:[]}}),Rd}var Ad,Hf;function lv(){if(Hf)return Ad;Hf=1;const e=Tn();return Ad=new e("tag:yaml.org,2002:map",{kind:"mapping",construct:function(t){return t!==null?t:{}}}),Ad}var Pd,qf;function cv(){if(qf)return Pd;qf=1;const e=rv();return Pd=new e({explicit:[iv(),sv(),lv()]}),Pd}var Td,Bf;function dv(){if(Bf)return Td;Bf=1;const e=Tn();function t(o){if(o===null)return!0;const i=o.length;return i===1&&o==="~"||i===4&&(o==="null"||o==="Null"||o==="NULL")}function n(){return null}function a(o){return o===null}return Td=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"}),Td}var Ed,Ff;function uv(){if(Ff)return Ed;Ff=1;const e=Tn();function t(o){if(o===null)return!1;const i=o.length;return i===4&&(o==="true"||o==="True"||o==="TRUE")||i===5&&(o==="false"||o==="False"||o==="FALSE")}function n(o){return o==="true"||o==="True"||o==="TRUE"}function a(o){return Object.prototype.toString.call(o)==="[object Boolean]"}return Ed=new e("tag:yaml.org,2002:bool",{kind:"scalar",resolve:t,construct:n,predicate:a,represent:{lowercase:function(o){return o?"true":"false"},uppercase:function(o){return o?"TRUE":"FALSE"},camelcase:function(o){return o?"True":"False"}},defaultStyle:"lowercase"}),Ed}var Md,Vf;function mv(){if(Vf)return Md;Vf=1;const e=ps(),t=Tn();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 o(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(!o(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 Md=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"]}}),Md}var jd,Wf;function pv(){if(Wf)return jd;Wf=1;const e=ps(),t=Tn(),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 o(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 jd=new t("tag:yaml.org,2002:float",{kind:"scalar",resolve:o,construct:i,predicate:p,represent:l,defaultStyle:"lowercase"}),jd}var Od,Kf;function fv(){return Kf||(Kf=1,Od=cv().extend({implicit:[dv(),uv(),mv(),pv()]})),Od}var Nd,Gf;function hv(){return Gf||(Gf=1,Nd=fv()),Nd}var $d,Zf;function gv(){if(Zf)return $d;Zf=1;const e=Tn(),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 o(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],D=+(m[11]||0);p=(z*60+D)*6e4,m[9]==="-"&&(p=-p)}const $=new Date(Date.UTC(f,S,y,k,R,A,l));return p&&$.setTime($.getTime()-p),$}function i(s){return s.toISOString()}return $d=new e("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:a,construct:o,instanceOf:Date,represent:i}),$d}var Dd,Jf;function bv(){if(Jf)return Dd;Jf=1;const e=Tn();function t(n){return n==="<<"||n===null}return Dd=new e("tag:yaml.org,2002:merge",{kind:"scalar",resolve:t}),Dd}var Ld,Yf;function vv(){if(Yf)return Ld;Yf=1;const e=Tn(),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 o(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 Ld=new e("tag:yaml.org,2002:binary",{kind:"scalar",resolve:n,construct:a,predicate:i,represent:o}),Ld}var zd,Xf;function yv(){if(Xf)return zd;Xf=1;const e=Tn(),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 o(i){return i!==null?i:[]}return zd=new e("tag:yaml.org,2002:omap",{kind:"sequence",resolve:a,construct:o}),zd}var Ud,Qf;function Sv(){if(Qf)return Ud;Qf=1;const e=Tn(),t=Object.prototype.toString;function n(o){if(o===null)return!0;const i=o,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(o){if(o===null)return[];const i=o,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 Ud=new e("tag:yaml.org,2002:pairs",{kind:"sequence",resolve:n,construct:a}),Ud}var Hd,eh;function xv(){if(eh)return Hd;eh=1;const e=Tn(),t=Object.prototype.hasOwnProperty;function n(o){if(o===null)return!0;const i=o;for(const s in i)if(t.call(i,s)&&i[s]!==null)return!1;return!0}function a(o){return o!==null?o:{}}return Hd=new e("tag:yaml.org,2002:set",{kind:"mapping",resolve:n,construct:a}),Hd}var qd,th;function Mm(){return th||(th=1,qd=hv().extend({implicit:[gv(),bv()],explicit:[vv(),yv(),Sv(),xv()]})),qd}var nh;function HC(){if(nh)return el;nh=1;const e=ps(),t=fs(),n=UC(),a=Mm(),o=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-]+!)$/,$=/^(?:!|[^,\[\]{}])(?:%[0-9a-f]{2}|[0-9a-z\-#;/?:@&=+$,_.!~*'()\[\]])*$/i;function z(d){return Object.prototype.toString.call(d)}function D(d){return d===10||d===13}function x(d){return d===9||d===32}function I(d){return d===9||d===32||d===10||d===13}function P(d){return d===44||d===91||d===93||d===123||d===125}function O(d){if(d>=48&&d<=57)return d-48;const M=d|32;return M>=97&&M<=102?M-97+10:-1}function T(d){return d===120?2:d===117?4:d===85?8:0}function F(d){return d>=48&&d<=57?d-48:-1}function H(d){switch(d){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 L(d){return d<=65535?String.fromCharCode(d):String.fromCharCode((d-65536>>10)+55296,(d-65536&1023)+56320)}function V(d,M,q){M==="__proto__"?Object.defineProperty(d,M,{configurable:!0,enumerable:!0,writable:!0,value:q}):d[M]=q}const Y=new Array(256),ie=new Array(256);for(let d=0;d<256;d++)Y[d]=H(d)?1:0,ie[d]=H(d);function _e(d,M){this.input=d,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=d.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 fe(d,M){const q={name:d.filename,buffer:d.input.slice(0,-1),position:d.position,line:d.line,column:d.position-d.lineStart};return q.snippet=n(q),new t(M,q)}function J(d,M){throw fe(d,M)}function Me(d,M){d.onWarning&&d.onWarning.call(null,fe(d,M))}function Se(d,M,q){const le=d.anchorMapTransactions;if(le.length!==0){const N=le[le.length-1];o.call(N,M)||(N[M]={existed:o.call(d.anchorMap,M),value:d.anchorMap[M]})}d.anchorMap[M]=q}function ae(d){d.anchorMapTransactions.push(Object.create(null))}function xe(d){const M=d.anchorMapTransactions.pop(),q=d.anchorMapTransactions;if(q.length===0)return;const le=q[q.length-1],N=Object.keys(M);for(let K=0,w=N.length;K<w;K+=1){const j=N[K];o.call(le,j)||(le[j]=M[j])}}function ee(d){const M=d.anchorMapTransactions.pop(),q=Object.keys(M);for(let le=q.length-1;le>=0;le-=1){const N=M[q[le]];N.existed?d.anchorMap[q[le]]=N.value:delete d.anchorMap[q[le]]}}function ue(d){return{position:d.position,line:d.line,lineStart:d.lineStart,lineIndent:d.lineIndent,firstTabInLine:d.firstTabInLine,tag:d.tag,anchor:d.anchor,kind:d.kind,result:d.result}}function ye(d,M){d.position=M.position,d.line=M.line,d.lineStart=M.lineStart,d.lineIndent=M.lineIndent,d.firstTabInLine=M.firstTabInLine,d.tag=M.tag,d.anchor=M.anchor,d.kind=M.kind,d.result=M.result}const We={YAML:function(M,q,le){M.version!==null&&J(M,"duplication of %YAML directive"),le.length!==1&&J(M,"YAML directive accepts exactly one argument");const N=/^([0-9]+)\.([0-9]+)$/.exec(le[0]);N===null&&J(M,"ill-formed argument of the YAML directive");const K=parseInt(N[1],10),w=parseInt(N[2],10);K!==1&&J(M,"unacceptable YAML version of the document"),M.version=le[0],M.checkLineBreaks=w<2,w!==1&&w!==2&&Me(M,"unsupported YAML version of the document")},TAG:function(M,q,le){let N;le.length!==2&&J(M,"TAG directive accepts exactly two arguments");const K=le[0];N=le[1],A.test(K)||J(M,"ill-formed tag handle (first argument) of the TAG directive"),o.call(M.tagMap,K)&&J(M,'there is a previously declared suffix for "'+K+'" tag handle'),$.test(N)||J(M,"ill-formed tag prefix (second argument) of the TAG directive");try{N=decodeURIComponent(N)}catch{J(M,"tag prefix is malformed: "+N)}M.tagMap[K]=N}};function Pe(d,M,q,le){if(M<q){const N=d.input.slice(M,q);if(le)for(let K=0,w=N.length;K<w;K+=1){const j=N.charCodeAt(K);j===9||j>=32&&j<=1114111||J(d,"expected valid JSON character")}else y.test(N)&&J(d,"the stream contains non-printable characters");d.result+=N}}function re(d,M,q,le){e.isObject(q)||J(d,"cannot merge mappings; the provided source object is unacceptable");const N=Object.keys(q);for(let K=0,w=N.length;K<w;K+=1){const j=N[K];d.maxTotalMergeKeys!==-1&&++d.totalMergeKeys>d.maxTotalMergeKeys&&J(d,"merge keys exceeded maxTotalMergeKeys ("+d.maxTotalMergeKeys+")"),o.call(M,j)||(V(M,j,q[j]),le[j]=!0)}}function Ce(d,M,q,le,N,K,w,j,oe){if(Array.isArray(N)){N=Array.prototype.slice.call(N);for(let X=0,Q=N.length;X<Q;X+=1)Array.isArray(N[X])&&J(d,"nested arrays are not supported inside keys"),typeof N=="object"&&z(N[X])==="[object Object]"&&(N[X]="[object Object]")}if(typeof N=="object"&&z(N)==="[object Object]"&&(N="[object Object]"),N=String(N),M===null&&(M={}),le==="tag:yaml.org,2002:merge")if(Array.isArray(K))for(let X=0,Q=K.length;X<Q;X+=1)re(d,M,K[X],q);else re(d,M,K,q);else!d.json&&!o.call(q,N)&&o.call(M,N)&&(d.line=w||d.line,d.lineStart=j||d.lineStart,d.position=oe||d.position,J(d,"duplicated mapping key")),V(M,N,K),delete q[N];return M}function De(d){const M=d.input.charCodeAt(d.position);M===10?d.position++:M===13?(d.position++,d.input.charCodeAt(d.position)===10&&d.position++):J(d,"a line break is expected"),d.line+=1,d.lineStart=d.position,d.firstTabInLine=-1}function Je(d,M,q){let le=0,N=d.input.charCodeAt(d.position);for(;N!==0;){for(;x(N);)N===9&&d.firstTabInLine===-1&&(d.firstTabInLine=d.position),N=d.input.charCodeAt(++d.position);if(M&&N===35)do N=d.input.charCodeAt(++d.position);while(N!==10&&N!==13&&N!==0);if(D(N))for(De(d),N=d.input.charCodeAt(d.position),le++,d.lineIndent=0;N===32;)d.lineIndent++,N=d.input.charCodeAt(++d.position);else break}return q!==-1&&le!==0&&d.lineIndent<q&&Me(d,"deficient indentation"),le}function et(d){let M=d.position,q=d.input.charCodeAt(M);return!!((q===45||q===46)&&q===d.input.charCodeAt(M+1)&&q===d.input.charCodeAt(M+2)&&(M+=3,q=d.input.charCodeAt(M),q===0||I(q)))}function rt(d,M){M===1?d.result+=" ":M>1&&(d.result+=e.repeat(`
74
- `,M-1))}function Be(d,M,q){let le,N,K,w,j,oe;const X=d.kind,Q=d.result;let pe=d.input.charCodeAt(d.position);if(I(pe)||P(pe)||pe===35||pe===38||pe===42||pe===33||pe===124||pe===62||pe===39||pe===34||pe===37||pe===64||pe===96)return!1;if(pe===63||pe===45){const de=d.input.charCodeAt(d.position+1);if(I(de)||q&&P(de))return!1}for(d.kind="scalar",d.result="",le=N=d.position,K=!1;pe!==0;){if(pe===58){const de=d.input.charCodeAt(d.position+1);if(I(de)||q&&P(de))break}else if(pe===35){const de=d.input.charCodeAt(d.position-1);if(I(de))break}else{if(d.position===d.lineStart&&et(d)||q&&P(pe))break;if(D(pe))if(w=d.line,j=d.lineStart,oe=d.lineIndent,Je(d,!1,-1),d.lineIndent>=M){K=!0,pe=d.input.charCodeAt(d.position);continue}else{d.position=N,d.line=w,d.lineStart=j,d.lineIndent=oe;break}}K&&(Pe(d,le,N,!1),rt(d,d.line-w),le=N=d.position,K=!1),x(pe)||(N=d.position+1),pe=d.input.charCodeAt(++d.position)}return Pe(d,le,N,!1),d.result?!0:(d.kind=X,d.result=Q,!1)}function He(d,M){let q,le,N=d.input.charCodeAt(d.position);if(N!==39)return!1;for(d.kind="scalar",d.result="",d.position++,q=le=d.position;(N=d.input.charCodeAt(d.position))!==0;)if(N===39)if(Pe(d,q,d.position,!0),N=d.input.charCodeAt(++d.position),N===39)q=d.position,d.position++,le=d.position;else return!0;else D(N)?(Pe(d,q,le,!0),rt(d,Je(d,!1,M)),q=le=d.position):d.position===d.lineStart&&et(d)?J(d,"unexpected end of the document within a single quoted scalar"):(d.position++,x(N)||(le=d.position));J(d,"unexpected end of the stream within a single quoted scalar")}function $e(d,M){let q,le,N,K=d.input.charCodeAt(d.position);if(K!==34)return!1;for(d.kind="scalar",d.result="",d.position++,q=le=d.position;(K=d.input.charCodeAt(d.position))!==0;){if(K===34)return Pe(d,q,d.position,!0),d.position++,!0;if(K===92){if(Pe(d,q,d.position,!0),K=d.input.charCodeAt(++d.position),D(K))Je(d,!1,M);else if(K<256&&Y[K])d.result+=ie[K],d.position++;else if((N=T(K))>0){let w=N,j=0;for(;w>0;w--)K=d.input.charCodeAt(++d.position),(N=O(K))>=0?j=(j<<4)+N:J(d,"expected hexadecimal character");d.result+=L(j),d.position++}else J(d,"unknown escape sequence");q=le=d.position}else D(K)?(Pe(d,q,le,!0),rt(d,Je(d,!1,M)),q=le=d.position):d.position===d.lineStart&&et(d)?J(d,"unexpected end of the document within a double quoted scalar"):(d.position++,x(K)||(le=d.position))}J(d,"unexpected end of the stream within a double quoted scalar")}function E(d,M){let q=!0,le,N,K;const w=d.tag;let j;const oe=d.anchor;let X,Q,pe,de;const ze=Object.create(null);let Te,Ne,Ye,Le=d.input.charCodeAt(d.position);if(Le===91)X=93,de=!1,j=[];else if(Le===123)X=125,de=!0,j={};else return!1;for(d.anchor!==null&&Se(d,d.anchor,j),Le=d.input.charCodeAt(++d.position);Le!==0;){if(Je(d,!0,M),Le=d.input.charCodeAt(d.position),Le===X)return d.position++,d.tag=w,d.anchor=oe,d.kind=de?"mapping":"sequence",d.result=j,!0;if(q?Le===44&&J(d,"expected the node content, but found ','"):J(d,"missed comma between flow collection entries"),Ne=Te=Ye=null,Q=pe=!1,Le===63){const ut=d.input.charCodeAt(d.position+1);I(ut)&&(Q=pe=!0,d.position++,Je(d,!0,M))}le=d.line,N=d.lineStart,K=d.position,qe(d,M,i,!1,!0),Ne=d.tag,Te=d.result,Je(d,!0,M),Le=d.input.charCodeAt(d.position),(pe||d.line===le)&&Le===58&&(Q=!0,Le=d.input.charCodeAt(++d.position),Je(d,!0,M),qe(d,M,i,!1,!0),Ye=d.result),de?Ce(d,j,ze,Ne,Te,Ye,le,N,K):Q?j.push(Ce(d,null,ze,Ne,Te,Ye,le,N,K)):j.push(Te),Je(d,!0,M),Le=d.input.charCodeAt(d.position),Le===44?(q=!0,Le=d.input.charCodeAt(++d.position)):q=!1}J(d,"unexpected end of the stream within a flow collection")}function U(d,M){let q,le=m,N=!1,K=!1,w=M,j=0,oe=!1,X,Q=d.input.charCodeAt(d.position);if(Q===124)q=!1;else if(Q===62)q=!0;else return!1;for(d.kind="scalar",d.result="";Q!==0;)if(Q=d.input.charCodeAt(++d.position),Q===43||Q===45)m===le?le=Q===43?S:f:J(d,"repeat of a chomping mode identifier");else if((X=F(Q))>=0)X===0?J(d,"bad explicit indentation width of a block scalar; it cannot be less than one"):K?J(d,"repeat of an indentation width identifier"):(w=M+X-1,K=!0);else break;if(x(Q)){do Q=d.input.charCodeAt(++d.position);while(x(Q));if(Q===35)do Q=d.input.charCodeAt(++d.position);while(!D(Q)&&Q!==0)}for(;Q!==0;){for(De(d),d.lineIndent=0,Q=d.input.charCodeAt(d.position);(!K||d.lineIndent<w)&&Q===32;)d.lineIndent++,Q=d.input.charCodeAt(++d.position);if(!K&&d.lineIndent>w&&(w=d.lineIndent),D(Q)){j++;continue}if(!K&&w===0&&J(d,"missing indentation for block scalar"),d.lineIndent<w){le===S?d.result+=e.repeat(`
75
- `,N?1+j:j):le===m&&N&&(d.result+=`
76
- `);break}q?x(Q)?(oe=!0,d.result+=e.repeat(`
77
- `,N?1+j:j)):oe?(oe=!1,d.result+=e.repeat(`
78
- `,j+1)):j===0?N&&(d.result+=" "):d.result+=e.repeat(`
79
- `,j):d.result+=e.repeat(`
80
- `,N?1+j:j),N=!0,K=!0,j=0;const pe=d.position;for(;!D(Q)&&Q!==0;)Q=d.input.charCodeAt(++d.position);Pe(d,pe,d.position,!1)}return!0}function G(d,M){const q=d.tag,le=d.anchor,N=[];let K=!1;if(d.firstTabInLine!==-1)return!1;d.anchor!==null&&Se(d,d.anchor,N);let w=d.input.charCodeAt(d.position);for(;w!==0&&(d.firstTabInLine!==-1&&(d.position=d.firstTabInLine,J(d,"tab characters must not be used in indentation")),w===45);){const j=d.input.charCodeAt(d.position+1);if(!I(j))break;if(K=!0,d.position++,Je(d,!0,-1)&&d.lineIndent<=M){N.push(null),w=d.input.charCodeAt(d.position);continue}const oe=d.line;if(qe(d,M,l,!1,!0),N.push(d.result),Je(d,!0,-1),w=d.input.charCodeAt(d.position),(d.line===oe||d.lineIndent>M)&&w!==0)J(d,"bad indentation of a sequence entry");else if(d.lineIndent<M)break}return K?(d.tag=q,d.anchor=le,d.kind="sequence",d.result=N,!0):!1}function ce(d,M,q){let le,N,K,w;const j=d.tag,oe=d.anchor,X={},Q=Object.create(null);let pe=null,de=null,ze=null,Te=!1,Ne=!1;if(d.firstTabInLine!==-1)return!1;d.anchor!==null&&Se(d,d.anchor,X);let Ye=d.input.charCodeAt(d.position);for(;Ye!==0;){!Te&&d.firstTabInLine!==-1&&(d.position=d.firstTabInLine,J(d,"tab characters must not be used in indentation"));const Le=d.input.charCodeAt(d.position+1),ut=d.line;if((Ye===63||Ye===58)&&I(Le))Ye===63?(Te&&(Ce(d,X,Q,pe,de,null,N,K,w),pe=de=ze=null),Ne=!0,Te=!0,le=!0):Te?(Te=!1,le=!0):J(d,"incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line"),d.position+=1,Ye=Le;else{if(N=d.line,K=d.lineStart,w=d.position,!qe(d,q,s,!1,!0))break;if(d.line===ut){for(Ye=d.input.charCodeAt(d.position);x(Ye);)Ye=d.input.charCodeAt(++d.position);if(Ye===58)Ye=d.input.charCodeAt(++d.position),I(Ye)||J(d,"a whitespace character is expected after the key-value separator within a block mapping"),Te&&(Ce(d,X,Q,pe,de,null,N,K,w),pe=de=ze=null),Ne=!0,Te=!1,le=!1,pe=d.tag,de=d.result;else if(Ne)J(d,"can not read an implicit mapping pair; a colon is missed");else return d.tag=j,d.anchor=oe,!0}else if(Ne)J(d,"can not read a block mapping entry; a multiline key may not be an implicit key");else return d.tag=j,d.anchor=oe,!0}if((d.line===ut||d.lineIndent>M)&&(Te&&(N=d.line,K=d.lineStart,w=d.position),qe(d,M,p,!0,le)&&(Te?de=d.result:ze=d.result),Te||(Ce(d,X,Q,pe,de,ze,N,K,w),pe=de=ze=null),Je(d,!0,-1),Ye=d.input.charCodeAt(d.position)),(d.line===ut||d.lineIndent>M)&&Ye!==0)J(d,"bad indentation of a mapping entry");else if(d.lineIndent<M)break}return Te&&Ce(d,X,Q,pe,de,null,N,K,w),Ne&&(d.tag=j,d.anchor=oe,d.kind="mapping",d.result=X),Ne}function W(d){let M=!1,q=!1,le,N,K=d.input.charCodeAt(d.position);if(K!==33)return!1;d.tag!==null&&J(d,"duplication of a tag property"),K=d.input.charCodeAt(++d.position),K===60?(M=!0,K=d.input.charCodeAt(++d.position)):K===33?(q=!0,le="!!",K=d.input.charCodeAt(++d.position)):le="!";let w=d.position;if(M){do K=d.input.charCodeAt(++d.position);while(K!==0&&K!==62);d.position<d.length?(N=d.input.slice(w,d.position),K=d.input.charCodeAt(++d.position)):J(d,"unexpected end of the stream within a verbatim tag")}else{for(;K!==0&&!I(K);)K===33&&(q?J(d,"tag suffix cannot contain exclamation marks"):(le=d.input.slice(w-1,d.position+1),A.test(le)||J(d,"named tag handle cannot contain such characters"),q=!0,w=d.position+1)),K=d.input.charCodeAt(++d.position);N=d.input.slice(w,d.position),R.test(N)&&J(d,"tag suffix cannot contain flow indicator characters")}N&&!$.test(N)&&J(d,"tag name cannot contain such characters: "+N);try{N=decodeURIComponent(N)}catch{J(d,"tag name is malformed: "+N)}return M?d.tag=N:o.call(d.tagMap,le)?d.tag=d.tagMap[le]+N:le==="!"?d.tag="!"+N:le==="!!"?d.tag="tag:yaml.org,2002:"+N:J(d,'undeclared tag handle "'+le+'"'),!0}function me(d){let M=d.input.charCodeAt(d.position);if(M!==38)return!1;d.anchor!==null&&J(d,"duplication of an anchor property"),M=d.input.charCodeAt(++d.position);const q=d.position;for(;M!==0&&!I(M)&&!P(M);)M=d.input.charCodeAt(++d.position);return d.position===q&&J(d,"name of an anchor node must contain at least one character"),d.anchor=d.input.slice(q,d.position),!0}function he(d){let M=d.input.charCodeAt(d.position);if(M!==42)return!1;M=d.input.charCodeAt(++d.position);const q=d.position;for(;M!==0&&!I(M)&&!P(M);)M=d.input.charCodeAt(++d.position);d.position===q&&J(d,"name of an alias node must contain at least one character");const le=d.input.slice(q,d.position);return o.call(d.anchorMap,le)||J(d,'unidentified alias "'+le+'"'),d.result=d.anchorMap[le],Je(d,!0,-1),!0}function Ze(d,M,q,le){const N=ue(d);return ae(d),ye(d,M),d.tag=null,d.anchor=null,d.kind=null,d.result=null,ce(d,q,le)&&d.kind==="mapping"?(xe(d),!0):(ee(d),ye(d,N),!1)}function qe(d,M,q,le,N){let K,w,j=1,oe=!1,X=!1,Q=null,pe,de,ze;d.depth>=d.maxDepth&&J(d,"nesting exceeded maxDepth ("+d.maxDepth+")"),d.depth+=1,d.listener!==null&&d.listener("open",d),d.tag=null,d.anchor=null,d.kind=null,d.result=null;const Te=K=w=p===q||l===q;if(le&&Je(d,!0,-1)&&(oe=!0,d.lineIndent>M?j=1:d.lineIndent===M?j=0:d.lineIndent<M&&(j=-1)),j===1)for(;;){const Ne=d.input.charCodeAt(d.position),Ye=ue(d);if(oe&&(Ne===33&&d.tag!==null||Ne===38&&d.anchor!==null)||!W(d)&&!me(d))break;Q===null&&(Q=Ye),Je(d,!0,-1)?(oe=!0,w=Te,d.lineIndent>M?j=1:d.lineIndent===M?j=0:d.lineIndent<M&&(j=-1)):w=!1}if(w&&(w=oe||N),j===1||p===q)if(i===q||s===q?de=M:de=M+1,ze=d.position-d.lineStart,j===1)if(w&&(G(d,ze)||ce(d,ze,de))||E(d,de))X=!0;else{const Ne=d.input.charCodeAt(d.position);Q!==null&&Te&&!w&&Ne!==124&&Ne!==62&&Ze(d,Q,Q.position-Q.lineStart,de)||K&&U(d,de)||He(d,de)||$e(d,de)?X=!0:he(d)?(X=!0,(d.tag!==null||d.anchor!==null)&&J(d,"alias node should not have any properties")):Be(d,de,i===q)&&(X=!0,d.tag===null&&(d.tag="?")),d.anchor!==null&&Se(d,d.anchor,d.result)}else j===0&&(X=w&&G(d,ze));if(d.tag===null)d.anchor!==null&&Se(d,d.anchor,d.result);else if(d.tag==="?"){d.result!==null&&d.kind!=="scalar"&&J(d,'unacceptable node kind for !<?> tag; it should be "scalar", not "'+d.kind+'"');for(let Ne=0,Ye=d.implicitTypes.length;Ne<Ye;Ne+=1)if(pe=d.implicitTypes[Ne],pe.resolve(d.result)){d.result=pe.construct(d.result),d.tag=pe.tag,d.anchor!==null&&Se(d,d.anchor,d.result);break}}else if(d.tag!=="!"){if(o.call(d.typeMap[d.kind||"fallback"],d.tag))pe=d.typeMap[d.kind||"fallback"][d.tag];else{pe=null;const Ne=d.typeMap.multi[d.kind||"fallback"];for(let Ye=0,Le=Ne.length;Ye<Le;Ye+=1)if(d.tag.slice(0,Ne[Ye].tag.length)===Ne[Ye].tag){pe=Ne[Ye];break}}pe||J(d,"unknown tag !<"+d.tag+">"),d.result!==null&&pe.kind!==d.kind&&J(d,"unacceptable node kind for !<"+d.tag+'> tag; it should be "'+pe.kind+'", not "'+d.kind+'"'),pe.resolve(d.result,d.tag)?(d.result=pe.construct(d.result,d.tag),d.anchor!==null&&Se(d,d.anchor,d.result)):J(d,"cannot resolve a node with !<"+d.tag+"> explicit tag")}return d.listener!==null&&d.listener("close",d),d.depth-=1,d.tag!==null||d.anchor!==null||X}function it(d){const M=d.position;let q=!1,le;for(d.version=null,d.checkLineBreaks=d.legacy,d.tagMap=Object.create(null),d.anchorMap=Object.create(null);(le=d.input.charCodeAt(d.position))!==0&&(Je(d,!0,-1),le=d.input.charCodeAt(d.position),!(d.lineIndent>0||le!==37));){q=!0,le=d.input.charCodeAt(++d.position);let N=d.position;for(;le!==0&&!I(le);)le=d.input.charCodeAt(++d.position);const K=d.input.slice(N,d.position),w=[];for(K.length<1&&J(d,"directive name must not be less than one character in length");le!==0;){for(;x(le);)le=d.input.charCodeAt(++d.position);if(le===35){do le=d.input.charCodeAt(++d.position);while(le!==0&&!D(le));break}if(D(le))break;for(N=d.position;le!==0&&!I(le);)le=d.input.charCodeAt(++d.position);w.push(d.input.slice(N,d.position))}le!==0&&De(d),o.call(We,K)?We[K](d,K,w):Me(d,'unknown document directive "'+K+'"')}if(Je(d,!0,-1),d.lineIndent===0&&d.input.charCodeAt(d.position)===45&&d.input.charCodeAt(d.position+1)===45&&d.input.charCodeAt(d.position+2)===45?(d.position+=3,Je(d,!0,-1)):q&&J(d,"directives end mark is expected"),qe(d,d.lineIndent-1,p,!1,!0),Je(d,!0,-1),d.checkLineBreaks&&k.test(d.input.slice(M,d.position))&&Me(d,"non-ASCII line breaks are interpreted as content"),d.documents.push(d.result),d.position===d.lineStart&&et(d)){d.input.charCodeAt(d.position)===46&&(d.position+=3,Je(d,!0,-1));return}d.position<d.length-1&&J(d,"end of the stream or a document separator is expected")}function nt(d,M){d=String(d),M=M||{},d.length!==0&&(d.charCodeAt(d.length-1)!==10&&d.charCodeAt(d.length-1)!==13&&(d+=`
81
- `),d.charCodeAt(0)===65279&&(d=d.slice(1)));const q=new _e(d,M),le=d.indexOf("\0");for(le!==-1&&(q.position=le,J(q,"null byte is not allowed in input")),q.input+="\0";q.input.charCodeAt(q.position)===32;)q.lineIndent+=1,q.position+=1;for(;q.position<q.length-1;)it(q);return q.documents}function we(d,M,q){M!==null&&typeof M=="object"&&typeof q>"u"&&(q=M,M=null);const le=nt(d,q);if(typeof M!="function")return le;for(let N=0,K=le.length;N<K;N+=1)M(le[N])}function Oe(d,M){const q=nt(d,M);if(q.length!==0){if(q.length===1)return q[0];throw new t("expected a single document in the stream, but found more")}}return el.loadAll=we,el.load=Oe,el}var Bd={},ah;function qC(){if(ah)return Bd;ah=1;const e=ps(),t=fs(),n=Mm(),a=Object.prototype.toString,o=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,$=42,z=44,D=45,x=58,I=61,P=62,O=63,T=64,F=91,H=93,L=96,V=123,Y=124,ie=125,_e={};_e[0]="\\0",_e[7]="\\a",_e[8]="\\b",_e[9]="\\t",_e[10]="\\n",_e[11]="\\v",_e[12]="\\f",_e[13]="\\r",_e[27]="\\e",_e[34]='\\"',_e[92]="\\\\",_e[133]="\\N",_e[160]="\\_",_e[8232]="\\L",_e[8233]="\\P";const fe=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"],J=/^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;function Me(w,j){if(j===null)return{};const oe={},X=Object.keys(j);for(let Q=0,pe=X.length;Q<pe;Q+=1){let de=X[Q],ze=String(j[de]);de.slice(0,2)==="!!"&&(de="tag:yaml.org,2002:"+de.slice(2));const Te=w.compiledTypeMap.fallback[de];Te&&o.call(Te.styleAliases,ze)&&(ze=Te.styleAliases[ze]),oe[de]=ze}return oe}function Se(w){let j,oe;const X=w.toString(16).toUpperCase();if(w<=255)j="x",oe=2;else if(w<=65535)j="u",oe=4;else if(w<=4294967295)j="U",oe=8;else throw new t("code point within a string may not be greater than 0xFFFFFFFF");return"\\"+j+e.repeat("0",oe-X.length)+X}const ae=1,xe=2;function ee(w){this.schema=w.schema||n,this.indent=Math.max(1,w.indent||2),this.noArrayIndent=w.noArrayIndent||!1,this.skipInvalid=w.skipInvalid||!1,this.flowLevel=e.isNothing(w.flowLevel)?-1:w.flowLevel,this.styleMap=Me(this.schema,w.styles||null),this.sortKeys=w.sortKeys||!1,this.lineWidth=w.lineWidth||80,this.noRefs=w.noRefs||!1,this.noCompatMode=w.noCompatMode||!1,this.condenseFlow=w.condenseFlow||!1,this.quotingType=w.quotingType==='"'?xe:ae,this.forceQuotes=w.forceQuotes||!1,this.replacer=typeof w.replacer=="function"?w.replacer:null,this.implicitTypes=this.schema.compiledImplicit,this.explicitTypes=this.schema.compiledExplicit,this.tag=null,this.result="",this.duplicates=[],this.usedDuplicates=null}function ue(w,j){const oe=e.repeat(" ",j);let X=0,Q="";const pe=w.length;for(;X<pe;){let de;const ze=w.indexOf(`
82
- `,X);ze===-1?(de=w.slice(X),X=pe):(de=w.slice(X,ze+1),X=ze+1),de.length&&de!==`
83
- `&&(Q+=oe),Q+=de}return Q}function ye(w,j){return`
84
- `+e.repeat(" ",w.indent*j)}function We(w,j){for(let oe=0,X=w.implicitTypes.length;oe<X;oe+=1)if(w.implicitTypes[oe].resolve(j))return!0;return!1}function Pe(w){return w===m||w===s}function re(w){return w>=32&&w<=126||w>=161&&w<=55295&&w!==8232&&w!==8233||w>=57344&&w<=65533&&w!==i||w>=65536&&w<=1114111}function Ce(w){return re(w)&&w!==i&&w!==p&&w!==l}function De(w,j,oe){const X=Ce(w),Q=X&&!Pe(w);return(oe?X:X&&w!==z&&w!==F&&w!==H&&w!==V&&w!==ie)&&w!==y&&!(j===x&&!Q)||Ce(j)&&!Pe(j)&&w===y||j===x&&Q}function Je(w){return re(w)&&w!==i&&!Pe(w)&&w!==D&&w!==O&&w!==x&&w!==z&&w!==F&&w!==H&&w!==V&&w!==ie&&w!==y&&w!==R&&w!==$&&w!==f&&w!==Y&&w!==I&&w!==P&&w!==A&&w!==S&&w!==k&&w!==T&&w!==L}function et(w){return!Pe(w)&&w!==x}function rt(w,j){const oe=w.charCodeAt(j);let X;return oe>=55296&&oe<=56319&&j+1<w.length&&(X=w.charCodeAt(j+1),X>=56320&&X<=57343)?(oe-55296)*1024+X-56320+65536:oe}function Be(w){return/^\n* /.test(w)}const He=1,$e=2,E=3,U=4,G=5;function ce(w,j,oe,X,Q,pe,de,ze){let Te,Ne=0,Ye=null,Le=!1,ut=!1;const Vt=X!==-1;let dn=-1,un=Je(rt(w,0))&&et(rt(w,w.length-1));if(j||de)for(Te=0;Te<w.length;Ne>=65536?Te+=2:Te++){if(Ne=rt(w,Te),!re(Ne))return G;un=un&&De(Ne,Ye,ze),Ye=Ne}else{for(Te=0;Te<w.length;Ne>=65536?Te+=2:Te++){if(Ne=rt(w,Te),Ne===l)Le=!0,Vt&&(ut=ut||Te-dn-1>X&&w[dn+1]!==" ",dn=Te);else if(!re(Ne))return G;un=un&&De(Ne,Ye,ze),Ye=Ne}ut=ut||Vt&&Te-dn-1>X&&w[dn+1]!==" "}return!Le&&!ut?un&&!de&&!Q(w)?He:pe===xe?G:$e:oe>9&&Be(w)?G:de?pe===xe?G:$e:ut?U:E}function W(w,j,oe,X,Q){w.dump=(function(){if(j.length===0)return w.quotingType===xe?'""':"''";if(!w.noCompatMode&&(fe.indexOf(j)!==-1||J.test(j)))return w.quotingType===xe?'"'+j+'"':"'"+j+"'";const pe=w.indent*Math.max(1,oe),de=w.lineWidth===-1?-1:Math.max(Math.min(w.lineWidth,40),w.lineWidth-pe),ze=X||w.flowLevel>-1&&oe>=w.flowLevel;function Te(Ne){return We(w,Ne)}switch(ce(j,ze,w.indent,de,Te,w.quotingType,w.forceQuotes&&!X,Q)){case He:return j;case $e:return"'"+j.replace(/'/g,"''")+"'";case E:return"|"+me(j,w.indent)+he(ue(j,pe));case U:return">"+me(j,w.indent)+he(ue(Ze(j,de),pe));case G:return'"'+it(j)+'"';default:throw new t("impossible error: invalid scalar style")}})()}function me(w,j){const oe=Be(w)?String(j):"",X=w[w.length-1]===`
85
- `,pe=X&&(w[w.length-2]===`
86
- `||w===`
87
- `)?"+":X?"":"-";return oe+pe+`
88
- `}function he(w){return w[w.length-1]===`
89
- `?w.slice(0,-1):w}function Ze(w,j){const oe=/(\n+)([^\n]*)/g;let X=(function(){let ze=w.indexOf(`
90
- `);return ze=ze!==-1?ze:w.length,oe.lastIndex=ze,qe(w.slice(0,ze),j)})(),Q=w[0]===`
91
- `||w[0]===" ",pe,de;for(;de=oe.exec(w);){const ze=de[1],Te=de[2];pe=Te[0]===" ",X+=ze+(!Q&&!pe&&Te!==""?`
92
- `:"")+qe(Te,j),Q=pe}return X}function qe(w,j){if(w===""||w[0]===" ")return w;const oe=/ [^ ]/g;let X,Q=0,pe,de=0,ze=0,Te="";for(;X=oe.exec(w);)ze=X.index,ze-Q>j&&(pe=de>Q?de:ze,Te+=`
93
- `+w.slice(Q,pe),Q=pe+1),de=ze;return Te+=`
94
- `,w.length-Q>j&&de>Q?Te+=w.slice(Q,de)+`
95
- `+w.slice(de+1):Te+=w.slice(Q),Te.slice(1)}function it(w){let j="",oe=0;for(let X=0;X<w.length;oe>=65536?X+=2:X++){oe=rt(w,X);const Q=_e[oe];!Q&&re(oe)?(j+=w[X],oe>=65536&&(j+=w[X+1])):j+=Q||Se(oe)}return j}function nt(w,j,oe){let X="";const Q=w.tag;for(let pe=0,de=oe.length;pe<de;pe+=1){let ze=oe[pe];w.replacer&&(ze=w.replacer.call(oe,String(pe),ze)),(q(w,j,ze,!1,!1)||typeof ze>"u"&&q(w,j,null,!1,!1))&&(X!==""&&(X+=","+(w.condenseFlow?"":" ")),X+=w.dump)}w.tag=Q,w.dump="["+X+"]"}function we(w,j,oe,X){let Q="";const pe=w.tag;for(let de=0,ze=oe.length;de<ze;de+=1){let Te=oe[de];w.replacer&&(Te=w.replacer.call(oe,String(de),Te)),(q(w,j+1,Te,!0,!0,!1,!0)||typeof Te>"u"&&q(w,j+1,null,!0,!0,!1,!0))&&((!X||Q!=="")&&(Q+=ye(w,j)),w.dump&&l===w.dump.charCodeAt(0)?Q+="-":Q+="- ",Q+=w.dump)}w.tag=pe,w.dump=Q||"[]"}function Oe(w,j,oe){let X="";const Q=w.tag,pe=Object.keys(oe);for(let de=0,ze=pe.length;de<ze;de+=1){let Te="";X!==""&&(Te+=", "),w.condenseFlow&&(Te+='"');const Ne=pe[de];let Ye=oe[Ne];w.replacer&&(Ye=w.replacer.call(oe,Ne,Ye)),q(w,j,Ne,!1,!1)&&(w.dump.length>1024&&(Te+="? "),Te+=w.dump+(w.condenseFlow?'"':"")+":"+(w.condenseFlow?"":" "),q(w,j,Ye,!1,!1)&&(Te+=w.dump,X+=Te))}w.tag=Q,w.dump="{"+X+"}"}function d(w,j,oe,X){let Q="";const pe=w.tag,de=Object.keys(oe);if(w.sortKeys===!0)de.sort();else if(typeof w.sortKeys=="function")de.sort(w.sortKeys);else if(w.sortKeys)throw new t("sortKeys must be a boolean or a function");for(let ze=0,Te=de.length;ze<Te;ze+=1){let Ne="";(!X||Q!=="")&&(Ne+=ye(w,j));const Ye=de[ze];let Le=oe[Ye];if(w.replacer&&(Le=w.replacer.call(oe,Ye,Le)),!q(w,j+1,Ye,!0,!0,!0))continue;const ut=w.tag!==null&&w.tag!=="?"||w.dump&&w.dump.length>1024;ut&&(w.dump&&l===w.dump.charCodeAt(0)?Ne+="?":Ne+="? "),Ne+=w.dump,ut&&(Ne+=ye(w,j)),q(w,j+1,Le,!0,ut)&&(w.dump&&l===w.dump.charCodeAt(0)?Ne+=":":Ne+=": ",Ne+=w.dump,Q+=Ne)}w.tag=pe,w.dump=Q||"{}"}function M(w,j,oe){const X=oe?w.explicitTypes:w.implicitTypes;for(let Q=0,pe=X.length;Q<pe;Q+=1){const de=X[Q];if((de.instanceOf||de.predicate)&&(!de.instanceOf||typeof j=="object"&&j instanceof de.instanceOf)&&(!de.predicate||de.predicate(j))){if(oe?de.multi&&de.representName?w.tag=de.representName(j):w.tag=de.tag:w.tag="?",de.represent){const ze=w.styleMap[de.tag]||de.defaultStyle;let Te;if(a.call(de.represent)==="[object Function]")Te=de.represent(j,ze);else if(o.call(de.represent,ze))Te=de.represent[ze](j,ze);else throw new t("!<"+de.tag+'> tag resolver accepts not "'+ze+'" style');w.dump=Te}return!0}}return!1}function q(w,j,oe,X,Q,pe,de){w.tag=null,w.dump=oe,M(w,oe,!1)||M(w,oe,!0);const ze=a.call(w.dump),Te=X;X&&(X=w.flowLevel<0||w.flowLevel>j);const Ne=ze==="[object Object]"||ze==="[object Array]";let Ye,Le;if(Ne&&(Ye=w.duplicates.indexOf(oe),Le=Ye!==-1),(w.tag!==null&&w.tag!=="?"||Le||w.indent!==2&&j>0)&&(Q=!1),Le&&w.usedDuplicates[Ye])w.dump="*ref_"+Ye;else{if(Ne&&Le&&!w.usedDuplicates[Ye]&&(w.usedDuplicates[Ye]=!0),ze==="[object Object]")X&&Object.keys(w.dump).length!==0?(d(w,j,w.dump,Q),Le&&(w.dump="&ref_"+Ye+w.dump)):(Oe(w,j,w.dump),Le&&(w.dump="&ref_"+Ye+" "+w.dump));else if(ze==="[object Array]")X&&w.dump.length!==0?(w.noArrayIndent&&!de&&j>0?we(w,j-1,w.dump,Q):we(w,j,w.dump,Q),Le&&(w.dump="&ref_"+Ye+w.dump)):(nt(w,j,w.dump),Le&&(w.dump="&ref_"+Ye+" "+w.dump));else if(ze==="[object String]")w.tag!=="?"&&W(w,w.dump,j,pe,Te);else{if(ze==="[object Undefined]")return!1;if(w.skipInvalid)return!1;throw new t("unacceptable kind of an object to dump "+ze)}if(w.tag!==null&&w.tag!=="?"){let ut=encodeURI(w.tag[0]==="!"?w.tag.slice(1):w.tag).replace(/!/g,"%21");w.tag[0]==="!"?ut="!"+ut:ut.slice(0,18)==="tag:yaml.org,2002:"?ut="!!"+ut.slice(18):ut="!<"+ut+">",w.dump=ut+" "+w.dump}}return!0}function le(w,j){const oe=[],X=[];N(w,oe,X);const Q=X.length;for(let pe=0;pe<Q;pe+=1)j.duplicates.push(oe[X[pe]]);j.usedDuplicates=new Array(Q)}function N(w,j,oe){if(w!==null&&typeof w=="object"){const X=j.indexOf(w);if(X!==-1)oe.indexOf(X)===-1&&oe.push(X);else if(j.push(w),Array.isArray(w))for(let Q=0,pe=w.length;Q<pe;Q+=1)N(w[Q],j,oe);else{const Q=Object.keys(w);for(let pe=0,de=Q.length;pe<de;pe+=1)N(w[Q[pe]],j,oe)}}}function K(w,j){j=j||{};const oe=new ee(j);oe.noRefs||le(w,oe);let X=w;return oe.replacer&&(X=oe.replacer.call({"":X},"",X)),q(oe,0,X,!0,!0)?oe.dump+`
96
- `:""}return Bd.dump=K,Bd}var oh;function BC(){if(oh)return hn;oh=1;const e=HC(),t=qC();function n(a,o){return function(){throw new Error("Function yaml."+a+" is removed in js-yaml 4. Use yaml."+o+" instead, which is now safe by default.")}}return hn.Type=Tn(),hn.Schema=rv(),hn.FAILSAFE_SCHEMA=cv(),hn.JSON_SCHEMA=fv(),hn.CORE_SCHEMA=hv(),hn.DEFAULT_SCHEMA=Mm(),hn.load=e.load,hn.loadAll=e.loadAll,hn.dump=t.dump,hn.YAMLException=fs(),hn.types={binary:vv(),float:pv(),map:lv(),null:dv(),pairs:Sv(),set:xv(),timestamp:gv(),bool:uv(),int:mv(),merge:bv(),omap:yv(),seq:sv(),str:iv()},hn.safeLoad=n("safeLoad","load"),hn.safeLoadAll=n("safeLoadAll","loadAll"),hn.safeDump=n("safeDump","dump"),hn}var FC=BC();const VC=zC(FC),{Type:W6,Schema:K6,FAILSAFE_SCHEMA:G6,JSON_SCHEMA:Z6,CORE_SCHEMA:J6,DEFAULT_SCHEMA:Y6,load:X6,loadAll:Q6,dump:e3,YAMLException:t3,types:n3,safeLoad:a3,safeLoadAll:o3,safeDump:r3}=VC,jm=3e3,Om=9999,i3="openpond.yaml",WC=["google","github","x"],Nm=new Set([22,2222,2375,2376,3108,5900,5901,6080,7818]),rh=h(r().trim().min(1).max(1e3)).max(50),ts=r().trim().min(1).max(4096).refine(Iv,{message:"path must be a relative workspace path"}),KC=r().trim().min(1).max(500).refine(e=>!e.includes("\0")&&!/\s/.test(e),"image ref must be a single OCI reference"),GC=r().trim().regex(/^sha256:[0-9a-f]{64}$/i),kv=r().trim().min(1).max(500).refine(e=>e.startsWith("/")&&!e.includes("\0"),"workspaceRoot must be an absolute guest path"),ZC=c({ref:KC,digest:GC.optional(),registrySecretRef:r().trim().min(1).max(500).optional(),platform:_("linux/amd64").optional(),workspaceRoot:kv.optional()}).strict(),JC=c({context:ts.default("."),path:ts.default("Dockerfile"),target:r().trim().min(1).max(191).optional(),buildArgs:ve(r().max(191),r().max(500)).optional(),registrySecretRefs:h(r().trim().min(1).max(500)).max(10).optional(),platform:_("linux/amd64").optional(),workspaceRoot:kv.optional()}).strict(),YC=c({base:r().trim().min(1).max(120).optional(),snapshot:r().trim().min(1).max(191).optional(),image:ZC.optional(),dockerfile:JC.optional()}).strict().superRefine((e,t)=>{[e.base,e.snapshot,e.image,e.dockerfile].filter(Boolean).length!==1&&t.addIssue({code:An.custom,message:"runtime must declare exactly one of base, snapshot, image, or dockerfile"})}),wv=c({cpu:u().positive().max(8).optional(),memoryGb:u().positive().max(32).optional(),diskGb:u().positive().max(100).optional()}).strict(),XC=c({provider:v(WC),scopes:h(r().trim().min(1).max(200)).max(100).default([]),capabilities:h(r().trim().min(1).max(200)).max(100).default([])}).strict(),QC=c({models:h(r().trim().min(1).max(200)).max(100).default([]),scopes:h(r().trim().min(1).max(200)).max(100).default([])}).strict(),eR=c({opchat:QC.optional()}).catchall(ve(r(),Re())).default({}),tR=c({name:r().trim().regex(/^[A-Za-z_][A-Za-z0-9_-]*$/).max(63).optional(),mountPath:r().trim().min(1).max(256).optional(),storageGb:u().int().positive().max(100).optional(),deleteOnSandboxDelete:C().optional()}).strict(),nR=c({port:u().int().min(jm).max(Om).refine(e=>!Nm.has(e),{message:"preview port is reserved"}),protocol:_("http").default("http"),label:r().trim().min(1).max(80).optional(),access:v(["private","public"]).default("private"),path:r().trim().min(1).max(512).refine(e=>e.startsWith("/"),{message:"preview path must start with /"}).default("/")}).strict(),_v=c({command:r().trim().min(1).max(1e3),cwd:ts.optional(),timeoutSeconds:u().int().positive().max(86400).optional(),requiresStart:C().default(!1),ports:h(nR).max(20).default([]),artifactPaths:h(ts).max(100).default([])}).strict(),ih=_v.extend({name:r().trim().min(1).max(80)}).strict(),aR=c({name:r().trim().min(1).max(80).optional(),service:r().trim().min(1).max(80).optional(),port:u().int().min(jm).max(Om).refine(e=>!Nm.has(e),{message:"app MCP port is reserved"}),path:r().trim().min(1).max(512).refine(e=>e.startsWith("/"),{message:"app MCP path must start with /"}).default("/mcp")}).strict(),oR=c({name:r().trim().min(1).max(80).optional(),port:u().int().min(jm).max(Om).refine(e=>!Nm.has(e),{message:"validation probe port is reserved"}),path:r().trim().min(1).max(512).refine(e=>e.startsWith("/"),{message:"validation probe path must start with /"}).default("/"),expectedStatus:u().int().min(100).max(599).default(200)}).strict(),rR=ve(r(),Re()).refine(e=>e.type==="object","input schema must be a JSON schema object"),iR=c({name:r().trim().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).max(191),required:C().default(!1),secret:C().default(!0),description:r().trim().max(500).optional()}).strict(),Fd=r().trim().min(1).max(120),sR=c({name:r().trim().min(1).max(120),description:r().trim().max(500).optional(),cron:r().trim().min(1).max(500).optional(),rate:r().trim().min(1).max(500).optional(),once:Fd.optional(),scheduleType:v(["rate","cron","once"]).optional(),scheduleExpression:r().trim().min(1).max(500).optional(),timezone:r().trim().min(1).max(100).optional(),enabled:C().default(!0),startAt:Fd.optional(),endAt:Fd.optional(),maxRuns:u().int().positive().nullable().optional(),runtimePolicy:v(["run_and_stop","run_and_archive","run_and_delete","use_existing_running"]).default("run_and_stop"),action:r().trim().min(1).max(120).optional(),actionName:r().trim().min(1).max(120).optional(),command:r().trim().min(1).max(2e3).optional(),target:c({kind:v(["start","action","service","command"]).optional(),name:r().trim().min(1).max(120).optional(),actionName:r().trim().min(1).max(120).optional(),command:r().trim().min(1).max(2e3).optional(),requiresStart:C().optional()}).strict().optional(),requiresStart:C().optional(),budget:c({maxUsd:r().trim().min(1).max(40).optional()}).strict().optional(),resources:wv.optional(),quotas:ve(r(),Re()).optional(),lifecycle:ve(r(),Re()).optional(),retentionPolicy:ve(r(),Re()).optional(),env:h(c({name:r().trim().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).max(191),value:r().optional(),secretRef:r().optional()}).strict()).max(100).optional(),integrationLeases:h(ve(r(),Re())).max(20).optional(),metadata:ve(r(),Re()).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:An.custom,path:["scheduleExpression"],message:"schedule must declare exactly one of cron, rate, once, or scheduleExpression"}),e.scheduleExpression&&!e.scheduleType&&t.addIssue({code:An.custom,path:["scheduleType"],message:"scheduleType is required with scheduleExpression"});const a=e.command??e.target?.command??null,o=e.target?.name??null,i=e.actionName??e.action??e.target?.actionName??(e.target?.kind==="action"?o:null),s=e.target?.kind??(a?"command":"action");s==="action"&&!i&&t.addIssue({code:An.custom,path:["action"],message:"schedule action target is required"}),s==="service"&&!o&&t.addIssue({code:An.custom,path:["target","name"],message:"schedule service target name is required"}),s==="command"&&!a&&t.addIssue({code:An.custom,path:["command"],message:"schedule command target is required"})}),lR=c({schemaVersion:_(1),name:r().trim().min(1).max(80).regex(/^[a-z0-9][a-z0-9-]*[a-z0-9]$/),version:r().trim().min(1).max(40),useCase:r().trim().min(1).max(80),description:r().trim().min(1).max(500),runtime:YC,resources:wv.optional(),setup:c({commands:rh.default([])}).strict().default({commands:[]}),validation:c({commands:rh.min(1),probes:h(oR).max(20).default([])}).strict(),start:_v,actions:h(ih).max(20).default([]),services:h(ih).max(20).default([]),schedules:h(sR).max(20).default([]),mcp:c({endpoints:h(aR).max(10).default([])}).strict().default({endpoints:[]}),volumes:h(tR).max(5).default([]),integrations:c({requiredLeases:h(XC).max(20).default([])}).strict().default({requiredLeases:[]}),permissions:eR,inputs:c({schema:rR.default({type:"object"}),env:h(iR).max(100).default([])}).strict().default({schema:{type:"object"},env:[]}),artifacts:c({paths:h(ts).max(100).default([])}).strict().default({paths:[]}),network:c({egress:v(["restricted","allow","block"]).default("restricted")}).strict().default({egress:"restricted"})}).strict().superRefine((e,t)=>{dR(e,t),$m(t,e.volumes.flatMap(n=>n.name?[n.name]:[]),"volume names must be unique","volumes"),uR(e,t),mR(e,t),pR(e,t),fR(e,t)}),cR=c({path:r(),message:r(),code:r()});function s3(e){return[{kind:"start",name:"start",...e.start,artifactPaths:Wd(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:Wd(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:Wd(t,e)}))]}function Iv(e){return!e.includes("\0")&&!e.startsWith("/")&&!e.split(/[\\/]+/).some(t=>t===".."||t==="")}function $m(e,t,n,a){const o=new Set;for(const i of t){if(o.has(i)){e.addIssue({code:An.custom,path:[a],message:n});return}o.add(i)}}function dR(e,t){const n=["start",...e.actions.map(a=>a.name),...e.services.map(a=>a.name)];$m(t,n,"start, action, and service names must be unique","actions")}function uR(e,t){const n=Vd(e.inputs.schema.properties),a=new Set(e.volumes.map(o=>o.name).filter(o=>!!o));for(const[o,i]of Object.entries(n)){const s=Vd(i),l=Vd(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(!Iv(m)){t.addIssue({code:An.custom,path:["inputs","schema","properties",o,"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:An.custom,path:["inputs","schema","properties",o,"x-openpond-upload","targetPath"],message:"upload target references an undeclared volume"})}}function mR(e,t){$m(t,e.inputs.env.map(n=>n.name),"env input names must be unique","inputs")}function pR(e,t){const n=new Map(e.services.map(o=>[o.name,new Set(o.ports.map(i=>i.port))])),a=new Set([...e.start.ports.map(o=>o.port),...e.services.flatMap(o=>o.ports.map(i=>i.port))]);for(const[o,i]of e.mcp.endpoints.entries()){if(i.service){const s=n.get(i.service);if(!s){t.addIssue({code:An.custom,path:["mcp","endpoints",o,"service"],message:`app MCP service does not exist: ${i.service}`});continue}s.has(i.port)||t.addIssue({code:An.custom,path:["mcp","endpoints",o,"port"],message:`app MCP port ${i.port} is not declared on service ${i.service}`});continue}a.has(i.port)||t.addIssue({code:An.custom,path:["mcp","endpoints",o,"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(o=>o.name)),a=new Set(e.services.map(o=>o.name));for(const[o,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:An.custom,path:["schedules",o,"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:An.custom,path:["schedules",o,"target","name"],message:`schedule service target does not exist: ${p}`})}}}function Vd(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Wd(e,t){return e.artifactPaths.length>0?e.artifactPaths:t.artifacts.paths}const hR=c({id:r(),name:r(),description:r().nullable(),scheduleType:r(),scheduleExpression:r(),enabled:C(),rawEnabled:C().optional(),syncStatus:r().nullable(),syncError:r().nullable().optional(),startAt:r().nullable(),endAt:r().nullable(),maxRuns:u().nullable(),executionCount:u().nullable(),lifecycleStatus:r().nullable(),lifecycleReason:r().nullable(),lastExecutionAt:r().nullable().optional(),lastExecutionStatus:r().nullable().optional(),lastRunNowAt:r().nullable().optional(),lastRunNowStatus:r().nullable().optional(),updatedAt:r(),deploymentId:r(),isProduction:C().optional(),payload:Re().optional()}).passthrough(),gR=c({total:u().int().nonnegative(),active:u().int().nonnegative(),paused:u().int().nonnegative(),enabled:u().int().nonnegative().optional(),disabled:u().int().nonnegative().optional(),nextRunAt:r().nullable().optional(),lastRunAt:r().nullable().optional(),schedules:h(hR).optional().default([]),truncated:C().optional()}).passthrough(),Kd=c({name:r(),kind:v(["start","action","service"]),command:r(),cwd:r().nullable(),timeoutSeconds:u().nullable(),requiresStart:C(),ports:h(c({port:u(),protocol:r(),label:r().nullable(),access:r(),path:r()}).passthrough()).default([]),artifactPaths:h(r()).default([])}).passthrough(),bR=c({schemaVersion:_(1),source:_("openpond.yaml"),manifestName:r(),manifestVersion:r(),manifestUseCase:r(),manifestDescription:r(),manifestPath:r(),manifestHash:r(),inputSchema:ve(r(),Re()).default({}),env:h(c({name:r(),required:C(),secret:C(),description:r().nullable()}).passthrough()).default([]),start:Kd,actions:h(Kd).default([]),services:h(Kd).default([]),defaultActionName:r().nullable(),updatedAt:r()}).passthrough(),vR=c({id:r(),name:r(),description:r().nullable(),visibility:r().nullable().optional(),gitOwner:r().nullable().optional(),gitRepo:r().nullable().optional(),gitHost:r().nullable().optional(),defaultBranch:r().nullable().optional(),sandbox:C().optional().default(!1),sandboxActionRegistry:bR.nullable().optional(),sandboxManifestHash:r().nullable().optional(),sandboxManifestPath:r().nullable().optional(),sandboxManifestSyncedAt:r().nullable().optional(),sandboxManifestError:r().nullable().optional(),updatedAt:r().nullable().optional(),latestDeployment:c({id:r().optional(),status:r().optional(),deploymentDomain:r().nullable().optional(),createdAt:r().optional(),isProduction:C().nullable().optional(),gitBranch:r().nullable().optional()}).nullable().optional(),scheduleSummary:gR.nullable().optional()}),yR=c({detected:C(),rootPath:r(),manifestPath:r(),manifestHash:r().nullable().optional().default(null),manifest:ve(r(),Re()).nullable().optional().default(null),normalizedManifest:lR.nullable().optional().default(null),valid:C().optional().default(!1),diagnostics:h(cR).optional().default([])}),SR=c({appId:r(),appName:r(),gitOwner:r().nullable(),gitRepo:r().nullable(),gitHost:r().nullable(),defaultBranch:r().nullable(),linkedAt:r()}),Cv=c({teamId:r(),projectId:r(),projectSlug:r().nullable().optional().default(null),projectName:r().nullable().optional().default(null),sourceRepoUrl:r().nullable().optional().default(null),defaultBranch:r().nullable().optional().default(null),lastUploadedCommit:r().nullable().optional().default(null),lastUploadTransport:v(["git_head","snapshot","api_source_upload"]).nullable().optional().default(null),manifestPath:r().nullable().optional().default(null),manifestHash:r().nullable().optional().default(null),syncedAt:r().nullable().optional().default(null),linkedAt:r()}),xR=v(["github_repo","internal_repo","template","manual"]),kR=c({id:r(),teamId:r(),name:r(),slug:r().nullable().optional().default(null),sourceType:xR.optional().default("manual"),sourceLabel:r().nullable().optional().default(null),defaultBranch:r().nullable().optional().default(null),internalRepoPath:r().nullable().optional().default(null),manifestPath:r().nullable().optional().default(null),manifestHash:r().nullable().optional().default(null),syncedAt:r().nullable().optional().default(null),organizationName:r().nullable().optional().default(null),organizationSlug:r().nullable().optional().default(null),createdAt:r().nullable().optional().default(null),updatedAt:r().nullable().optional().default(null)}),wR=c({id:r(),name:r(),path:r(),workspacePath:r(),repoPath:r().nullable(),source:v(["folder","git"]),hiddenFromDefaultSidebar:C().optional(),sandboxTemplate:yR.nullable().optional().default(null),linkedOpenPondApp:SR.nullable().optional().default(null),linkedSandboxProject:Cv.nullable().optional().default(null),preferredSandboxAgentId:r().nullable().optional().default(null),createdAt:r(),updatedAt:r()});c({path:r().trim().min(1).optional(),name:r().trim().min(1).max(120).optional(),createNew:C().optional(),baseDirectory:r().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:Cv.nullable().optional(),preferredSandboxAgentId:r().nullable().optional(),hiddenFromDefaultSidebar:C().optional()});const _R=["connected_app_search","connected_app_read","connected_app_write"],Gd="https://openpond.ai",Dm=["slack","google","github","turnkey","x","microsoft_teams","mcp"],Lm={slack:[Nt("slack.channel.bind","Bind channels","Bind Slack channels or threads to OpenPond profiles.","setup",!1),Nt("slack.message.ingest","Ingest messages","Ingest Slack channel or thread activity into OpenPond context.","setup",!1)],microsoft_teams:[Nt("microsoft_teams.channel.bind","Bind channels","Bind Teams channels or chats to OpenPond profiles.","setup",!1),Nt("microsoft_teams.message.ingest","Ingest messages","Ingest Teams channel or chat activity into OpenPond context.","setup",!1)],google:[Nt("google.drive.file.read","Read Drive files","Find and read Google Drive files.","read",!0),Nt("google.drive.file.write","Write Drive files","Create or update approved Google Drive files.","write",!0),Nt("google.docs.read","Read Docs","Read Google Docs content and structure.","read",!0),Nt("google.docs.write","Edit Docs","Apply approved Google Docs edits.","write",!0),Nt("google.comments.read","Read comments","Read Google file comments.","read",!0),Nt("google.comments.write","Write comments","Create or resolve approved Google comments.","write",!0)],github:[Nt("github.repo.read","Read repositories","Read repository metadata and file context.","read",!0),Nt("github.issue.read","Read issues","Read GitHub issues and comments.","read",!0),Nt("github.issue.write","Update issues","Create or update approved GitHub issue content.","write",!0),Nt("github.pull_request.read","Read pull requests","Read pull request metadata, diffs, checks, and reviews.","read",!0),Nt("github.pull_request.write","Update pull requests","Create approved comments or pull request updates.","write",!0)],turnkey:[Nt("turnkey.wallets.read","Read Agent Wallet","Read the connected OpenPond Agent Wallet address and metadata.","read",!0),Nt("turnkey.balances.read","Read wallet balances","Read balances for the connected OpenPond Agent Wallet.","read",!0),Nt("turnkey.activities.read","Read wallet activity","Read recent Turnkey activity for the connected OpenPond Agent Wallet.","read",!0)],x:[Nt("x.profile.read","Read profile","Read the connected X profile.","read",!0),Nt("x.search.read","Search X","Search public X posts when granted.","read",!0),Nt("x.mentions.read","Read mentions","Read mentions for the connected X account.","read",!0),Nt("x.post.write","Post","Create approved X posts.","write",!0),Nt("x.reply.write","Reply","Create approved X replies.","write",!0)],mcp:[Nt("mcp.tool.discover","Discover tools","Discover team-scoped MCP tools.","tooling",!1),Nt("mcp.tool.call","Call tools","Call approved MCP tools through the team endpoint.","tooling",!1)]},zm={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:[]},IR={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
- `)},l3=Dm.map(e=>{const t=Av(e),n=IR[e];return{...t,provider:e,body:n,sourceHash:`connected-app-skill:${e}:${VR(n)}`,charCount:n.length}});function CR(e){const t=Um(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=UR(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",o=new Set(t.capabilities.filter(l=>l.access===a&&l.leaseable).map(l=>l.id)),i=e.capabilityIds.filter(l=>!o.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=AR(e);return s.ok?{ok:!0,request:e}:s}function RR(e){const t=Wl(e);return t?zm[t]:[]}function AR(e){const t=MR(e.args),n=RR(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 o=e.capabilityIds.filter(s=>!a.capabilityIds.includes(s));if(o.length>0)return{ok:!1,error:`Connected app operation ${a.id} does not allow capability ${o[0]}.`};const i=OR(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 PR=[{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"}],Vl=PR,TR=Dm.map(e=>{const t=Vl.filter(a=>a.providerFamily===e),n=t[0];return{id:e,label:Ji(e),shortLabel:n.shortLabel,category:n.category,icon:n.icon,description:n.description,setupSurfaces:t,capabilities:Lm[e],skills:LR(e),tools:zR(e),operations:zm[e],leasePolicy:HR(e)}});function Rv(e){const t=ER(e);return t?Vl.find(n=>n.id===t)??null:null}function Um(e){const t=Wl(e);return t?TR.find(n=>n.id===t)??null:null}function c3(e){const t=Rv(e.appId),n=$R(e.baseUrl),a=t?.kind==="mcp"?"/sandboxes/mcp":"/sandboxes/apps",o=new URL(a,n);t?.kind!=="mcp"&&o.searchParams.set("app",t?.deepLinkAppId??e.appId);const i=e.teamId?.trim();return i&&o.searchParams.set("teamId",i),o.toString()}function ER(e){const t=e?.trim().toLowerCase().replace(/[-\s]+/g,"_");return t?t==="teams"||t==="microsoft"?"microsoft_teams":Vl.some(n=>n.id===t)?t:null:null}function Wl(e){const t=e?.trim().toLowerCase().replace(/[-\s]+/g,"_");return t?t==="teams"||t==="microsoft"?"microsoft_teams":Dm.includes(t)?t:Rv(t)?.providerFamily??null:null}function Zd(e={}){const t=qR(e.connections??[]);return Vl.map(n=>{const a=Um(n.providerFamily),o=n.statusSource==="integration_connection"?t.filter(l=>l.provider===n.providerFamily):[],i=o.some(l=>l.status==="active"),s=BR(n,i);return{...n,providerLabel:a.label,setupSurfaceLabel:DR(n.setupSurface),status:s,statusLabel:FR(n,s,o),connections:o,connected:i,capabilities:sh(n,a.capabilities),capabilityLabels:sh(n,a.capabilities).map(l=>l.label),leasePolicy:a.leasePolicy}})}function Nt(e,t,n,a,o){return{id:e,label:t,description:n,access:a,leaseable:o}}function Et(e,t,n,a,o,i){return{id:e,operation:t,label:n,description:a,capabilityIds:o,...i?{input:i}:{},requiresReadback:t==="write",requiresRuntimeLease:!1}}function MR(e){return jR(e.operation)}function jR(e){return typeof e=="string"&&e.trim()?e.trim():null}function OR(e,t){return t==="write"?NR(e.input)?e.input:{}:e}function NR(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function $R(e){const t=e?.trim();if(!t)return Gd;try{const n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?Gd:(n.pathname="/",n.search="",n.hash="",n.toString())}catch{return Gd}}function Ji(e){return e==="microsoft_teams"?"Microsoft Teams":e==="mcp"?"OpenPond MCP":e==="x"?"X":e[0].toUpperCase()+e.slice(1)}function DR(e){return e==="native_bot"?"Native app":e==="oauth_connector"?"OAuth connector":e==="wallet_connector"?"Wallet connector":"MCP endpoint"}function LR(e){return[Av(e)]}function Av(e){return{name:`${e}-connected-app`,description:`Use ${Ji(e)} safely through connected app tools.`,path:`integration_skills/${e}.md`}}function zR(e){if(e==="mcp")return[];const t=Lm[e],n=zm[e],a=t.filter(s=>s.access==="read").map(s=>s.id),o=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 ${Ji(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 ${Ji(e)} object through a server-owned connected app connector.`,capabilityIds:a,write:!1}),o.length>0&&n.some(s=>s.operation==="write")&&i.push({name:"connected_app_write",description:`Perform an explicitly approved ${Ji(e)} write through a server-owned connected app connector.`,capabilityIds:o,write:!0}),i}function UR(e){return e==="search"?"connected_app_search":e==="read"?"connected_app_read":"connected_app_write"}function HR(e){const t=Lm[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 sh(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 qR(e){return e.flatMap(t=>{const n=Wl(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 BR(e,t){return e.statusSource==="integration_connection"?t?"connected":"disconnected":"setup_available"}function FR(e,t,n){if(t==="connected"){const a=n.filter(o=>o.status==="active").length;return a>1?`${a} connected`:"Connected"}return t==="disconnected"?"Not connected":e.statusSource==="native_binding"?"Bot setup":"Configure"}function VR(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 WR=v(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),KR=v(["search","read","write"]),GR=v(_R);c({provider:WR,operation:KR,toolName:GR,sessionId:r().trim().min(1).max(200),turnId:r().trim().min(1).max(200),toolCallId:r().trim().min(1).max(300),userPrompt:r().max(2e5),connectionIds:h(r().trim().min(1).max(300)).min(1).max(8),capabilityIds:h(r().trim().min(1).max(200)).min(1).max(64),args:ve(r(),Re()).default({})}).strict().superRefine((e,t)=>{const n=CR(e);n.ok||t.addIssue({code:An.custom,message:n.error})});c({ok:C(),output:r().nullable().optional(),data:Re().optional()}).strict();const ZR="local_path:";function Pv(e){return`${ZR}${e.trim()}`}c({appId:r(),source:v(["openpond","github","local_git","local_folder","unknown"]),workspacePath:r(),repoPath:r(),initialized:C(),remoteUrl:r().nullable(),expectedRemoteUrl:r().nullable(),currentBranch:r().nullable(),headCommit:r().nullable().optional().default(null),upstreamBranch:r().nullable().optional().default(null),ahead:u().int().nonnegative().optional().default(0),behind:u().int().nonnegative().optional().default(0),diverged:C().optional().default(!1),linkedSourceHeadCommit:r().nullable().optional().default(null),aheadOfLinkedSource:u().int().nonnegative().optional().default(0),behindLinkedSource:u().int().nonnegative().optional().default(0),divergedFromLinkedSource:C().optional().default(!1),linkedSourceComparisonError:r().nullable().optional().default(null),lastFetchAt:r().nullable().optional().default(null),defaultBranch:r().nullable(),branches:h(r()),dirty:C(),changedFilesCount:u(),untrackedFilesCount:u(),error:r().nullable(),updatedAt:r()});const JR=c({path:r(),status:r(),additions:u(),deletions:u(),patch:r(),content:r().nullable().optional().default(null)}),YR=c({appId:r(),repoPath:r(),initialized:C(),dirty:C(),filesChanged:u(),additions:u(),deletions:u(),repoFiles:h(r()).optional().default([]),files:h(JR),error:r().nullable(),updatedAt:r()});c({branch:r().trim().min(1).max(160)});c({path:r().trim().min(1),content:r()});const lh=c({line:u().int().nonnegative(),character:u().int().nonnegative()}),XR=c({start:lh,end:lh}),QR=c({path:r(),range:XR,severity:v(["error","warning","info","hint"]),message:r(),source:r().nullable().optional().default(null),code:r().nullable().optional().default(null)}),Tv=c({id:r(),root:r(),status:v(["connected","unavailable","error"]),message:r().nullable().optional().default(null)});c({path:r().trim().min(1),content:r().optional(),waitForDiagnostics:C().optional().default(!0)});c({appId:r(),path:r(),diagnostics:h(QR),servers:h(Tv),updatedAt:r()});const eA=c({operation:v(["hover","definition","references","documentSymbol"]),path:r().trim().min(1),content:r().optional(),line:u().int().nonnegative().optional(),character:u().int().nonnegative().optional()});c({appId:r(),operation:eA.shape.operation,path:r(),results:Re(),servers:h(Tv),updatedAt:r()});const tA=c({pinned:C().optional(),archived:C().optional(),order:u().optional()}),nA=ve(r(),tA),Ev=v(["local","sandbox"]),aA=v(["pinned","saved_for_later"]),Mv=c({id:r().min(1),workspaceKind:Ev,workspaceId:r().min(1),workspaceName:r().min(1),path:r().min(1),status:aA,order:u().int().nonnegative().nullable().default(null),sourceSessionId:r().min(1).nullable().default(null),available:C().default(!0),createdAt:r().min(1),updatedAt:r().min(1)});c({items:h(Mv)});c({workspaceKind:Ev,workspaceId:r().trim().min(1),workspaceName:r().trim().min(1),path:r().trim().min(1),status:v(["pinned","saved_for_later","none"]),order:u().int().nonnegative().nullable().optional(),sourceSessionId:r().trim().min(1).nullable().optional()});v(["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 d3(e){return["sidebar-file",e.workspaceKind,encodeURIComponent(e.workspaceId),encodeURIComponent(oA(e.path))].join(":")}const rA=c({id:r(),name:r(),type:r(),status:r(),isActive:C().nullable(),price:r().nullable(),currency:r().nullable(),credits:r().nullable()}).passthrough(),iA=c({reachable:C(),authenticated:C().nullable(),apiBase:r(),latencyMs:u(),status:u().nullable(),service:r().nullable(),checkedAt:r(),error:r().nullable()}),sA=c({id:r().nullable(),email:r().nullable(),name:r().nullable(),handle:r().nullable(),image:r().nullable(),timezone:r().nullable(),isAdmin:C().nullable(),isVerified:C().nullable(),dailyAgentAppId:r().nullable(),dailyAgentDeploymentId:r().nullable(),credits:r().nullable()}),lA=c({handle:r(),baseUrl:r().nullable().optional()}),cA=c({state:v(["signed_out","signed_in","loading","switching","auth_error"]),activeProfile:lA.nullable(),label:r(),email:r().nullable(),avatarUrl:r().nullable(),environment:r().nullable(),baseUrl:r().nullable(),apiBaseUrl:r().nullable(),chatApiBaseUrl:r().nullable().optional().default(null),creditsLabel:r().nullable(),profile:sA.nullable(),products:h(rA),apiHealth:iA.nullable(),accounts:h(c({handle:r(),baseUrl:r().nullable(),apiBaseUrl:r().nullable().optional().default(null),chatApiBaseUrl:r().nullable().optional(),environment:r().nullable(),isActive:C(),authHealth:v(["signed_out","signed_in","auth_error","unknown"]),displayLabel:r().nullable(),email:r().nullable().optional().default(null),avatarUrl:r().nullable()})),error:r().nullable()}),ch=c({asOf:r().nullable(),refreshing:C(),lastRefreshError:r().nullable(),source:v(["fresh","cache","empty"])}),dA=c({available:C(),binaryPath:r().nullable(),version:r().nullable(),authHealth:v(["unknown","signed_in","signed_out","auth_error"]),account:c({type:r(),email:r().nullable(),planType:r().nullable(),label:r().nullable()}).nullable().default(null),appServer:c({status:v(["idle","starting","ready","error"]),lastError:r().nullable()})}),Hm="gpt-5.6-sol",hs="openpond-chat",Uo="openpond",ns=hs,Kl="default",Gl="high",gs="ask",Zr=Vo,qm=v(["default","auto-review","full-access"]),bs=v(["ask","full-access","disabled"]),Zl=v(["low","medium","high","xhigh"]),vs=v(["sandbox_app","local_project","sandbox","sandbox_template"]);v(["openpond"]);const uA=v(["provider_usage","provider_tokenizer","model_family","heuristic"]),mA=c({provider:Zr,model:r().min(1),usedTokens:u().int().nonnegative(),maxContextTokens:u().int().positive(),usableContextTokens:u().int().positive(),percentFull:u().min(0).max(100),source:uA,updatedAtEventId:r().nullable()}),Lu=c({pinned:C().default(!1),projects:C().default(!1),cloudProjects:C().default(!1),chats:C().default(!1),savedForLater:C().default(!0)}),pA=v(["auto","off"]),fA=v(["typescript","python","rust"]),jv=v(["auto","disabled","custom"]),Ma=c({mode:jv.default("auto"),customCommand:r().trim().max(4096).default("")}),Il=c({languageServers:pA.default("auto"),diagnosticsWhileEditing:C().default(!0),checkOnSave:C().default(!0),languages:c({typescript:Ma.optional().default(()=>Ma.parse({})),python:Ma.optional().default(()=>Ma.parse({})),rust:Ma.optional().default(()=>Ma.parse({}))}).optional().default(()=>({typescript:Ma.parse({}),python:Ma.parse({}),rust:Ma.parse({})}))}),hA=c({language:fA,label:r(),mode:jv,status:v(["found","missing","disabled","error"]),command:r().nullable(),message:r().nullable()});c({settings:Il,languages:h(hA),updatedAt:r()});const gA=c({id:r(),root:r(),status:v(["starting","connected","unavailable","error"]),message:r().nullable().optional().default(null),openedDocuments:u().int().nonnegative(),pendingRequests:u().int().nonnegative(),lastUsedAt:r(),stderrTail:r()});c({clients:h(gA),maxClients:u().int().positive(),idleTimeoutMs:u().int().positive(),updatedAt:r()});const zu=c({autoEnabled:C().default(!0),triggerPercent:u().int().min(50).max(95).default(85),summaryModel:v(["same_model"]).default("same_model")}),Uu=c({defaultModelRef:sn.nullable().default(null),creationMode:v(["defaults","customize"]).default("customize"),autoApproveEvidence:C().default(!1)}),dh=c({defaultChatProvider:Zr.default(Uo),defaultChatModel:r().min(1).default(ns),defaultChatModelRef:sn.nullable().optional(),subagents:es.optional().default(()=>es.parse({})),codexPermissionMode:qm.default(Kl),codexReasoningEffort:Zl.default(Gl),openPondCommandAccessMode:bs.default(gs),defaultBranchPrefix:r().trim().max(48).default("feat/"),defaultNewProjectDirectory:r().trim().max(4096).default(""),defaultTeamId:r().trim().max(191).nullable().default(null),advancedWorkspaceControls:C().default(!1),contextCompaction:zu.optional().default(()=>zu.parse({})),training:Uu.optional().default(()=>Uu.parse({})),sidebarWidth:u().int().min(244).max(560).default(332),diffPanelWidth:u().int().min(320).max(2400).default(560),sidebarSectionsCollapsed:Lu.optional().default(()=>Lu.parse({})),editor:Il.optional().default(()=>Il.parse({}))}),bA="default",Ov=[{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.`}],Bm=r().trim().min(1).max(120),vA=c({id:Bm,name:r(),source:v(["built_in","custom"]).default("custom"),description:r(),content:r()}),uh=c({activeTemplateId:Bm.default(bA),customized:C().default(!1),soul:r(),soulPath:r().nullable(),updatedAt:r().nullable(),templates:h(vA).default(()=>[...Ov])}),yA=c({id:r(),host:r(),port:u(),startedAt:r(),storePath:r(),version:r(),runtimeVersion:r()}),Fm=v(["chat","work","development"]);v(["chat","models","development"]);const SA="work",Fe=r().trim().min(1).nullable(),ra=ve(r(),Re()).default({}),xA=v(["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"]),Nv=v(["/create","/edit","openpond extend","create_as_agent","suggest_workflow","local_import","lab_create","lab_improve","training"]),kA=v(["create","improve","import","promote"]),wA=v(["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"]),tl=v(["always_require_plan_approval","approval_already_granted"]);v(["local_profile","hosted_profile","promote_local_to_hosted","managed_artifact"]);const _A=fn("kind",[c({kind:_("local"),sourceAuthority:_("local_profile"),activeProfile:r().trim().min(1).nullable(),repoPath:Fe,sourcePath:Fe,localHead:Fe,confirmationPolicy:tl.default("always_require_plan_approval")}),c({kind:_("hosted"),sourceAuthority:_("hosted_profile"),teamId:Fe,projectId:Fe,activeProfile:r().trim().min(1).nullable(),sourceRef:Fe,baseSha:Fe,confirmationPolicy:tl.default("always_require_plan_approval")}),c({kind:_("promote_local_to_hosted"),sourceAuthority:_("promote_local_to_hosted"),teamId:Fe,projectId:Fe,activeProfile:r().trim().min(1).nullable(),repoPath:Fe,sourcePath:Fe,localHead:Fe,hostedHead:Fe,sourceRef:Fe,confirmationPolicy:tl.default("always_require_plan_approval")}),c({kind:_("managed_artifact"),sourceAuthority:_("managed_artifact"),activeProfile:r().trim().min(1).nullable(),confirmationPolicy:tl.default("always_require_plan_approval")})]),IA=c({id:Fe,kind:v(["user","system","automation"]).default("user"),label:Fe}),CA=c({profileId:r().trim().min(1),conversationId:Fe,originTurnId:Fe,projectId:Fe,targetProject:c({id:Fe,name:Fe,workspacePath:Fe,sourceRef:Fe,baseSha:Fe}).nullable()}),Ki=c({messageIds:h(r().trim().min(1)).default([]),conversationExcerpts:h(c({messageId:Fe,role:r().trim().min(1).nullable(),excerpt:r().trim().min(1),reason:r().trim().min(1).nullable()})).default([]),attachments:h(c({id:Fe,name:r().trim().min(1),mediaType:Fe,ref:Fe})).default([]),apps:h(c({id:r().trim().min(1),name:r().trim().min(1),connectionId:Fe,required:C().default(!1)})).default([]),tools:h(c({name:r().trim().min(1),inputSummary:Fe,outputSummary:Fe,artifactRefs:h(r().trim().min(1)).default([]),sideEffects:h(r().trim().min(1)).default([])})).default([]),signalRefs:h(r().trim().min(1)).default([]),evalRefs:h(r().trim().min(1)).default([]),targetRepoAssumptions:h(r().trim().min(1)).default([])}),yr={id:Fe,displayName:Fe},Vm=fn("kind",[c({kind:_("unselected"),...yr}),c({kind:_("agent"),...yr,defaultActionKey:Fe}),c({kind:_("skill"),...yr,skillName:Fe}),c({kind:_("extension"),...yr,slot:Fe}),c({kind:_("model"),...yr,trainingPlanId:Fe,trainingJobId:Fe,artifactId:Fe}),c({kind:_("configuration"),...yr,key:Fe})]),Hu=v(["agent","skill","extension","model","configuration"]),RA=c({schemaVersion:_("openpond.createImprove.evidenceSnapshot.v1"),id:r().trim().min(1),contentHash:r().trim().min(8),consent:c({status:v(["granted","denied","revoked"]),scope:v(["metadata_only","selected_turns","full_session","direct_intent"]),reviewedBy:Fe,reviewedAt:r().trim().min(1)}),sources:h(c({kind:v(["signal","conversation","direct_correction","manual_intent","artifact"]),id:r().trim().min(1),sourceHash:r().trim().min(8),excerptRef:Fe})).min(1),reviewerIntent:r().trim().min(1),createdAt:r().trim().min(1),metadata:ra}),$v=c({schemaVersion:_("openpond.createImprove.tasksetRef.v1"),id:r().trim().min(1),revision:u().int().positive(),contentHash:r().trim().min(8),evidenceSnapshotIds:h(r().trim().min(1)).min(1),policyBoundary:c({policyVisibleFields:h(r().trim().min(1)).default([]),privilegedFields:h(r().trim().min(1)).default([]),hiddenGraderRefs:h(r().trim().min(1)).default([]),connectedAppScopes:h(r().trim().min(1)).default([])}),targetRecommendation:c({kind:Hu,rationale:h(r().trim().min(1)).min(1),confidence:u().min(0).max(1)}),authoringSplitRefs:h(r().trim().min(1)).default([]),privateSplitRefs:h(r().trim().min(1)).default([]),approvedBy:Fe,approvedAt:r().trim().min(1),metadata:ra}),AA=c({kind:v(["npm_package","runtime_tool","setup_command","secret","integration","volume","target_project","external_service"]),name:r().trim().min(1),status:v(["declared","required","blocked","satisfied"]).default("declared"),detail:Fe,metadata:ra}),PA=c({mode:v(["chat","direct_action","chat_and_direct_actions"]),label:r().trim().min(1),detail:r().trim().min(1),defaultActionKey:Fe,directActionHint:Fe,artifactPolicy:r().trim().min(1)}),TA=c({schemaVersion:_("openpond.createImprove.plan.v1"),id:r().trim().min(1),runId:r().trim().min(1),status:v(["draft","pending_approval","approved","rejected","cancelled","superseded"]).default("pending_approval"),objective:r().trim().min(1),summary:r().trim().min(1),capturedContextSummary:r().trim().min(1),defaultChatAction:c({key:Fe,label:Fe,required:C().default(!0)}),sourcePlan:h(c({path:r().trim().min(1),operation:v(["create","update","delete","inspect"]),reason:r().trim().min(1)})).default([]),requirements:h(AA).default([]),checks:h(c({name:r().trim().min(1),command:r().trim().min(1),required:C().default(!0)})).default([]),approvalId:Fe,approvedAt:Fe,editedFromPlanId:Fe,metadata:ra,createdAt:r().trim().min(1),updatedAt:r().trim().min(1)}),EA=c({id:r().trim().min(1),label:r().trim().min(1),value:r().trim().min(1),description:Fe,metadata:ra}),MA=c({value:r().trim().min(1),label:Fe,detail:Fe,answeredAt:r().trim().min(1),metadata:ra}),jA=c({id:r().trim().min(1),kind:v(["single_choice","free_text"]).default("single_choice"),title:r().trim().min(1),prompt:r().trim().min(1),required:C().default(!0),status:v(["pending","answered","skipped"]).default("pending"),options:h(EA).default([]),answer:MA.nullable().default(null),metadata:ra}),OA=c({schemaVersion:_("openpond.createImprove.workflowCapture.v1"),id:r().trim().min(1),runId:r().trim().min(1),command:Nv,objective:r().trim().min(1),conversationExcerpts:Ki.shape.conversationExcerpts,attachments:Ki.shape.attachments,apps:Ki.shape.apps,tools:Ki.shape.tools,sideEffects:h(r().trim().min(1)).default([]),profileActions:h(r().trim().min(1)).default([]),externalProviders:h(r().trim().min(1)).default([]),environmentVariables:h(r().trim().min(1)).default([]),files:h(r().trim().min(1)).default([]),schedules:h(r().trim().min(1)).default([]),webhooks:h(r().trim().min(1)).default([]),channelTargets:h(r().trim().min(1)).default([]),outputArtifacts:h(r().trim().min(1)).default([]),targetRepoAssumptions:h(r().trim().min(1)).default([]),traceRefs:h(r().trim().min(1)).default([]),metadata:ra,createdAt:r().trim().min(1)}),Dv=c({provider:_("github"),number:u().int().positive(),url:r().url(),state:v(["open","merged","closed"]),baseBranch:r().trim().min(1),headBranch:r().trim().min(1),mergeCommit:Fe,openedAt:r().trim().min(1),updatedAt:r().trim().min(1)}),NA=c({baseBranch:r().trim().min(1),baseCommit:r().trim().min(1),branch:r().trim().min(1),headCommit:Fe,remoteName:r().trim().min(1).default("origin"),remoteUrl:Fe,worktreePath:Fe,changedPaths:h(r().trim().min(1)).default([]),diffStat:Fe,pullRequest:Dv.nullable().default(null)}),$A=c({id:r().trim().min(1),target:Vm,status:v(["draft","authored","checking","evaluated","accepted","rejected","failed"]),git:NA.nullable().default(null),parentCandidateId:Fe.default(null),tasksetRef:$v.nullable().default(null),authoringModelRef:Fe.default(null),allowedPaths:h(r().trim().min(1)).default([]),sourceRefs:h(r().trim().min(1)).default([]),artifactRefs:h(r().trim().min(1)).default([]),checkRefs:h(r().trim().min(1)).default([]),evaluationReceiptRefs:h(r().trim().min(1)).default([]),createdAt:r().trim().min(1),updatedAt:r().trim().min(1),metadata:ra}),DA=c({id:r().trim().min(1),candidateId:Fe,target:Vm,evaluatorKind:v(["agent_sdk","taskset","extension","skill","configuration","checks"]).default("checks"),subject:v(["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(r().trim().min(1)).default([]),status:v(["pending","passed","failed","blocked"]),publishGate:v(["passed","failed","not_applicable"]).default("not_applicable"),summaryCounts:c({total:u().int().nonnegative(),passed:u().int().nonnegative(),failed:u().int().nonnegative()}).nullable().default(null),evalRefs:h(r().trim().min(1)).default([]),artifactRefs:h(r().trim().min(1)).default([]),summary:Fe,createdAt:r().trim().min(1),metadata:ra}),LA=c({mode:v(["foreground","background"]).default("background"),pauseAllowed:C().default(!0),cancellationAllowed:C().default(!0)}),zA=c({mode:v(["single","bounded","until_evals_pass"]).default("single"),maximumAttempts:u().int().min(1).max(20).default(1),currentAttempt:u().int().min(0).max(20).default(0)}),UA=c({kind:v(["candidate_authoring","local_apply","hosted_turn","training_job","evaluation","pull_request","release"]),id:r().trim().min(1),status:Fe,metadata:ra}),HA=c({status:v(["not_requested","pending","released","rejected","rolled_back"]),profileCommit:Fe,profileTag:Fe,releaseReceiptRef:Fe,pullRequest:Dv.nullable().default(null),updatedAt:Fe}),ys=c({schemaVersion:_("openpond.createImprove.run.v1"),id:r().trim().min(1),revision:u().int().nonnegative(),operation:kA,surface:xA,command:Nv,objective:r().trim().min(1),state:wA,adapter:_A,actor:IA,scope:CA,context:Ki,target:Vm,evidenceSnapshots:h(RA).default([]),tasksetRef:$v.nullable().default(null),targetSelection:c({status:v(["open","recommended","confirmed"]),preselectedKind:Hu.nullable(),confirmedKind:Hu.nullable()}).nullable().default(null),plan:TA.nullable(),workflowCapture:OA.nullable(),executionPolicy:LA.default({mode:"background",pauseAllowed:!0,cancellationAllowed:!0}),iterationPolicy:zA.default({mode:"single",maximumAttempts:1,currentAttempt:0}),approvalIds:h(r().trim().min(1)).default([]),questionIds:h(r().trim().min(1)).default([]),questions:h(jA).default([]),candidates:h($A).default([]),evaluationReceipts:h(DA).default([]),checkRefs:h(r().trim().min(1)).default([]),sourceRefs:h(r().trim().min(1)).default([]),externalExecutionRefs:h(UA).default([]),localProfileCommit:Fe,hostedSourceCommit:Fe,hostedSourceRef:Fe,releaseOutcome:HA.default({status:"not_requested",profileCommit:null,profileTag:null,releaseReceiptRef:null,pullRequest:null,updatedAt:null}),blockedReason:Fe,appliedActionIds:h(r().trim().min(1)).max(200).default([]),metadata:ra,createdAt:r().trim().min(1),updatedAt:r().trim().min(1)}),ba={runId:r().trim().min(1),expectedRevision:u().int().nonnegative(),actionId:r().trim().min(1)};fn("type",[c({...ba,type:_("answer_question"),questionId:r().trim().min(1),value:r().trim().min(1)}),c({...ba,type:_("approve_plan")}),c({...ba,type:_("revise_plan"),revision:r().trim().min(1)}),c({...ba,type:_("cancel"),reason:Fe.optional().default(null)}),c({...ba,type:_("pause")}),c({...ba,type:_("resume")}),c({...ba,type:_("open_pull_request"),candidateId:r().trim().min(1)}),c({...ba,type:_("apply_candidate"),candidateId:r().trim().min(1)}),c({...ba,type:_("reject_candidate"),candidateId:r().trim().min(1),reason:Fe.optional().default(null)}),c({...ba,type:_("reconcile_pull_request"),candidateId:r().trim().min(1)})]);c({schemaVersion:_("openpond.createImprove.runList.v1"),runs:h(ys),generatedAt:r().trim().min(1)});function u3(e){const t=PA.safeParse(e?.actionShape);return t.success?t.data:null}const Wo=c({source:v(["local","github","openpond_git"]),repositoryId:r().trim().min(1),profileId:r().trim().min(1)}),qA=c({ref:Wo,revision:r().nullable(),sourceHash:r()}),BA=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),FA=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 VA(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 o=t.byteLength*8,i=new DataView(a.buffer);i.setUint32(n-8,Math.floor(o/4294967296),!1),i.setUint32(n-4,o>>>0,!1);const s=new Uint32Array(BA),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 D=l[z-15],x=l[z-2],I=va(D,7)^va(D,18)^D>>>3,P=va(x,17)^va(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],$=s[7];for(let z=0;z<64;z+=1){const D=k&R^~k&A,x=m&f^m&S^f&S,I=va(m,2)^va(m,13)^va(m,22),P=va(k,6)^va(k,11)^va(k,25),O=$+P+D+FA[z]+l[z]>>>0,T=I+x>>>0;$=A,A=R,R=k,k=y+O>>>0,y=S,S=f,f=m,m=O+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]+$>>>0}return Array.from(s,p=>p.toString(16).padStart(8,"0")).join("")}function va(e,t){return e>>>t|e<<32-t}const WA=2e3,Lv=25e7,ne=r().trim().min(1).max(240),Ie=r().regex(/^[a-f0-9]{64}$/),Qe=r().datetime({offset:!0}),It=ve(r(),Re()).default({}),se=c({id:ne,contentHash:Ie}).strict(),zn=c({id:ne,path:r().trim().min(1).max(WA).refine(GA),contentHash:Ie,sizeBytes:u().int().nonnegative().max(Lv),mediaType:r().trim().min(1).max(200),visibility:v(["policy","verifier","host_private"])}).strict(),Un=c({id:ne,contentHash:Ie,mediaType:r().trim().min(1).max(200).nullable().default(null),sizeBytes:u().int().nonnegative().max(Lv).nullable().default(null)}).strict(),Jl=v(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]);function zv(e){return`${JSON.stringify(qu(e),null,2)}
124
- `}function KA(e){return VA(e)}function wt(e){return KA(zv(e))}function GA(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function qu(e){return Array.isArray(e)?e.map(qu):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,qu(n)]))}const Jr=ve(r(),Re()).default({}),ea=u().int().nonnegative(),Yl=r().trim().min(1).max(1e5),Uv=c({kind:v(["personal","team"]),id:ne}).strict(),ZA=c({name:ne,release:se.nullable(),revision:ea}).strict();c({schemaVersion:_("openpond.harnessWorkspace.v1"),id:ne,ownerScope:Uv,name:r().trim().min(1).max(240),location:v(["local","hosted"]),sourceRevision:r().trim().min(1).max(500),revision:ea,dirty:C(),currentChannel:ZA,createdAt:Qe,updatedAt:Qe,metadata:Jr}).strict();const Ur=v(["runtime","memory","prompt","skill","agent","product","taskset","training"]),Hv=v(["text_instruction","memory","dependency_selection","executable_code","business_logic","financial_logic","permission","connected_app","publication","deployment","training","model_binding","team_or_global"]),qv=c({id:ne,route:Ur,operation:v(["create","update","delete"]),target:r().trim().min(1).max(2e3),summary:r().trim().min(1).max(2e3),content:r().max(1e6).nullable(),contentHash:Ie.nullable(),effects:h(Hv).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=wt(e.content);e.contentHash!==n&&t.addIssue({code:"custom",message:`edit contentHash is ${e.contentHash}; expected ${n}`,path:["contentHash"]})}),Bv=c({workspaceId:ne,revision:ea,sourceRevision:r().trim().min(1).max(500),channelRevision:ea}).strict(),za=c({id:ne,revision:ea,contentHash:Ie}).strict(),JA=c({schemaVersion:_("openpond.harnessTurnSnapshot.v1"),workspaceId:ne,workspaceRevision:ea,sourceRevision:r().trim().min(1).max(500),channelName:ne,channelRevision:ea,harnessRelease:se,toolCatalogHash:Ie.nullable().optional(),overlay:za.nullable().optional().default(null)}).strict(),YA=c({schemaVersion:_("openpond.harnessRunOverlay.v1"),id:ne,runId:ne,baseHarnessRelease:se,workspace:Bv,revision:ea,status:v(["active","frozen","abandoned"]),edits:h(qv).max(1e3),createdAt:Qe,updatedAt:Qe,metadata:Jr}).strict();YA.extend({contentHash:Ie}).strict();const Fv=c({kind:v(["tool_event","recovery","validation","user_turn","work_output","work_receipt"]),id:ne,contentHash:Ie.nullable()}).strict(),Vv=c({id:ne,kind:v(["dependency","schema","package","file_render","skill","prompt","business_formula","targeted_evaluation","observed_recovery","memory","component_activation"]),description:Yl,required:C()}).strict(),XA=c({schemaVersion:_("openpond.harnessImprovementProposal.v1"),id:ne,overlay:za,baseHarnessRelease:se,expectedWorkspace:Bv,requestedScope:v(["personal","team","global"]),route:Ur,risk:v(["low","review","restricted"]),effects:h(Hv).min(1).max(20),evidence:h(Fv).min(1).max(1e3),edits:h(qv).min(1).max(1e3),validationPlan:h(Vv).min(1).max(100),expectedOutcome:Yl,createdAt:Qe,metadata:Jr}).strict().superRefine((e,t)=>{const n=new Set(e.effects);for(const[a,o]of e.edits.entries()){o.route!==e.route&&t.addIssue({code:"custom",message:"every edit route must match the proposal route",path:["edits",a,"route"]});for(const i of o.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"]})});XA.extend({contentHash:Ie}).strict();const QA=c({schemaVersion:_("openpond.harnessTargetedValidationReceipt.v1"),id:ne,proposal:se,validationId:ne,kind:Vv.shape.kind,status:v(["passed","failed","blocked","skipped"]),summary:Yl,evidenceRefs:h(Fv).max(1e3),createdAt:Qe,metadata:Jr}).strict();QA.extend({contentHash:Ie}).strict();const eP=v(["advanced","retained","conflict","rolled_back"]),tP=c({schemaVersion:_("openpond.harnessAdvanceReceipt.v1"),id:ne,workspaceId:ne,ownerScope:Uv,proposal:se.nullable(),expectedWorkspaceRevision:ea,observedWorkspaceRevision:ea,previousChannelRevision:ea,nextChannelRevision:ea,previousRelease:se.nullable(),nextRelease:se.nullable(),validationReceipts:h(se).max(100),decision:eP,reason:Yl,rollbackOf:se.nullable(),createdAt:Qe,metadata:Jr}).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"]})});tP.extend({contentHash:Ie}).strict();const nP=c({schemaVersion:_("openpond.harnessOverlayMergeReceipt.v1"),id:ne,workspaceId:ne,baseHarnessRelease:se,leftOverlay:za,rightOverlay:za,decision:v(["merged","conflict"]),mergedOverlay:za.nullable(),conflictTargets:h(r().trim().min(1).max(2e3)).max(1e3),requiresRevalidation:_(!0),createdAt:Qe,metadata:Jr}).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"]})});nP.extend({contentHash:Ie}).strict();const Wv=v(["openpond.lab"]),Bu=c({id:r(),experience:Fm.default(SA),provider:Zr,modelRef:sn.nullable().optional(),openPondCommandAccessMode:bs.default(gs),systemKind:Wv.nullable().optional(),hiddenFromDefaultSidebar:C().optional(),parentSessionId:r().nullable().optional(),parentTurnId:r().nullable().optional(),subagentRunId:r().nullable().optional(),subagentRoleId:Gr.nullable().optional(),subagentDelegationMode:Fl.nullable().optional(),title:r(),appId:r().nullable(),appName:r().nullable(),workspaceKind:vs.optional(),workspaceId:r().nullable().optional(),workspaceName:r().nullable().optional(),localProjectId:r().nullable().optional(),cloudProjectId:r().nullable().optional(),cloudTeamId:r().nullable().optional(),currentProfile:Wo.nullable().optional(),metadata:ve(r(),Re()).optional(),cwd:r().nullable(),codexThreadId:r().nullable(),createdAt:r(),updatedAt:r(),status:v(["idle","active","failed","closed"]),runtimeSeconds:u().int().nonnegative().optional(),runtimeRunningSince:r().nullable().optional(),pinned:C(),savedForLater:C().optional(),archived:C(),order:u()});c({id:r(),sessionId:r(),providerTurnId:r().nullable(),modelRef:sn.nullable().optional(),prompt:r(),startedAt:r(),completedAt:r().nullable(),status:v(["in_progress","completed","failed","interrupted"]),error:r().nullable(),metadata:ve(r(),Re()).optional().default({}),createImproveRun:ys.nullable().optional().default(null),profileSnapshot:qA.nullable().optional(),harnessSnapshot:JA.nullable().optional()});const aP=c({id:r(),sessionId:r(),turnId:r().nullable(),providerRequestId:vn([r(),u()]),kind:v(["command","file_change","permissions","user_input","create_plan","subagent_patch_apply","legacy_exec","legacy_patch"]),title:r(),detail:r(),status:v(["pending","accepted","accepted_for_session","declined","cancelled"]),createdAt:r()}),oP=c({key:v(["files","diffs","checks","deploys","sources","schedules","tool_runs","logs","app_config"]),label:r(),status:v(["placeholder","available","error"]),summary:r()}),Kv=c({id:r().trim().min(1).max(191),agentId:r().trim().min(1).max(191).optional().nullable(),sourcePath:r().trim().min(1).max(2e3).optional().nullable(),sourceActionId:r().trim().min(1).max(191).optional().nullable(),name:r().trim().min(1).max(191).optional().nullable(),label:r().trim().min(1).max(160).optional().nullable(),description:r().trim().max(1e3).optional().nullable(),visibility:r().trim().max(80).optional().nullable(),inputSchema:vn([r().trim().max(191),ve(r(),Re())]).optional().nullable(),outputSchema:vn([r().trim().max(191),ve(r(),Re())]).optional().nullable(),approvalPolicy:ve(r(),Re()).optional().nullable(),artifactPolicy:ve(r(),Re()).optional().nullable(),setupRequirements:h(ve(r(),Re())).optional(),mcp:ve(r(),Re()).optional().nullable(),schedulePolicy:ve(r(),Re()).optional().nullable(),trace:ve(r(),Re()).optional().nullable(),implementation:ve(r(),Re()).optional().nullable(),invokesModel:C().optional()}),rP=c({command:v(["inspect","build","validate","eval","traces","run"]),status:v(["passed","failed"]),checkedAt:r(),exitCode:u().nullable().optional(),sourceHead:r().nullable().optional()}),iP=c({id:r(),name:r(),path:r(),enabled:C()}),sP=c({name:r(),description:r(),path:r(),scope:_("profile"),enabled:C(),sourcePath:r(),charCount:u(),sourceHash:r(),validationStatus:v(["valid","warning","error"]),validationMessages:h(r()),resourceFiles:h(r()).optional().default([])}),lP=c({id:r(),name:r(),path:r(),agentId:r().nullable(),sourcePath:r()}),Gv=c({path:r(),originalPath:r().nullable().optional(),indexStatus:r().nullable(),worktreeStatus:r().nullable(),status:r(),category:v(["added","modified","deleted","renamed","untracked","changed"])}),cP=c({isRepo:C(),branch:r().nullable(),head:r().nullable(),shortHead:r().nullable(),dirty:C(),upstream:r().nullable(),ahead:u().nullable(),behind:u().nullable(),remoteUrl:r().nullable(),files:h(Gv),fileCount:u().int().nonnegative().optional(),error:r().nullable()}),dP=c({actionCount:u(),generatedAt:r().nullable(),manifestPath:r().nullable(),registryPath:r().nullable(),stale:C(),error:r().nullable()}),uP=c({skillCount:u(),generatedAt:r().nullable(),stale:C(),error:r().nullable()}),mh=c({ref:r(),source:v(["action_catalog","source_upload_metadata"]),actionId:r().nullable(),kind:r().nullable(),label:r(),status:r(),required:C(),blocking:C()}),mP=c({status:v(["ready","setup_required","blocked"]),requirementCount:u(),blockingCount:u(),optionalMissingCount:u(),readyCount:u(),requirements:h(mh),blockingRequirements:h(mh)}),pP=c({changedAgents:h(r()),newAgents:h(r()),deletedAgents:h(r()),changedSkills:h(r()).optional().default([]),changedActions:h(r()),changedExtensions:h(r()),setupChanges:h(r()),envRequirementChanges:h(r()),files:h(Gv),fileCount:u().int().nonnegative().optional()}),fP=c({status:r(),agentId:r().nullable().optional(),deployPlanStatus:r().nullable().optional(),canRun:C().nullable().optional(),canDeploy:C().nullable().optional(),sourceRef:r().nullable().optional(),sourceCommitSha:r().nullable().optional(),manifestHash:r().nullable().optional(),manifestPath:r().nullable().optional(),setupCommands:h(r()).optional(),validationCommands:h(r()).optional(),requiredChecks:h(r()).optional(),evalNames:h(r()).optional(),blockedReasons:h(r()).optional(),staleReasons:h(r()).optional(),runtimeId:r().nullable().optional(),sandboxId:r().nullable().optional(),traceArtifactRefs:h(r()).optional(),evalResultArtifactRefs:h(r()).optional(),validatorArtifactRefs:h(r()).optional(),checkedAt:r().nullable().optional(),error:r().nullable().optional()}),hP=c({status:r(),agentId:r().nullable().optional(),runtimeAgentId:r().nullable().optional(),projectId:r().nullable().optional(),sourceRoot:r().nullable().optional(),sourceRef:r().nullable().optional(),sourceCommitSha:r().nullable().optional(),manifestHash:r().nullable().optional(),manifestPath:r().nullable().optional(),manifestSyncedAt:r().nullable().optional(),fileCount:u().nullable().optional(),totalBytes:u().nullable().optional(),generatedManifestPath:r().nullable().optional(),synthesizedOpenPondYaml:C().nullable().optional(),uploadMetadataPath:r().nullable().optional(),setupCommands:h(r()).optional(),validationCommands:h(r()).optional(),materializedAt:r().nullable().optional(),error:r().nullable().optional()}),gP=c({status:r(),agentId:r().nullable().optional(),snapshotId:r().nullable().optional(),sourceRef:r().nullable().optional(),sourceCommitSha:r().nullable().optional(),manifestHash:r().nullable().optional(),manifestPath:r().nullable().optional(),buildStatus:r().nullable().optional(),validationStatus:r().nullable().optional(),evalStatus:r().nullable().optional(),publishedAt:r().nullable().optional(),error:r().nullable().optional()}),bP=c({status:r(),agentId:r().nullable().optional(),runId:r().nullable().optional(),runtimeId:r().nullable().optional(),sandboxId:r().nullable().optional(),sourceRef:r().nullable().optional(),sourceCommitSha:r().nullable().optional(),manifestHash:r().nullable().optional(),setupGateStatus:r().nullable().optional(),setupRequirementRefs:h(r()).optional(),artifactRefs:h(r()).optional(),traceArtifactRefs:h(r()).optional(),evalArtifactRefs:h(r()).optional(),startedAt:r().nullable().optional(),completedAt:r().nullable().optional(),error:r().nullable().optional()}),vP=c({teamId:r().nullable(),projectId:r().nullable(),sourceRef:r().nullable(),sourceCommitSha:r().nullable(),lastPushedAt:r().nullable(),lastPushedLocalHead:r().nullable(),lastPushedHostedHead:r().nullable(),promotionStatus:r().nullable().optional().default(null),hostedRunStatus:r().nullable().optional().default(null),hostedRunAgentId:r().nullable().optional().default(null),hostedRunId:r().nullable().optional().default(null),hostedRunAt:r().nullable().optional().default(null),hostedSourceMaterialization:hP.nullable().optional().default(null),hostedSourceCheck:fP.nullable().optional().default(null),hostedPublish:gP.nullable().optional().default(null),hostedRun:bP.nullable().optional().default(null)}),yP=c({state:v(["none","ready","dirty","pending_commit","error"]),message:r(),agentCount:u(),actionCount:u(),defaultAction:r().nullable(),checkFresh:C(),checkStaleReason:r().nullable(),localHead:r().nullable(),hostedHead:r().nullable()}),Zv=c({mode:v(["none","local"]),repoPath:r().nullable(),activeProfile:r().nullable(),sourcePath:r().nullable(),manifestPath:r().nullable(),agents:h(iP),skills:h(sP).optional().default([]),evals:h(lP).optional().default([]),git:cP.nullable(),catalog:dP,skillCatalog:uP.optional().default({skillCount:0,generatedAt:null,stale:!0,error:null}),actionCatalog:h(Kv),sourceSetupRequirements:h(ve(r(),Re())),setupGate:mP,diff:pP,hosted:vP.nullable(),summary:yP,lastCheck:rP.nullable(),error:r().nullable()}),SP=c({ref:Wo,name:r(),repoPath:r(),sourcePath:r().nullable(),state:Zv}),xP=c({lastUsed:Wo.nullable(),profiles:h(SP)});function kP(){return{lastUsed:null,profiles:[]}}function wP(){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 _P=c({name:r(),description:r(),path:r(),sourcePath:r(),enabled:C(),charCount:u().int().nonnegative(),sourceHash:r(),validationStatus:v(["valid","error"]),validationMessages:h(r()),resourceFiles:h(r()),updatedAt:r().nullable()}),IP=v(["codex","profile","extension"]);c({skillName:r(),scope:IP,path:r(),byteSize:u().int().nonnegative(),isBinary:C(),content:r().nullable()});const CP=[{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"]}],RP=c({name:r(),description:r(),relativePath:r(),sourcePath:r(),charCount:u().int().nonnegative(),sourceHash:r(),resourceFiles:h(r()),validationStatus:v(["valid","error"]),validationMessages:h(r())}),Jv=c({id:r(),source:_("github"),owner:r(),repo:r(),repositoryUrl:r().url(),requestedRef:r(),resolvedCommit:r(),sourcePath:r(),readmePath:r().nullable(),installedAt:r(),updatedAt:r(),packageHash:r(),skills:h(RP),validationStatus:v(["valid","error"]),validationMessages:h(r())});Jv.omit({installedAt:!0,updatedAt:!0,sourcePath:!0}).extend({sourcePath:Fb()});const AP=c({rootPath:r(),registryPath:r(),extensions:h(Jv),error:r().nullable()});c({source:r().trim().min(1),ref:r().trim().min(1).optional()});const PP=c({latestSequence:u().int().nonnegative(),oldestSequence:u().int().nonnegative(),totalEvents:u().int().nonnegative(),limit:u().int().nonnegative(),hasMoreBefore:C()});c({server:yA,account:cA,codex:dA,preferences:dh.optional().default(()=>dh.parse({})),providers:Mf.optional().default(()=>Mf.parse({})),personalization:uh.optional().default(()=>uh.parse({soul:Ov[0].content,soulPath:null,updatedAt:null})),apps:h(vR),localProjects:h(wR).optional().default([]),cloudProjects:h(kR).optional().default([]),profile:Zv.optional().default(wP),profileLibrary:xP.optional().default(kP),codexPersonalSkills:h(_P).optional().default([]),extensionCatalog:AP.optional().default({rootPath:"",registryPath:"",extensions:[],error:null}),codexHistorySessions:h(Bu).optional().default([]),sidebarAppPreferences:nA,sidebarFileBookmarks:h(Mv).optional().default([]),appsError:r().nullable(),appsMeta:ch,accountMeta:ch,sessions:h(Bu),events:h(jf),eventWindow:PP.optional(),approvals:h(aP),placeholders:h(oP),diagnostics:h(jf)});const Wm=v(["openpond_hosted","local_byok","codex_app_server","unknown"]),Yv=v(["provider_usage","codex_context_usage","missing"]),TP=v(["provider_usage_body","provider_response_headers"]),EP=v(["chat_turn","tool_loop","slash_command","create_improve_planner","harness_refiner","context_compaction","subagent","codex_context","other"]),MP=v(["foreground","tool_loop","compaction","subagent","refiner","other"]),Xv=v(["user_facing","background","system"]),Qv=v(["started","completed","failed","interrupted"]),Km=v(["composer_selection","prompt_parse","server_parser","model_tool","api"]),e0=v(["chat","settings","goal","create_improve","compaction","system"]),t0=v(["direct_chat","tool_loop","slash_command","planner","summary","scan","subagent","other"]),jP=c({surface:e0,workflowKind:t0,sessionId:r().trim().min(1).nullable().default(null),turnId:r().trim().min(1).nullable().default(null),goalId:r().trim().min(1).nullable().default(null),subagentRunId:r().trim().min(1).nullable().default(null),subagentRoleId:r().trim().min(1).nullable().default(null),createImproveRunId:r().trim().min(1).nullable().default(null),commandName:r().trim().min(1).max(160).nullable().default(null),commandSource:Km.nullable().default(null),appId:r().trim().min(1).nullable().default(null),workspaceKind:vs.nullable().default(null),workspaceId:r().trim().min(1).nullable().default(null),localProjectId:r().trim().min(1).nullable().default(null),cloudProjectId:r().trim().min(1).nullable().default(null),sourceEventSequence:u().int().nonnegative().nullable().default(null)}),OP=c({surface:e0.optional(),workflowKind:t0.optional(),goalId:r().trim().min(1).nullable().optional(),subagentRunId:r().trim().min(1).nullable().optional(),subagentRoleId:r().trim().min(1).nullable().optional(),createImproveRunId:r().trim().min(1).nullable().optional(),commandName:r().trim().min(1).max(160).nullable().optional(),commandSource:Km.nullable().optional()}).strict(),Yr=r().trim().min(1).max(160),NP=c({id:r().trim().min(1),requestId:r().trim().min(1),requestOrdinal:u().int().nonnegative(),sessionId:r().trim().min(1).nullable(),turnId:r().trim().min(1).nullable(),provider:Yr,model:r().trim().min(1),route:Wm,source:Yv,requestKind:EP,visibility:Xv,status:Qv,startedAt:r().trim().min(1),completedAt:r().trim().min(1).nullable(),durationMs:u().int().nonnegative().nullable(),firstTokenMs:u().int().nonnegative().nullable(),promptTokens:u().int().nonnegative().nullable(),cachedPromptTokens:u().int().nonnegative().nullable(),uncachedPromptTokens:u().int().nonnegative().nullable(),cacheWritePromptTokens:u().int().nonnegative().nullable(),cacheTelemetrySource:TP.nullable(),completionTokens:u().int().nonnegative().nullable(),totalTokens:u().int().nonnegative().nullable(),errorType:r().trim().min(1).max(160).nullable(),errorMessage:r().trim().min(1).max(2e3).nullable(),attribution:jP}),n0=c({from:r().trim().min(1),to:r().trim().min(1),bucket:v(["day","all_time"])}),Gm=vn([_("all"),Xv]),Zm=v(["all","started","completed","failed","interrupted","missing"]),$P=c({range:v(["7d","30d","90d","all"]).default("30d"),visibility:Gm.default("all"),status:Zm.default("all"),provider:Yr.optional(),model:r().trim().min(1).optional()});$P.extend({sessionId:r().trim().min(1).optional(),turnId:r().trim().min(1).optional(),limit:u().int().positive().max(500).default(100)});const Ko=c({requests:u().int().nonnegative(),promptTokens:u().int().nonnegative().nullable(),cacheTelemetryRequests:u().int().nonnegative(),cacheHitRequests:u().int().nonnegative(),cachedPromptTokens:u().int().nonnegative().nullable(),uncachedPromptTokens:u().int().nonnegative().nullable(),cacheWritePromptTokens:u().int().nonnegative().nullable(),cacheHitRate:u().min(0).max(1).nullable(),cacheRequestHitRate:u().min(0).max(1).nullable(),cacheTelemetryCoverage:u().min(0).max(1),completionTokens:u().int().nonnegative().nullable(),totalTokens:u().int().nonnegative().nullable(),averageLatencyMs:u().nonnegative().nullable(),p95LatencyMs:u().nonnegative().nullable(),averageFirstTokenMs:u().nonnegative().nullable(),p95FirstTokenMs:u().nonnegative().nullable(),failures:u().int().nonnegative(),failureRate:u().nonnegative(),firstSeenAt:r().trim().min(1),lastSeenAt:r().trim().min(1)}),DP=Ko.extend({provider:Yr,model:r().trim().min(1),route:Wm}),LP=Ko.extend({sessionId:r().trim().min(1),title:r().trim().min(1).nullable(),workspaceKind:vs.nullable(),workspaceId:r().trim().min(1).nullable()}),zP=Ko.extend({commandName:r().trim().min(1),commandSource:Km.nullable()}),UP=Ko.extend({route:Wm}),HP=Ko.extend({status:Qv}),qP=Ko.extend({source:Yv}),BP=Ko.extend({cohort:MP}),FP=c({date:r().trim().min(1),totalTokens:u().int().nonnegative(),requests:u().int().nonnegative(),models:h(c({provider:Yr,model:r().trim().min(1),totalTokens:u().int().nonnegative(),requests:u().int().nonnegative()}))}),VP=c({requests:u().int().nonnegative(),completedRequests:u().int().nonnegative(),failedRequests:u().int().nonnegative(),missingUsageRequests:u().int().nonnegative(),promptTokens:u().int().nonnegative().nullable(),cacheTelemetryRequests:u().int().nonnegative(),cacheHitRequests:u().int().nonnegative(),cachedPromptTokens:u().int().nonnegative().nullable(),uncachedPromptTokens:u().int().nonnegative().nullable(),cacheWritePromptTokens:u().int().nonnegative().nullable(),cacheHitRate:u().min(0).max(1).nullable(),cacheRequestHitRate:u().min(0).max(1).nullable(),cacheTelemetryCoverage:u().min(0).max(1),completionTokens:u().int().nonnegative().nullable(),totalTokens:u().int().nonnegative().nullable(),averageLatencyMs:u().nonnegative().nullable(),p95LatencyMs:u().nonnegative().nullable(),averageFirstTokenMs:u().nonnegative().nullable(),p95FirstTokenMs:u().nonnegative().nullable(),failureRate:u().nonnegative(),activeModelCount:u().int().nonnegative(),peakDailyTokens:u().int().nonnegative(),longestRequestMs:u().int().nonnegative().nullable(),activeDays:u().int().nonnegative(),currentStreakDays:u().int().nonnegative(),longestStreakDays:u().int().nonnegative()});c({generatedAt:r().trim().min(1),range:n0,filters:c({visibility:Gm,status:Zm,provider:Yr.nullable(),model:r().trim().min(1).nullable()}),totals:VP,daily:h(FP),models:h(DP),threads:h(LP),commands:h(zP),routes:h(UP),statuses:h(HP),sources:h(qP),cohorts:h(BP)});c({generatedAt:r().trim().min(1),range:n0,filters:c({visibility:Gm,status:Zm,provider:Yr.nullable(),model:r().trim().min(1).nullable(),sessionId:r().trim().min(1).nullable(),turnId:r().trim().min(1).nullable()}),limit:u().int().positive(),hasMore:C(),records:h(NP)});const WP=v(["usage_spike","model_usage_spike","latency_regression","failure_cluster","missing_usage_frames"]);c({type:WP,title:r().trim().min(1),summary:r().trim().min(1),severity:v(["nit","concern","blocker"]),payload:ve(r(),Re()).default({})});const KP=v(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),GP=v(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),ZP=v(["native_bot","oauth_connector","wallet_connector","mcp_endpoint"]),JP=c({kind:_("integration"),provider:KP,appIds:h(GP).min(1).max(4),setupSurfaces:h(ZP).min(1).max(4),connectionIds:h(r().trim().min(1)).max(8).optional(),capabilities:h(r().trim().min(1)).max(64).optional()}).strict(),Oo={maxAttachments:10,maxAttachmentBytes:12*1024*1024,maxAttachmentBase64Chars:Math.ceil(12*1024*1024*4/3)+16,maxTextChars:2e5},YP=v(["image","text","file"]),XP=c({sessionId:r().trim().min(1).max(200),turnId:r().trim().min(1).max(200),attachmentId:r().trim().min(1).max(200),storageName:r().trim().min(1).max(240),contentType:r().trim().min(1).max(160)}),QP=c({sessionId:r().trim().min(1).max(200),turnId:r().trim().min(1).max(200),attachmentId:r().trim().min(1).max(200),storageName:r().trim().min(1).max(1024),contentType:r().trim().min(1).max(160)}),a0=c({id:r().trim().min(1),name:r().trim().min(1).max(240),mediaType:r().trim().min(1).max(160),sizeBytes:u().int().nonnegative().max(Oo.maxAttachmentBytes),kind:YP,lineCount:u().int().nonnegative().max(Oo.maxAttachmentBytes+1).optional(),relativePath:r().trim().min(1).max(1024).optional(),text:r().max(Oo.maxTextChars).optional(),contentsBase64:r().max(Oo.maxAttachmentBase64Chars).optional()}),eT=a0.omit({text:!0,contentsBase64:!0}).extend({imagePreview:XP.optional(),filePreview:QP.optional()});c({experience:Fm.optional(),provider:Zr.default(Uo),modelRef:sn.optional(),openPondCommandAccessMode:bs.optional(),systemKind:Wv.nullable().optional(),hiddenFromDefaultSidebar:C().optional(),parentSessionId:r().trim().min(1).max(200).nullable().optional(),parentTurnId:r().trim().min(1).max(200).nullable().optional(),subagentRunId:r().trim().min(1).max(200).nullable().optional(),subagentRoleId:Gr.nullable().optional(),subagentDelegationMode:Fl.nullable().optional(),appId:r().nullable().optional(),appName:r().nullable().optional(),workspaceKind:vs.optional(),workspaceId:r().nullable().optional(),workspaceName:r().nullable().optional(),localProjectId:r().nullable().optional(),cloudProjectId:r().nullable().optional(),cloudTeamId:r().nullable().optional(),currentProfile:Wo.nullable().optional(),metadata:ve(r(),Re()).optional(),cwd:r().nullable().optional(),title:r().optional(),autoTitlePrompt:r().trim().min(1).max(2e4).optional()});c({teamId:r().trim().min(1),projectName:r().trim().min(1).max(120).optional(),branch:r().trim().min(1).max(120).optional(),chatSessionId:r().trim().min(1).max(200).optional(),displayPrompt:r().trim().min(1).max(2e3).optional()});c({branch:r().trim().min(1).max(120).optional()});c({prompt:r().min(1),metadata:ve(r(),Re()).optional(),usageAttribution:OP.optional().nullable(),cwd:r().nullable().optional(),model:r().nullable().optional(),modelRef:sn.optional(),mentionedAppIds:h(r().trim().min(1)).max(8).optional(),mentionedConnectedApps:h(JP).max(8).optional(),openPondActionCatalog:h(Kv).max(100).optional(),attachments:h(a0).max(Oo.maxAttachments).optional(),createImproveRun:ys.optional().nullable(),approvalPolicy:v(["untrusted","on-failure","on-request","never"]).default("on-request"),sandbox:v(["read-only","workspace-write","danger-full-access"]).default("workspace-write"),codexPermissionMode:qm.default("default"),codexReasoningEffort:Zl.optional()});c({prompt:r().min(1),error:r().min(1),target:v(["cloud_workspace","hybrid_sandbox"])});c({reason:v(["manual"]).default("manual"),model:r().nullable().optional(),modelRef:sn.optional()});c({experience:Fm.optional(),provider:Zr.optional(),modelRef:sn.nullable().optional(),openPondCommandAccessMode:bs.optional(),pinned:C().optional(),savedForLater:C().optional(),archived:C().optional(),order:u().optional(),title:r().optional(),parentSessionId:r().trim().min(1).max(200).nullable().optional(),parentTurnId:r().trim().min(1).max(200).nullable().optional(),subagentRunId:r().trim().min(1).max(200).nullable().optional(),subagentRoleId:Gr.nullable().optional(),subagentDelegationMode:Fl.nullable().optional(),appId:r().nullable().optional(),appName:r().nullable().optional(),workspaceKind:vs.optional(),workspaceId:r().nullable().optional(),workspaceName:r().nullable().optional(),localProjectId:r().nullable().optional(),cloudProjectId:r().nullable().optional(),cloudTeamId:r().nullable().optional(),currentProfile:Wo.nullable().optional(),metadata:ve(r(),Re()).optional(),cwd:r().nullable().optional()});c({command:r().trim().min(1),cwd:r().trim().min(1).max(4096).nullable().optional(),timeoutSeconds:u().int().min(1).max(3600).optional()});c({appIds:h(r()).min(1)});c({defaultChatProvider:Zr.optional(),defaultChatModel:r().min(1).optional(),defaultChatModelRef:sn.nullable().optional(),subagents:es.optional(),codexPermissionMode:qm.optional(),codexReasoningEffort:Zl.optional(),openPondCommandAccessMode:bs.optional(),defaultBranchPrefix:r().trim().max(48).optional(),defaultNewProjectDirectory:r().trim().max(4096).optional(),defaultTeamId:r().trim().max(191).nullable().optional(),advancedWorkspaceControls:C().optional(),contextCompaction:zu.optional(),training:Uu.optional(),sidebarWidth:u().int().min(244).max(560).optional(),diffPanelWidth:u().int().min(320).max(2400).optional(),sidebarSectionsCollapsed:Lu.optional(),editor:Il.optional()});c({message:r().trim().min(1).max(4e3),surface:r().trim().min(1).max(120).default("app"),stack:r().max(12e3).nullable().optional(),context:ve(r(),Re()).optional()}).strict();c({activeTemplateId:Bm,templateName:r().trim().min(1).max(80),soul:r().trim().min(1).max(8e3),saveAsNew:C().optional().default(!1)});c({decision:v(["accept","acceptForSession","decline","cancel"])});c({branch:r().trim().min(1).max(240).nullable().optional(),surface:v(["desktop","terminal"])});c({handle:r().min(1),baseUrl:r().nullable().optional()});c({handle:r().min(1),baseUrl:r().nullable().optional()});c({handle:r().min(1).optional(),apiKey:r().min(1),baseUrl:r().nullable().optional(),apiBaseUrl:r().nullable().optional(),chatApiBaseUrl:r().nullable().optional(),environment:r().nullable().optional(),setActive:C().optional()});c({handle:r().min(1),currentBaseUrl:r().nullable().optional(),baseUrl:r().nullable().optional(),apiBaseUrl:r().nullable().optional(),chatApiBaseUrl:r().nullable().optional(),environment:r().nullable().optional(),setActive:C().optional()});c({appId:r(),exists:C(),configPath:r().nullable().optional(),envVar:r().nullable(),toolName:r().nullable(),version:vn([r(),u()]).nullable(),source:v(["hosted_env","local_file","defaults","missing"]),currentConfig:ve(r(),Re()).nullable(),defaults:ve(r(),Re()).nullable(),schema:ve(r(),Re()).nullable(),error:r().nullable().optional(),updatedAt:r()}).passthrough();const Cl=v(["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:Cl,args:ve(r(),Re()).optional().default({}),source:v(["ui_button","chat_action","terminal_command","hook"]).default("chat_action")});c({ok:C(),action:Cl,appId:r().nullable().optional(),output:r(),data:Re().optional()});const Ss=c({id:r().trim().min(1).max(200),title:r().trim().min(1).max(240),sourceTaskId:r().trim().min(1).max(200),sourceTurnId:r().trim().min(1).max(200),revision:u().int().positive().default(1),createdAt:r().datetime()}),xs=c({kind:v(["structural","visual","test","user_review"]),status:v(["passed","failed","not_run"]),label:r().trim().min(1).max(240),detail:r().trim().max(4e3).nullable().optional(),ref:r().trim().max(4096).nullable().optional()}),o0=c({kind:_("local"),path:r().trim().min(1).max(4096),deviceId:r().trim().min(1).max(200)}),r0=c({kind:_("managed"),fileId:r().trim().min(1).max(200),downloadPath:r().trim().min(1).max(4096)}),tT=c({kind:_("external"),provider:r().trim().min(1).max(120),resourceId:r().trim().min(1).max(500),url:r().url().nullable()}),i0=Ss.extend({kind:_("file"),contentType:r().trim().min(1).max(200),sizeBytes:u().int().nonnegative(),sha256:r().regex(/^[a-f0-9]{64}$/),location:fn("kind",[o0,r0,tT]),validation:h(xs).max(32).default([])}),nT=Ss.extend({kind:_("source_change"),projectId:r().trim().min(1).max(200),ref:r().trim().min(1).max(500),url:r().url().nullable(),validation:h(xs).max(32).default([])}),aT=Ss.extend({kind:_("deployment"),deploymentId:r().trim().min(1).max(200),url:r().url(),validation:h(xs).max(32).default([])}),oT=Ss.extend({kind:_("external_resource"),provider:r().trim().min(1).max(120),resourceId:r().trim().min(1).max(500),url:r().url(),contentType:r().trim().min(1).max(200).nullable(),validation:h(xs).max(32).default([])}),s0=c({id:r().trim().min(1).max(191),label:r().trim().min(1).max(160).nullable(),description:r().trim().max(1e3).nullable(),inputSchema:ve(r(),Re()).nullable(),outputSchema:ve(r(),Re()).nullable(),schedulePolicy:ve(r(),Re()).nullable()}),l0=c({base:r().trim().min(1).max(200),resources:ve(r(),Re()),modelPolicy:ve(r(),Re()).nullable(),setup:ve(r(),Re()).nullable()}),rT=c({id:r().trim().min(1).max(200),kind:v(["sdk_validation","sdk_eval"]),status:v(["passed","failed"]),summary:r().trim().min(1).max(2e3),artifactPath:r().trim().min(1).max(4096),artifactSha256:r().regex(/^[a-f0-9]{64}$/)}),iT=c({path:r().trim().min(1).max(4096),sizeBytes:u().int().nonnegative(),sha256:r().regex(/^[a-f0-9]{64}$/),contentsBase64:r()});c({schema:_("openpond.agent-package.v1"),agentId:r().trim().min(1).max(191),versionId:r().trim().min(1).max(200),digest:r().regex(/^[a-f0-9]{64}$/),title:r().trim().min(1).max(240),source:c({files:h(iT).min(1).max(1e3),totalSizeBytes:u().int().nonnegative()}),manifest:ve(r(),Re()),actions:h(s0).min(1).max(256),runtimeRequirements:l0,receipts:h(rT).min(2).max(64)});const sT=Ss.extend({kind:_("agent_package"),agentId:r().trim().min(1).max(191),versionId:r().trim().min(1).max(200),digest:r().regex(/^[a-f0-9]{64}$/),packageFileId:r().trim().min(1).max(200),manifestFileId:r().trim().min(1).max(200),actions:h(s0).min(1).max(256),runtimeRequirements:l0,validationReceiptIds:h(r().trim().min(1).max(200)).min(1).max(32),evalReceiptIds:h(r().trim().min(1).max(200)).min(1).max(32),sourceFileCount:u().int().positive(),sourceSizeBytes:u().int().nonnegative(),location:fn("kind",[o0,r0]),validation:h(xs).max(32).default([])}),m3=fn("kind",[i0,nT,aT,oT,sT]);c({outputs:h(i0)});const lT=v(["sandbox_template","sandbox","generic_git","plain_folder"]),cT=v(["sandbox_template"]).nullable();c({productKind:lT,actions:c({files:C(),git:C(),sandboxRuntime:C(),sandboxTemplate:C()}),checks:c({validate:Cl.nullable(),build:Cl.nullable(),postEdit:cT}),ui:c({showSandboxTemplateActions:C(),showSandboxRuntimeActions:C()})});const dT=c({id:r(),name:r(),dnsName:r().nullable(),os:r().nullable(),online:C(),active:C(),isSelf:C(),tailscaleIps:h(r()),lastSeen:r().nullable()}),uT=c({installed:C(),running:C(),version:r().nullable(),backendState:r().nullable(),tailnetName:r().nullable(),magicDnsSuffix:r().nullable(),machineName:r().nullable(),dnsName:r().nullable(),authUrl:r().nullable(),tailscaleIps:h(r()),health:h(r()),error:r().nullable(),peers:h(dT)}),mT=c({enabled:C(),reachable:C(),targetUrl:r().nullable(),httpsUrl:r().nullable(),httpsHost:r().nullable(),httpsPort:u().nullable(),setupUrl:r().nullable(),configText:r().nullable(),error:r().nullable()}),pT=c({localUrl:r(),localWebUrl:r(),remoteUrl:r().nullable(),remoteWebUrl:r().nullable(),tokenHash:r(),tailscaleUpCommand:r(),serveCommand:r(),disableCommand:r(),operatorCommand:r(),webUiAvailable:C(),updatedAt:r(),tailscale:uT,serve:mT});c({message:r(),status:pT});const c0=v(["github","openpond_git"]),d0=v(["private","public"]),fT=v(["actions","prompts","goals","evals","examples","tasksets","extensions"]),hT=c({agentIds:h(r().trim().min(1)).max(100),skillNames:h(r().trim().min(1)).max(200),optionalContent:h(fT).max(20).default([])}),u0=c({provider:c0,owner:r().trim().min(1).max(191).nullable().optional(),repository:r().trim().min(1).max(191),visibility:d0.default("private")}),gT=c({ref:Wo,selection:hT,target:u0}),bT=c({path:r(),sizeBytes:u().int().nonnegative(),category:r()});c({sourceHash:r(),sourceRevision:r().nullable(),clean:C(),blockedReasons:h(r()),warnings:h(r()),files:h(bT),excludedFiles:h(r()),target:u0,replacesExisting:C()});gT.extend({expectedSourceHash:r().trim().min(1),confirmed:_(!0)});c({provider:c0,owner:r(),repository:r(),visibility:d0,remoteUrl:r(),webUrl:r(),revision:r()});const vT=v(["cron","rate"]),m0=v(["queued","running","succeeded","failed","skipped"]),p0=c({id:r(),localProjectId:r(),localProjectName:r(),agentRootPath:r(),agentName:r(),scheduleName:r(),scheduleType:vT,scheduleExpression:r(),timezone:r().nullable(),targetAction:r(),input:ve(r(),Re()).optional().default({}),enabledByDefault:C(),enabled:C(),sourceHash:r(),manifestHash:r().nullable(),agentVersionId:r().nullable().optional(),agentPackageDigest:r().nullable().optional(),nextRunAt:r().nullable(),lastRunAt:r().nullable(),lastRunStatus:m0.nullable(),lastRunId:r().nullable(),lastError:r().nullable(),createdAt:r(),updatedAt:r()}),f0=c({id:r(),scheduleId:r(),localProjectId:r(),scheduleName:r(),scheduledFor:r(),trigger:v(["schedule","manual"]),status:m0,targetAction:r(),agentVersionId:r().nullable().optional(),agentPackageDigest:r().nullable().optional(),startedAt:r().nullable(),completedAt:r().nullable(),exitCode:u().int().nullable(),stdout:r().nullable(),stderr:r().nullable(),result:ve(r(),Re()).nullable(),traceArtifactRef:r().nullable(),error:r().nullable(),createdAt:r(),updatedAt:r()});c({schedules:h(p0),scheduler:c({running:C(),nextTickAt:r().nullable(),lastSyncAt:r().nullable(),scanRunning:C()})});c({runs:h(f0)});c({enabled:C().optional()});c({input:ve(r(),Re()).optional()});c({schedule:p0,run:f0});const yT=v(["sunday","monday","tuesday","wednesday","thursday","friday","saturday"]),Jm=c({version:_(1),kind:v(["once","daily","weekdays","weekly","monthly"]),timeZone:r().trim().min(1).max(100),startDate:r().regex(/^\d{4}-\d{2}-\d{2}$/),localTime:r().regex(/^([01]\d|2[0-3]):([0-5]\d)$/),weekdays:h(yT).min(1).max(7).optional(),dayOfMonth:u().int().min(1).max(31).optional(),end:fn("kind",[c({kind:_("never")}),c({kind:_("on_date"),date:r().regex(/^\d{4}-\d{2}-\d{2}$/)}),c({kind:_("after_occurrences"),occurrences:u().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"]})}),ST=c({id:r(),expression:r().nullable(),timeZone:r(),recurrence:Jm.nullable(),configurationVersion:u().int(),enabled:C(),nextRunAt:r().nullable(),lastTriggeredAt:r().nullable(),delivery:ve(r(),Re()).default({})}),xT=c({id:r(),definitionKey:r(),version:u().int(),name:r(),prompt:r(),modelId:r(),schedules:h(ST)}),kT=c({id:r(),definitionId:r(),scheduleId:r().nullable(),definitionName:r(),definitionVersion:u().int(),conversationId:r(),triggerKind:v(["manual","schedule","webhook","retry"]),status:r(),notificationStatus:r(),deliveryStatus:r(),deliveryError:r().nullable(),createdAt:r()});c({definitions:h(xT),runs:h(kT),asOf:r(),webBaseUrl:r().url().optional()});c({clientRequestId:r().trim().min(1).max(191),sourceTurnId:r().trim().min(1).max(191).nullable().optional(),name:r().trim().min(1).max(180),prompt:r().trim().min(1).max(2e4),recurrence:Jm,modelId:r().trim().min(1).max(191).default("openpond-chat")});vn([c({enabled:C()}),c({name:r().trim().min(1).max(180),prompt:r().trim().min(1).max(2e4),recurrence:Jm})]);const Ym=ve(r(),Re());c({userId:r(),role:v(["owner","admin","member"]),name:r(),handle:r().nullable(),image:r().nullable()});const wT=c({userId:r(),role:v(["owner","admin","member"]),name:r(),handle:r().nullable(),image:r().nullable(),lastReadSequence:u().int().nonnegative()}),_T=c({id:r(),messageId:r(),refType:v(["hosted_ai_thread","goal","openpond_session","project","agent_run","message_reply"]),refId:r(),preview:Ym,createdAt:r()}),h0=c({id:r(),messageId:r().nullable(),clientAttachmentId:r(),kind:_("image"),name:r(),mediaType:v(["image/png","image/jpeg","image/webp","image/gif"]),sizeBytes:u().int().positive(),status:v(["pending","ready","failed"]),createdAt:r(),readyAt:r().nullable()});c({attachment:h0,uploadUrl:r().url().nullable(),uploadHeaders:ve(r(),r()),expiresAt:r().nullable()});c({url:r().url(),expiresAt:r()});const Xm=c({id:r(),threadId:r(),teamId:r(),clientRequestId:r().nullable(),authorType:v(["user","agent","system"]),authorUserId:r().nullable(),authorAgentId:r().nullable(),sequence:u().int().nonnegative(),kind:v(["text","system","command_result"]),body:r(),metadata:Ym,editedAt:r().nullable(),deletedAt:r().nullable(),createdAt:r(),refs:h(_T),attachments:h(h0)}),IT=c({id:r(),teamId:r(),kind:v(["general","dm","group","channel"]),title:r().nullable(),createdByUserId:r(),lastMessageId:r().nullable(),lastMessageSequence:u().int().nonnegative(),lastMessageAt:r(),createdAt:r(),updatedAt:r(),unreadCount:u().int().nonnegative(),pinnedAt:r().nullable(),mutedAt:r().nullable(),archivedAt:r().nullable(),participants:h(wT),lastMessage:Xm.nullable()});c({thread:IT,messages:h(Xm),hasMoreBefore:C()});c({threadId:r(),mutedAt:r().nullable()});const CT=v(["pending","running","completed","failed","interrupted","cancelled"]),ph=c({id:r(),conversationId:r(),threadId:r(),teamId:r(),requestedByUserId:r(),executorUserId:r().nullable(),providerId:r(),modelId:r(),clientRequestId:r(),baseMessageSequence:u().int().nonnegative(),status:CT,partialBody:r().nullable(),userMessageId:r(),assistantMessageId:r().nullable(),errorCode:r().nullable(),cancelledByUserId:r().nullable(),leaseExpiresAt:r().nullable(),heartbeatAt:r().nullable(),createdAt:r(),updatedAt:r()}),RT=c({id:r(),conversationId:r(),sequence:u().int().nonnegative(),role:v(["user","assistant","system","action"]),body:r(),createdByUserId:r().nullable(),createdAt:r()});c({conversationId:r(),parentThreadId:r(),parentMessageId:r(),teamId:r(),title:r().nullable(),providerId:r().nullable(),modelId:r(),createdByUserId:r(),messages:h(RT),turns:h(ph),activeTurn:ph.nullable(),createdAt:r(),updatedAt:r()});const g0=c({id:u().int().nonnegative(),teamId:r(),threadId:r(),conversationId:r().nullable(),type:v(["thread.created","message.created","message.updated","message.deleted","read.updated","ai_thread.created","ai_turn.updated"]),payload:Ym,createdAt:r()});c({events:h(g0),cursor:u().int().nonnegative(),hasMore:C()});c({httpUrl:r().min(1),realtimeUrl:r().min(1),region:r().min(1),token:r().min(1),expiresAt:r().min(1),teamId:r().min(1),userId:r().min(1)});const Qm=ve(r(),Re()),ta=r().nullable(),AT=v(["draft","published","archived"]),ep=v(["owner","admin","member"]),b0=v(["active","left"]),v0=v(["mentions","all","none"]),y0=v(["public_preview","members"]),PT=v(["members","admins"]),TT=c({canPreview:C(),canJoin:C(),canLeave:C(),canRead:C(),canPost:C(),canUpload:C(),canMention:C(),canManage:C(),requiresRulesAcceptance:C(),currentRulesVersionId:r().nullable()}),S0=c({id:r(),communityId:r(),version:u().int().positive(),title:r(),requiresReacceptance:C(),publishedAt:r()}),ET=S0.extend({bodyMarkdown:r(),contentHash:r()}),MT=c({role:ep,status:b0,notificationMode:v0}),jT=c({id:r(),communityId:r(),userId:r(),role:ep,status:b0,notificationMode:v0,joinedAt:r(),leftAt:ta,createdAt:r(),updatedAt:r()}),x0=c({id:r(),slug:r(),displayName:r(),description:r(),imageUrl:r().nullable(),status:AT,visibility:v(["public","private"]),joinPolicy:v(["open","closed"]),historyVisibility:y0,featuredAt:ta,publishedAt:ta,archivedAt:ta,memberCount:u().int().nonnegative(),membership:MT.nullable(),capabilities:TT,currentRules:S0.nullable()});c({items:h(x0),nextCursor:r().nullable()});const k0=c({lastReadSequence:u().int().nonnegative(),lastReadAt:ta.optional(),mutedAt:ta,pinnedAt:ta}),tp=c({id:r(),communityId:r(),chatThreadId:r().nullable(),slug:r(),displayName:r(),topic:r(),position:u().int().nonnegative(),visibility:y0,postingPolicy:PT,isDefault:C(),archivedAt:ta,lastMessageSequence:u().int().nonnegative(),unreadCount:u().int().nonnegative(),readState:k0.nullable()});x0.omit({currentRules:!0}).extend({currentRules:ET.nullable(),channels:h(tp),previewMessageLimit:u().int().positive()});const OT=c({id:r(),messageId:r(),refType:v(["hosted_ai_thread","goal","openpond_session","project","agent_run","message_reply"]),refId:r(),preview:Qm,createdAt:r()}),w0=c({id:r(),messageId:r().nullable(),clientAttachmentId:r(),kind:_("image"),name:r(),mediaType:v(["image/png","image/jpeg","image/webp","image/gif"]),sizeBytes:u().int().positive(),status:v(["pending","ready","failed"]),createdAt:r(),readyAt:ta});c({attachment:w0,uploadUrl:r().url().nullable(),uploadHeaders:ve(r(),r()),expiresAt:ta});c({url:r().url(),expiresAt:r()});const _0=c({id:r(),threadId:r(),teamId:Fb(),clientRequestId:r().nullable(),authorType:v(["user","agent","system"]),authorUserId:r().nullable(),authorAgentId:r().nullable(),sequence:u().int().nonnegative(),kind:v(["text","system","command_result"]),body:r(),metadata:Qm,editedAt:ta,deletedAt:ta,createdAt:r(),refs:h(OT),attachments:h(w0)});c({messages:h(_0),hasMoreBefore:C(),channelId:r(),readState:k0.omit({lastReadAt:!0}).nullable(),preview:C()});const NT=c({userId:r(),handle:r().nullable(),name:r().nullable(),role:ep});c({items:h(NT),nextCursor:r().nullable()});const I0=c({id:u().int().nonnegative(),communityId:r(),channelId:r(),threadId:r(),type:v(["thread.created","message.created","message.updated","message.deleted","read.updated"]),payload:Qm,createdAt:r()});c({events:h(I0),cursor:u().int().nonnegative(),hasMore:C()});c({httpUrl:r().min(1),realtimeUrl:r().min(1),region:r().min(1),token:r().min(1),expiresAt:r().min(1),communityId:r().min(1),userId:r().min(1),channel:r().min(1)});c({membership:jT,channels:h(tp)});c({channels:h(tp)});const Ln=r().trim().min(1).max(240),Qa=r().trim().min(1),C0=ve(r(),Re()).default({}),R0=v(["nominated","needs_review","approved_for_creation","creating","needs_task_review","baselining","ready_for_export","rejected","dismissed","retired","blocked"]),A0=v(["no_training","prompting","retrieval","sft","preference","grpo_rft","sdft_opsd","sdpo","agentic_rl"]),$T=c({id:Ln,kind:v(["repeated_success","accepted_correction","agent_action_recurrence","outcome_linked_change","frontier_cost","expert_label","runtime_feedback"]),sourceRefIds:h(Ln).min(1).max(1e4),occurredAt:Qa,signature:r().trim().min(1).max(2e3),summary:r().trim().min(1).max(5e3),confidence:u().min(0).max(1),consented:C(),metadata:C0}),DT=c({frequency:u().min(0).max(1),businessValue:u().min(0).max(1),frontierCost:u().min(0).max(1),signalQuality:u().min(0).max(1),verifiability:u().min(0).max(1),repeatability:u().min(0).max(1),privacyRisk:u().min(0).max(1),overall:u().min(0).max(1)}),LT=c({tactic:A0,eligible:C(),reasons:h(r().trim().min(1).max(5e3)).min(1).max(100),blockers:h(r().trim().min(1).max(5e3)).max(100).default([]),requiredSignals:h(r().trim().min(1).max(500)).max(100).default([]),generatedBy:v(["decision_table","baseline_reassessment"])}),P0=c({schemaVersion:_("openpond.taskCandidate.v1"),id:Ln,profileId:Ln,status:R0,fingerprint:r().trim().min(1).max(512),title:r().trim().min(1).max(500),summary:r().trim().min(1).max(1e4),workflowSignature:r().trim().min(1).max(2e3),evidence:h($T).min(1).max(1e5),scorecard:DT,recommendation:LT,mergedIntoId:Ln.nullable(),createdAt:Qa,updatedAt:Qa,metadata:C0}),Xl=c({schemaVersion:_("openpond.taskMinerConfig.v1"),enabled:C().default(!1),localOnly:C().default(!0),observationWindowDays:u().int().min(1).max(365).default(30),minimumRecurrence:u().int().min(2).max(100).default(3),clustering:_("hybrid_deterministic_first").default("hybrid_deterministic_first"),consentRequired:C().default(!0)});c({items:h(P0),generatedAt:Qa,config:Xl});c({status:R0.optional(),mergeIntoId:Ln.nullable().optional()});c({profileId:Ln,sourceIds:h(Ln).max(1e5).default([]),sessionIds:h(Ln).max(1e5).default([]),config:Xl.optional()});const zT=c({schemaVersion:_("openpond.taskMinerRun.v1"),id:Ln,profileId:Ln,status:v(["queued","running","cancelling","cancelled","succeeded","failed"]),config:Xl,sourceIds:h(Ln).max(1e5),sessionIds:h(Ln).max(1e5).default([]),progress:c({stage:v(["queued","ingesting","preparing","clustering","persisting","complete"]),processedSources:u().int().nonnegative(),totalSources:u().int().nonnegative(),candidatesFound:u().int().nonnegative(),skippedSources:u().int().nonnegative().default(0)}),candidateIds:h(Ln).max(1e5),cancelRequested:C(),error:r().trim().min(1).max(2e4).nullable(),createdAt:Qa,startedAt:Qa.nullable(),completedAt:Qa.nullable(),updatedAt:Qa}),na=r().trim().min(1).max(240),Ua=r().trim().min(1),ao=r().trim().min(8).max(256),T0=r().trim().min(1).max(1e3).refine(e=>!e.startsWith("/")&&!e.startsWith("\\")&&!e.split(/[\\/]/).includes(".."),"Artifact paths must be relative and stay inside the Dataset."),lo=v(["train","validation","test","frozen_eval"]),UT=c({name:r().trim().min(1).max(500),semanticRole:v(["row_id","cluster_id","prompt","messages","demonstration","chosen","rejected","expected_output","privileged_context","reward","feedback","tag","metadata"]),logicalType:v(["string","integer","float","boolean","json","messages"]),nullable:C(),policy:v(["visible","privileged","metadata"])}),HT=c({schemaVersion:_("openpond.datasetSemanticSchema.v1"),fields:h(UT).min(1).max(1e4),schemaHash:ao}),qT=c({id:na,split:lo,path:T0,contentHash:ao,schemaHash:ao,sizeBytes:u().int().nonnegative(),rowCount:u().int().positive(),rowGroupCount:u().int().positive()}),np=c({schemaVersion:_("openpond.datasetArtifact.v1"),id:na,tasksetId:na,tasksetRevision:u().int().positive(),contentHash:ao,format:_("parquet"),schema:HT,shards:h(qT).min(1).max(1e5),rowCount:u().int().positive(),splitCounts:ve(lo,u().int().nonnegative()),sourceReceiptRefs:h(na).min(1).max(1e5),mappingHash:ao,qualityReportHash:ao,createdAt:Ua}),BT=c({schemaVersion:_("openpond.datasetArtifactSummary.v1"),artifactId:na,tasksetId:na,tasksetRevision:u().int().positive(),format:_("parquet"),rowCount:u().int().positive(),splitCounts:ve(lo,u().int().nonnegative()),sizeBytes:u().int().nonnegative(),contentHash:ao,available:C(),unavailableReason:r().trim().min(1).max(2e3).nullable(),createdAt:Ua}),FT=c({schemaVersion:_("openpond.datasetCatalogItem.v1"),tasksetId:na,tasksetRevision:u().int().positive(),artifactId:na.nullable(),name:r().trim().min(1).max(500),status:v(["draft","awaiting_disclosure_approval","awaiting_materialization_approval","materializing","validating","needs_review","baselining","ready","blocked","failed","archived"]),storageKind:v(["inline","parquet"]),rowCount:u().int().nonnegative(),splitCounts:ve(lo,u().int().nonnegative()),sizeBytes:u().int().nonnegative().nullable(),available:C(),unavailableReason:r().trim().min(1).max(2e3).nullable(),createdAt:Ua,updatedAt:Ua});c({schemaVersion:_("openpond.datasetCatalog.v1"),profileId:na,datasets:h(FT),generatedAt:Ua});c({schemaVersion:_("openpond.datasetArtifactRegistry.v1"),manifest:np,profileId:na,storageRoot:r().trim().min(1).max(4e3),relativeManifestPath:T0,available:C(),unavailableReason:r().trim().min(1).max(2e3).nullable(),verifiedAt:Ua.nullable(),createdAt:Ua,updatedAt:Ua});c({split:lo.nullable().default(null),cursor:r().trim().min(1).max(2e3).nullable().default(null),limit:u().int().min(1).max(100).default(25),columns:h(r().trim().min(1).max(500)).max(100).default([])});c({schemaVersion:_("openpond.datasetRowPage.v1"),tasksetId:na,tasksetRevision:u().int().positive(),artifactHash:ao,split:lo.nullable(),rows:h(ve(r(),Re())).max(100),nextCursor:r().max(2e3).nullable(),totalRows:u().int().nonnegative(),returnedRows:u().int().nonnegative()});const VT=c({schemaVersion:_("openpond.datasetStorageSettings.v1"),datasetStorePath:r().trim().min(1).max(4e3),updatedAt:Ua}),WT=c({id:na,label:r().trim().min(1).max(500),path:r().trim().min(1).max(4e3),datasetStorePath:r().trim().min(1).max(4e3),kind:v(["local","network","removable","cache"]),configured:C(),mounted:C(),writable:C(),totalBytes:u().int().nonnegative().nullable(),freeBytes:u().int().nonnegative().nullable()});c({schemaVersion:_("openpond.datasetStorageState.v1"),settings:VT,storageRoots:h(WT)});c({datasetStorePath:r().trim().min(1).max(4e3)});const Fu=r().trim().min(1).max(240),KT=r().trim().min(1),Ql=r().trim().min(8).max(256),GT=ve(r(),Re()).default({}),ZT=r().trim().min(7).max(256),JT=v(["pending","approved","review","blocked"]),ap=c({id:Fu,profileId:Fu,title:r().trim().min(1).max(500),sourceHash:Ql,occurredAt:KT,licensingStatus:JT,secretScanStatus:v(["pending","passed","blocked"]),piiScanStatus:v(["pending","passed","review","blocked"]),metadata:GT}),YT=ap.extend({schemaVersion:_("openpond.huggingFaceDatasetSource.v1"),kind:_("huggingface"),repositoryId:r().trim().regex(/^[^/\s]+\/[^/\s]+$/).max(500),repositoryUrl:r().url().max(2e3),revision:ZT,configuration:r().trim().min(1).max(500),upstreamSplits:h(r().trim().min(1).max(500)).min(1).max(1e3),gated:C(),private:C(),declaredLicense:r().trim().min(1).max(500).nullable(),sourceFileHashes:h(Ql).min(1).max(1e5)}),XT=ap.extend({schemaVersion:_("openpond.uploadedFileDatasetSource.v1"),kind:_("uploaded_file"),originalFileNames:h(r().trim().min(1).max(500)).min(1).max(1e3),mediaTypes:h(r().trim().min(1).max(200)).min(1).max(1e3),sourceFileHashes:h(Ql).min(1).max(1e3),totalBytes:u().int().nonnegative(),parserVersion:r().trim().min(1).max(200)}),QT=ap.extend({schemaVersion:_("openpond.generatedDatasetSource.v1"),kind:_("generated"),generatorId:Fu,generatorVersion:r().trim().min(1).max(200),seed:u().int(),generatorHash:Ql}),eE=fn("kind",[YT,XT,QT]),je=r().trim().min(1).max(240),Ve=r().regex(/^[a-f0-9]{64}$/),$t=r().datetime({offset:!0}),st=c({id:je,contentHash:Ve}).strict(),Ho=st.extend({revision:u().int().positive()}).strict(),tE=c({id:je,purpose:r().trim().min(1).max(500),audience:v(["orchestrator","environment","privileged_scorer","trainer","infrastructure"]),required:C(),ttlSeconds:u().int().positive().max(86400),scopes:h(r().trim().min(1).max(500)).max(100).default([])}).strict(),nE=c({declarationId:je,leaseRef:r().trim().min(8).max(1e3),audience:tE.shape.audience,expiresAt:$t}).strict(),aE=c({schemaVersion:_("openpond.harnessActionBinding.v1"),actionId:je,modelToolName:r().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:r().trim().min(1).max(1e3),inputSchema:ve(r(),Re()),actionSchemaHash:Ve,agentRelease:st,implementationHash:Ve,runtimeBindingId:je,capabilityReceiptHash:Ve,sideEffect:v(["read","write"]),studentVisible:C(),timeoutMs:u().int().positive().max(36e5),episodeArgumentBindings:h(c({argument:je,source:_("case_id")}).strict()).max(20).default([])}).strict(),Ue=r().trim().min(1).max(240),Gt=r().trim().min(1),oo=r().trim().min(8).max(256),ec=r().trim().regex(/^[a-f0-9]{64}$/),E0=r().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),yn=ve(r(),Re()).default({}),Pn=Ue.nullable();function Xr(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 Hr=lo,rE=v(["draft","awaiting_disclosure_approval","awaiting_materialization_approval","materializing","validating","needs_review","baselining","ready","blocked","failed","archived"]),M0=v(["general","benchmark"]),j0=c({schemaVersion:_("openpond.tasksetBenchmark.v1"),definitionId:Ue,releaseId:Ue,releaseHash:ec,managedReleasePath:r().trim().min(1).max(1e3).refine(Xr,"Benchmark release paths must remain relative."),adaptationSplit:Hr,evaluationSplit:Hr,primaryMetric:v(["foreground_tokens","success_rate","latency_ms","cost_usd"]),qualityGate:v(["none","non_regression","all_pass"]),source:v(["builtin","imported"]),metadata:yn}),O0=c({schemaVersion:_("openpond.tasksetPreferenceComparisonBinding.v1"),releaseId:Ue,releaseHash:ec,publishedAt:Gt,metadata:yn}),iE=v(["slash_train","session_menu","bulk_selection","training_page","task_candidate"]),sE=v(["defaults","customize"]),lE=v(["automated","manual"]),op=v(["demonstrations","preferences","verifiable_reward","rubric","discovery"]),_n=r().trim().max(1e5),rp=fn("kind",[c({kind:_("demonstrations"),behavior:_n,examples:h(c({id:Ue,prompt:_n,response:_n})).max(1e3).default([])}),c({kind:_("preferences"),preference:_n,pairs:h(c({id:Ue,prompt:_n,chosen:_n,rejected:_n,rationale:_n})).max(1e3).default([])}),c({kind:_("verifiable_reward"),task:_n,rules:h(c({id:Ue,points:u().finite(),condition:_n})).max(1e3).default([]),otherwisePoints:u().finite().default(0)}),c({kind:_("rubric"),task:_n,criteria:h(c({id:Ue,label:r().trim().max(500),description:_n})).max(1e3).default([]),positiveExample:_n,negativeExample:_n,boundaryExample:_n})]),cE=c({status:v(["pending","granted","denied","revoked"]),scope:v(["metadata_only","selected_turns","full_session"]),grantedBy:Pn,grantedAt:Gt.nullable(),purpose:_("task_authoring_and_evaluation")}),N0=c({schemaVersion:_("openpond.trainingSource.v1"),id:Ue,profileId:Ue,sessionId:Ue,turnIds:h(Ue).max(1e3).default([]),workspaceId:Pn,sourceHash:oo,clusterKey:Ue,title:r().trim().min(1).max(500),occurredAt:Gt,consent:cE,connectedAppIds:h(Ue).max(100).default([]),secretScanStatus:v(["pending","passed","blocked"]),piiScanStatus:v(["pending","passed","review","blocked"]),licensingStatus:v(["pending","approved","review","blocked"]),metadata:yn}),$0=vn([N0,eE]);c({schemaVersion:_("openpond.trainingSourceEstimate.v1"),sessionId:Ue,messageCount:u().int().nonnegative(),estimatedTokens:u().int().nonnegative(),textBytes:u().int().nonnegative()});c({query:r().max(500).default(""),offset:u().int().nonnegative().default(0),limit:u().int().min(1).max(100).default(20),candidates:h(c({sessionId:Ue,title:r().trim().min(1).max(500),updatedAt:Gt})).max(500).default([])});const dE=c({sessionId:Ue,title:r().trim().min(1).max(500),updatedAt:Gt,snippet:r().max(2e3).nullable()});c({schemaVersion:_("openpond.trainingChatSearchResult.v1"),query:r(),offset:u().int().nonnegative(),limit:u().int().positive(),total:u().int().nonnegative(),hasMore:C(),indexedChats:u().int().nonnegative(),totalChats:u().int().nonnegative(),indexing:C(),entries:h(dE)});const ip=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([])}),uE=c({id:Ue,sourceRefId:Ue,artifactRef:r().trim().min(1).max(4e3).refine(Xr,"Task asset references must be safe relative paths."),fileName:r().trim().min(1).max(500).refine(oE,"Task asset file names must not contain path separators."),mediaType:r().trim().min(1).max(200),sha256:ec,sizeBytes:u().int().nonnegative().max(25e7),split:Hr,metadata:yn}),mE=c({path:r().trim().min(1).max(1e3).refine(Xr,"Required output paths must stay inside the Work output directory."),mediaType:r().trim().min(1).max(200),schemaRef:Ue.nullable().optional(),maxBytes:u().int().positive().max(1e7).optional(),metadata:yn}),D0=c({schemaVersion:_("openpond.taskData.v1"),id:Ue,clusterKey:Ue,split:Hr,input:ve(r(),Re()),expectedOutput:ve(r(),Re()).nullable(),policyVisibleContext:ve(r(),Re()).default({}),privilegedContextRef:Pn,sourceRefs:h(Ue).min(1).max(100),assets:h(uE).max(1e3).optional(),resourceRefs:h(Ue).max(1e3).optional(),requiredOutputs:h(mE).max(100).optional(),tags:h(Ue).max(100).default([]),metadata:yn}),pE=c({id:Ue,kind:v(["file","catalog","configuration","code_module"]),path:r().trim().min(1).max(1e3).refine(Xr,"Environment resource paths must remain relative."),mediaType:r().trim().min(1).max(200).nullable().optional(),visibility:v(["policy_visible","policy_hidden","privileged"]),required:C(),metadata:yn}),Qr=c({id:Ue,taskId:Pn,sourceRefs:h(Ue).min(1).max(100),artifactRef:Ue,approved:C(),confidence:u().min(0).max(1),metadata:yn}),L0=Qr.extend({kind:_("demonstration"),prompt:r().max(1e5).nullable().default(null),response:r().max(2e5).nullable().default(null)}),z0=Qr.extend({kind:_("preference"),prompt:r().max(1e5),chosen:r().max(2e5),rejected:r().max(2e5),rationale:r().max(1e5).nullable().default(null)}),U0=Qr.extend({kind:_("correction"),original:r().max(2e5),corrected:r().max(2e5),rationale:r().max(1e5).nullable().default(null)}),H0=Qr.extend({kind:_("feedback"),feedback:r().max(1e5),polarity:v(["positive","negative","mixed","neutral"])}),q0=Qr.extend({kind:_("reward"),task:r().max(1e5),rules:h(c({id:Ue,points:u().finite(),condition:r().trim().min(1).max(1e5)})).min(1).max(1e3),otherwisePoints:u().finite(),executable:C()}),B0=Qr.extend({kind:_("label"),labelKind:_("rubric"),task:r().max(1e5),criteria:h(c({id:Ue,label:r().trim().min(1).max(500),description:r().trim().min(1).max(1e5)})).min(1).max(1e3),calibrationExamples:c({positive:r().trim().min(1).max(2e5),negative:r().trim().min(1).max(2e5),boundary:r().trim().min(1).max(2e5)})});fn("kind",[L0,z0,U0,H0,q0,B0]);const F0=c({demonstrations:h(L0).max(1e5).default([]),preferences:h(z0).max(1e5).default([]),corrections:h(U0).max(1e5).default([]),feedback:h(H0).max(1e5).default([]),rewards:h(q0).max(1e5).default([]),labels:h(B0).max(1e5).default([])}),V0=c({protocolVersion:_("openpond.taskEnvironment.v1"),kind:v(["chat","agent","program","stateful_harness","work"]),entrypoint:r().trim().min(1).max(1e3),stateful:C(),deterministicSeeds:C(),toolNames:h(Ue).max(200).default([]),actionBindings:h(aE).max(200).optional(),lifecycle:h(v(["create","reset","step","grade","cleanup"])).min(1),defaultTimeoutMs:u().int().positive().max(36e5),networkPolicy:v(["none","declared_read_only","declared_scoped"]),resources:h(pE).max(1e4).optional(),metadata:yn}),sp=c({schemaVersion:_("openpond.tasksetCapabilities.v1"),taskKind:v(["chat","single_agent","multi_agent","custom_program"]),supportedSignals:h(v(["demonstration","preference","correction","feedback","reward","label"])),compatibleMethods:h(v(["none","retrieval","sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"])),rewardKinds:h(v(["none","exact","deterministic","model_judge","human"])),requiresTools:C(),requiresState:C(),requiresPrivilegedGrading:C(),environmentPlacements:h(v(["local","remote","colocated","provider_native"])),exportable:C(),portabilityBlockers:h(r().trim().min(1).max(2e3)).default([])}),W0=c({schemaVersion:_("openpond.tasksetMetricPolicy.v1"),primaryMetric:Ue,aggregation:v(["mean_score","pass_rate","weighted_mean","custom"]),missingReward:v(["zero","exclude"]),customAggregator:c({module:r().trim().min(1).max(1e3).refine(Xr,"Custom metric modules must use a safe relative path."),exportName:E0,contentHash:ec,timeoutMs:u().int().positive().max(3e5),networkPolicy:_("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"]})}),K0=v(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]),tc=c({id:Ue,version:r().trim().min(1).max(100),label:r().trim().min(1).max(500),weight:u().min(0).max(1e3).default(1),hardGate:C().default(!1),rewardEligible:C().default(!1),privileged:C().default(!1),metadata:yn}),fE=tc.extend({kind:v(["content","schema","file","diff","test","runtime_event","state"]),config:ve(r(),Re())}),hE=tc.extend({kind:_("model_judge"),rubric:r().trim().min(1).max(5e4),judge:sn,calibrationFixtureRefs:h(Ue).min(1).max(500),calibrationStatus:v(["pending","passed","failed"]),temperature:u().min(0).max(2).default(0)}),gE=tc.extend({kind:_("human"),rubric:r().trim().min(1).max(5e4),reviewerRole:r().trim().min(1).max(500)}),bE=tc.extend({kind:_("custom_verifier"),module:r().trim().min(1).max(1e3).refine(Xr,"Custom verifier modules must use a safe relative path."),exportName:E0,timeoutMs:u().int().positive().max(3e5),networkPolicy:_("none")}),lp=vn([fE,hE,gE,bE]),cp=v(["positive","negative","boundary","adversarial","prompt_injection","infrastructure_failure"]),G0=c({id:Ue,taskId:Ue,label:cp,output:ve(r(),Re()),infrastructureError:r().trim().min(1).max(1e4).nullable(),expectedPassed:C(),expectedRewardEligible:C(),metadata:yn}),vE=c({id:Ue,taskIndex:u().int().nonnegative(),label:cp,output:ve(r(),Re()),infrastructureError:r().trim().min(1).max(1e4).nullable(),expectedPassed:C(),expectedRewardEligible:C(),metadata:yn}),yE=c({path:r().trim().min(1).max(1e3),role:v(["environment","verifier","fixture"]),content:r().max(25e4)}),SE=c({schemaVersion:_("openpond.taskAttempt.v1"),id:Ue,tasksetId:Ue,taskId:Ue,split:Hr,attempt:u().int().nonnegative(),seed:u().int(),modelRef:sn.nullable(),startedAt:Gt,completedAt:Gt,output:ve(r(),Re()),runtimeEventRefs:h(Ue).max(1e4).default([]),artifactRefs:h(Ue).max(1e4).default([]),privilegedOutcomeRef:Pn,infrastructureError:r().trim().min(1).max(1e4).nullable(),costUsd:u().nonnegative().nullable(),latencyMs:u().int().nonnegative(),userInterventions:u().int().nonnegative().default(0),metadata:yn}),xE=c({schemaVersion:_("openpond.taskAttemptArtifact.v1"),id:Ue,tasksetId:Ue,taskId:Ue,attemptId:Ue,kind:v(["raw_model_response","runtime_trace","environment_state","grader_evidence","output_artifact"]),path:r().trim().min(1).max(4e3),mediaType:r().trim().min(1).max(200).nullable().optional(),sha256:oo,sizeBytes:u().int().nonnegative(),createdAt:Gt,metadata:yn}),kE=c({graderId:Ue,graderVersion:r().trim().min(1).max(100),score:u().min(0).max(1),passed:C(),hardGate:C(),rewardEligible:C(),feedback:r().trim().max(2e4).nullable(),evidenceRefs:h(Ue).max(1e4).default([]),judge:sn.nullable().optional().default(null),calibrationStatus:v(["not_applicable","pending","passed","failed"])}),wE=c({schemaVersion:_("openpond.gradeResult.v1"),id:Ue,attemptId:Ue,graderSetHash:oo,score:u().min(0).max(1).nullable(),passed:C(),components:h(kE).min(1).max(1e3),failureClass:K0.nullable(),feedback:h(r().trim().min(1).max(2e4)).max(1e3).default([]),rewardEligible:C(),createdAt:Gt});v(["stable_hash_top_n","rft_easy_curriculum_v1"]);const _E=c({schemaVersion:_("openpond.graderAuditReport.v1"),id:Ue,tasksetId:Ue,tasksetHash:oo,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:cp,gradeId:Ue,reason:r().trim().min(1).max(5e3)})).max(1e5),createdAt:Gt}),Z0=c({primaryMethod:v(["sft","dpo","grpo","ppo","sdft","opsd","sdpo"]),bootstrap:c({method:_("sft"),purpose:_("trajectory_bootstrap"),demonstrationRefs:h(Ue).min(1).max(1e5),limitations:h(r().trim().min(1).max(5e3)).min(1).max(100)}).nullable()}),J0=v(["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"]),IE=c({method:v(["sft","dpo","grpo","ppo"]),status:v(["recommended","compatible","needs_dataset_work"]),reasonCodes:h(J0).default([]),reasons:h(r().trim().min(1).max(5e3)).default([])}),Y0=c({schemaVersion:_("openpond.tasksetReadiness.v1"),tasksetId:Ue,tasksetHash:oo,ready:C(),recommendedMethod:v(["none","retrieval","sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),trainingPath:Z0.nullable().default(null),methodReadiness:h(IE).default([]),compatibleDestinationClasses:h(v(["export","custom","hosted_managed"])),blockers:h(c({code:Ue,message:r().trim().min(1).max(5e3),path:r().trim().max(2e3).nullable()})).default([]),warnings:h(r().trim().min(1).max(5e3)).default([]),generatedAt:Gt}),CE=c({schemaVersion:_("openpond.capabilityDiagnosis.v1"),summary:r().trim().min(1).max(1e4),stableBehavior:h(r().trim().min(1).max(5e3)).max(100).default([]),changingKnowledge:h(r().trim().min(1).max(5e3)).max(100).default([]),requiredContext:h(r().trim().min(1).max(5e3)).max(100).default([]),requiredTools:h(Ue).max(100).default([]),intervention:A0,trainingEligible:C(),rationale:h(r().trim().min(1).max(5e3)).min(1).max(100),confidence:u().min(0).max(1)}),RE=c({id:Ue,sourceId:Ue,sourceTurnId:Pn,split:Hr,origin:v(["extracted","corrected","synthetic","expert_authored"]),inputPrompt:r().trim().min(1).max(1e5),expectedOutputText:r().trim().min(1).max(2e5).nullable(),rationale:r().trim().min(1).max(5e3)}),X0=c({attempt:u().int().positive(),summary:r().trim().min(1).max(5e3),createdAt:Gt}),AE=c({schemaVersion:_("openpond.taskAuthoringProvenance.v1"),model:sn.nullable(),modelConfig:yn,skillHash:oo,promptTemplateVersion:r().trim().min(1).max(200),buildIntent:op.default("demonstrations"),buildSpecification:rp.nullable().default(null),evidenceHashes:h(oo).max(1e5),tasksetSdkVersion:r().trim().min(1).max(100),sourceCommit:r().trim().min(1).max(256).nullable(),repairHistory:h(X0).max(1e3),createdAt:Gt}),fh=c({schemaVersion:_("openpond.taskset.v1"),id:Ue,revision:u().int().positive().default(1),profileId:Ue,profileRelease:Ho.nullable().optional(),createImproveRunId:Pn.default(null),name:r().trim().min(1).max(500),objective:r().trim().min(1).max(2e4),purpose:M0.default("general"),benchmark:j0.nullable().default(null),preferenceComparison:O0.nullable().default(null),status:rE,sourceRefs:h($0).min(1).max(1e5),datasetArtifact:np.nullable().optional(),policy:ip,environment:V0,capabilities:sp,metrics:W0.optional(),tasks:h(D0).max(1e6),graders:h(lp).min(1).max(1e3),graderFixtures:h(G0).min(1).max(1e5),learningSignals:F0,authoringProvenance:AE,readiness:Y0.nullable(),contentHash:oo,createdAt:Gt,updatedAt:Gt,metadata:yn}).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"]})}),PE=c({schemaVersion:_("openpond.taskDesignProposal.v1"),id:Ue,name:r().trim().min(1).max(500),objective:r().trim().min(1).max(2e4),diagnosis:CE.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:sp.shape.taskKind,sourceIds:h(Ue).min(1).max(1e5),assumptions:h(r().trim().min(1).max(5e3)).max(1e3),successCriteria:h(r().trim().min(1).max(5e3)).min(1).max(1e3),proposedGraders:h(lp).max(1e3).default([]),graderFixtures:h(vE).max(1e5).default([]),generatedFiles:h(yE).max(1e3).default([]),proposedExamples:h(RE).max(1e5).default([]),proposedMethod:Y0.shape.recommendedMethod,trainingPath:Z0.nullable().default(null),policy:ip,warnings:h(r().trim().min(1).max(5e3)).default([]),createdAt:Gt}),TE=5;function p3(e,t="New model"){const n=e?.trim().split(/\s+/).filter(Boolean)??[];return n.length===0?t:n.slice(0,TE).join(" ")}const ei=c({schemaVersion:_("openpond.baseModelPreference.v1"),modelId:Ue,revision:r().trim().min(1).max(256).nullable(),tokenizerRevision:r().trim().min(1).max(256).nullable(),chatTemplateHash:r().trim().min(8).max(256).nullable(),modelAssetId:Pn,source:v(["managed","local","builtin"])}),EE=c({schemaVersion:_("openpond.taskCreationRequest.v1"),id:Ue,profileId:Ue,surface:iE,mode:sE,entryMode:lE.default("manual"),resourceIntent:v(["workproduct","dataset"]).default("workproduct"),buildIntent:op.default("demonstrations"),buildSpecification:rp.nullable().default(null),objective:r().trim().min(1).max(2e4).nullable(),methodHint:v(["sft","dpo","grpo","ppo"]).nullable().default(null),preferredBaseModelId:Ue.nullable().default(null),preferredBaseModel:ei.nullable().default(null),sourceIds:h(Ue).max(1e5),candidateId:Pn,analysisModel:sn.nullable(),analysisReasoningEffort:Zl.nullable().default(null),createImproveRunId:Pn.default(null),targetIntent:c({kind:v(["agent","skill","extension","model","configuration"]).nullable(),id:Pn,displayName:r().trim().min(1).max(500).nullable(),operation:v(["create","improve"])}).default({kind:"model",id:null,displayName:null,operation:"create"}),disclosure:c({status:v(["not_required","pending","approved","declined"]),content:_("raw_excerpts"),sourceIds:h(Ue).max(1e5),providerModel:sn.nullable(),approvalId:Pn,approvedAt:Gt.nullable()}).default({status:"not_required",content:"raw_excerpts",sourceIds:[],providerModel:null,approvalId:null,approvedAt:null}),createdAt:Gt}),Q0=c({schemaVersion:_("openpond.taskCreationSnapshot.v1"),id:Ue,request:EE,state:v(["planning","awaiting_disclosure_approval","awaiting_questions","recommendation_ready","awaiting_materialization_approval","materializing","validating","ready","blocked","failed","cancelled"]),proposal:PE.nullable(),materializedTasksetId:Pn,disclosureApprovalId:Pn,materializationApprovalId:Pn,blockingQuestions:h(c({id:Ue,kind:v(["objective","consent","success_signal","privacy_licensing","interpretation"]),prompt:r().trim().min(1).max(5e3),answer:r().trim().min(1).max(2e4).nullable()})).default([]),transcript:h(c({id:Ue,role:v(["user","assistant","system","tool"]),text:r().max(1e5),createdAt:Gt})).max(1e4).default([]),repairHistory:h(X0).max(1e3).default([]),blockedReason:r().trim().min(1).max(1e4).nullable(),createdAt:Gt,updatedAt:Gt});c({schemaVersion:_("openpond.taskCreationTranscript.v1"),creationId:Ue,profileId:Ue,messages:Q0.shape.transcript,updatedAt:Gt});function ME(e){return e.schemaVersion==="openpond.trainingSource.v1"}const Yi=r().trim().min(1).max(240),hh=r().trim().min(1),jE=r().trim().min(8).max(256),OE=r().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),NE=ve(r(),Re()).default({});function gh(e){const t=e.trim().replaceAll("\\","/");return!t||t.startsWith("/")||t==="."||t===".."?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}const $E=D0.extend({sourceRefs:h(Yi).max(100).default([])}),DE=v(["draft","validating","needs_review","published"]),LE=c({enabled:C(),candidateCount:u().int().min(2).max(4),minimumSamples:u().int().min(1).max(1e4).default(100),allowTies:C(),allowRejectAll:C(),rubric:r().trim().max(5e4),criteria:h(c({id:Yi,label:r().trim().min(1).max(500),description:r().trim().max(1e4),weight:u().nonnegative().max(1e3)})).max(100)}),zE=c({mode:v(["text","structured_json","artifacts"]),jsonSchema:ve(r(),Re()).nullable(),renderer:c({module:r().trim().min(1).max(1e3).refine(gh,"Renderer modules must use a safe relative path."),exportName:OE,configRef:r().trim().min(1).max(1e3).refine(gh,"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"]})}),UE=c({schemaVersion:_("openpond.tasksetDraft.v1"),id:Yi,revision:u().int().positive(),profileId:Yi,name:r().trim().max(500),objective:r().trim().max(2e4),purpose:M0.default("general"),benchmark:j0.nullable().default(null),preferenceComparison:O0.nullable().default(null),status:DE,sourceRefs:h($0).max(1e5).default([]),datasetArtifact:np.nullable().optional(),policy:ip,environment:V0,output:zE.default({mode:"text",jsonSchema:null,renderer:null}),capabilities:sp,metrics:W0,review:LE,tasks:h($E).max(1e6).default([]),graders:h(lp).max(1e3).default([]),graderFixtures:h(G0).max(1e5).default([]),learningSignals:F0,publishedTasksetRef:c({id:Yi,revision:u().int().positive(),contentHash:jE}).nullable(),createdAt:hh,updatedAt:hh,metadata:NE}).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"]})}),Tr=r().trim().min(1).max(240),fl=r().trim().min(1),Vu=r().trim().min(8).max(256),ey=ve(r(),Re()).default({}),HE=v(["created","inspecting","awaiting_source_review","awaiting_mapping","awaiting_materialization_approval","materializing","validating","ready","cancelling","cancelled","failed"]),ty=c({schemaVersion:_("openpond.huggingFaceDatasetLocator.v1"),repositoryId:r().trim().regex(/^[^/\s]+\/[^/\s]+$/).max(500),repositoryUrl:r().url().max(2e3),requestedRevision:r().trim().min(1).max(256).nullable()}),qE=c({path:r().trim().min(1).max(1e3),logicalType:r().trim().min(1).max(500),nullable:C(),sampleValues:h(Re()).max(5)}),BE=c({configuration:r().trim().min(1).max(500),split:r().trim().min(1).max(500),rowCount:u().int().nonnegative().nullable(),sizeBytes:u().int().nonnegative().nullable()}),FE=c({schemaVersion:_("openpond.huggingFaceDatasetInspection.v1"),id:Tr,locator:ty,resolvedRevision:r().trim().min(7).max(256),title:r().trim().min(1).max(500),description:r().max(2e4).nullable(),declaredLicense:r().trim().min(1).max(500).nullable(),gated:C(),private:C(),configurations:h(r().trim().min(1).max(500)).min(1).max(1e3),splits:h(BE).min(1).max(1e4),columns:h(qE).min(1).max(1e4),previewRows:h(ve(r(),Re())).max(25),sourceFiles:h(c({path:r().trim().min(1).max(2e3),configuration:r().trim().min(1).max(500),split:r().trim().min(1).max(500),revision:r().trim().min(7).max(256),sizeBytes:u().int().nonnegative().nullable(),contentHash:Vu.nullable()})).max(1e5),inspectedAt:fl,metadata:ey}),VE=v(["row_id","cluster_id","prompt","messages","demonstration","chosen","rejected","expected_output","privileged_context","reward","feedback","tag","metadata"]),WE=c({sourcePath:r().trim().min(1).max(1e3),target:VE,transform:v(["identity","string","json","messages","numeric","math_final_answer"]),policy:v(["visible","privileged","metadata"]),required:C()}),ny=c({schemaVersion:_("openpond.datasetImportMapping.v1"),sourceSchemaHash:Vu,configuration:r().trim().min(1).max(500),upstreamSplits:h(r().trim().min(1).max(500)).min(1).max(1e3),preset:v(["prompt_only","prompt_completion","messages","preference","prompt_expected_answer","prompt_privileged_solution","prompt_feedback"]),bindings:h(WE).min(1).max(1e4),nullPolicy:v(["reject","drop","preserve"]),invalidRowPolicy:v(["reject_import","drop_with_receipt"]),splitPolicy:c({seed:u().int(),assignments:ve(r(),lo),validationPercent:u().min(0).max(100),frozenEvalPercent:u().min(0).max(100)}),importerVersion:r().trim().min(1).max(200),mappingHash:Vu}),KE=c({phase:v(["idle","metadata","download","mapping","parquet_write","verification","publish"]),completedBytes:u().int().nonnegative(),totalBytes:u().int().nonnegative().nullable(),completedRows:u().int().nonnegative(),totalRows:u().int().nonnegative().nullable(),message:r().trim().min(1).max(2e3).nullable()}),GE=c({schemaVersion:_("openpond.datasetImportJob.v1"),id:Tr,profileId:Tr,sourceKind:v(["huggingface","uploaded_file"]),status:HE,locator:ty.nullable(),inspection:FE.nullable(),mapping:ny.nullable(),progress:KE,targetStorageRoot:r().trim().min(1).max(4e3).nullable(),tasksetId:Tr.nullable(),tasksetRevision:u().int().positive().nullable(),artifactId:Tr.nullable(),error:r().trim().min(1).max(2e4).nullable(),cancellationRequested:C(),createdAt:fl,updatedAt:fl,completedAt:fl.nullable(),metadata:ey});c({profileId:Tr,url:r().trim().min(1).max(2e3)});c({name:r().trim().min(1).max(500),objective:r().trim().min(1).max(2e4),mapping:ny,targetStorageRoot:r().trim().min(1).max(4e3).nullable(),licenseApproved:C().default(!1)});const Ya=je.nullable(),ja=u().int().nonnegative(),ZE=r().regex(/^[a-f0-9]{40}$/),JE=c({name:r().trim().min(1).max(160),startedAt:$t,completedAt:$t,durationMs:u().nonnegative(),clock:v(["monotonic","provider","wall"]),outcome:v(["succeeded","failed","cancelled"])}).strict(),YE=c({schemaVersion:_("openpond.correlatedTelemetryReceipt.v1"),stage:v(["training","evaluation","deployment","inference"]),correlation:c({modelRunId:Ya,modelVersionId:Ya,policyVersion:ja.nullable(),taskId:Ya,rolloutGroupId:Ya,providerResourceId:Ya,deploymentId:Ya,inferenceRequestId:Ya}).strict(),spans:h(JE).max(1e4),usage:c({promptTokens:ja.nullable(),generatedTokens:ja.nullable(),gpuSeconds:u().nonnegative().nullable(),workerActiveSeconds:u().nonnegative().nullable(),optimizerSteps:ja.nullable(),rolloutGroups:ja.nullable(),successfulTrajectories:ja.nullable(),failedTrajectories:ja.nullable(),peakGpuMemoryBytes:ja.nullable(),peakGpuUtilizationPercent:u().min(0).max(100).nullable()}).strict(),resource:c({provider:je,resourceIds:h(je).max(1e3),gpuType:r().trim().min(1).max(300).nullable(),gpuCount:ja.nullable(),baseProfileId:Ya,baseRepository:r().trim().min(1).max(512).nullable(),baseRevision:ZE.nullable(),adapterContentHash:Ve.nullable()}).strict(),cost:c({currency:_("USD"),providerReportedUsd:u().nonnegative().nullable(),quotedHourlyUsd:u().nonnegative().nullable(),estimatedUsd:u().nonnegative().nullable(),methodologyVersion:r().trim().min(1).max(160),pricingInputs:ve(r().trim().min(1).max(160),u().finite()),unitEstimates:ve(r().trim().min(1).max(160),u().nonnegative())}).strict(),recordedAt:$t,contentHash:Ve}).strict(),XE=v(["base_reference","lora_adapter"]),ay=c({baseModel:c({source:_("huggingface"),repoId:je,revision:r().regex(/^[a-f0-9]{40}$/),configHash:Ve,tokenizerHash:Ve,licenseId:je,gated:C()}).strict(),processor:c({repository:je,revision:r().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."})}),QE=c({schemaVersion:_("openpond.modelVersion.v1"),id:je,modelId:je,profileId:je,version:u().int().nonnegative(),kind:XE,status:v(["available","failed"]),baseModel:ei,taskset:Ho,releaseGraph:c({resolvedBundleHash:Ve,profileRelease:Ho,harnessRelease:st,agentRelease:st.nullable(),grader:c({id:je,contentHash:Ve}).strict()}).strict(),artifactLineageId:je.nullable(),adapterStatus:v(["not_trained","trained"]),createdAt:$t,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."})}),eM=c({schemaVersion:_("openpond.rewardModelVersion.v1"),id:je,modelId:je,profileId:je,version:u().int().positive(),role:_("reward"),status:v(["available","failed"]),scope:v(["synthetic_smoke","human_preference"]),baseModel:ei,runtime:ay.nullable().default(null),taskset:Ho,preferenceDatasetRelease:st,releaseGraph:c({resolvedBundleHash:Ve,profileRelease:Ho,harnessRelease:st,grader:c({id:je,contentHash:Ve}).strict()}).strict(),artifacts:c({checkpoint:st.extend({objectRef:r().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/),files:h(c({path:r().trim().min(1).max(512),sizeBytes:u().int().positive(),sha256:Ve}).strict()).min(4).max(128)}).strict(),adapter:st,scalarHead:st,bucketHead:st.nullable(),processorRelease:st}).strict(),qualificationReport:st.nullable(),createdAt:$t,contentHash:Ve}).strict(),tM=c({schemaVersion:_("openpond.rewardModelRunReceipt.v1"),provider:je,providerRunId:je,resolvedBundleHash:Ve,finalCheckpoint:st.extend({objectRef:r().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/)}).strict(),adapter:st,scalarHead:st,bucketHead:st.nullable(),processorRelease:st,optimizerEvidence:st,parameterDeltaHash:Ve,cleanup:c({computeReleased:C(),providerTerminalObserved:C()}).strict(),contentHash:Ve}).strict(),nM=dC(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:_("openpond.rewardModelRun.v1"),id:je,rewardModelId:je,rewardModelVersionId:je.nullable(),profileId:je,role:_("reward"),scope:v(["synthetic_smoke","human_preference"]),status:v(["prepared","running","succeeded","failed","cancelled"]),taskset:Ho,tasksetRelease:st,preferenceDatasetRelease:st,recipeRelease:st,destinationId:je,quote:c({maximumSpendUsd:u().positive(),hourlyCostUsd:u().nonnegative().nullable()}).strict(),managedRunId:je.nullable(),progress:c({completedSteps:u().int().nonnegative(),totalSteps:u().int().positive(),latestLoss:u().finite().nullable()}).strict(),receipt:tM.nullable(),qualificationReport:st.nullable(),accruedSpendUsd:u().nonnegative().nullable(),failureOwner:v(["authoring","admission","provider","runner","artifact","qualification","cleanup"]).nullable(),failure:r().trim().min(1).max(5e3).nullable(),startedAt:$t,completedAt:$t.nullable(),updatedAt:$t}).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."})}),aM=c({schemaVersion:_("openpond.modelRunReceipt.v1"),provider:je,providerRunId:je,assignmentHash:Ve,resultHash:Ve,transcriptHash:Ve,traceHash:Ve.nullable(),resolvedBundleHash:Ve,artifactPath:r().trim().min(1).max(2e3),cleanup:c({computeReleased:C(),tunnelClosed:C()}).strict(),telemetry:YE.nullable().default(null),contentHash:Ve}).strict(),Sr=c({inputTokens:u().int().nonnegative(),outputTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative(),costUsd:u().nonnegative().nullable()}).strict(),bh=r().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),dp=c({phase:v(["baseline","adaptation","candidate_adaptation","candidate"]),taskId:je,attemptId:je,sessionId:je.nullable(),turnId:je.nullable(),passed:C(),score:u().min(0).max(1).nullable(),failureClass:K0.nullable(),inputTokens:u().int().nonnegative(),outputTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative(),latencyMs:u().int().nonnegative(),costUsd:u().nonnegative().nullable(),startedAt:$t}).strict(),vh=c({targetTaskCount:u().int().nonnegative(),comparedTaskCount:u().int().nonnegative(),passedTaskCount:u().int().nonnegative(),failedTaskCount:u().int().nonnegative(),lowerTaskCount:u().int().nonnegative(),higherTaskCount:u().int().nonnegative(),unchangedTaskCount:u().int().nonnegative()}).strict(),oy=c({target:_("all_tasks_lower"),targetTaskCount:u().int().nonnegative(),comparedTaskCount:u().int().nonnegative(),passedTaskCount:u().int().nonnegative(),failedTaskCount:u().int().nonnegative(),lowerTaskCount:u().int().nonnegative(),higherTaskCount:u().int().nonnegative(),unchangedTaskCount:u().int().nonnegative(),baselineTokens:u().int().nonnegative(),refinedTokens:u().int().nonnegative(),tokenDelta:u().int(),tokenDeltaPercent:u().finite().nullable(),complete:C(),passed:C(),cohorts:c({adaptation:vh,heldOut:vh}).strict()}).strict(),up=c({baseline:Sr,adaptation:Sr,candidateAdaptation:Sr,candidate:Sr,refiner:Sr,grader:Sr}).strict(),oM=c({usage:up,observedSpendUsd:u().nonnegative(),attempts:h(dp).max(1e4)}).strict(),rM=c({id:je,contentHash:Ve,artifactPath:r().trim().min(1).max(2e3)}).strict(),iM=c({schemaVersion:_("openpond.modelEvaluationReceipt.v1"),benchmarkId:je,resultManifest:c({id:je,contentHash:Ve,artifactPath:r().trim().min(1).max(2e3)}).strict(),stages:c({baseline:st,adaptation:st,refiner:st,candidateAdaptation:st,candidate:st,comparison:st}).strict(),usage:up,quality:c({baselinePassRate:u().min(0).max(1),candidatePassRate:u().min(0).max(1),adaptationBaselinePassRate:u().min(0).max(1),adaptationCandidatePassRate:u().min(0).max(1),adaptationCandidatePassed:C(),heldOutCandidatePassed:C(),passed:C()}).strict(),foregroundTokenDelta:u().int(),foregroundTokenDeltaPercent:u().finite().nullable(),taskEfficiency:oy.optional(),efficiency:c({grossForegroundTokenSavings:u().int(),overheadTokens:u().int().nonnegative(),firstPassNetTokenSavings:u().int(),breakEvenReuseCount:u().int().nonnegative().nullable(),amortizedTokenSavings:u().int(),amortizedReuseCount:u().int().positive()}).strict(),budget:c({maximumSpendUsd:u().nonnegative(),observedSpendUsd:u().nonnegative(),enforced:C()}).strict(),evidenceSnapshot:st,lineage:c({adaptationEvidenceHash:Ve,refinerInputHash:Ve,refinerOutcomeHash:Ve,validationHash:Ve,applyReceiptHash:Ve,candidateRelease:st,valid:C()}).strict(),invalidReasons:h(r().trim().min(1).max(2e3)).max(100),attempts:h(dp).max(1e4).default([]),terminalClassification:v(["improved","no_improvement","regressed","inconclusive","cancelled","infrastructure_failure"]),profileGit:c({ref:r().trim().min(1).max(2e3),commit:bh,baseCommit:bh}).strict().nullable(),contentHash:Ve}).strict(),sM=c({schemaVersion:_("openpond.modelEvaluationStopReceipt.v1"),benchmarkId:je,terminalClassification:_("inconclusive"),stopReason:v(["candidate_harness_unchanged","candidate_lineage_invalid"]),reason:r().trim().min(1).max(5e3),stoppedAfter:_("refiner"),baselineHarness:st,candidateHarness:st,refiner:c({id:je,contentHash:Ve,outcomeCount:u().int().nonnegative()}).strict(),usage:up,budget:c({maximumSpendUsd:u().nonnegative(),observedSpendUsd:u().nonnegative(),enforced:C()}).strict(),evidenceSnapshot:st,attempts:h(dp).max(1e4),contentHash:Ve}).strict(),lM=c({benchmarkId:je,model:sn,upstreamModel:c({providerId:je,modelId:r().trim().min(1).max(300),revision:r().trim().min(1).max(300),pricing:c({version:r().trim().min(1).max(300),source:r().trim().min(1).max(300),effectiveAt:$t,inputUsdPerMillionTokens:u().nonnegative(),cachedInputUsdPerMillionTokens:u().nonnegative(),outputUsdPerMillionTokens:u().nonnegative()}).strict().optional()}).strict(),reasoningEffort:r().trim().min(1).max(100).nullable(),seeds:h(u().int()).min(1).max(100),repetitions:u().int().positive().max(20),maximumSpendUsd:u().nonnegative(),attemptPlan:h(c({stage:v(["baseline","adaptation","candidate_adaptation","candidate"]),split:r().trim().min(1).max(100),taskIds:h(je).min(1).max(1e5),attemptCount:u().int().positive()}).strict()).length(4)}).strict(),cM=c({schemaVersion:_("openpond.modelRun.v1"),id:je,modelId:je,modelVersionId:je,profileId:je,kind:v(["rollout_smoke","training","evaluation"]),status:v(["prepared","running","succeeded","failed","cancelled"]),method:v(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]).nullable(),destinationId:je.nullable(),taskset:Ho,harnessRelease:st.nullable().optional(),quote:c({maximumSpendUsd:u().nonnegative(),hourlyCostUsd:u().nonnegative().nullable()}).strict().nullable(),evaluation:lM.nullable().default(null),evaluationProgress:c({stage:v(["baseline","adaptation","refiner","candidate_adaptation","candidate","comparison"]),completedAttempts:u().int().nonnegative(),totalAttempts:u().int().positive(),accounting:oM.nullable().default(null),evidenceSnapshot:rM.nullable().default(null)}).strict().nullable().default(null),reward:c({raw:u(),components:ve(r(),u())}).strict().nullable(),receipt:vn([aM,iM,sM]).nullable(),adapterArtifactLineageId:je.nullable(),failure:r().trim().min(1).max(5e3).nullable(),startedAt:$t,completedAt:$t.nullable(),updatedAt:$t}).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 f3(e){const t=new Map;for(const R of e.attempts){const A=`${R.phase}\0${R.taskId}`,$=t.get(A);(!$||R.startedAt>$.startedAt||R.startedAt===$.startedAt&&R.attemptId>$.attemptId)&&t.set(A,R)}const n=[...t.values()],a=[["adaptation","adaptation","candidate_adaptation"],["held_out","baseline","candidate"]].flatMap(([R,A,$])=>{const z=new Map(n.filter(D=>D.phase===$).map(D=>[D.taskId,D]));return n.filter(D=>D.phase===A).flatMap(D=>{const x=z.get(D.taskId);return x?[{cohort:R,taskId:D.taskId,baseline:D,refined:x,tokenDelta:x.totalTokens-D.totalTokens}]:[]})}),o=new Set(n.filter(R=>R.phase==="baseline"||R.phase==="adaptation").map(R=>R.taskId)).size,i=e.targetTaskCount??o;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($=>$.tokenDelta<0).length,failedTaskCount:R.filter($=>$.tokenDelta>=0).length,lowerTaskCount:R.filter($=>$.tokenDelta<0).length,higherTaskCount:R.filter($=>$.tokenDelta>0).length,unchangedTaskCount:R.filter($=>$.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:oy.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 $a=r().trim().min(1).max(240),ka=r().trim().min(8).max(256),ry=v(["grpo","dapo","gspo-token"]),as=c({id:$a,revision:r().trim().min(1).max(256),tokenizerRevision:r().trim().min(1).max(256),chatTemplateHash:ka}),dM=c({maxRollouts:u().int().positive().max(1e6),maxEnvironmentExecutions:u().int().positive().max(1e6),maxInputTokens:u().int().positive(),maxOutputTokens:u().int().positive(),maxOptimizerSteps:u().int().positive().max(1e6),wallTimeMs:u().int().positive(),maximumCostUsd:u().nonnegative().nullable()}),uM=c({method:_("grpo"),groupSize:u().int().min(2).max(128),normalization:_("group_standardized"),loss:ry}),iy=c({method:_("ppo"),valueModel:as,gamma:u().min(0).max(1),gaeLambda:u().min(0).max(1),policyClip:u().positive().max(1),valueClip:u().positive().max(10),valueLossCoefficient:u().nonnegative().max(10),ppoEpochs:u().int().positive().max(100),minibatchSize:u().int().positive().max(1e5)}),mM=fn("method",[uM,iy]),sy=c({rewardModelVersion:c({id:$a,contentHash:ka}).strict(),qualificationReport:c({id:$a,contentHash:ka}).strict(),checkpoint:c({id:$a,contentHash:ka,objectRef:r().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/),files:h(c({path:r().trim().min(1).max(512),sizeBytes:u().int().positive(),sha256:ka}).strict()).min(4).max(128)}).strict(),runtime:ay,processorRelease:c({id:$a,contentHash:ka}).strict(),rewardComposerRelease:c({id:$a,contentHash:ka}).strict(),qualificationKind:v(["synthetic_smoke","human_heldout"])}).strict(),ly=c({schemaVersion:_("openpond.policyOptimization.v1"),policyModel:as,referenceModel:as,dataset:c({tasksetId:$a,tasksetHash:ka,split:_("train"),selectionStrategy:v(["stable_hash_top_n","rft_easy_curriculum_v1"]),selectionSeed:u().int(),maxExamples:u().int().positive().max(1e5)}),sampler:c({temperature:u().min(0).max(2),topP:u().min(0).max(1),maxOutputTokens:u().int().positive().max(32768),maxTurns:u().int().positive().max(1e3),concurrency:u().int().positive().max(1e3)}),environment:c({id:$a,version:r().trim().min(1).max(256),toolContractHash:ka}),reward:c({graderId:$a,graderHash:ka,learnedPreference:sy.nullable().default(null)}),kl:c({coefficient:u().nonnegative().nullable(),referenceConstraint:_("fixed_reference")}),budgets:dM,checkpointEverySteps:u().int().positive(),seed:u().int(),evaluationSplit:_("frozen_eval"),optimizer:mM}),ke=r().trim().min(1).max(240),ht=r().trim().min(1),dt=r().trim().min(8).max(256),ks=ve(r(),Re()).default({}),cy=c({schemaVersion:_("openpond.localModelChatConfiguration.v1").default("openpond.localModelChatConfiguration.v1"),profile:v(["efficient","full_harness","custom"]).default("efficient"),systemPromptMode:v(["lean","full_harness","custom"]).default("lean"),customSystemPrompt:r().max(2e4).nullable().default(null),contextWindowTokens:u().int().min(128).max(32768).default(1024),maxOutputTokens:u().int().min(1).max(512).default(64),temperature:u().min(0).max(2).default(0),repetitionPenalty:u().min(.5).max(2).default(1.1),noRepeatNgramSize:u().int().min(0).max(10).default(3),compaction:v(["off","when_needed"]).default("when_needed"),keepWarmSeconds:u().int().min(0).max(3600).default(300),updatedAt:ht.nullable().default(null)}),pM=cy.parse({}),fM=c({schemaVersion:_("openpond.managedAdapterServingProjection.v1"),teamId:ke.nullable().default(null),source:_("sandbox_managed_rl"),sourceRef:ke,canonicalArtifactId:ke.nullable(),canonicalArtifactState:v(["imported_unvalidated","evaluating","promotable","rejected","deleted"]).nullable(),canonicalDeploymentId:ke.nullable(),canonicalDeploymentState:v(["requested","deploying","ready","degraded","deleting","deleted","failed"]).nullable(),state:v(["pending","imported","ready","failed"]),customerBindingAllowed:C().default(!1),artifactContentHash:dt.nullable().default(null),baseProfileId:ke.nullable().default(null),publishedAt:ht.nullable(),lastSyncedAt:ht,lastError:r().trim().min(1).max(5e3).nullable()});function h3(e){const t=e.managedServing;return!!(t?.source==="sandbox_managed_rl"&&t.canonicalArtifactState==="promotable"&&t.customerBindingAllowed)}function dy(e){return e.state==="ready"&&e.canonicalArtifactState==="promotable"&&e.canonicalDeploymentState==="ready"&&e.customerBindingAllowed&&!!e.teamId&&!!e.canonicalArtifactId&&!!e.canonicalDeploymentId}function g3(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"&&dy(t)&&t.canonicalArtifactId&&t.canonicalDeploymentId?{kind:"sandbox_customer_binding",evaluationArtifactId:null,canonicalArtifactId:t.canonicalArtifactId,canonicalDeploymentId:t.canonicalDeploymentId}:null}function b3(e){const t=e.managedServing;return t?dy(t)&&t.canonicalArtifactId&&t.canonicalDeploymentId?{kind:"sandbox_serving",canonicalArtifactId:t.canonicalArtifactId,canonicalDeploymentId:t.canonicalDeploymentId}:null:{kind:"source_artifact",canonicalArtifactId:null,canonicalDeploymentId:null}}const mp="openpond.crossSystemOperations.v1",v3="1.0.0",uy="openpond.crossSystemTools.v1",hM=["search_crm","query_billing","search_support","run_python"],gM=v(["train","validation","frozen_eval"]),bM=v(["easy","medium","hard"]),vM=v(["renewal_risk_v2"]);v(["renewal_exposure","collections_prioritization","invoice_reconciliation","sla_escalation","contract_billing_mismatch"]);c({seed:u().int().nonnegative(),split:gM,difficulty:bM,scenarioProfile:vM.optional()});const Jd={anyOf:[{type:"string",minLength:1,maxLength:256},{type:"null"}],default:null},Yd={type:"integer",minimum:1,maximum:50,default:25},my=[{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:Jd,limit:Yd}}},{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:Jd,limit:Yd}}},{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:Jd,limit:Yd}}},{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}}}}],ws=PM({schemaVersion:uy,tools:my}),yM=[`Use only the four registered synthetic Cross-System Operations tools. Contract ${ws}.`,"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(" "),SM=15;function xM(e="auto"){return[yM,"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: ${SM}.`,`Registered tool signatures: ${my.map(kM).join("; ")}`].join(`
125
- `)}xM();function kM(e){const t=Rl(e.parameters),n=Rl(t.properties),a=py(t.required),o=Object.fromEntries(a.map(i=>[i,hl(n[i])]));return`${e.name}(${JSON.stringify(o)})`}function hl(e){const t=Rl(e),n=Wu(t.anyOf);if(n.length)return n.map(hl).join("|");const a=Wu(t.enum);if(a.length)return a.join("|");if(t.type==="array")return[hl(t.items)];if(t.type==="object"){const o=Rl(t.properties),i=py(t.required);return Object.fromEntries(i.map(s=>[s,hl(o[s])]))}return typeof t.type=="string"?t.type:"unknown"}function Rl(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Wu(e){return Array.isArray(e)?e:[]}function py(e){return Wu(e).filter(t=>typeof t=="string")}const Al=v(hM),wM=fn("kind",[c({kind:_("model"),turn:u().int().nonnegative(),content:r().max(1e5)}),c({kind:_("tool_call"),turn:u().int().nonnegative(),callId:r().trim().min(1).max(240),name:Al,arguments:ve(r(),Re())}),c({kind:_("tool_result"),turn:u().int().nonnegative(),callId:r().trim().min(1).max(240),name:Al,ok:C(),result:Re(),rows:u().int().nonnegative(),bytes:u().int().nonnegative(),durationMs:u().int().nonnegative(),error:r().trim().min(1).max(2e4).nullable()}),c({kind:_("final"),turn:u().int().nonnegative(),content:r().max(1e5)})]),_M=c({schemaVersion:_(mp),id:r().trim().min(1).max(240),worldId:r().trim().min(1).max(240),taskId:r().trim().min(1).max(240),toolContractHash:_(ws),modelRef:c({providerId:r().trim().min(1),modelId:r().trim().min(1)}).nullable(),status:v(["completed","budget_exhausted","cancelled","infrastructure_failure"]),steps:h(wM).max(1e3),startedAt:r().trim().min(1),completedAt:r().trim().min(1),infrastructureError:r().trim().min(1).max(2e4).nullable(),metadata:ve(r(),Re()).default({})}),IM=c({schemaVersion:_(mp),trajectoryId:r().trim().min(1).max(240),outcome:v(["correct","incorrect","parse_failure","budget_exhausted","tool_schema_violation","infrastructure_failure","cancelled"]),reward:u().min(0).max(1.15).nullable(),rewardEligible:C(),exactAnswer:C(),components:c({exactAnswer:u().min(0).max(1),efficiency:u().min(0).max(.1),conciseOutput:u().min(0).max(.05)}),metrics:c({toolCalls:u().int().nonnegative(),rowsRead:u().int().nonnegative(),bytesRead:u().int().nonnegative(),consecutiveRetrievalCalls:u().int().nonnegative(),wallTimeMs:u().int().nonnegative(),parseFailures:u().int().nonnegative(),budgetExhausted:C()}),parsedAnswer:Re().nullable(),feedback:h(r().trim().min(1).max(5e3)).max(100)}),CM=c({id:r().trim().min(1).max(240),type:_("function"),function:c({name:Al,arguments:r().max(2e4)})}),fy=c({role:v(["system","user","assistant","tool"]),content:r().max(2e5).nullable(),tool_call_id:r().trim().min(1).max(240).optional(),tool_calls:h(CM).max(4).optional()});c({schemaVersion:_(mp),id:r().trim().min(1).max(240),taskId:r().trim().min(1).max(240),worldId:r().trim().min(1).max(240),trajectoryId:r().trim().min(1).max(240),toolContractHash:_(ws),approval:c({status:_("approved"),approvedBy:r().trim().min(1).max(240),approvedAt:r().trim().min(1)}),messages:h(fy).min(3).max(1e3)});const RM=c({tasksetTaskId:r().trim().min(1).max(240),environmentTaskId:r().trim().min(1).max(240),family:v(["renewal_exposure","collections_prioritization","invoice_reconciliation","sla_escalation","contract_billing_mismatch"]),prompt:r().trim().min(1).max(1e5),finalAnswer:r().trim().min(1).max(2e5),trajectoryId:r().trim().min(1).max(240),trajectoryHash:r().trim().min(8).max(256),toolNames:h(Al).min(1).max(100),toolCallCount:u().int().positive(),messageCount:u().int().min(3),reward:u().min(0).max(1.15),messages:h(fy).min(3).max(1e3)}),AM=c({status:_("approved"),approvedBy:r().trim().min(1).max(240),approvedAt:r().trim().min(1),previewHash:r().trim().min(8).max(256),trajectoryCount:u().int().positive()});c({schemaVersion:_("openpond.crossSystemExpertBootstrapPreview.v1"),tasksetId:r().trim().min(1).max(240),tasksetHash:r().trim().min(8).max(256),tasksetRevision:u().int().positive(),previewHash:r().trim().min(8).max(256),toolContractHash:_(ws),status:v(["ready_for_review","approved"]),approval:AM.nullable(),tasks:h(RM).min(1).max(100)});function PM(e){const t=Ku(e);let n=2166136261,a=2654435769;for(let o=0;o<t.length;o+=1){const i=t.charCodeAt(o);n=Math.imul(n^i,16777619),a=Math.imul(a^i,2246822507)}return`${uy}:${yh(n)}${yh(a)}`}function Ku(e){return Array.isArray(e)?`[${e.map(Ku).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${Ku(n)}`).join(",")}}`:JSON.stringify(e)}function yh(e){return(e>>>0).toString(16).padStart(8,"0")}const TM=c({schemaVersion:_("openpond.singleTurnPolicyTrajectory.v1"),id:ke,taskId:ke,status:v(["completed","infrastructure_failure"]),promptHash:dt,responseText:r().max(2e6),infrastructureError:r().trim().min(1).max(1e4).nullable(),startedAt:ht,completedAt:ht,metadata:ks}),EM=c({schemaVersion:_("openpond.ppoTrajectory.v1"),id:ke,taskId:ke,policyModelId:ke,referenceModelId:ke,valueModelId:ke,steps:h(c({index:u().int().nonnegative(),observationHash:dt,actionTokenIds:h(u().int().nonnegative()).min(1),terminated:C(),truncated:C(),reward:u(),policyLogProbability:u(),referenceLogProbability:u(),valuePrediction:u(),return:u(),advantage:u(),mask:u().min(0).max(1)})).min(1).max(1e5),createdAt:ht}),MM=c({schemaVersion:_("openpond.exactAnswerVerifierResult.v1"),outcome:v(["correct","incorrect","parse_failure","infrastructure_failure"]),graderSetHash:dt,score:u().min(0).max(1).nullable(),passed:C(),rewardEligible:C(),expectedAnswerHash:dt,extractedAnswer:r().max(2e4).nullable(),feedback:h(r().trim().min(1).max(2e4)).max(1e3)}),jM=c({schemaVersion:_("openpond.rolloutTrajectoryReceipt.v1"),id:ke,jobId:ke,planId:ke,tasksetId:ke,tasksetHash:dt,taskId:ke,split:_("train"),correlationId:ke,provider:ke,providerTrace:c({invocationId:ke,experimentId:ke,rolloutId:ke,runId:ke,rowId:ke}),optimizerMethod:v(["grpo","ppo"]).default("grpo"),evidenceLevels:c({requested:v(["trajectory","aggregate","provider_reported"]),observed:v(["trajectory","aggregate","provider_reported"]),providerReported:v(["trajectory","aggregate","provider_reported"])}).default({requested:"trajectory",observed:"trajectory",providerReported:"provider_reported"}),budgetUsage:c({rollouts:u().int().nonnegative(),environmentExecutions:u().int().nonnegative(),inputTokens:u().int().nonnegative(),outputTokens:u().int().nonnegative(),optimizerSteps:u().int().nonnegative(),costUsd:u().nonnegative()}).default({rollouts:0,environmentExecutions:0,inputTokens:0,outputTokens:0,optimizerSteps:0,costUsd:0}),environment:c({id:ke,version:r().trim().min(1).max(256),worldId:ke,worldHash:dt,toolContractHash:dt}),policy:c({modelId:ke,checkpointId:ke.nullable(),completionParametersHash:dt}),status:v(["received","running","succeeded","failed"]),failureClass:v(["policy_failure","parse_failure","tool_schema_violation","budget_exhausted","cancelled","environment_failure","infrastructure_failure"]).nullable(),reward:c({eligible:C(),raw:u().min(0).max(1.15).nullable(),normalized:u().min(0).max(1).nullable(),components:ve(r(),u())}),trajectory:vn([_M,TM,EM]).nullable(),verifier:vn([IM,MM]).nullable(),providerStatus:ve(r(),Re()).default({}),receivedAt:ht,startedAt:ht.nullable(),completedAt:ht.nullable(),updatedAt:ht}),y3="dataset-exact-answer",S3="dataset-exact-answer-v1",x3="no-tools-v1",co=v(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),nc=v(["lora","full"]),Va=v(["openpond_managed"]),OM=c({schemaVersion:_("openpond.sftRecipe.v1"),method:_("sft"),parameterization:_("lora"),baseModel:c({id:ke,revision:r().trim().min(1).max(256),tokenizerRevision:r().trim().min(1).max(256),chatTemplateHash:dt}),dataset:c({trainSplit:_("train"),validationSplit:v(["validation","frozen_eval"]),completionOnly:C(),maxSequenceLength:u().int().positive().max(32768),maxExamples:u().int().positive().max(1e5).default(1e3),selectionStrategy:_("stable_hash_top_n").default("stable_hash_top_n"),selectionSeed:u().int().default(17)}),lora:c({rank:u().int().positive().max(256),alpha:u().positive().max(1024),dropout:u().min(0).max(1),targetModules:h(ke).min(1).max(100)}),optimizer:c({learningRate:u().positive(),epochs:u().positive().max(100),maxSteps:u().int().positive().max(1e6),batchSize:u().int().positive().max(1e4),gradientAccumulationSteps:u().int().positive().max(1e4),seed:u().int()}),resourceLimits:c({cpuThreads:u().int().positive().max(256),memoryBytes:u().int().positive(),wallTimeMs:u().int().positive()})});c({id:ke,input:ve(r(),Re()),expectedOutput:ve(r(),Re()),tags:h(ke).max(100).default([])});c({id:ke,prompt:r().min(1).max(5e5),chosen:r().min(1).max(5e5),rejected:r().min(1).max(5e5),sourceRefs:h(ke).min(1).max(1e4)});c({id:ke,input:ve(r(),Re()),tags:h(ke).max(100).default([])});c({schemaVersion:_("openpond.rewardModelRecipe.v1"),method:_("reward_model"),parameterization:_("lora_with_scalar_head"),runScope:v(["synthetic_smoke","human_preference"]),baseModel:c({id:ke,revision:r().trim().min(1).max(256),tokenizerRevision:r().trim().min(1).max(256),processorRevision:r().trim().min(1).max(256),chatTemplateHash:dt}).strict(),tasksetRelease:st,preferenceDatasetRelease:st,processorRelease:st,input:c({kind:_("structured_text"),serialization:_("scenario_input_and_candidate_json_v1"),maxCharacters:u().int().positive().max(5e5)}).strict().default({kind:"structured_text",serialization:"scenario_input_and_candidate_json_v1",maxCharacters:32e3}),lora:c({rank:u().int().positive().max(256),alpha:u().positive().max(1024),dropout:u().min(0).max(1),targetModules:h(ke).min(1).max(100)}).strict(),heads:c({scalar:_("pooled_hidden_state_linear"),bucket:v(["none","three_class"]).default("three_class")}).strict(),loss:c({ranking:_("bradley_terry"),rankingWeight:u().positive(),bucketWeight:u().nonnegative(),tieWeight:u().nonnegative()}).strict(),optimizer:c({learningRate:u().positive(),maxSteps:u().int().positive().max(1e5),batchSize:u().int().positive().max(1e4),gradientAccumulationSteps:u().int().positive().max(1e4),seed:u().int(),checkpointEverySteps:u().int().positive().max(1e5)}).strict(),resourceLimits:c({wallTimeMs:u().int().positive().max(1440*60*1e3),maxExamples:u().int().positive().max(1e5),maxInputCharacters:u().int().positive().max(5e5).default(32e3),maxImagePixels:u().int().positive().max(1e8).optional(),maximumSpendUsd:u().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 NM=c({schemaVersion:_("openpond.rftRecipe.v1"),method:_("grpo"),parameterization:_("lora"),baseModel:c({id:ke,revision:r().trim().min(1).max(256),tokenizerRevision:r().trim().min(1).max(256),chatTemplateHash:dt}),dataset:c({trainSplit:_("train"),validationSplit:v(["validation","frozen_eval"]),maxPromptTokens:u().int().positive().max(32768),maxExamples:u().int().positive().max(1e5).default(1e3),selectionStrategy:v(["stable_hash_top_n","rft_easy_curriculum_v1"]).default("stable_hash_top_n")}),lora:c({rank:u().int().positive().max(256)}),rollout:c({groupSize:u().int().min(2).max(64),concurrency:u().int().positive().max(32),maxTurns:u().int().positive().max(100),maxOutputTokens:u().int().positive().max(8192),temperature:u().min(0).max(2),topP:u().positive().max(1),seed:u().int()}),optimizer:c({learningRate:u().positive(),maxSteps:u().int().positive().max(1e5)}),loss:c({method:ry.default("grpo"),klBeta:u().min(0).nullable().default(null)}).default({method:"grpo",klBeta:null}),reward:c({graderId:ke,graderHash:dt,environmentId:ke,environmentVersion:r().trim().min(1).max(256),toolContractHash:dt,learnedPreference:sy.nullable().optional()}),resourceLimits:c({wallTimeMs:u().int().positive().max(1440*60*1e3),maxRollouts:u().int().positive().max(1e5),maxPayloadBytes:u().int().positive().max(10*1024*1024)}),policyOptimization:ly.nullable().default(null)}),$M=c({schemaVersion:_("openpond.dpoRecipe.v1"),method:_("dpo"),parameterization:_("lora"),policyModel:as,referenceModel:as,dataset:c({trainSplit:_("train"),validationSplit:v(["validation","frozen_eval"]),maxPairs:u().int().positive().max(1e5),maxPromptTokens:u().int().positive().max(32768),maxCompletionTokens:u().int().positive().max(32768),selectionStrategy:_("stable_hash_top_n"),selectionSeed:u().int()}),lora:c({rank:u().int().positive().max(256),alpha:u().positive().max(1024),dropout:u().min(0).max(1),targetModules:h(ke).min(1).max(100)}),loss:c({variant:_("sigmoid"),beta:u().positive().max(10),labelSmoothing:u().min(0).max(.5).default(0)}),optimizer:c({learningRate:u().positive(),epochs:u().positive().max(100),maxSteps:u().int().positive().max(1e6),batchSize:u().int().positive().max(1e4),gradientAccumulationSteps:u().int().positive().max(1e4),seed:u().int()}),referenceLogprobs:c({cacheSchemaVersion:_("openpond.dpoReferenceLogprobs.v1"),cacheKey:dt,invalidationHash:dt}),resourceLimits:c({cpuThreads:u().int().positive().max(256),memoryBytes:u().int().positive(),wallTimeMs:u().int().positive()})}),DM=c({schemaVersion:_("openpond.ppoRecipe.v1"),method:_("ppo"),parameterization:_("lora"),policyOptimization:ly.extend({optimizer:iy}),lora:c({rank:u().int().positive().max(256),alpha:u().positive().max(1024),dropout:u().min(0).max(1),targetModules:h(ke).min(1).max(100)}),valueHead:c({initialization:_("policy_hidden_state_linear"),optimizerLearningRate:u().positive(),artifactName:_("value_head.safetensors")}),policyLearningRate:u().positive(),resume:c({checkpointId:ke.nullable(),policyHash:dt,referenceHash:dt,valueModelHash:dt,optimizerStateHash:dt.nullable()}),resourceLimits:c({cpuThreads:u().int().positive().max(256),memoryBytes:u().int().positive(),wallTimeMs:u().int().positive()})}),LM=c({schemaVersion:_("openpond.unsupportedRecipe.v1"),method:co.exclude(["sft","dpo","grpo","ppo"]),parameterization:nc,unsupportedReason:r().trim().min(1).max(5e3)}),pp=vn([OM,$M,NM,DM,LM]),zM=c({schemaVersion:_("openpond.trainingDestinationCapabilities.v1"),destinationId:Va,available:C(),methods:h(co),parameterizations:h(nc),modelAllowlist:h(ke).default([]),maxDatasetBytes:u().int().nonnegative().nullable(),environmentPlacements:h(v(["none","local","remote","colocated","provider_native"])),nonProduction:C(),unavailableReason:r().trim().min(1).max(5e3).nullable(),checkedAt:ht}),UM=c({destinationId:Va,available:C(),methods:h(co),parameterizations:h(nc),nonProduction:C(),unavailableReason:r().trim().min(1).max(5e3).nullable()}),HM=c({schemaVersion:_("openpond.baseModelCandidate.v1"),selectionKey:ke,label:r().trim().min(1).max(500),sourceLabel:r().trim().min(1).max(500),preference:ei,available:C(),nonProduction:C(),unavailableReason:r().trim().min(1).max(5e3).nullable(),methods:h(co),executionOptions:h(UM).min(1)}),qM=c({code:ke,severity:v(["warning","error"]),path:r().trim().max(2e3).nullable(),message:r().trim().min(1).max(5e3)}),BM=c({schemaVersion:_("openpond.trainingCompatibility.v1"),compatible:C(),destinationId:Va,tasksetId:ke,recipeMethod:co,issues:h(qM),checkedAt:ht}),FM=vn([J0,v(["destination_unavailable","destination_method_unsupported","destination_model_unsupported","destination_parameterization_unsupported","experimental_destination"])]);c({method:co,state:v(["recommended","compatible","needs_dataset_work","destination_unavailable","experimental_destination"]),reasonCodes:h(FM).default([]),reasons:h(r().trim().min(1).max(5e3)).default([]),destinationId:Va.nullable().default(null)});const VM=v(["small","standard","custom","small_experiment"]),WM=c({schemaVersion:_("openpond.modelProject.v1"),id:ke,profileId:ke,revision:u().int().positive().default(1),name:r().trim().min(1).max(200),objective:r().trim().max(5e3).nullable(),defaultBaseModel:ei.nullable(),defaultDestinationId:Va.nullable(),hosted:c({schemaVersion:_("openpond.hostedModelProjectLink.v1"),teamId:ke,projectId:ke,portableProjectId:ke,revision:u().int().positive(),etag:dt,syncedSourceRevision:u().int().positive(),syncedAt:ht,tasksets:h(c({localTasksetId:ke,releaseId:ke,releaseRevision:u().int().positive(),releaseHash:dt,hostedTasksetId:ke,syncedAt:ht}).strict()).max(1e4).default([])}).strict().nullable().default(null),tasksetSyncs:h(c({localTasksetId:ke,releaseId:ke,releaseRevision:u().int().positive(),releaseHash:dt,state:v(["syncing","synced","sync_failed"]),hostedTasksetId:ke.nullable().default(null),lastAttemptAt:ht,syncedAt:ht.nullable().default(null),lastError:r().trim().min(1).max(5e3).nullable().default(null)}).strict()).max(1e4).default([]),createdAt:ht,updatedAt:ht}),KM=c({schemaVersion:_("openpond.modelRunDraft.v1"),id:ke,profileId:ke,modelId:ke,status:v(["draft","ready_to_run","launched","cancelled"]),title:r().trim().min(1).max(200),datasetMode:v(["existing","build"]).nullable(),tasksetRef:c({id:ke,revision:u().int().positive(),contentHash:dt}).nullable(),harnessRelease:st.nullable().optional(),tasksetRelease:st.nullable().optional(),datasetCreationId:ke.nullable(),buildIntent:op.nullable(),buildSpecification:rp.nullable(),baseModel:ei.nullable(),method:co.nullable(),destinationId:Va.nullable(),managedRolloutPlacement:v(["local","remote"]).optional(),runPreset:VM.nullable(),recipe:pp.nullable(),createdAt:ht,updatedAt:ht}),hy=c({schemaVersion:_("openpond.trainingPlan.v1"),id:ke,modelId:ke,tasksetId:ke,tasksetHash:dt,harnessRelease:st.nullable().optional(),modelImprovementQualification:st.nullable().optional(),destinationId:Va,recipe:pp,environmentPlacement:v(["none","local","remote","colocated","provider_native"]),compatibility:BM,dataPolicy:c({exportApproved:C(),approvedSourceIds:h(ke),retentionDays:u().int().nonnegative().nullable(),region:r().trim().min(1).max(200).nullable()}),estimatedCostUsd:u().nonnegative().nullable(),createdAt:ht,contentHash:dt}),GM=c({path:r().trim().min(1).max(2e3),sha256:dt,sizeBytes:u().int().nonnegative(),role:v(["manifest","task_data","grader","environment","recipe","policy","provenance"])}),fp=c({schemaVersion:_("openpond.trainingBundle.v1"),id:ke,planId:ke,tasksetId:ke,tasksetHash:dt,recipeHash:dt,files:h(GM).min(1).max(1e6),totalSizeBytes:u().int().nonnegative(),sourceIds:h(ke),excludedSourceIds:h(ke),containsRawChats:_(!1),containsSecrets:_(!1),containsHiddenGraderAssets:_(!1),createdAt:ht,contentHash:dt});c({schemaVersion:_("openpond.trainingBundleExport.v1"),manifest:fp,files:h(c({path:r().trim().min(1).max(2e3),sha256:dt,sizeBytes:u().int().nonnegative(),encoding:_("base64"),content:r()})).min(1),contentHash:dt});c({schemaVersion:_("openpond.trainingPreparedStart.v1"),plan:hy,bundle:fp,approvalActor:ke.nullable(),preparedAt:ht});c({schemaVersion:_("openpond.trainingApproval.v1"),id:ke,planId:ke,bundleHash:dt,harnessRelease:st.nullable().optional(),modelImprovementQualification:st.nullable().optional(),destinationId:Va,modelId:ke,method:co,parameterization:nc,maximumCostUsd:u().nonnegative().nullable(),approvedBy:ke,approvedAt:ht});const ZM=v(["queued","starting","running","cancelling","cancelled","succeeded","failed","reconciling"]),gy=c({schemaVersion:_("openpond.trainingJob.v1"),id:ke,planId:ke,bundleHash:dt,approvalId:ke,destinationId:Va,status:ZM,nonProduction:C(),workerPid:u().int().positive().nullable(),startedAt:ht.nullable(),completedAt:ht.nullable(),error:r().trim().min(1).max(2e4).nullable(),createdAt:ht,updatedAt:ht,metadata:ks}),JM=c({schemaVersion:_("openpond.trainingJobEvent.v1"),id:ke,jobId:ke,sequence:u().int().nonnegative(),type:v(["queued","start","progress","metric","checkpoint","cancel","complete","failure","reconcile"]),timestamp:ht,payload:ks}),YM=c({schemaVersion:_("openpond.sftStepMetric.v1"),step:u().int().nonnegative(),maxSteps:u().int().positive(),timestamp:ht,epoch:u().nonnegative().nullable(),loss:u().nullable(),learningRate:u().nonnegative().nullable(),gradientNorm:u().nonnegative().nullable(),entropy:u().nonnegative().nullable(),meanTokenAccuracy:u().min(0).max(1).nullable(),preferenceAccuracy:u().min(0).max(1).nullable().default(null),preferenceMargin:u().nullable().default(null),chosenReward:u().nullable().default(null),rejectedReward:u().nullable().default(null),chosenLogProbability:u().nullable().default(null),rejectedLogProbability:u().nullable().default(null),reward:u().nullable().default(null),policyLoss:u().nullable().default(null),advantageLoss:u().nullable().default(null),inputTokensSeen:u().int().nonnegative().nullable(),memoryBytes:u().int().nonnegative().nullable(),elapsedSeconds:u().nonnegative().nullable()}),XM=c({schemaVersion:_("openpond.policyOptimizationMetric.v1"),method:v(["grpo","ppo"]),step:u().int().nonnegative(),timestamp:ht,learningRate:u().nonnegative().nullable().default(null),policyLoss:u().nullable(),valueLoss:u().nullable(),meanReward:u().nullable(),meanReturn:u().nullable(),kl:u().nullable(),entropy:u().nullable(),policyClipFraction:u().min(0).max(1).nullable(),valueClipFraction:u().min(0).max(1).nullable(),explainedVariance:u().nullable(),rolloutLearnerLag:u().int().nonnegative().nullable(),inputTokens:u().int().nonnegative(),outputTokens:u().int().nonnegative(),environmentExecutions:u().int().nonnegative(),costUsd:u().nonnegative().nullable()}),QM=c({schemaVersion:_("openpond.managedTrainingRunEvidence.v1"),provider:ke,providerRunId:ke,state:ke,progress:c({targetOptimizerSteps:u().int().nonnegative(),committedOptimizerSteps:u().int().nonnegative()}),reward:c({finalMean:u().nullable(),trajectoryCount:u().int().nonnegative(),eligibleTrajectoryCount:u().int().nonnegative()}),usage:c({inputTokens:u().int().nonnegative(),outputTokens:u().int().nonnegative(),environmentExecutions:u().int().nonnegative()}),resource:c({provider:ke,gpuType:r().trim().min(1).max(300).nullable(),gpuCount:u().int().nonnegative().nullable(),hourlyCostUsd:u().nonnegative().nullable()}),cost:c({totalUsd:u().nonnegative().nullable()}),checkpoint:c({id:ke,policyVersion:u().int().nonnegative(),sha256:dt.nullable(),sizeBytes:u().int().nonnegative().nullable()}).nullable(),evaluations:h(c({kind:v(["baseline","candidate"]),policyVersion:u().int().nonnegative(),score:u().nullable(),threshold:u().nullable(),passed:C().nullable()})),canonicalPublication:c({state:ke.nullable(),artifactId:ke.nullable()}),syncedAt:ht}),Sh=c({count:u().int().nonnegative(),scoredCount:u().int().nonnegative(),meanScore:u().min(0).max(1).nullable(),passedCount:u().int().nonnegative(),passRate:u().min(0).max(1).nullable()}),xh=c({status:v(["scored","unavailable"]),score:u().min(0).max(1).nullable(),passed:C(),rewardEligible:C(),failureClass:v(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),feedback:h(r().trim().min(1).max(2e4)).max(1e3),components:h(c({graderId:ke,score:u().min(0).max(1),passed:C(),feedback:r().trim().max(2e4).nullable()})).max(1e3)}),ej=c({taskId:ke,input:ve(r(),Re()),baseOutput:ve(r(),Re()).nullable(),trainedOutput:ve(r(),Re()).nullable(),baseGrade:xh.nullable(),trainedGrade:xh.nullable()}),tj=c({schemaVersion:_("openpond.trainingEvaluationSummary.v1"),jobId:ke,tasksetId:ke,base:Sh,trained:Sh,meanScoreDelta:u().min(-1).max(1).nullable(),examples:h(ej).max(1e6)});c({schemaVersion:_("openpond.trainingRunDetail.v1"),job:gy,events:h(JM),stepMetrics:h(YM),policyMetrics:h(XM).default([]),managedEvidence:QM.nullable().default(null),evaluation:tj.nullable(),generatedAt:ht});const nj=c({schemaVersion:_("openpond.trainingArtifact.v1"),id:ke,jobId:ke,kind:v(["adapter","checkpoint","metrics","log","manifest","evaluation"]),path:r().trim().min(1).max(4e3),sha256:dt,sizeBytes:u().int().nonnegative(),baseModelId:ke.nullable(),baseModelRevision:r().trim().min(1).max(256).nullable(),tokenizerRevision:r().trim().min(1).max(256).nullable(),chatTemplateHash:dt.nullable(),nonProduction:C(),createdAt:ht,metadata:ks}),aj=c({schemaVersion:_("openpond.modelArtifactLineage.v1"),id:ke,modelId:ke,artifactId:ke,jobId:ke,tasksetId:ke,tasksetHash:dt,graderHash:dt,planHash:dt,bundleHash:dt,recipeHash:dt,workerVersion:r().trim().min(1).max(256),trainerVersion:r().trim().min(1).max(256),importedAt:ht,frozenEvaluationArtifactId:ke.nullable(),promotable:C(),pinned:C().default(!1),status:v(["imported","rejected"]).default("imported"),rejectedAt:ht.nullable().default(null),rejectionReason:r().trim().min(1).max(5e3).nullable().default(null),chatConfiguration:cy.default(pM),managedServing:fM.nullable().default(null)}),oj=v(["chat_manual","agent","extension","authoring_optimizer"]),rj=c({schemaVersion:_("openpond.modelBinding.v1"),id:ke,profileId:ke,role:oj,roleTargetId:ke,modelArtifactLineageId:ke,tasksetId:ke,evaluationArtifactId:ke.nullable(),status:v(["active","rolled_back"]),priorBindingId:ke.nullable(),rollbackTargetBindingId:ke.nullable(),promotedBy:ke,promotedAt:ht,rolledBackAt:ht.nullable(),metadata:ks});c({schemaVersion:_("openpond.trainingActivity.v1"),profileId:ke,active:C(),activeCounts:c({jobs:u().int().nonnegative(),creations:u().int().nonnegative(),minerRuns:u().int().nonnegative(),datasetImports:u().int().nonnegative()}),revision:dt,generatedAt:ht});c({schemaVersion:_("openpond.tasksetOperationalState.v1"),tasksetId:ke,attempts:h(SE),artifacts:h(xE),grades:h(wE),generatedAt:ht});c({schemaVersion:_("openpond.trainingState.v1"),profileId:ke,sources:h(N0),creations:h(Q0),tasksetDrafts:h(UE).default([]),tasksets:h(fh),benchmarkRuns:h(xd()).default([]),benchmarkComparisons:h(xd()).default([]),datasetImports:h(GE).default([]),datasetArtifacts:h(BT).default([]),graderAuditReports:h(_E),evaluationResults:h(xd()).default([]),candidates:h(P0),minerConfig:Xl,minerRuns:h(zT).default([]),modelProjects:h(WM).default([]),modelRunDrafts:h(KM).default([]),modelVersions:h(QE).default([]),modelRuns:h(cM).default([]),rewardModelVersions:h(eM).default([]),rewardModelRuns:h(nM).default([]),modelTasksets:h(fh).default([]),plans:h(hy),bundles:h(fp),jobs:h(gy),artifacts:h(nj),models:h(aj),rolloutReceipts:h(jM).default([]),modelBindings:h(rj).default([]),destinations:h(zM),baseModelCandidates:h(HM).default([]),activityRevision:dt.optional(),generatedAt:ht});const Ha=r().trim().min(1).max(1e5),ij=v(["no_action","harness_maintenance","runtime","product","taskset","model_improvement"]),sj=v(["none","runtime_service","product_team","human_review","evaluation_system","training_system"]),by=v(["observation","trigger","route_decision","refiner_outcome","proposal","validation","apply_receipt","harness_advance","rollback","work_outcome","taskset","evaluation","training_qualification","model_candidate"]),hp=c({kind:v(["personal","team"]),id:ne}).strict(),gp=c({policy:se,state:v(["authorized","revoked","deleted","expired"]),checkedAt:Qe}).strict(),os=c({evidence:se,kind:by,sourceRef:ne,sourcePolicy:gp,occurrenceKey:Ie,occurredAt:Qe}).strict(),lj=c({evidence:se,sourcePolicy:gp.nullable(),reason:v(["outside_scope","before_watermark","duplicate","resolved","revoked","deleted","expired","sensitive","unverified","budget"])}).strict(),kh=c({cursor:Ie,throughCreatedAt:Qe}).strict(),cj=c({fingerprint:Ie,recurrenceFamily:r().trim().min(1).max(1e3),statement:Ha,candidateDisposition:v(["observe","confirm"]).optional(),independentOccurrences:u().int().positive().max(1e6),unresolvedOccurrences:u().int().positive().max(1e6)}).strict().refine(e=>e.unresolvedOccurrences<=e.independentOccurrences,"unresolved occurrences cannot exceed independent occurrences"),vy=v(["harness","runtime","product","retrieval","tools","evaluation","model"]),dj=c({layer:vy,status:v(["not_applicable","unresolved","resolved","blocked"]),reason:Ha,evidenceRefs:h(se).max(1e3)}).strict(),yy=c({schemaVersion:_("openpond.harnessEvaluationReviewReceipt.v1"),id:ne,ownerScope:hp,workspaceRef:ne,harnessRelease:se,previousWatermark:kh.nullable(),nextWatermark:kh,selectedEvidence:h(os).max(1e4),excludedEvidence:h(lj).max(1e4),claim:cj.nullable(),classification:ij,triage:h(dj).max(16),reason:Ha,nextAuthority:sj,maxEstimatedCostUsd:u().finite().nonnegative(),tasksetProposal:se.nullable(),evaluation:se.nullable(),trainingQualification:se.nullable(),policyVersion:ne,createdAt:Qe,metadata:It}).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"})}),uj=yy.extend({contentHash:Ie}).strict();function _s(e){const t=yy.parse(e);return uj.parse({...t,contentHash:wt(t)})}c({id:ne,evidence:se,kind:by,sourceRef:ne,occurredAt:Qe,payload:ve(r(),Re())}).strict();const mj=c({schemaVersion:_("openpond.harnessEvaluationReviewModelDecision.v2"),decision:_("no_action"),reason:Ha,ignoredEvidence:h(c({id:ne,reason:r().trim().min(1).max(2e3)}).strict()).max(1e3)}).strict(),pj=c({schemaVersion:_("openpond.harnessEvaluationReviewModelDecision.v2"),decision:_("review"),classification:v(["harness_maintenance","runtime","product","taskset"]),selectedEvidenceIds:h(ne).min(1).max(1e3),ignoredEvidence:h(c({id:ne,reason:r().trim().min(1).max(2e3)}).strict()).max(1e3),recurrenceFamily:r().trim().min(1).max(1e3),statement:Ha,triageLayer:vy,expectedOutcome:Ha,counterevidence:r().trim().max(1e4),confidence:u().min(0).max(1),candidateDisposition:v(["observe","confirm"]).nullable(),reason:Ha}).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"]})}),fj=c({schemaVersion:_("openpond.harnessEvaluationReviewModelDecision.v2"),decision:_("resolve_candidate"),candidateId:ne,candidateFingerprint:Ie,selectedEvidenceIds:h(ne).min(1).max(1e3),ignoredEvidence:h(c({id:ne,reason:r().trim().min(1).max(2e3)}).strict()).max(1e3),confidence:u().min(0).max(1),reason:Ha}).strict();fn("decision",[mj,pj,fj]);c({schemaVersion:_("openpond.harnessEvaluationReviewNavigationDecision.v1"),selectedEvidenceIds:h(ne).min(1).max(50),reason:Ha}).strict();const ac=c({name:r().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:r().trim().min(1).max(2e3),inputSchema:ve(r(),Re()),inputSchemaHash:Ie,sideEffect:v(["read","write"]),timeoutMs:u().int().positive().max(36e5)}).strict(),bp=c({id:ne,required:C(),scopes:h(r().trim().min(1).max(500)).max(100).default([]),portability:v(["portable","host_adapter","local_only","hosted_only"])}).strict(),hj=c({portable:C(),blockers:h(r().trim().min(1).max(2e3)).max(1e3),localOnlyAssetRefs:h(ne).max(1e4),hostPrivateAssetRefs:h(ne).max(1e4)}).strict(),gj=c({schemaVersion:_("openpond.agentSnapshot.v2"),id:ne,sourceRelease:se.nullable(),instructions:h(zn).max(1e4),skills:h(zn).max(1e4),agents:h(zn).max(1e4),toolDeclarations:h(ac).max(200),capabilityRequirements:h(bp).max(200),dependencyLock:zn,portability:hj,metadata:It}).strict();gj.extend({contentHash:Ie}).strict();const Sy=c({create:_(!0),reset:_(!0),step:_(!0),collect:_(!0),destroy:_(!0),resetScope:v(["task","attempt"])}).strict(),xy=c({visibleEvidence:h(ne).max(1e3),privilegedEvidence:h(ne).max(1e3),privateVerifierIsolation:C()}).strict(),bj=c({schemaVersion:_("openpond.harnessRelease.v2"),id:ne,agentSnapshot:se,program:zn,tools:h(ac).max(200),lifecycle:Sy,graderInterface:xy,files:h(zn).max(1e5),metadata:It}).strict();bj.extend({contentHash:Ie}).strict();const vj=c({id:ne,turn:u().int().nonnegative(),kind:v(["message","tool_call","terminal"]),name:ne.nullable(),arguments:ve(r(),Re()),content:r().max(1e6).nullable()}).strict(),yj=c({actionId:ne,turn:u().int().nonnegative(),terminal:C(),output:ve(r(),Re()),artifactRefs:h(Un).max(1e5)}).strict(),Sj=c({sequence:u().int().nonnegative(),type:v(["created","reset","action","observation","terminal","failure","collected","destroyed"]),payloadHash:Ie,metadata:It}).strict();c({schemaVersion:_("openpond.harnessTrace.v1"),manifest:se,taskId:ne,seed:r().trim().min(1).max(500),events:h(Sj).max(1e6),actions:h(vj).max(1e5),observations:h(yj).max(1e5),terminal:C(),failureClass:Jl.nullable(),output:ve(r(),Re()),contentHash:Ie}).strict();const oc=r().trim().min(1).max(1e5),Is=ve(r(),Re()).default({}),xj=v(["completed_tool_batch","before_model_step","turn_completed","turn_paused"]),ky=c({kind:xj,eventSequence:u().int().nonnegative(),occurredAt:Qe}).strict(),wy=c({id:ne,sequence:u().int().nonnegative().nullable(),contentHash:Ie}).strict(),kj=v(["tool_failure","retry","recovery","validation","user_turn","reusable_success","completion_detour"]),wj=v(["open","recovered","terminal"]),_j=c({name:r().trim().min(1).max(500),invocationKey:Ie}).strict(),Ij=c({schemaVersion:_("openpond.improvementObservation.v1"),id:ne,runRef:ne,turnId:ne,harnessRelease:se,overlay:za.nullable(),eventRefs:h(wy).min(1).max(100),kind:kj,state:wj,tool:_j.nullable(),deterministicClass:r().trim().min(1).max(500).nullable(),summary:oc,createdAt:Qe,metadata:Is}).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"]})});Ij.extend({contentHash:Ie}).strict();const Cj=c({schemaVersion:_("openpond.refinementTriggerPolicy.v1"),maxEstimatedCostUsd:u().finite().nonnegative(),cooldownMs:u().int().nonnegative(),maxPendingPlans:u().int().min(1).max(100),maxEvidenceEvents:u().int().min(1).max(1e3),maxProposalEdits:u().int().min(1).max(1e3),maxProposalBytes:u().int().min(1).max(1e7)}).strict(),Rj=v(["no_action","route_deterministically","queue_refiner"]),Aj=c({schemaVersion:_("openpond.refinementTriggerDecision.v1"),id:ne,runRef:ne,turnId:ne,harnessRelease:se,overlay:za.nullable(),observations:h(se).max(100),decision:Rj,deterministicRoute:Ur.nullable(),suggestedRoutes:h(Ur).max(8),reason:oc,deduplicationKey:Ie,policy:Cj,estimatedMaxCostUsd:u().finite().nonnegative(),pendingPlanCount:u().int().nonnegative(),boundary:ky,cooldownUntil:Qe.nullable(),createdAt:Qe,metadata:Is}).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"]})});Aj.extend({contentHash:Ie}).strict();const Pj=v(["runtime_service","refiner_model","human_review","evaluation_system","training_system"]),Tj=c({schemaVersion:_("openpond.improvementRouteDecision.v1"),id:ne,trigger:se,route:Ur,authority:Pj,automatic:C(),reason:oc,createdAt:Qe,metadata:Is}).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"]})});Tj.extend({contentHash:Ie}).strict();const Ej=c({schemaVersion:_("openpond.harnessRefinerOutcome.v1"),id:ne,trigger:se,decision:v(["no_action","proposed"]),proposal:se.nullable(),reason:oc,evidenceRefs:h(se).max(100),estimatedCostUsd:u().finite().nonnegative(),createdAt:Qe,metadata:Is}).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"]})});Ej.extend({contentHash:Ie}).strict();const Mj=v(["applied","retained","declined","conflict","rolled_back"]),jj=c({schemaVersion:_("openpond.improvementApplyReceipt.v1"),id:ne,proposal:se,beforeOverlay:za,afterOverlay:za.nullable(),decision:Mj,boundary:ky,validationRefs:h(se).max(100),outcomeEvidenceRefs:h(wy).max(1e3),rollbackOf:se.nullable(),createdAt:Qe,metadata:Is}).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"]})});jj.extend({contentHash:Ie}).strict();const Go=c({provider:ne,model:ne,revision:r().trim().min(1).max(500).nullable().default(null),artifactHash:Ie.nullable().default(null),tokenizerRevision:r().trim().min(1).max(500).nullable().default(null),chatTemplateHash:Ie.nullable().default(null)}).strict(),Oj=v(["memory","prompt","skill","agent"]),Nj=v(["runtime","product","taskset","training"]),$j=c({id:r().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),text:r().trim().min(1).max(1e4)}).strict(),_y=c({schemaVersion:_("openpond.refinerReviewProfile.v1"),id:r().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),version:r().trim().min(1).max(120),name:r().trim().min(1).max(200),objective:r().trim().min(1).max(1e4),instructions:h($j).max(100),allowedProposalRoutes:h(Oj).max(4),allowedExternalRoutes:h(Nj).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"]})}),wh=c({schemaVersion:_("openpond.refinerRelease.v1"),id:r().trim().min(1).max(240),coreVersion:r().trim().min(1).max(120),coreHash:Ie,profile:_y,profileHash:Ie,composedPromptHash:Ie,createdAt:Qe,contentHash:Ie}).strict(),Dj=c({schemaVersion:_("openpond.refinerBinding.v1"),channel:_("active"),revision:u().int().nonnegative(),release:se,updatedAt:Qe}).strict(),Lj=c({schemaVersion:_("openpond.refinerTransitionReceipt.v1"),id:r().trim().min(1).max(240),operation:v(["initialize","update","activate","rollback"]),bindingChanged:C(),previousRelease:se.nullable(),nextRelease:se,actor:r().trim().min(1).max(240),reason:r().trim().min(1).max(1e4),authoringSkillHash:Ie.nullable(),validation:c({valid:C(),messages:h(r().max(2e3)).max(100)}).strict(),createdAt:Qe,contentHash:Ie}).strict(),zj=c({schemaVersion:_("openpond.localHarnessRefinerDecision.v1"),decision:_("no_action"),reason:r().trim().min(1).max(1e4)}).strip(),Uj=c({schemaVersion:_("openpond.localHarnessRefinerDecision.v1"),decision:_("route"),route:v(["runtime","product","taskset","training"]),summary:r().trim().min(1).max(2e3),expectedOutcome:r().trim().min(1).max(1e4),reason:r().trim().min(1).max(1e4)}).strip(),Hj=c({schemaVersion:_("openpond.localHarnessRefinerDecision.v1"),decision:_("propose"),route:v(["memory","prompt","skill","agent"]),operation:v(["create","update","delete"]),target:r().trim().min(1).max(2e3),summary:r().trim().min(1).max(2e3),createContent:r().min(1).max(2e4).nullable(),find:r().min(1).max(8e3).nullable(),replace:r().max(8e3).nullable(),expectedOutcome:r().trim().min(1).max(1e4),reason:r().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"]})}),qj=fn("decision",[zj,Uj,Hj]),Bj=qj,vp=c({kind:v(["single_deterministic","recurrent_independent"]),supportingEvidenceIds:h(r().trim().min(1).max(2e3)).min(1).max(100),counterevidence:h(r().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"]})}),Fj=c({schemaVersion:_("openpond.localHarnessRefinerDecision.v2"),decision:_("no_action"),reason:r().trim().min(1).max(1e4)}).strict(),Vj=c({schemaVersion:_("openpond.localHarnessRefinerDecision.v2"),decision:_("route"),route:v(["runtime","product","taskset","training"]),summary:r().trim().min(1).max(2e3),evidenceBasis:vp,expectedOutcome:r().trim().min(1).max(1e4),reason:r().trim().min(1).max(1e4)}).strict(),Wj=c({schemaVersion:_("openpond.localHarnessRefinerDecision.v2"),decision:_("propose"),route:v(["memory","prompt","skill","agent"]),operation:v(["create","update","delete"]),target:r().trim().min(1).max(2e3),summary:r().trim().min(1).max(2e3),evidenceBasis:vp,createContent:r().min(1).max(2e4).nullable(),find:r().min(1).max(8e3).nullable(),replace:r().max(8e3).nullable(),expectedOutcome:r().trim().min(1).max(1e4),reason:r().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"]})}),Iy=fn("decision",[Fj,Vj,Wj]);vn([Bj,Iy]);const yp=c({memory:C(),prompt:C(),skill:C(),agent:C()}).strict(),Cy=v(["memory","instruction","skill","agent"]),_h=c({path:r().trim().min(1).max(2e3),kind:Cy,content:r().max(6e4),loaded:C()}).strict(),Ih=c({path:r().trim().min(1).max(2e3),kind:Cy,loaded:C()}).strict(),Kj=c({capabilities:yp,trigger:ve(r(),Re()),observations:h(ve(r(),Re())).max(20),admissibleEvidenceIds:h(r().trim().min(1).max(2e3)).max(1e4),reviewPacket:c({currentTurn:c({id:r().trim().min(1).max(2e3),status:r().trim().min(1).max(100).nullable(),error:r().max(2100).nullable(),prompt:r().max(8100).nullable(),assistantOutput:r().max(8100).nullable(),assistantOutputLinkCount:u().int().nonnegative()}).strict(),priorConversation:h(c({turnId:r().trim().min(1).max(2e3),status:r().trim().min(1).max(100).nullable(),prompt:r().max(3100).nullable(),assistantOutput:r().max(3100).nullable()}).strict()).max(3),timeline:h(ve(r(),Re())).max(60),artifacts:h(ve(r(),Re())).max(30),artifactDiagnostics:h(ve(r(),Re())).max(20),executionProfile:c({modelRequestCount:u().int().nonnegative(),failedModelRequestCount:u().int().nonnegative(),promptTokens:u().int().nonnegative(),completionTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative(),toolFailureCount:u().int().nonnegative(),retryCount:u().int().nonnegative(),recoveryCount:u().int().nonnegative()}).strict(),priorIncidents:h(ve(r(),Re())).max(3),truncation:c({timelineEventCount:u().int().nonnegative(),includedTimelineEventCount:u().int().nonnegative(),timelineTruncated:C()}).strict()}).strict(),runtimeActivation:c({admittedRelease:se,currentRelease:se,rebasedOntoCurrent:C(),admittedSourceFiles:h(_h).max(100),admittedSourceCatalog:h(Ih).max(1e3)}).strict(),sourceFiles:h(_h).max(100),sourceCatalog:h(Ih).max(1e3),additionalEvidence:Re().nullable().optional()}).strict(),Gj=c({id:r().trim().min(1).max(240),revision:u().int().nonnegative(),contentHash:Ie}).strict();c({schemaVersion:_("openpond.hostedHarnessRefinerRequest.v2"),requestId:r().trim().min(1).max(240),idempotencyKey:r().trim().min(1).max(240),evidenceHash:Ie,harness:c({admittedRelease:se,currentRelease:se,overlay:Gj,workspace:c({id:r().trim().min(1).max(240),revision:u().int().nonnegative(),sourceRevision:Ie,channelRevision:u().int().nonnegative()}).strict(),capabilities:yp}).strict(),evidence:Kj}).strict();const Zj=c({promptTokens:u().int().nonnegative(),completionTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative()}).strict();c({schemaVersion:_("openpond.hostedHarnessRefinerResponse.v2"),requestId:r().trim().min(1).max(240),evidenceHash:Ie,admittedRelease:se,currentRelease:se,decision:Iy,serviceRevision:r().trim().min(1).max(240),usage:Zj}).strict();const Jj=r().trim().min(1).max(2e3),Sp=r().trim().min(1).max(1e5),Yj=v(["create","update","delete"]),Xj=v(["memory","prompt","skill","agent"]),Qj=v(["runtime","product","taskset","training"]),eO=v(["no_action","routed","applied","retained","failed"]),tO=v(["not_applicable","pending","passed","rejected","failed"]),nO=v(["not_applicable","pending","passed","failed"]),aO=c({schemaVersion:_("openpond.harnessRefinerActivityReceipt.v1"),id:ne,runRef:ne,turnId:ne,result:eO,decision:v(["no_action","route","propose"]).nullable(),route:Ur.nullable(),operation:Yj.nullable(),target:r().trim().min(1).max(2e3).nullable(),summary:Jj,evidenceBasis:vp.nullable(),critiqueStatus:tO,validationStatus:nO,trigger:se,outcome:se.nullable(),proposal:se.nullable(),applyReceipt:se.nullable(),inputHarness:se,outputHarness:se.nullable(),createdAt:Qe}).strict().superRefine((e,t)=>{const n=e.result==="applied"||e.result==="retained";e.result==="no_action"?Ch(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"||!Qj.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"}),Ch(t,e,{critiqueStatus:"not_applicable",validationStatus:"not_applicable"})):n?((e.decision!=="propose"||!Xj.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"]})});aO.extend({contentHash:Ie}).strict();const oO=v(["unresolved","confirmed","resolved","rejected","expired"]),rO=c({kind:v(["applied_change","later_success","manual_rejection","source_revoked","expired"]),reason:Sp,evidenceRefs:h(se).max(1e3),resolvedAt:Qe}).strict(),iO=c({schemaVersion:_("openpond.harnessRefinementCandidate.v1"),id:ne,ownerScope:hp,workspaceRef:ne,fingerprint:Ie,recurrenceFamily:r().trim().min(1).max(1e3),statement:Sp,status:oO,occurrences:h(os).max(1e3),counterevidence:h(os).max(1e3),sourceReviews:h(se).min(1).max(100),relatedHarnessReleases:h(se).max(100),firstSeenAt:Qe,lastSeenAt:Qe,lastReviewedAt:Qe,expiresAt:Qe,resolution:rO.nullable(),createdAt:Qe,updatedAt:Qe}).strict().superRefine((e,t)=>{No(t,e.occurrences,"occurrences"),No(t,e.counterevidence,"counterevidence"),No(t,e.sourceReviews,"sourceReviews"),No(t,e.relatedHarnessReleases,"relatedHarnessReleases");const n=new Set(e.occurrences.map(o=>o.occurrenceKey));e.counterevidence.some(o=>n.has(o.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(o=>o.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"]}),uO(t,e)});iO.extend({contentHash:Ie}).strict();const sO=v(["created","merged","rejected","expired","reopened","resolved"]),lO=c({schemaVersion:_("openpond.harnessRefinementCandidateLifecycleReceipt.v1"),id:ne,candidateId:ne,decision:sO,beforeCandidate:se.nullable(),afterCandidate:se,review:se,addedEvidence:h(os).max(1e3),removedEvidence:h(se).max(1e3),reason:Sp,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"]}),No(t,e.addedEvidence,"addedEvidence"),No(t,e.removedEvidence,"removedEvidence");const n=new Set(e.removedEvidence.map(a=>Gu(a)));e.addedEvidence.some(a=>n.has(Gu(a.evidence)))&&t.addIssue({code:"custom",message:"candidate lifecycle evidence cannot be added and removed together",path:["removedEvidence"]})});lO.extend({contentHash:Ie}).strict();const cO=c({schemaVersion:_("openpond.harnessCrossRunRefinementRequest.v1"),id:ne,ownerScope:hp,workspaceRef:ne,candidate:se,candidateFingerprint:Ie,review:se,admittedHarness:se,evidence:h(os).min(1).max(1e3),capabilities:yp,deduplicationKey:Ie,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"]}),No(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=dO(e);e.deduplicationKey!==n&&t.addIssue({code:"custom",message:`cross-run refinement deduplicationKey is ${e.deduplicationKey}; expected ${n}`,path:["deduplicationKey"]})});cO.extend({contentHash:Ie}).strict();function dO(e){return wt({schemaVersion:"openpond.harnessCrossRunRefinementIdentity.v1",workspaceRef:e.workspaceRef,candidateFingerprint:e.candidateFingerprint,admittedHarness:e.admittedHarness})}function Ch(e,t,n){for(const[a,o]of Object.entries(n))t[a]!==o&&e.addIssue({code:"custom",message:`${a} must be ${String(o)}`,path:[a]})}function No(e,t,n){const a=t.map(o=>Gu(o));new Set(a).size!==a.length&&e.addIssue({code:"custom",message:`${n} references must be unique`,path:[n]})}function Gu(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 uO(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 o=n[a-1],i=n[a];Date.parse(o[1])<=Date.parse(i[1])||e.addIssue({code:"custom",message:`${i[0]} must not precede ${o[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 mO=c({adapterId:ne,placement:v(["local","remote","colocated","provider_native"]),runtimeVersion:r().trim().min(1).max(200),capabilityReceipt:Ie}).strict(),pO=c({maxTurns:u().int().positive().max(1e5),timeoutMs:u().int().positive().max(864e5),maxOutputBytes:u().int().positive().max(25e7),maximumSpendUsd:u().nonnegative().nullable()}).strict(),fO=c({schemaVersion:_("openpond.runManifest.v1"),id:ne,harnessRelease:se,tasksetRelease:se,model:Go,runtimeTarget:mO,limits:pO,approval:c({id:ne,contentHash:Ie}).strict().nullable(),createdAt:Qe,metadata:It}).strict();fO.extend({contentHash:Ie}).strict();const Ry=c({schemaVersion:_("openpond.attemptReceipt.v1"),id:ne,runManifest:se,taskId:ne,seed:r().trim().min(1).max(500),terminal:C(),failureClass:Jl.nullable(),outputHash:Ie.nullable(),traceHash:Ie,artifactRefs:h(Un).max(1e5),graderEvidenceRefs:h(Un).max(1e4),startedAt:Qe,completedAt:Qe,latencyMs:u().int().nonnegative(),costUsd:u().nonnegative().nullable(),legacyAttemptRef:ne.nullable().default(null),metadata:It}).strict(),Ay=Ry.extend({contentHash:Ie}).strict(),hO=c({schemaVersion:_("openpond.evaluationResult.v1"),id:ne,runManifest:se,harnessRelease:se,tasksetRelease:se,model:Go,receiptRefs:h(se).min(1).max(1e6),attemptCount:u().int().positive(),rewardEligibleCount:u().int().nonnegative(),terminalCount:u().int().nonnegative(),meanScore:u().min(0).max(1).nullable(),failureCounts:ve(Jl,u().int().nonnegative()),metadata:It}).strict();hO.extend({contentHash:Ie}).strict();const gO=c({schemaVersion:_("openpond.harnessCompatibility.v1"),id:ne,baseHarnessRelease:se,candidateHarnessRelease:se,tasksetRelease:se,environmentHash:Ie,toolContractHash:Ie,policyHash:Ie,graderInterfaceHash:Ie,metadata:It}).strict();gO.extend({contentHash:Ie}).strict();function bO(e){const t=Ay.safeParse(e);if(!t.success)return!1;const{contentHash:n,...a}=t.data;return wt(Ry.parse(a))===n}const qr=v(["train","validation","test","frozen_eval"]),vO=c({path:r().trim().min(1).max(2e3).refine(RO),mediaType:r().trim().min(1).max(200),schemaRef:zn.nullable().default(null),maxBytes:u().int().positive().max(25e7).nullable().default(null),metadata:It}).strict(),yO=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(),Py=c({protocolVersion:_("openpond.environment.v1"),kind:v(["text","agent","work","custom_program"]),entrypoint:r().trim().min(1).max(1e3),stateful:C(),deterministicSeeds:C(),lifecycle:h(v(["create","reset","step","collect","destroy"])).min(5).max(5),networkPolicy:v(["none","declared_read_only","declared_scoped"]),defaultTimeoutMs:u().int().positive().max(36e5)}).strict(),rc=c({id:ne,version:r().trim().min(1).max(100),weight:u().nonnegative().max(1e3).default(1),hardGate:C().default(!1),rewardEligible:C().default(!1),privileged:C().default(!1)}),SO=rc.extend({kind:v(["content","schema","artifact","runtime_event","state"]),config:ve(r(),Re())}).strict(),xO=rc.extend({kind:_("model_judge"),rubricRef:zn,calibrationStatus:v(["pending","passed","failed"])}).strict(),kO=rc.extend({kind:_("custom_verifier"),verifierRef:zn,timeoutMs:u().int().positive().max(3e5),networkPolicy:_("none")}).strict(),wO=rc.extend({kind:_("human"),rubricRef:zn,reviewerRole:r().trim().min(1).max(500)}).strict(),Ty=vn([SO,xO,kO,wO]),_O=c({id:ne,clusterKey:ne,split:qr,input:ve(r(),Re()),expectedOutput:ve(r(),Re()).nullable(),policyVisibleContext:ve(r(),Re()).default({}),privilegedContextRef:ne.nullable(),artifactRefs:h(zn).max(1e3).default([]),requiredOutputs:h(vO).max(1e3).optional(),tags:h(ne).max(100).default([])}).strict(),IO=c({schemaVersion:_("openpond.tasksetRelease.v2"),id:ne,revision:u().int().positive(),policy:yO,environment:Py,environmentRelease:c({id:ne,contentHash:Ie}).strict().optional(),tools:h(ac).max(200),capabilities:h(bp).max(200),tasks:h(_O).min(1).max(1e6),graders:h(Ty).min(1).max(1e3),verifierSetRelease:c({id:ne,contentHash:Ie}).strict().optional(),metadata:It}).strict(),CO=IO.extend({contentHash:Ie}).strict();function RO(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}CO.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 Ey=v(["foreground_tokens","success_rate","latency_ms","cost_usd"]),My=v(["baseline","candidate"]),AO=c({split:qr,taskIds:h(ne).min(1).max(1e5),seeds:h(r().trim().min(1).max(500)).min(1).max(100),repetitions:u().int().positive().max(20),runtimeTargetHash:Ie,environmentHash:Ie,toolContractHash:Ie,limitsHash:Ie}).strict();c({schemaVersion:_("openpond.benchmarkDefinition.v1"),id:ne,title:r().trim().min(1).max(500),description:r().trim().min(1).max(5e3),tasksetRelease:se,adaptationSplit:qr,evaluationSplit:qr,primaryMetric:Ey,qualityGate:v(["none","non_regression","all_pass"]),caseCounts:c({adaptation:u().int().nonnegative(),evaluation:u().int().positive()}).strict(),metadata:It}).strict();c({schemaVersion:_("openpond.benchmarkRunRequest.v1"),phase:My,model:Go,reasoningEffort:r().trim().min(1).max(100).nullable(),split:qr,seeds:h(r().trim().min(1).max(500)).min(1).max(100),repetitions:u().int().positive().max(20),metadata:It}).strict();const PO=c({inputTokens:u().int().nonnegative(),outputTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative()}).strict(),TO=c({schemaVersion:_("openpond.benchmarkRunSummary.v1"),id:ne,phase:My,tasksetRelease:se,harnessRelease:se,evaluationResult:se,model:Go,reasoningEffort:r().trim().min(1).max(100).nullable(),protocol:AO,attemptCount:u().int().positive(),passedCount:u().int().nonnegative(),terminalCount:u().int().nonnegative(),usage:PO,costUsd:u().nonnegative().nullable(),latencyMs:u().int().nonnegative(),createdAt:Qe,metadata:It}).strict();TO.extend({contentHash:Ie}).strict();const EO=c({schemaVersion:_("openpond.benchmarkComparison.v1"),id:ne,baseline:se,candidate:se,tasksetRelease:se,primaryMetric:Ey,qualityPassed:C(),baselinePassRate:u().min(0).max(1),candidatePassRate:u().min(0).max(1),foregroundTokenDelta:u().int(),foregroundTokenDeltaPercent:u().finite().nullable(),improved:C(),createdAt:Qe,metadata:It}).strict();EO.extend({contentHash:Ie}).strict();const xp=v(["scored","unscorable"]),ic=v(["policy","environment","collector","verifier","provider","host","user","scheduler"]),jy=v(["completed","policy_failure","incomplete_output","task_deadline","environment_failure","collector_failure","verifier_failure","provider_failure","host_failure","infrastructure_timeout","cancelled"]),MO=c({schemaVersion:_("openpond.environmentRelease.v1"),id:ne,revision:u().int().positive(),contract:Py,actionSchemaRef:zn.nullable(),observationSchemaRef:zn.nullable(),stateSchemaRef:zn.nullable(),artifactCollection:c({maxArtifacts:u().int().positive().max(1e5),maxTotalBytes:u().int().positive().max(1e10)}).strict(),adapterConformanceHashes:ve(ne,Ie),metadata:It}).strict();MO.extend({contentHash:Ie}).strict();const jO=v(["collected","missing","skipped","failed"]),Rh=v(["not_requested","passed","failed"]),OO=c({requiredOutputPath:r().trim().min(1).max(2e3).nullable(),collectedPath:r().trim().min(1).max(4e3).nullable(),declaredMediaType:r().trim().min(1).max(200).nullable(),detectedMediaType:r().trim().min(1).max(200).nullable(),artifact:Un.nullable(),status:jO,parseStatus:Rh,schemaStatus:Rh,errorCode:ne.nullable(),failureOwner:ic.nullable(),evidenceRefs:h(Un).max(1e4),metadata:It}).strict(),NO=c({schemaVersion:_("openpond.artifactManifest.v1"),id:ne,attemptRef:se,entries:h(OO).max(1e5),createdAt:Qe,metadata:It}).strict();NO.extend({contentHash:Ie}).strict();const $O=c({schemaVersion:_("openpond.verifierSetRelease.v1"),id:ne,revision:u().int().positive(),graders:h(Ty).min(1).max(1e3),isolation:c({processBoundary:v(["same_process","isolated_process","container"]),networkPolicy:_("none"),defaultTimeoutMs:u().int().positive().max(3e5)}).strict(),calibrationReceiptRefs:h(se).max(1e4),metadata:It}).strict();$O.extend({contentHash:Ie}).strict();const DO=c({verifierId:ne,verifierVersion:r().trim().min(1).max(100),status:xp,rawScore:u().finite().nullable(),normalizedScore:u().min(0).max(1).nullable(),weight:u().nonnegative().max(1e3),passed:C(),hardGate:C(),rewardEligible:C(),rewardContribution:u().min(0).max(1).nullable(),failureOwner:ic.nullable(),feedback:h(r().max(2e4)).max(1e3),visibleEvidenceRefs:h(Un).max(1e4),privilegedEvidenceRefs:h(Un).max(1e4),metadata:It}).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"]})}),Oy=c({schemaVersion:_("openpond.rewardReceipt.v1"),id:ne,attemptRef:se,verifierSetRef:se,artifactManifestRef:se,status:xp,reward:u().min(0).max(1).nullable(),learningEligible:C(),passed:C(),outcomeClass:jy,failureOwner:ic.nullable(),components:h(DO).min(1).max(1e4),visibleEvidenceRefs:h(Un).max(1e5),privilegedEvidenceRefs:h(Un).max(1e5),supersedes:se.nullable(),createdAt:Qe,metadata:It}).strict();function Ny(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"]})}Oy.superRefine(Ny);Oy.extend({contentHash:Ie}).strict().superRefine(Ny);const LO="openpond.workEvidenceReceipt.v1",zO="openpond.workProcessTrace.v1",UO="openpond.workFeedbackReceipt.v1",$y="openpond.workEvidenceEligibility.v1",HO=r().regex(/^urn:openpond:work:[a-f0-9]{64}$/,"Work source references must be opaque SHA-256 URNs."),qO=r().regex(/^urn:openpond:workspace:[a-f0-9]{64}$/,"Workspace references must be opaque SHA-256 URNs."),BO=r().regex(/^urn:openpond:artifact:[a-f0-9]{64}$/,"Evidence artifacts must use content-addressed SHA-256 URNs."),gn=Un.extend({id:BO}).strict().superRefine((e,t)=>{e.id!==Hy(e.contentHash)&&t.addIssue({code:"custom",message:"Evidence artifact id must contain its content hash.",path:["id"]})}),FO=v(["tool","validation","state_transition","approval","question","artifact","cleanup"]),VO=v(["agent","environment"]),WO=v(["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"]),KO=v(["started","completed","failed","cancelled"]),GO=v(["filesystem","source_control","command","browser","connected_app","sandbox","agent","other"]),ZO=v(["structural","visual","test","user_review","other"]),JO=v(["running","completed","failed","cancelled","timeout"]),YO=v(["requested","approved","denied","answered","dismissed"]),XO=v(["policy","validation","environment","infrastructure","timeout","cancelled","unknown"]),QO=v(["missing_start","missing_terminal","source_truncated","unsupported_events_dropped","uncorrelated_environment_step","artifact_unavailable"]),e2=c({sequence:u().int().nonnegative().max(1e6),timestamp:Qe,layer:VO,kind:FO,action:WO,status:KO,inputHash:Ie.nullable(),outputHash:Ie.nullable(),receiptHash:Ie.nullable(),parentReceiptHash:Ie.nullable(),artifactRefs:h(gn).max(1e3),attributes:c({toolCategory:GO.nullable(),validationKind:ZO.nullable(),transitionState:JO.nullable(),interventionOutcome:YO.nullable(),artifactCount:u().int().nonnegative().max(1e5),exitCode:u().int().min(-1).max(255).nullable(),durationMs:u().int().nonnegative().max(31536e6).nullable(),cpuTimeMs:u().int().nonnegative().max(31536e6).nullable(),memoryPeakBytes:u().int().nonnegative().max(0x4000000000000).nullable(),errorClass:XO.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"]})}),Dy=c({schemaVersion:_(zO),sourceRevisionHash:Ie,sanitationPolicyVersion:ne,incomplete:C(),incompleteReasons:h(QO).max(10),droppedEventCount:u().int().nonnegative().max(1e6),steps:h(e2).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"]})}),t2=Dy.safeExtend({contentHash:Ie}).strict(),n2=v(["policy_failure","validation_failure","model_failure","environment_failure","infrastructure_failure","timeout","cancelled","unknown"]),a2=c({status:v(["completed","failed","cancelled","timeout"]),failureClass:n2.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"]})}),kp=c({schemaVersion:_(LO),id:r().regex(/^work-evidence-[a-f0-9]{24}$/),source:c({surface:v(["desktop","hosted"]),experience:v(["work","development"]),opaqueRef:HO,revisionHash:Ie}).strict(),agentSnapshot:se.nullable(),model:Go,runtime:c({adapterId:ne,adapterVersion:ne,capabilityRef:gn.nullable()}).strict(),inputHash:Ie,terminal:a2,trace:c({sanitizedRef:gn,traceHash:Ie,sanitationPolicyVersion:ne,incomplete:C()}).strict(),outputRefs:h(gn).max(1e4),artifactRefs:h(gn).max(1e5),validationEvidenceRefs:h(gn).max(1e4),interventions:c({approvals:u().int().nonnegative().max(1e6),questions:u().int().nonnegative().max(1e6),steeringEvents:u().int().nonnegative().max(1e6),otherUserInterventions:u().int().nonnegative().max(1e6)}).strict(),timing:c({startedAt:Qe,completedAt:Qe,latencyMs:u().int().nonnegative().max(31536e6)}).strict(),usage:c({promptTokens:u().int().nonnegative().nullable(),completionTokens:u().int().nonnegative().nullable(),totalTokens:u().int().nonnegative().nullable()}).strict(),costUsd:u().nonnegative().max(1e6).nullable(),provenance:c({consentReceiptRef:gn,consentScope:_("work_process_and_artifacts"),consentGrantedAt:Qe,policyVersion:ne,projectorVersion:ne,disclosure:_("portable_sanitized"),ownershipScope:v(["personal","workspace"]),workspaceRef:qO.nullable(),participantPolicy:v(["creator_only","all_participants"]),retention:c({policy:_("source_bound"),deleteWithSource:_(!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"]}),Xd(e.outputRefs,["outputRefs"],t),Xd(e.artifactRefs,["artifactRefs"],t),Xd(e.validationEvidenceRefs,["validationEvidenceRefs"],t)}),Ly=kp.safeExtend({contentHash:Ie}).strict(),o2=v(["accepted","needs_correction","not_useful"]),r2=v(["correct","complete","high_quality","incorrect","incomplete","wrong_format","unsafe","stale","irrelevant","other"]),zy=c({schemaVersion:_(UO),id:r().regex(/^work-feedback-[a-f0-9]{24}$/),evidenceReceiptRef:gn,outputRevisionRef:gn.nullable(),verdict:o2,reasonCodes:h(r2).max(16),correctionRef:gn.nullable(),correctedOutputRevisionRef:gn.nullable(),actor:_("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"]})}),Uy=zy.safeExtend({contentHash:Ie}).strict();function Hy(e){return`urn:openpond:artifact:${e}`}function i2(e){return`urn:openpond:work:${wt(e)}`}function Cs(e){return gn.parse({id:Hy(e.contentHash),contentHash:e.contentHash,mediaType:e.mediaType??null,sizeBytes:e.sizeBytes??null})}function qy(e){const t=Dy.parse(e);return t2.parse({...t,contentHash:wt(t)})}function s2(e){const t=kp.parse(e);return Ly.parse({...t,contentHash:wt(t)})}function By(e,t){const n=zy.parse(e),a=Uy.parse({...n,contentHash:wt(n)});return t&&d2(a,t),a}function l2(e){return u2(e,Ly,kp)}function c2(e){return Cs({contentHash:e.contentHash,mediaType:"application/vnd.openpond.work-evidence+json",sizeBytes:null})}function d2(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 u2(e,t,n){const a=t.safeParse(e);if(!a.success)return!1;const{contentHash:o,...i}=a.data;return wt(n.parse(i))===o}function Xd(e,t,n){const a=e.map(o=>o.contentHash);new Set(a).size!==a.length&&n.addIssue({code:"custom",message:"Artifact content hashes must be unique.",path:t})}const m2=v(["active","revoked","deleted","expired"]);v(["discovery_only","eval_candidate","demonstration_candidate","preference_candidate","reward_candidate"]);const p2=v(["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"]),wr=c({eligible:C(),blockers:h(p2).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."})}),Fy=c({schemaVersion:_($y),evidenceReceiptHash:Ie,policyState:m2,decisions:c({discovery_only:wr,eval_candidate:wr,demonstration_candidate:wr,preference_candidate:wr,reward_candidate:wr}).strict()}).strict(),f2=Fy.extend({contentHash:Ie}).strict();function Vy(e){const t=l2(e.evidence),n=(e.feedback??[]).filter(x=>{if(!Uy.safeParse(x).success)return!1;try{return By(g2(x),e.evidence),!0}catch{return!1}}),a=h2(e.policyState),o=[...t?[]:["invalid_evidence_receipt"],...a],i=[...o,...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?Ay.safeParse(y.attemptReceipt):null,R=k?.success===!0&&bO(k.data),A=y?.sourceEvidenceReceiptHash===e.evidence.contentHash,$=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=[...o,...y?[]:["attempt_receipt_missing"],...y&&!R?["attempt_receipt_invalid"]:[],...y&&!A?["attempt_receipt_unbound"]:[],...y&&R&&A&&!$?["attempt_not_reward_eligible"]:[]],D=Fy.parse({schemaVersion:$y,evidenceReceiptHash:e.evidence.contentHash,policyState:e.policyState,decisions:{discovery_only:Hi(o),eval_candidate:Hi(i),demonstration_candidate:Hi(p),preference_candidate:Hi(S),reward_candidate:Hi(z)}});return f2.parse({...D,contentHash:wt(D)})}function h2(e){return e==="revoked"?["consent_revoked"]:e==="deleted"?["source_deleted"]:e==="expired"?["retention_expired"]:[]}function Hi(e){const t=[...new Set(e)];return wr.parse({eligible:t.length===0,blockers:t})}function g2(e){const{contentHash:t,...n}=e;return n}c({schemaVersion:_("openpond.workEvidenceAuthoringInput.v1"),evidenceReceiptRef:gn,inputHash:Ie,agentSnapshot:se.nullable(),sanitizedTraceRef:gn,outputRefs:h(gn).max(1e4),validationEvidenceRefs:h(gn).max(1e4),incomplete:C(),evalCandidate:C(),blockerCodes:h(r().trim().min(1).max(120)).max(32)}).strict();const rs="2026-08-04T12:00:00.000Z",Wy="2026-08-04T12:00:02.500Z",Zu=wt({fixture:"desktop-work",revision:1}),is=Cs({contentHash:wt("fixture output"),mediaType:"text/plain",sizeBytes:14}),Ky=Cs({contentHash:wt({kind:"test",status:"passed"}),mediaType:"application/json",sizeBytes:null}),b2=Cs({contentHash:wt({scope:"work_process_and_artifacts",grantedAt:rs}),mediaType:"application/json",sizeBytes:null}),wp=qy({schemaVersion:"openpond.workProcessTrace.v1",sourceRevisionHash:Zu,sanitationPolicyVersion:"openpond.desktop-work-sanitizer.v1",incomplete:!1,incompleteReasons:[],droppedEventCount:1,steps:[_r(0,rs,"agent","state_transition","turn_started","started",{transitionState:"running"}),_r(1,"2026-08-04T12:00:00.500Z","agent","tool","tool_invoked","started",{toolCategory:"filesystem",inputHash:wt({path:"hashed-only"}),receiptHash:wt("fixture-tool-call")}),_r(2,"2026-08-04T12:00:01.000Z","environment","artifact","artifact_created","completed",{outputHash:is.contentHash,artifacts:[is],receiptHash:wt("fixture-environment-operation"),parentReceiptHash:wt("fixture-tool-call")}),_r(3,"2026-08-04T12:00:01.500Z","environment","validation","validation_completed","completed",{validationKind:"test",outputHash:Ky.contentHash,receiptHash:wt("fixture-validation"),parentReceiptHash:wt("fixture-tool-call")}),_r(4,Wy,"agent","state_transition","turn_completed","completed",{transitionState:"completed"})]}),v2=new TextEncoder().encode(zv(wp)).byteLength,Qd=Cs({contentHash:wp.contentHash,mediaType:"application/vnd.openpond.work-process-trace+json",sizeBytes:v2}),Lo=s2({schemaVersion:"openpond.workEvidenceReceipt.v1",id:`work-evidence-${wt([Zu,Qd.contentHash]).slice(0,24)}`,source:{surface:"desktop",experience:"work",opaqueRef:i2(["fixture-session","fixture-turn"]),revisionHash:Zu},agentSnapshot:{id:"fixture-agent-snapshot",contentHash:wt("fixture-agent")},model:{provider:"fixture",model:"scripted",revision:"1",artifactHash:null,tokenizerRevision:null,chatTemplateHash:null},runtime:{adapterId:"desktop-work",adapterVersion:"1",capabilityRef:null},inputHash:wt("fixture prompt"),terminal:{status:"completed",failureClass:null},trace:{sanitizedRef:Qd,traceHash:Qd.contentHash,sanitationPolicyVersion:wp.sanitationPolicyVersion,incomplete:!1},outputRefs:[is],artifactRefs:[is],validationEvidenceRefs:[Ky],interventions:{approvals:0,questions:0,steeringEvents:0,otherUserInterventions:0},timing:{startedAt:rs,completedAt:Wy,latencyMs:2500},usage:{promptTokens:12,completionTokens:8,totalTokens:20},costUsd:0,provenance:{consentReceiptRef:b2,consentScope:"work_process_and_artifacts",consentGrantedAt:rs,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}}}),Gy=By({schemaVersion:"openpond.workFeedbackReceipt.v1",id:`work-feedback-${wt([Lo.contentHash,"accepted"]).slice(0,24)}`,evidenceReceiptRef:c2(Lo),outputRevisionRef:is,verdict:"accepted",reasonCodes:["correct","complete"],correctionRef:null,correctedOutputRevisionRef:null,actor:"user",createdAt:"2026-08-04T12:01:00.000Z"},Lo);qy({schemaVersion:"openpond.workProcessTrace.v1",sourceRevisionHash:wt({fixture:"incomplete",revision:1}),sanitationPolicyVersion:"openpond.desktop-work-sanitizer.v1",incomplete:!0,incompleteReasons:["missing_terminal","unsupported_events_dropped"],droppedEventCount:2,steps:[_r(0,rs,"agent","state_transition","turn_started","started",{transitionState:"running"})]});Vy({evidence:Lo,feedback:[Gy],policyState:"active",reconstructability:{input:!0,environment:!0,verifier:!0}});Vy({evidence:Lo,feedback:[Gy],policyState:"revoked",reconstructability:{input:!0,environment:!0,verifier:!0}});({...Lo,source:{...Lo.source}});function _r(e,t,n,a,o,i,s){return{sequence:e,timestamp:t,layer:n,kind:a,action:o,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 y2=c({schemaVersion:_("openpond.graderEvidence.v1"),graderId:ne,graderVersion:r().trim().min(1).max(100),score:u().min(0).max(1).nullable(),passed:C(),rewardEligible:C(),failureClass:Jl.nullable(),feedback:h(r().max(2e4)).max(1e3),visibleEvidenceRefs:h(ne).max(1e4),privilegedEvidenceRefs:h(ne).max(1e4)}).strict();y2.extend({contentHash:Ie}).strict();const S2=v(["calibration","training_reward","validation","frozen_eval"]);v(["human","model","deterministic","fixture"]);v(["production","synthetic_smoke"]);const x2=v(["markdown","text","code","json","image"]),k2=c({id:ne,label:r().trim().min(1).max(500),instruction:r().trim().min(1).max(1e4),weight:u().nonnegative().max(1e3)}).strict(),w2=c({source:v(["attempt_output","artifact"]),path:r().trim().min(1).max(2e3),renderer:x2}).strict(),_2=c({showTaskPrompt:C(),randomizeCandidateOrder:C(),hideModelIdentity:C(),parts:h(w2).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."})}),I2=c({strategy:_("randomized_blinded_v1"),maxAssignmentsPerCandidate:u().int().positive().max(1e4)}).strict(),C2=c({algorithm:_("mean_pairwise_win_fraction_v1"),quorum:u().int().positive().max(100),rejectAllThreshold:u().min(.5).max(1)}).strict(),R2=c({algorithm:_("pairwise_win_fraction_v1"),verifierId:ne,verifierVersion:r().trim().min(1).max(100),weight:u().positive().max(1e3)}).strict(),A2=c({minimumSamples:u().int().positive().max(1e5),minimumOrderAgreement:u().min(0).max(1),minimumTieAgreement:u().min(0).max(1),minimumOrderSwapAgreement:u().min(0).max(1)}).strict(),P2=c({schemaVersion:_("openpond.preferenceComparisonRelease.v1"),id:ne,revision:u().int().positive(),tasksetRelease:se,candidateCount:u().int().min(2).max(4),resultMode:_("ordered_tie_groups"),allowTies:C(),allowRejectAll:C(),presentation:_2,rubricRef:Un,criteria:h(k2).max(20),assignment:I2,aggregation:C2,rewardProjection:R2,calibration:A2,metadata:It}).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."})});P2.extend({contentHash:Ie}).strict();const T2=c({id:ne,contentHash:Ie}).strict(),E2=c({tasksetRelease:se,harnessReleases:h(se).min(1).max(4),runManifestRefs:h(se).min(1).max(4),harnessCompatibilityReceiptRefs:h(se).max(6),environmentRelease:se,verifierSetRelease:se,toolContractHash:Ie,policyHash:Ie}).strict(),M2=c({attemptRef:se,runManifestRef:se,artifactManifestRef:se,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."})}),j2=c({schemaVersion:_("openpond.comparisonAssignment.v1"),id:ne,comparisonRelease:se,taskRef:T2,lineage:E2,candidates:h(M2).min(2).max(4),presentedCandidateOrder:h(ne).min(2).max(4),purpose:S2,createdAt:Qe,metadata:It}).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."})});j2.extend({contentHash:Ie}).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 Zy=h(h(ne).min(1).max(4)).max(4),O2=fn("kind",[c({kind:v(["human","model","deterministic"]),releaseRef:se}).strict(),c({kind:_("fixture"),releaseRef:se,fixtureRelease:se,labelSource:_("synthetic"),qualificationEligibility:_("smoke_only")}).strict()]),N2=c({schemaVersion:_("openpond.preferenceReceipt.v1"),id:ne,assignmentRef:se,reviewer:O2,order:Zy,rejectAll:C(),criterionScores:ve(ne,ve(ne,u().finite().min(0).max(1))),feedbackArtifactRef:Un.nullable(),startedAt:Qe,completedAt:Qe,metadata:It}).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."})});N2.extend({contentHash:Ie}).strict();const $2=c({schemaVersion:_("openpond.preferenceAggregationReceipt.v1"),id:ne,assignmentRef:se,comparisonRelease:se,receiptRefs:h(se).min(1).max(100),order:Zy,rejectAll:C(),pairwiseWinFractions:ve(ne,u().min(0).max(1)),quorum:u().int().positive().max(100),createdAt:Qe,metadata:It}).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."})});$2.extend({contentHash:Ie}).strict();const D2=c({schemaVersion:_("openpond.preferenceCalibrationReport.v1"),id:ne,comparisonRelease:se,automatedReviewer:se,humanReceiptRefs:h(se).min(1).max(1e5),modelReceiptRefs:h(se).min(1).max(1e5),sampleCount:u().int().positive().max(1e5),orderAgreement:u().min(0).max(1),tieAgreement:u().min(0).max(1),orderSwapAgreement:u().min(0).max(1),passed:C(),createdAt:Qe,metadata:It}).strict();D2.extend({contentHash:Ie}).strict();const L2=v(["reward_train","reward_validation","reward_qualification"]),z2=v(["human","synthetic_fixture"]),U2=v(["synthetic_smoke","human_heldout"]),H2=c({id:ne,assignmentRef:se,scenarioRef:se,scenarioSplit:v(["train","validation"]),preferenceResultRef:se,receiptRefs:h(se).min(1).max(100),attemptRefs:h(se).min(2).max(4),artifactManifestRefs:h(se).min(2).max(4),orderedBuckets:h(h(ne).min(1).max(4)).max(4),rejectAll:C(),partition:L2,metadata:It}).strict().superRefine((e,t)=>{const n=e.attemptRefs.map(o=>o.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(o=>!n.includes(o)))&&t.addIssue({code:"custom",path:["orderedBuckets"],message:"Ordered buckets must contain every group Attempt exactly once."})}),q2=c({groupId:ne,preferredAttemptRef:se,dispreferredAttemptRef:se,relation:v(["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."})}),B2=c({schemaVersion:_("openpond.preferenceDatasetRelease.v1"),id:ne,revision:u().int().positive(),tasksetRelease:se,comparisonRelease:se,authority:z2,qualificationEligibility:v(["smoke_only","human_heldout"]),fixtureRelease:se.nullable(),groups:h(H2).min(1).max(1e5),derivedPairs:h(q2).max(1e6),createdAt:Qe,metadata:It}).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(o=>o.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(o=>[o.id,o]));for(const[o,i]of e.derivedPairs.entries()){const s=a.get(i.groupId);if(!s){t.addIssue({code:"custom",path:["derivedPairs",o,"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",o],message:"Derived preference pairs must reference Attempts in their source group."})}});B2.extend({contentHash:Ie}).strict();const F2=c({sampleCount:u().int().positive(),finiteScoreRate:u().min(0).max(1),scoreVariance:u().nonnegative(),checkpointReloadPassed:C(),processorCompatibilityPassed:C(),invalidAttemptExclusionPassed:C(),orderedPairAccuracy:u().min(0).max(1).nullable(),bucketAccuracy:u().min(0).max(1).nullable(),tieAgreement:u().min(0).max(1).nullable()}).strict(),V2=c({schemaVersion:_("openpond.rewardModelQualificationReport.v1"),id:ne,kind:U2,rewardModelVersion:se,preferenceDatasetRelease:se,tasksetRelease:se,processorRelease:se,metrics:F2,passed:C(),productionRewardEligible:C(),createdAt:Qe,metadata:It}).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."})});V2.extend({contentHash:Ie}).strict();const W2=r().trim().min(1).max(1e5),K2=v(["no_training","sft","preference","rl"]),G2=c({kind:v(["none","demonstrations","chosen_rejected","scalar_reward"]),strength:v(["absent","weak","usable"]),calibrated:C(),confounded:C(),variance:u().finite().nonnegative().nullable(),evidenceRefs:h(se).max(1e5)}).strict(),Jy=c({schemaVersion:_("openpond.modelImprovementQualificationReceipt.v1"),id:ne,review:se,harnessRelease:se,tasksetRelease:se.nullable(),baselineEvaluation:se.nullable(),model:Go,environmentHash:Ie.nullable(),toolContractHash:Ie.nullable(),permissionContractHash:Ie.nullable(),policyHash:Ie.nullable(),verifierRef:se.nullable(),sourcePolicies:h(gp).max(1e4),trainingEvidenceRefs:h(se).max(1e5),frozenEvaluationEvidenceRefs:h(se).max(1e5),privacyApproval:se.nullable(),budgetApproval:se.nullable(),maximumCostUsd:u().finite().nonnegative(),signal:G2,decision:K2,reasons:h(W2).min(1).max(100),createdAt:Qe,metadata:It}).strict().superRefine((e,t)=>{const n=new Set(e.trainingEvidenceRefs.map(Ah));if(e.frozenEvaluationEvidenceRefs.some(o=>n.has(Ah(o)))&&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(o=>o.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"]})}),Z2=Jy.extend({contentHash:Ie}).strict();function Yy(e){const t=Jy.parse(e);return Z2.parse({...t,contentHash:wt(t)})}function Ah(e){return`${e.id}:${e.contentHash}`}const Rs="2026-08-08T12:00:00.000Z",Xy=Yt("harness-release"),Qy={policy:Yt("source-policy"),state:"authorized",checkedAt:Rs},zo=(e,t)=>({evidence:Yt(e),kind:t,sourceRef:`source-${e}`,sourcePolicy:Qy,occurrenceKey:wt(`occurrence-${e}`),occurredAt:Rs}),J2={cursor:wt("review-watermark"),throughCreatedAt:Rs},sc=(e,t=3)=>({fingerprint:wt(`claim-${e}`),recurrenceFamily:e,statement:`The ${e} behavior remains unresolved after smaller-layer triage.`,independentOccurrences:t,unresolvedOccurrences:t}),lc=_s({schemaVersion:"openpond.harnessEvaluationReviewReceipt.v1",id:"review-no-action",ownerScope:{kind:"personal",id:"owner-1"},workspaceRef:"workspace-1",harnessRelease:Xy,previousWatermark:null,nextWatermark:J2,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:Rs,metadata:{}});_s({...As(lc),id:"review-runtime",selectedEvidence:[zo("runtime-failure","observation")],claim:sc("runtime-transport-failure",1),classification:"runtime",triage:[{layer:"runtime",status:"unresolved",reason:"The adapter failed before model policy could affect the result.",evidenceRefs:[Yt("runtime-failure")]}],reason:"A deterministic runtime regression is the smallest correct fix.",nextAuthority:"runtime_service"});_s({...As(lc),id:"review-product",selectedEvidence:[zo("product-routing","route_decision")],claim:sc("product-routing-defect",1),classification:"product",triage:[{layer:"product",status:"unresolved",reason:"The product selected an unrelated Skill for an ordinary Work turn.",evidenceRefs:[Yt("product-routing")]}],reason:"Product routing must be corrected before behavioral Evaluation.",nextAuthority:"product_team"});const Y2=_s({...As(lc),id:"review-taskset",selectedEvidence:[zo("failure-1","work_outcome"),zo("failure-2","work_outcome"),zo("failure-3","work_outcome")],claim:sc("search-budget-allocation"),classification:"taskset",triage:[{layer:"harness",status:"unresolved",reason:"The active research Skill did not resolve three independent failures.",evidenceRefs:[Yt("failure-1"),Yt("failure-2"),Yt("failure-3")]}],reason:"The repeated behavioral claim now needs controlled measurement.",nextAuthority:"human_review",tasksetProposal:Yt("taskset-proposal"),maxEstimatedCostUsd:2}),X2=Yy({schemaVersion:"openpond.modelImprovementQualificationReceipt.v1",id:"qualification-rl-blocked",review:Ju(Y2),harnessRelease:Xy,tasksetRelease:Yt("taskset-release"),baselineEvaluation:Yt("baseline-evaluation"),model:Q2(),environmentHash:wt("environment"),toolContractHash:wt("tools"),permissionContractHash:wt("permissions"),policyHash:wt("policy"),verifierRef:Yt("verifier"),sourcePolicies:[Qy],trainingEvidenceRefs:[Yt("training-evidence")],frozenEvaluationEvidenceRefs:[Yt("frozen-evidence")],privacyApproval:Yt("privacy-approval"),budgetApproval:Yt("budget-approval"),maximumCostUsd:25,signal:{kind:"scalar_reward",strength:"weak",calibrated:!0,confounded:!1,variance:0,evidenceRefs:[Yt("reward-audit")]},decision:"no_training",reasons:["The observed reward is constant and cannot support RL."],createdAt:Rs,metadata:{blockedMethod:"rl"}}),Ph=Yy({...As(X2),id:"qualification-rl-qualified",signal:{kind:"scalar_reward",strength:"usable",calibrated:!0,confounded:!1,variance:.18,evidenceRefs:[Yt("reward-audit")]},decision:"rl",reasons:["The frozen baseline has usable variance and a calibrated sequential reward."]});_s({...As(lc),id:"review-model-improvement",selectedEvidence:[zo("baseline-evaluation","evaluation"),zo("qualification-rl-qualified","training_qualification")],claim:sc("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:[Yt("baseline-evaluation"),Ju(Ph)]}],reason:"The qualified claim may proceed to a separately approved managed-training plan.",nextAuthority:"training_system",tasksetProposal:Yt("taskset-proposal"),evaluation:Yt("baseline-evaluation"),trainingQualification:Ju(Ph),maxEstimatedCostUsd:25});function Yt(e){return{id:e,contentHash:wt(e)}}function Ju(e){return{id:e.id,contentHash:e.contentHash}}function As(e){const{contentHash:t,...n}=e;return n}function Q2(){return{provider:"openpond",model:"openpond-chat",revision:"model-revision-1",artifactHash:wt("model-artifact"),tokenizerRevision:"tokenizer-1",chatTemplateHash:wt("chat-template")}}const eS=c({schemaVersion:_("openpond.optimizerTrainingSample.v1"),tokenIds:h(u().int().nonnegative()).min(2).max(32768),mask:h(C()).min(2).max(32768),logprobs:h(u().finite()).min(2).max(32768),temperatures:h(u().positive().finite()).min(2).max(32768),envName:r().trim().min(1).max(200),modelRequestId:r().trim().min(1).max(1e3),promptTokenCount:u().int().positive(),completionTokenCount:u().int().positive(),servedPolicyVersion:u().int().nonnegative()}).strict().superRefine((e,t)=>{const n=e.tokenIds.length;for(const[a,o]of[["mask",e.mask],["logprobs",e.logprobs],["temperatures",e.temperatures]])o.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"})}),eN=c({id:ne,environmentRelease:se,status:v(["completed","failed","timed_out","cancelled"]),startedAt:Qe,completedAt:Qe,traceRefs:h(Un).max(1e4),metadata:It}).strict(),tN=c({receiptRef:se,status:xp,value:u().min(0).max(1).nullable(),learningEligible:C(),passed:C(),outcomeClass:jy,failureOwner:ic.nullable(),components:ve(ne,u().min(0).max(1).nullable())}).strict(),tS=c({schemaVersion:_("openpond.canonicalRolloutRecord.v1"),id:ne,attemptRef:se,artifactManifestRef:se,tasksetRelease:se,environmentRelease:se,verifierSetRelease:se,harnessRelease:se,taskId:ne,split:qr,model:Go,seed:r().trim().min(1).max(500),reward:tN,traceRef:Un,optimizerSample:eS.nullable(),environmentExecutions:h(eN).min(1).max(1e5),startedAt:Qe,completedAt:Qe,metadata:It}).strict();function nS(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."})}tS.superRefine(nS);c({...tS.shape,contentHash:Ie}).strict().superRefine(nS);c({schemaVersion:_("openpond.rolloutQualification.v1"),rolloutCount:u().int().nonnegative(),scoredCount:u().int().nonnegative(),optimizerEligibleCount:u().int().nonnegative(),unscorableCount:u().int().nonnegative(),zeroRewardCount:u().int().nonnegative(),rewardMean:u().min(0).max(1).nullable(),rewardVariance:u().nonnegative().nullable(),distinctRewardCount:u().int().nonnegative(),eligibleForRl:C(),reasons:h(r().trim().min(1).max(1e3)).max(100)}).strict();const nN="openpond.runTelemetryEvent.v1",aN="openpond.metricDefinition.v1",aS="openpond.metricObservation.v1",_p=v(["policy_visible","team_visible","host_private"]),oN=v(["runtime","environment","grader","optimizer","control_plane","evaluation"]),rN=v(["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"]),oS=c({modelProjectId:ne,runId:ne,modelVersionId:ne.nullable(),harnessReleaseHash:Ie,tasksetReleaseHash:Ie,environmentReleaseHash:Ie.nullable(),checkpointId:ne.nullable(),step:u().int().nonnegative().nullable(),rolloutGroupId:ne.nullable(),attemptId:ne.nullable(),scenarioId:ne.nullable()}).strict(),rS=c({schemaVersion:_(nN),eventId:ne,sequence:u().int().nonnegative(),occurredAt:Qe,source:oN,type:rN,visibility:_p,lineage:oS,attributes:It}).strict(),iN=v(["gauge","counter","distribution"]),sN=v(["ratio","count","seconds","milliseconds","tokens","bytes","usd","scalar"]),lN=v(["higher","lower","neutral"]),cN=v(["last","sum","mean","min","max","p50","p95"]),iS=c({schemaVersion:_(aN),id:ne,displayName:r().trim().min(1).max(200),description:r().trim().min(1).max(2e3),valueType:iN,unit:sN,direction:lN,aggregation:cN,visibility:_p,boundedDimensions:h(r().trim().min(1).max(100)).max(32)}).strict(),sS=c({schemaVersion:_(aS),observationId:ne,metricId:ne,eventId:ne,sequence:u().int().nonnegative(),observedAt:Qe,value:u().finite(),lineage:oS,dimensions:ve(r().trim().min(1).max(100),r().max(500))}).strict();c({schemaVersion:_("openpond.runTelemetryBatch.v1"),events:h(rS).max(1e3),observations:h(sS).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 o=a.schemaVersion===aS?a.observationId:a.eventId,i=`${a.lineage.runId}:${a.sequence}:${o}`;n.has(i)&&t.addIssue({code:"custom",message:"Telemetry batch contains a duplicate idempotency key."}),n.add(i)}});const en=e=>iS.parse({schemaVersion:"openpond.metricDefinition.v1",...e}),dN=[en({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"]}),en({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"]}),en({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"]}),en({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"]}),en({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"]}),en({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"]}),en({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"]}),en({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"]}),en({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"]}),en({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"]}),en({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"]}),en({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"]}),en({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"]}),en({id:"tokens.input",displayName:"Input tokens",description:"Input tokens processed.",valueType:"counter",unit:"tokens",direction:"neutral",aggregation:"sum",visibility:"team_visible",boundedDimensions:["split","source"]}),en({id:"tokens.output",displayName:"Output tokens",description:"Output tokens generated.",valueType:"counter",unit:"tokens",direction:"neutral",aggregation:"sum",visibility:"team_visible",boundedDimensions:["split","source"]}),en({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"]}),en({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"]}),en({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"]}),en({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"]}),en({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(dN.map(e=>[e.id,e]));const uN=h(iS).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(u().int().nonnegative()).max(1e4),scenarioIds:h(ne).max(1e5),rolloutGroupIds:h(ne).max(1e5),attemptIds:h(ne).max(1e6),splits:h(r().trim().min(1).max(100)).max(32),failureOwners:h(r().trim().min(1).max(100)).max(32),graders:h(r().trim().min(1).max(200)).max(1e3),rewardEligible:C().nullable()}).strict();const mN=c({id:ne,contentHash:Ie,kind:v(["rollout","attempt","trace","grader","checkpoint","artifact"]),visibility:_p}).strict(),pN=c({schemaVersion:_("openpond.telemetryEvidenceCompleteness.v1"),runId:ne,status:v(["complete","partial","missing"]),expectedEventTypes:h(r().trim().min(1).max(100)).max(100),observedEventTypes:h(r().trim().min(1).max(100)).max(100),missingEventTypes:h(r().trim().min(1).max(100)).max(100),lastSequence:u().int().nonnegative().nullable(),sequenceGaps:h(u().int().nonnegative()).max(1e4)}).strict(),fN=c({step:u().int().nonnegative().nullable(),observedAt:Qe,value:u().finite(),sampleCount:u().int().positive()}).strict();c({schemaVersion:_("openpond.runMetricSummary.v1"),runId:ne,metricId:ne,aggregation:v(["last","sum","mean","min","max","p50","p95"]),value:u().finite().nullable(),sampleCount:u().int().nonnegative(),series:h(fN).max(1e5)}).strict();const hN=c({schemaVersion:_("openpond.telemetryExportBundle.v1"),id:ne,runId:ne,exportedAt:Qe,definitions:uN,events:h(rS).max(1e6),observations:h(sS).max(1e7),evidenceRefs:h(mN).max(1e6),completeness:pN}).strict();hN.extend({contentHash:Ie}).strict();const gN=v(["trajectory","reward","demonstration","preference","correction","critique","targeted_feedback","grader_evidence","infrastructure_failure"]),bN=c({datasetRelease:st,harnessRelease:st,evidenceSetRelease:st.nullable(),profileRelease:st.nullable(),model:c({source:r().trim().min(1).max(200),revision:r().trim().min(1).max(500),artifactHash:Ve.nullable()}).strict(),environmentHash:Ve,graderHash:Ve,toolContractHash:Ve,verificationReceiptHash:Ve.nullable()}).strict(),Wa=c({schemaVersion:_("openpond.learningSignal.v1"),id:je,taskId:je.nullable(),episodeId:je.nullable(),policyVersion:u().int().nonnegative().nullable(),lineage:bN,approved:C(),verifier:v(["deterministic","model_judge","human","none"]),createdAt:$t,contentHash:Ve,metadata:ve(r(),Re()).default({})}).strict(),vN=Wa.extend({kind:_("trajectory"),payload:c({traceRef:r().trim().min(1).max(2e3),traceHash:Ve,terminal:C(),failureClass:v(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),optimizerSample:eS.nullable().optional()}).strict()}).strict(),yN=Wa.extend({kind:_("reward"),payload:c({reward:u().finite(),components:ve(r(),u().finite()),eligible:C(),graderEvidenceRefs:h(je).max(1e3)}).strict()}).strict(),SN=Wa.extend({kind:_("demonstration"),payload:c({prompt:r().max(5e5),response:r().max(1e6)}).strict()}).strict(),xN=Wa.extend({kind:_("preference"),payload:c({prompt:r().max(5e5),chosen:r().max(1e6),rejected:r().max(1e6),rationale:r().max(5e5).nullable()}).strict()}).strict(),kN=Wa.extend({kind:_("correction"),payload:c({original:r().max(1e6),corrected:r().max(1e6),rationale:r().max(5e5).nullable()}).strict()}).strict(),wN=Wa.extend({kind:_("critique"),payload:c({response:r().max(1e6),critique:r().max(5e5),severity:v(["note","warning","error"])}).strict()}).strict(),_N=Wa.extend({kind:_("targeted_feedback"),payload:c({turnIndex:u().int().nonnegative(),target:v(["reasoning","tool","answer","policy"]),feedback:r().max(5e5)}).strict()}).strict(),IN=Wa.extend({kind:_("grader_evidence"),payload:c({graderId:je,score:u().finite().nullable(),passed:C(),privilegedArtifactRefs:h(r().trim().min(1).max(2e3))}).strict()}).strict(),CN=Wa.extend({kind:_("infrastructure_failure"),approved:_(!1),verifier:_("none"),payload:c({code:je,phase:je,retryable:C(),rewardEligible:_(!1)}).strict()}).strict(),lS=fn("kind",[vN,yN,SN,xN,kN,wN,_N,IN,CN]);c({schemaVersion:_("openpond.learningSignalBatch.v1"),manifestId:je,manifestHash:Ve,sequence:u().int().nonnegative(),signals:h(lS).min(1).max(1e5),contentHash:Ve}).strict();const Ip=c({adapterId:je,placement:v(["local","remote","colocated","provider_native"]),capabilityReceipt:Ve,runtimeVersion:r().trim().min(1).max(200),dataPlane:c({provider:je,dataPlaneId:je,cellId:je,runnerPoolId:je,runtimeImageDigest:r().regex(/^sha256:[a-f0-9]{64}$/),capabilityReceipt:Ve}).strict().nullable()}).strict(),Cp=c({adapterId:je,kind:v(["local","ssh","managed","custom"]),deviceOrPool:r().trim().min(1).max(1e3),capabilityReceipt:Ve,provider:je.nullable()}).strict(),Rp=c({adapterId:je,workerVersion:r().trim().min(1).max(200),workerImageDigest:r().regex(/^sha256:[a-f0-9]{64}$/).nullable(),upstreamRevision:r().trim().min(1).max(500),capabilityReceipt:Ve}).strict(),RN=c({schemaVersion:_("openpond.harnessRunManifest.v1"),id:je,harnessRelease:st,datasetRelease:st,evidenceSets:h(st).max(1e4),model:c({source:r().trim().min(1).max(200),revision:r().trim().min(1).max(500),artifactHash:Ve.nullable(),tokenizerRevision:r().trim().min(1).max(500),chatTemplateHash:Ve}).strict(),recipe:c({method:r().trim().min(1).max(100),version:r().trim().min(1).max(200),configHash:Ve}).strict(),runtimeTarget:Ip,computeTarget:Cp,engine:Rp,resolvedBundleHash:Ve,secretLeaseRefs:h(nE).max(1e3),approval:c({approvalHash:Ve,approvedAt:$t,maximumSpendUsd:u().nonnegative().nullable()}).strict(),createdAt:$t}).strict(),AN=RN.extend({contentHash:Ve}).strict(),PN=c({schemaVersion:_("openpond.resolvedTrainingBundle.v1"),projection:_("trainer"),harnessRelease:st,datasetRelease:st,evidenceSetRelease:st.nullable(),files:h(c({path:r().trim().min(1).max(2e3),sha256:Ve,sizeBytes:u().int().nonnegative()}).strict()).max(1e5)}).strict();PN.extend({contentHash:Ve}).strict();const TN=c({id:je,turn:u().int().nonnegative(),kind:v(["message","tool_call","terminal"]),name:je.nullable(),arguments:ve(r(),Re()),content:r().max(1e6).nullable(),contentHash:Ve}).strict(),EN=c({actionId:je,turn:u().int().nonnegative(),terminal:C(),output:ve(r(),Re()),artifactRefs:h(r().trim().min(1).max(2e3)),contentHash:Ve}).strict(),MN=c({sequence:u().int().nonnegative(),type:v(["created","reset","action","observation","terminal","graded","feedback","failure","collected","destroyed"]),timestamp:$t,payloadHash:Ve,metadata:ve(r(),Re()).default({})}).strict(),Th=c({graderId:je,graderVersion:r().trim().min(1).max(200),score:u().finite().nullable(),passed:C(),rewardEligible:C(),failureClass:v(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),feedback:h(r().max(5e5)),visibleEvidenceRefs:h(r().trim().min(1).max(2e3)),privilegedEvidenceRefs:h(r().trim().min(1).max(2e3)),contentHash:Ve}).strict();c({schemaVersion:_("openpond.harnessRunTrace.v1"),manifest:st,taskId:je,seed:r().trim().min(1).max(500),events:h(MN).max(1e6),actions:h(TN).max(1e5),observations:h(EN).max(1e5),graderEvidence:h(Th).max(1e4),learningSignals:h(lS).max(1e5),terminal:C(),failureClass:Th.shape.failureClass,artifactHash:Ve,contentHash:Ve}).strict();const jN=r().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"),ON=v(["instruction","skill","skill_resource","agent","dependency_lock","program","asset"]),NN=c({id:je,kind:ON,path:jN,parentId:je.nullable(),mediaType:r().trim().min(1).max(200),visibility:v(["policy","verifier","host_private"]),portability:v(["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:_("openpond.harnessSourceManifest.v1"),name:r().trim().min(1).max(240),files:h(NN).min(2).max(1e5),toolDeclarations:h(ac).max(200),capabilityRequirements:h(bp).max(200),lifecycle:Sy,graderInterface:xy,runtimeProtocol:r().trim().min(1).max(500),metadata:ve(r(),Re()).default({})}).strict().superRefine((e,t)=>{const n=new Set,a=new Map,o=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"]}),o.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),o.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:r(),sourcePath:r(),binding:Dj,currentRelease:wh,releases:h(wh),transitions:h(Lj)}).strict();c({profile:_y,activate:C().default(!0),reason:r().trim().min(1).max(1e4),actor:r().trim().min(1).max(240).default("local-user"),authoringSkillHash:r().regex(/^[a-f0-9]{64}$/).nullable().default(null)}).strict();c({release:se,reason:r().trim().min(1).max(1e4),actor:r().trim().min(1).max(240).default("local-user")}).strict();const $N=c({schemaVersion:_("openpond.trainingEngineCapabilities.v1"),adapterId:je,available:C(),methods:h(r().trim().min(1).max(100)),signalKinds:h(gN),modelFamilies:h(r().trim().min(1).max(200)),precisions:h(v(["fp32","fp16","bf16","tf32","int8","int4"])),topologies:h(r().trim().min(1).max(200)),workerProtocolVersion:r().trim().min(1).max(200),upstreamRevision:r().trim().min(1).max(500),workerImageDigest:r().regex(/^sha256:[a-f0-9]{64}$/).nullable().default(null),capabilityReceipt:Ve,checkedAt:$t,unavailableReason:r().trim().min(1).max(5e3).nullable()}).strict(),DN=c({schemaVersion:_("openpond.computeTargetCapabilities.v1"),adapterId:je,kind:v(["local","ssh","managed","custom"]),provider:je.nullable(),available:C(),devices:h(c({id:je,kind:v(["cpu","gpu","accelerator"]),vendor:r().trim().min(1).max(200),name:r().trim().min(1).max(500),memoryBytes:u().int().nonnegative().nullable(),runtime:r().trim().min(1).max(200)}).strict()),supportsWorkerImages:C(),supportsArtifactTransfer:C(),supportsCancellation:C(),capabilityReceipt:Ve,checkedAt:$t,unavailableReason:r().trim().min(1).max(5e3).nullable()}).strict(),LN=c({schemaVersion:_("openpond.harnessRuntimeCapabilities.v1"),adapterId:je,available:C(),placements:h(v(["local","remote","colocated","provider_native"])),lifecycle:h(v(["create","reset","step","grade","collect","destroy"])),deterministicReplay:C(),privilegedIsolation:C(),capabilityReceipt:Ve,checkedAt:$t,unavailableReason:r().trim().min(1).max(5e3).nullable()}).strict();c({schemaVersion:_("openpond.resolvedTrainingPlan.v1"),manifest:AN,recipe:pp,runtime:Ip,compute:Cp,engine:Rp,execution:c({trainingPlanId:je,approvalId:je}).strict().nullable(),maximumSpendUsd:u().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,o,i]of n)JSON.stringify(o)!==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:_("openpond.adapterValidationReceipt.v1"),adapterId:je,valid:C(),issues:h(c({code:je,path:r().trim().max(2e3).nullable(),message:r().trim().min(1).max(5e3)}).strict()),capabilityReceipt:Ve,planHash:Ve,createdAt:$t,contentHash:Ve}).strict();c({runId:je,adapterId:je,routeId:je.optional(),providerJobId:r().trim().min(1).max(1e3).nullable(),tenantId:je.optional(),leaseId:je.nullable(),manifestHash:Ve.optional(),inputBundleHash:Ve.optional(),createdAt:$t}).strict();c({runId:je,state:v(["queued","preparing","running","cancelling","cancelled","succeeded","failed"]),phase:r().trim().min(1).max(200),progress:u().min(0).max(1).nullable(),updatedAt:$t,errorCode:je.nullable()}).strict();c({runId:je,manifestHash:Ve,artifacts:h(c({kind:v(["checkpoint","adapter","metrics","trace","evaluation","receipt"]),objectRef:r().trim().min(1).max(2e3),sha256:Ve,sizeBytes:u().int().nonnegative()}).strict()),contentHash:Ve}).strict();const Yu=v(["ready","model_download_required","compute_setup_required","provider_managed","unsupported"]),zN=c({id:je,label:r().trim().min(1).max(500),description:r().trim().min(1).max(2e3),destinationId:je,computeAdapterId:je,runtimeAdapterId:je,engineAdapterId:je,methods:h(r().trim().min(1).max(100)),capabilityPills:h(r().trim().min(1).max(100)),executionMode:v(["local_worker","provider_native"]),approvalPolicy:c({providerId:Vo,providerLabel:r().trim().min(1).max(200),settingsActionLabel:r().trim().min(1).max(500).nullable(),exportApprovalRequired:C(),exportDescription:r().trim().min(1).max(2e3).nullable(),preparationRequired:C(),minimumSpendUsd:u().nonnegative(),maximumSpendUsd:u().positive(),defaultMaximumSpendUsd:u().positive(),minimumRetentionDays:u().int().positive(),maximumRetentionDays:u().int().positive(),defaultRetentionDays:u().int().positive(),methodRequirement:r().trim().min(1).max(2e3).nullable()}).strict().nullable(),limits:c({maximumSequenceLength:u().int().positive(),maximumOutputTokens:u().int().positive(),maximumTrainingExamples:u().int().positive().nullable()}).strict(),defaults:c({loraRank:u().int().positive(),maxSteps:u().int().positive(),rolloutGroupSize:u().int().min(2).max(32),rolloutConcurrency:u().int().positive().max(32),rolloutOutputTokens:u().int().positive()}).strict(),available:C(),unavailableReason:r().trim().min(1).max(5e3).nullable()}).strict(),UN=c({selectionKey:je,label:r().trim().min(1).max(500),source:v(["local","builtin","huggingface","managed","search"]),modelId:r().trim().min(1).max(1e3),revision:r().trim().min(1).max(500).nullable(),tokenizerRevision:r().trim().min(1).max(500).nullable(),chatTemplateHash:Ve.nullable(),modelAssetId:je.nullable(),expectedBytes:u().int().nonnegative().nullable(),cached:C(),known:C(),searchResolved:C(),computeAdapterIds:h(je),engineAdapterIds:h(je),preparationState:Yu,reason:r().trim().min(1).max(5e3).nullable(),compatibilities:h(c({targetId:je,methods:h(r().trim().min(1).max(100)),state:Yu,reason:r().trim().min(1).max(5e3).nullable()}).strict())}).strict();c({schemaVersion:_("openpond.trainingCatalog.v1"),models:h(UN).max(1e5),engines:h($N),compute:h(DN),runtimes:h(LN),targets:h(zN),generatedAt:$t,contentHash:Ve}).strict();c({schemaVersion:_("openpond.trainingPreparationPlan.v1"),modelRunId:je,state:Yu,reason:r().trim().min(1).max(5e3).nullable(),runtime:Ip.nullable(),compute:Cp.nullable(),engine:Rp.nullable(),downloads:h(c({kind:_("model"),label:r().trim().min(1).max(500),expectedBytes:u().int().nonnegative(),digest:r().trim().min(8).max(500),cached:C(),state:v(["ready","required","downloading","cancelled","failed"]),progress:u().min(0).max(1).nullable(),cancellable:C(),diskImpactBytes:u().int().nonnegative()}).strict()),dataMovement:h(c({direction:v(["upload","download","none"]),label:r().trim().min(1).max(500),bytes:u().int().nonnegative().nullable()}).strict()),quoteUsd:u().nonnegative().nullable(),maximumSpendUsd:u().nonnegative().nullable(),retentionDays:u().int().nonnegative().nullable(),sideEffectsStarted:_(!1),contentHash:Ve}).strict();function HN(e,t,n){const a=new Headers;a.set("Accept","text/event-stream"),a.set("Authorization",`Bearer ${e.token}`);const o=new URL(`${e.serverUrl.replace(/\/$/,"")}/v1/events`);return n!==void 0&&Number.isSafeInteger(n)&&n>0&&o.searchParams.set("afterSequence",String(n)),{url:o.toString(),init:{headers:a,signal:t}}}function qN(e){return Math.min(500*2**Math.max(0,e),1e4)}async function BN(e,t,n,a){cS(e);const o=e.body.getReader(),i=new TextDecoder;let s="";for(;!a?.aborted;){const{done:l,value:p}=await o.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),Mh(f,t,n),m=s.indexOf(`
128
-
129
- `)}}!a?.aborted&&s.trim()&&Mh(s,t,n)}function cS(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 FN(e,t,n,a,o={}){const i=new AbortController,s=o.fetchImpl??fetch,l=o.reconnectDelayMs??qN;let p=Eh(o.afterSequence),m=!1;return(async()=>{let f=0;for(;!i.signal.aborted;)try{const S=HN(e,i.signal,p),y=await s(S.url,S.init);if(cS(y),m=!0,f=0,await BN(y,k=>{const R=Eh(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 VN(l(f),i.signal),f+=1}})().catch(()=>{}),{close(){i.abort()},isOpen(){return m}}}function Eh(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0?e:0}function Mh(e,t,n){let a="message";const o=[];for(const i of e.split(`
130
- `))i.startsWith(":")||(i.startsWith("event: ")&&(a=i.slice(7).trim()),i.startsWith("data: ")&&o.push(i.slice(6)));if(a==="ready"){n?.();return}if(!(a!=="runtime"||o.length===0))try{t(JSON.parse(o.join(`
131
- `)))}catch{}}async function VN(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 o=await fetch(`${e.serverUrl}${t}`,{...n,headers:a});if(!o.ok){const i=await o.json().catch(()=>({})),s=i&&typeof i=="object"&&"error"in i?String(i.error):o.statusText;throw new Error(s)}return await o.json()}function k3(e){const t=new URL("/v1/terminal",e.serverUrl);return t.protocol=t.protocol==="https:"?"wss:":"ws:",t.toString()}function w3(e){return["openpond-terminal",`openpond-token.${KN(e.token)}`]}function WN(e){const t=new TextEncoder().encode(e);let n="";for(let a=0;a<t.length;a+=32768){const o=t.subarray(a,a+32768);n+=String.fromCharCode(...o)}return btoa(n)}function KN(e){return WN(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function GN(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 ZN={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"})},JN={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?${YN(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 YN(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 XN={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 o=new URLSearchParams({path:n});a.offsetBytes!==void 0&&o.set("offsetBytes",String(a.offsetBytes)),a.maxBytes!==void 0&&o.set("maxBytes",String(a.maxBytes));const i=await B(e,`/v1/sandboxes/${encodeURIComponent(t)}/files?${o.toString()}`);return{...i,contents:i.file.isBinary?"":GN(i.file.contentsBase64)}}},QN={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)})},e$={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})})},t$={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:o,...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)})},n$={sandbox:(e,t)=>B(e,`/v1/sandboxes/${encodeURIComponent(t)}`)},a$={...e$,...t$,...n$,...QN,...XN},o$={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 o=new URLSearchParams;return a.beforeSequence!=null&&o.set("beforeSequence",String(a.beforeSequence)),a.limit!=null&&o.set("limit",String(a.limit)),B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages${o.size?`?${o}`:""}`)},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,o)=>B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages/${encodeURIComponent(a)}`,{method:"PATCH",body:JSON.stringify({body:o})}),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`)},Ap="openpond-app-server-url",ss="openpond-app-token",r$=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 Xu(e){const t=e.getItem(Ap)?.trim(),n=e.getItem(ss)?.trim();return t&&n?{serverUrl:t,token:n}:null}function Pl(e){if(!e)return null;try{const t="__openpond_storage_probe__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return null}}function xr(e,t){e.setItem(Ap,t.serverUrl),e.setItem(ss,t.token)}function Oh(e,t){const n=Xu(e);n?.serverUrl!==t.serverUrl||n.token!==t.token||(e.removeItem(Ap),e.removeItem(ss))}function i$(){const e=window.__OPENPOND_WEB_CONNECTION__,t=e?.serverUrl?.trim(),n=e?.token?.trim();return t&&n?{serverUrl:t,token:n}:null}function s$(){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 l$(){window.location.hash&&window.history.replaceState(null,"",`${window.location.pathname}${window.location.search}`)}function nl(e,t){t&&(e.some(n=>n.serverUrl===t.serverUrl&&n.token===t.token)||e.push(t))}function c$(){const e=[],t=Pl(window.sessionStorage),n=Pl(window.localStorage),a=dS(),o=t?.getItem(ss)??n?.getItem(ss);return nl(e,null),nl(e,a&&o?{serverUrl:a,token:o.trim()}:null),nl(e,t?Xu(t):null),nl(e,n?Xu(n):null),e}async function eu(e){const t=new AbortController,n=window.setTimeout(()=>t.abort(),r$);try{const a=await fetch(`${e}/health`,{signal:t.signal}),o=await a.json().catch(()=>null);return a.ok&&o?.server==="openpond-app-server"}catch{return!1}finally{window.clearTimeout(n)}}async function d$(){if(window.openpond)return window.openpond.getConnection();const e=Pl(window.sessionStorage),t=Pl(window.localStorage),n=s$();if(n&&await eu(n.serverUrl))return t&&xr(t,n),e&&xr(e,n),l$(),{...n,platform:navigator.platform};const a=i$();if(a&&await eu(a.serverUrl))return t&&xr(t,a),e&&xr(e,a),{...a,platform:navigator.platform};const o=c$();for(const i of o){if(await eu(i.serverUrl))return t&&xr(t,i),e&&xr(e,i),{...i,platform:navigator.platform};e&&Oh(e,i),t&&Oh(t,i)}throw new Error("No reachable OpenPond app server. Start `openpond ui` again and open the full printed URL.")}const Z={...o$,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 o=new URLSearchParams({teamId:t});return a.beforeSequence!=null&&o.set("beforeSequence",String(a.beforeSequence)),a.limit!=null&&o.set("limit",String(a.limit)),B(e,`/v1/team-chat/threads/${encodeURIComponent(n)}?${o.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=Nh(t),a=n.size?`?${n.toString()}`:"";return B(e,`/v1/usage${a}`)},usageRecords:(e,t={})=>{const n=Nh(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 o=a.size?`?${a.toString()}`:"";return B(e,`/v1/local-agent-schedules/${encodeURIComponent(t)}/runs${o}`)},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 o=a.size?`?${a.toString()}`:"";return B(e,`/v1/providers/${encodeURIComponent(t)}/models${o}`)},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 o=a.size?`?${a.toString()}`:"";return B(e,`/v1/codex-history/${encodeURIComponent(t)}${o}`)},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`),...ZN,...a$,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 o=a.toString()?`?${a.toString()}`:"";return B(e,`/v1/projects/${encodeURIComponent(t)}/cloud-source/preview${o}`)},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({})}),...JN,resolveApproval:(e,t,n)=>B(e,`/v1/approvals/${t}`,{method:"POST",body:JSON.stringify(n)})};function Nh(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 u$=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),m$=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,a)=>a?a.toUpperCase():n.toLowerCase()),$h=e=>{const t=m$(e);return t.charAt(0).toUpperCase()+t.slice(1)},uS=(...e)=>e.filter((t,n,a)=>!!t&&t.trim()!==""&&a.indexOf(t)===n).join(" ").trim(),p$=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var f$={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 h$=g.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:a,className:o="",children:i,iconNode:s,...l},p)=>g.createElement("svg",{ref:p,...f$,width:t,height:t,stroke:e,strokeWidth:a?Number(n)*24/Number(t):n,className:uS("lucide",o),...!i&&!p$(l)&&{"aria-hidden":"true"},...l},[...s.map(([m,f])=>g.createElement(m,f)),...Array.isArray(i)?i:[i]]));const bt=(e,t)=>{const n=g.forwardRef(({className:a,...o},i)=>g.createElement(h$,{ref:i,iconNode:t,className:uS(`lucide-${u$($h(e))}`,`lucide-${e}`,a),...o}));return n.displayName=$h(e),n};const g$=[["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"}]],b$=bt("archive-restore",g$);const v$=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],y$=bt("arrow-left",v$);const S$=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}]],mS=bt("bookmark",S$);const x$=[["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"}]],pS=bt("bookmark-x",x$);const k$=[["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"}]],Dh=bt("book-open-text",k$);const w$=[["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"}]],_$=bt("boxes",w$);const I$=[["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"}]],C$=bt("calendar-clock",I$);const R$=[["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"}]],Qu=bt("chart-column-stacked",R$);const A$=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Mo=bt("check",A$);const P$=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],fS=bt("circle-check",P$);const T$=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],ro=bt("chevron-down",T$);const E$=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],qo=bt("chevron-right",E$);const M$=[["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"}]],j$=bt("circle-alert",M$);const O$=[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]],cc=bt("cloud",O$);const N$=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],$$=bt("credit-card",N$);const D$=[["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"}]],L$=bt("download",D$);const z$=[["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"}]],tu=bt("external-link",z$);const U$=[["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"}]],H$=bt("file-output",U$);const q$=[["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"}]],Pp=bt("file-text",q$);const B$=[["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"}]],F$=bt("folder",B$);const V$=[["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"}]],hS=bt("folder-git-2",V$);const W$=[["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"}]],K$=bt("github",W$);const G$=[["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"}]],gS=bt("earth",G$);const Z$=[["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"}]],J$=bt("circle-question-mark",Z$);const Y$=[["path",{d:"M2 5h20",key:"1fs1ex"}],["path",{d:"M6 12h12",key:"8npq4p"}],["path",{d:"M9 19h6",key:"456am0"}]],X$=bt("list-filter",Y$);const Q$=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],eD=bt("loader-circle",Q$);const tD=[["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"}]],nD=bt("maximize-2",tD);const aD=[["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"}]],dc=bt("message-square",aD);const oD=[["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"}]],Tp=bt("ellipsis",oD);const rD=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],bS=bt("panel-left",rD);const iD=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],em=bt("panel-right",iD);const sD=[["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"}]],Ep=bt("pin",sD);const lD=[["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"}]],Mp=bt("pin-off",lD);const cD=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],dD=bt("search",cD);const uD=[["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=bt("settings",uD);const mD=[["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"}]],pD=bt("shapes",mD);const fD=[["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"}]],Op=bt("square-pen",fD);const hD=[["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=bt("square-terminal",hD);const gD=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],bD=bt("user-round",gD);const vD=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],ti=bt("x",vD);function yD({platform:e}){return!uc()||Np(e)?null:b.jsxs("div",{className:"window-controls","aria-label":"Window controls",children:[b.jsx("button",{type:"button",className:"window-control minimize",title:"Minimize",onClick:()=>{nu("minimize")},children:b.jsx(ro,{size:14})}),b.jsx("button",{type:"button",className:"window-control maximize",title:"Maximize",onClick:()=>{nu("toggleMaximize")},children:b.jsx(nD,{size:12})}),b.jsx("button",{type:"button",className:"window-control close",title:"Close",onClick:()=>{nu("close")},children:b.jsx(ti,{size:13})})]})}function Np(e){const t=e?.toLowerCase()??"";return t==="darwin"||t.includes("mac")}function uc(){if(typeof window>"u")return!1;const e=window.openpond;return!!(e?.minimizeWindow||e?.toggleMaximizeWindow||e?.closeWindow)}async function nu(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 SD=[{destination:"walkthroughs",icon:Dh,label:"Walkthroughs"},{destination:"external",icon:Dh,label:"Docs",url:"https://openpond.ai/docs"},{destination:"external",icon:Pp,label:"Blog",url:"https://openpond.ai/blog"},{destination:"external",icon:$$,label:"Pricing",url:"https://openpond.ai/pricing"},{destination:"external",icon:gS,label:"Web app",url:"https://openpond.ai/sandboxes"},{destination:"external",icon:K$,label:"GitHub",url:"https://github.com/openpond/openpond"},{destination:"external",icon:dc,label:"Submit issue",url:"https://github.com/openpond/openpond/issues/new/choose"}];function xD({onOpenWalkthroughs:e,walkthroughsActive:t}){const[n,a]=g.useState(!1),o=g.useRef(null);return g.useEffect(()=>{if(!n)return;function i(l){o.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]),b.jsxs("div",{className:"sidebar-help-menu",ref:o,children:[b.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:b.jsx(J$,{size:17})}),n?b.jsx("div",{className:"sidebar-help-popover",role:"menu","aria-label":"Help",children:SD.map(i=>{const s=i.icon,l=b.jsxs(b.Fragment,{children:[b.jsx(s,{size:15}),b.jsx("span",{children:i.label})]});return i.destination==="walkthroughs"?b.jsx("button",{"aria-current":t?"page":void 0,className:"sidebar-help-item",onClick:()=>{a(!1),e()},role:"menuitem",type:"button",children:l},i.label):b.jsx("a",{className:"sidebar-help-item",href:i.url,onClick:p=>{p.preventDefault(),a(!1),kD(i.url)},rel:"noreferrer",role:"menuitem",target:"_blank",children:l},i.label)})}):null]})}async function kD(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-help",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const _3=[{value:"chat",label:"Chat"},{value:"work",label:"Work"}],au=[{value:"chat",label:"Work",description:"Chat and complete tasks"},{value:"models",label:"Models",description:"Evaluate, train, and serve models"}];function yS(e){return e==="chat"?"New chat":"New task"}const tm="modelsTab",nm="modelProjectId",ou="openpond:models-tab-change",ru="openpond:model-project-change",wD=new Set(["overview","tasksets","training","evals","serving"]);function Lh(e){const t=new URLSearchParams(e).get(tm);return t==="runs"||t==="rollouts"?"training":t==="versions"?"overview":t&&wD.has(t)?t:"overview"}function _D(e,t){const n=new URLSearchParams(e);t==="overview"?n.delete(tm):n.set(tm,t);const a=n.toString();return a?`?${a}`:""}function zh(e){return new URLSearchParams(e).get(nm)}function ID(e,t){const n=new URLSearchParams(e);t?n.set(nm,t):n.delete(nm);const a=n.toString();return a?`?${a}`:""}function CD({experience:e="work",productArea:t="chat",beginNewChat:n,setSectionMenuOpen:a,setSelectedAppId:o,setSelectedProjectId:i,setSelectedSessionId:s,setView:l,view:p,modelProjects:m=[],modelTrainingActivityByProjectId:f={}}){const[S,y]=g.useState(()=>typeof window>"u"?"overview":Lh(window.location.search)),[k,R]=g.useState(()=>typeof window>"u"?null:zh(window.location.search));g.useEffect(()=>{const x=()=>y(Lh(window.location.search));return window.addEventListener("popstate",x),window.addEventListener(ou,x),()=>{window.removeEventListener("popstate",x),window.removeEventListener(ou,x)}},[]),g.useEffect(()=>{const x=()=>R(zh(window.location.search));return window.addEventListener("popstate",x),window.addEventListener(ru,x),()=>{window.removeEventListener("popstate",x),window.removeEventListener(ru,x)}},[]);function A(){o(null),i(null),s(null),a(null)}function $(x){A(),l("labs"),y(x);const I=_D(window.location.search,x);window.history.pushState(window.history.state,"",`${window.location.pathname}${I}${window.location.hash}`),window.dispatchEvent(new Event(ou))}function z(x){const I=ID(window.location.search,x||null);window.history.pushState(window.history.state,"",`${window.location.pathname}${I}${window.location.hash}`),window.dispatchEvent(new Event(ru))}const D=k?f[k]??null:null;return b.jsxs("nav",{className:"sidebar-nav","aria-label":"Primary",children:[t==="models"?null:b.jsxs("button",{className:"nav-command nav-command-new-task",type:"button",onClick:()=>n(null),children:[b.jsx(Op,{size:18}),b.jsx("span",{children:yS(e)})]}),t==="models"?b.jsxs(b.Fragment,{children:[b.jsxs("label",{className:"sidebar-model-project-picker",children:[b.jsx("span",{children:"Model Project"}),b.jsxs("select",{"aria-label":"Select Model Project",disabled:!m.length,value:k??"",onChange:x=>z(x.target.value),children:[m.length?null:b.jsx("option",{value:"",children:"No Model Projects"}),m.map(x=>b.jsx("option",{value:x.id,children:x.name},x.id))]})]}),b.jsxs("button",{className:`nav-command ${p==="labs"&&S==="overview"?"active":""}`,"aria-label":"Overview",type:"button",onClick:()=>$("overview"),children:[b.jsx(Qu,{size:16}),b.jsx("span",{children:"Overview"})]}),b.jsxs("button",{className:`nav-command ${p==="labs"&&S==="tasksets"?"active":""}`,"aria-label":"Taskset",type:"button",onClick:()=>$("tasksets"),children:[b.jsx(_$,{size:16}),b.jsx("span",{children:"Taskset"})]}),b.jsxs("button",{className:`nav-command ${D?"nav-command-training-live ":""}${p==="labs"&&S==="training"?"active":""}`,"aria-label":D?`Training, ${D.label}`:"Training",type:"button",onClick:()=>$("training"),children:[b.jsx(Qu,{size:16}),b.jsx("span",{children:"Training"}),D?b.jsx("span",{className:"nav-command-training-status","aria-label":`Training ${D.label.toLowerCase()}`,title:`Training ${D.label.toLowerCase()}`,children:b.jsx("span",{className:"sidebar-running-dot","aria-hidden":"true"})}):null]}),b.jsxs("button",{className:`nav-command ${p==="labs"&&S==="evals"?"active":""}`,"aria-label":"Evals",type:"button",onClick:()=>$("evals"),children:[b.jsx(fS,{size:16}),b.jsx("span",{children:"Evals"})]}),b.jsxs("button",{className:`nav-command ${p==="labs"&&S==="serving"?"active":""}`,"aria-label":"Serving",type:"button",onClick:()=>$("serving"),children:[b.jsx(cc,{size:16}),b.jsx("span",{children:"Serving"})]})]}):null,t==="chat"?b.jsxs(b.Fragment,{children:[b.jsxs("button",{className:`nav-command nav-command-prominent ${p==="scheduled"?"active":""}`,"aria-label":"Workflows",type:"button",onClick:()=>{A(),l("scheduled")},children:[b.jsx(C$,{size:18}),b.jsx("span",{children:"Workflows"})]}),b.jsxs("button",{className:`nav-command nav-command-prominent ${p==="outputs"?"active":""}`,"aria-label":"Outputs",type:"button",onClick:()=>{A(),l("outputs")},children:[b.jsx(H$,{size:18}),b.jsx("span",{children:"Outputs"})]}),b.jsxs("button",{className:`nav-command nav-command-prominent ${p==="apps"?"active":""}`,"aria-label":"Apps",type:"button",onClick:()=>{A(),l("apps")},children:[b.jsx(pD,{size:18}),b.jsx("span",{children:"Apps"})]}),b.jsxs("button",{className:`nav-command nav-command-prominent ${p==="projects"?"active":""}`,"aria-label":"Projects",type:"button",onClick:()=>{A(),l("projects")},children:[b.jsx(hS,{size:18}),b.jsx("span",{children:"Projects"})]})]}):null]})}function RD({setSectionMenuOpen:e,setSelectedAppId:t,setSelectedProjectId:n,setSelectedSessionId:a,setView:o,view:i}){function s(){t(null),n(null),a(null),e(null),o("get-started")}return b.jsx("nav",{className:"sidebar-utility-nav","aria-label":"Resources",children:b.jsx(xD,{onOpenWalkthroughs:s,walkthroughsActive:i==="get-started"})})}const gl=5,Cn=15,am=10,Ct={defaultChatProvider:Uo,subagents:jC(),codexPermissionMode:Kl,codexReasoningEffort:Gl,openPondCommandAccessMode:gs,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:""}}}},I3={activeTemplateId:"default",customized:!1,soul:"",soulPath:null,updatedAt:null,templates:[]},SS=[{value:hs,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"}],iu=[{value:"openpond",label:"OpenPond Chat"},{value:"codex",label:"OpenAI Codex",description:"Codex login"}],AD=["openai","xai","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],PD=["openpond","codex",...AD],xS=new Set(PD),kS=[{value:Hm,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"}],C3=[{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."}],R3=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"xhigh",label:"Extra High",shortLabel:"Extra High"}],A3=[{value:"ask",label:"Ask",description:"Ask before running shell commands."},{value:"full-access",label:"Full access",description:"Run shell commands without approval prompts."}],P3=[{value:"auto",label:"Auto",description:"Use installed language servers when available."},{value:"off",label:"Off",description:"Disable editor language servers."}],T3=[{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 $p(e){return e.kind==="local"}function TD(e){return e.kind==="cloud"}function gt(e,t){return`${e}:${t}`}function wS(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),o=t.slice(n+1);return(a==="local"||a==="cloud")&&o?{kind:a,id:o}:{kind:"local",id:t}}function $o(e){return`${e.type}:${e.id}`}function Tl(e){const t=e.currentTarget.getBoundingClientRect();return e.clientY<t.top+t.height/2?"before":"after"}function El(e,t,n,a="before"){if(t===n)return e;const o=e.filter(s=>s!==t),i=o.indexOf(n);return i===-1?e:(o.splice(a==="after"?i+1:i,0,t),o)}function Uh(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function ED(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),o=new Set(a.map(i=>i.key));return[...a,...e.filter(i=>!o.has(i.key))]}function Dp(e,t){return e?.statuses?.[t]??null}function _S(e,t){return e?.providers?.[t]??null}function IS(e,t){return e?.modelCaches?.[t]??null}function MD(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 jD(e){return e==="openpond"?SS:e==="codex"||e==="openai"?kS:[]}function OD(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 E3(e){return xS.has(e)}function om(e,t={}){if(!e)return t.localOnly,iu;const n=t.includeUnavailable??!1,a=t.enabledOnly??!1,o=[];for(const i of Tm){if(!xS.has(i)||t.localOnly&&i==="openpond")continue;const s=Dp(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||o.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 o.length>0?o:iu}function ls(e,t){const a=(IS(t,e)?.models??[]).map(MD),o=_S(t,e),i=[...o?.modelOverrides??[],o?.defaultModel].filter(s=>!!s?.trim()).map(s=>({value:s,label:s}));return OD([...a,...i,...jD(e)])}function ND(e,t,n){if(e==="codex"||e==="openai")return!0;const a=t.trim();if(!a)return!1;const o=IS(n,e)?.models.find(i=>i.id===a);return o?!!o.capabilities.reasoning:ls(e,n).some(i=>i.value===a&&/\breasoning\b/i.test(i.description??""))}function Ml(e,t){const n=_S(t,e)?.defaultModel?.trim();if(n)return n;const a=Dp(t,e)?.defaultModel?.trim();if(a)return a;const o=ls(e,t)[0]?.value?.trim();return o||(e==="codex"?Hm:e==="openpond"?hs:"")}function uo(e,t,n){const a=t?.trim();if(e==="codex"&&(a==="codex-default"||a==="gpt-5.5"))return Hm;const o=ls(e,n);return a&&o.some(i=>i.value===a)||a&&e!=="codex"&&o.length===0&&!n?a:Ml(e,n)}function CS(e,t){const n=e.modelRef?.providerId??e.provider;return{provider:n,model:uo(n,e.modelRef?.modelId,t)}}function Lp(e,t,n){return uo(e,t,n)||void 0}function la(e,t,n){const a=Lp(e,t,n);return a?{providerId:e,modelId:a}:void 0}function Hh(e){return e==="full-access"?{approvalPolicy:"never",sandbox:"danger-full-access"}:{approvalPolicy:"on-request",sandbox:"workspace-write"}}function Zn(e){const t=e?.defaultChatProvider??Ct.defaultChatProvider;return{defaultChatProvider:t,defaultChatModel:uo(t,e?.defaultChatModel),subagents:es.parse(e?.subagents??Ct.subagents),codexPermissionMode:e?.codexPermissionMode??Ct.codexPermissionMode,codexReasoningEffort:e?.codexReasoningEffort??Ct.codexReasoningEffort,openPondCommandAccessMode:e?.openPondCommandAccessMode??Ct.openPondCommandAccessMode,defaultBranchPrefix:RS(e?.defaultBranchPrefix),defaultNewProjectDirectory:e?.defaultNewProjectDirectory??Ct.defaultNewProjectDirectory,defaultTeamId:e?.defaultTeamId?.trim()||null,advancedWorkspaceControls:e?.advancedWorkspaceControls??Ct.advancedWorkspaceControls,contextCompaction:{autoEnabled:e?.contextCompaction?.autoEnabled??Ct.contextCompaction.autoEnabled,triggerPercent:e?.contextCompaction?.triggerPercent??Ct.contextCompaction.triggerPercent,summaryModel:e?.contextCompaction?.summaryModel??Ct.contextCompaction.summaryModel},training:{defaultModelRef:e?.training?.defaultModelRef??Ct.training.defaultModelRef,creationMode:e?.training?.creationMode??Ct.training.creationMode,autoApproveEvidence:e?.training?.autoApproveEvidence??Ct.training.autoApproveEvidence},sidebarWidth:e?.sidebarWidth??Ct.sidebarWidth,diffPanelWidth:e?.diffPanelWidth??Ct.diffPanelWidth,sidebarSectionsCollapsed:{pinned:e?.sidebarSectionsCollapsed?.pinned??Ct.sidebarSectionsCollapsed.pinned,projects:e?.sidebarSectionsCollapsed?.projects??Ct.sidebarSectionsCollapsed.projects,cloudProjects:e?.sidebarSectionsCollapsed?.cloudProjects??Ct.sidebarSectionsCollapsed.cloudProjects,chats:e?.sidebarSectionsCollapsed?.chats??Ct.sidebarSectionsCollapsed.chats,savedForLater:e?.sidebarSectionsCollapsed?.savedForLater??Ct.sidebarSectionsCollapsed.savedForLater},editor:{languageServers:e?.editor?.languageServers??Ct.editor.languageServers,diagnosticsWhileEditing:e?.editor?.diagnosticsWhileEditing??Ct.editor.diagnosticsWhileEditing,checkOnSave:e?.editor?.checkOnSave??Ct.editor.checkOnSave,languages:{typescript:{mode:e?.editor?.languages?.typescript?.mode??Ct.editor.languages.typescript.mode,customCommand:e?.editor?.languages?.typescript?.customCommand??Ct.editor.languages.typescript.customCommand},python:{mode:e?.editor?.languages?.python?.mode??Ct.editor.languages.python.mode,customCommand:e?.editor?.languages?.python?.customCommand??Ct.editor.languages.python.customCommand},rust:{mode:e?.editor?.languages?.rust?.mode??Ct.editor.languages.rust.mode,customCommand:e?.editor?.languages?.rust?.customCommand??Ct.editor.languages.rust.customCommand}}}}}function RS(e){const t=e?.trim()??Ct.defaultBranchPrefix;if(!t)return"";const a=t.toLowerCase().replace(/[^a-z0-9._/-]+/g,"-").replace(/\/{2,}/g,"/").replace(/^-+/,"").slice(0,48).split("/").map(o=>o.replace(/^-+|-+$/g,"")).filter(Boolean).join("/");return a?`${a}/`:""}function M3(e,t){return e==="openpond"?"OpenPond Chat":Dp(t,e)?.displayName??(e==="codex"?"OpenAI Codex":e)}function j3(e,t,n){if(n){const a=ls(n,t).find(o=>o.value===e);if(a)return a.label}if(t)for(const a of Tm){const o=ls(a,t).find(i=>i.value===e);if(o)return o.label}return[...SS,...kS].find(a=>a.value===e)?.label??e}function $D(e,t){return t==="chat"?e.filter(n=>n.experience==="chat"):e.filter(n=>n.experience==="work"||n.experience==="development")}function DD(e){return e.experience==="chat"?"Chat":"Work"}const zp="taskDraft";function AS(e){if(e?.experience!=="work")return null;const t=e.metadata?.[zp];if(!t||typeof t!="object"||Array.isArray(t))return null;const n=t.prompt;return typeof n=="string"&&n.trim()?n:null}function cs(e){return AS(e)!==null}function LD(e){return(e.split(/\r?\n/u).map(n=>n.trim()).find(Boolean)||"Task draft").slice(0,64)}function su(e,t,n=new Date().toISOString()){const a={version:1,prompt:t,savedAt:n};return{...e??{},[zp]:a}}function zD(e){const t={...e??{}};return delete t[zp],t}function eo(e){const t=al(e.metadata?.trainingTasksetId)??al(e.metadata?.tasksetId);return t?{id:t,name:al(e.metadata?.trainingTasksetName)??al(e.metadata?.tasksetName)??UD(t)}:null}function UD(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 al(e){return typeof e=="string"&&e.trim()?e.trim():null}const qh=[{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"}],HD=[{value:"recent",label:"Recent first"},{value:"manual",label:"Manual order"}];function Bh(e){const t=[];if(e.filter==="done")t.push(...e.doneSessions.filter(a=>!eo(a)));else if(e.filter==="all")t.push(...e.activeSessions.filter(a=>!eo(a)),...e.doneSessions.filter(a=>!eo(a)));else if(e.filter==="tasksets")t.push(...e.activeSessions.filter(a=>Fh(a,e.selectedTasksetId)),...e.doneSessions.filter(a=>Fh(a,e.selectedTasksetId)));else for(const a of e.activeSessions)eo(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,o)=>[a,o])):null;return e.sort==="recent"?t.sort((a,o)=>Wh(a,o,n)):t.sort((a,o)=>{const i=n?.get(a.id),s=n?.get(o.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!==o.order?a.order-o.order:Wh(a,o)})}function Fh(e,t){const n=eo(e);return!!(n&&(!t||n.id===t))}function qD(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 BD(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 Vh(e,t,n){const a=new Set(t);let o=0;return e.map(i=>{if(!a.has(i))return i;const s=n[o];return o+=1,s??i})}function Wh(e,t,n=null){const a=jl(e),o=jl(t);if(a!==o)return a?-1:1;if(a&&o){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 jl(e){return e.pinned&&!e.savedForLater&&!e.archived}function PS(e){return`${e.kind}:${e.id}`}function ds(e,t){return!!(e&&t&&e.kind===t.kind&&e.id===t.id)}function FD(e){return{kind:"session",id:e}}function VD(e){return{kind:"project",id:e}}function WD(e){return{kind:"draft",id:e}}function KD(e){return e.selectedSessionId?FD(e.selectedSessionId):e.selectedProjectId?VD(e.selectedProjectId):WD(e.selectedAppId?`app:${e.selectedAppId}`:"new-chat")}function GD(e){if(!e.previousScope||e.previousScope.kind!=="draft"||e.activeScope.kind!=="session")return[...e.tabs];if(ds(e.previousScope,e.activeScope))return[...e.tabs];const t=e.now??Date.now();return e.tabs.map(n=>ds(n.scope,e.previousScope)?{...n,scope:e.activeScope,updatedAt:t}:n)}function O3(e,t){return e.filter(n=>ds(n.scope,t))}function N3(e,t){return!!(e&&ds(e.scope,t))}function ZD(e){const t={};for(const n of e){const a=PS(n.scope),o=t[a]??{scope:n.scope,tabCount:0,runningCount:0,failedCount:0,lastExitCode:null,status:"none"};o.tabCount+=1,n.commandStatus==="running"&&(o.runningCount+=1),(n.commandStatus==="failed"||n.status==="error")&&(o.failedCount+=1),n.lastExitCode!==null&&(o.lastExitCode=n.lastExitCode),o.status=YD(o.status,n.status,n.commandStatus),t[a]=o}return t}function JD(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 YD(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 TS(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"],o=QD(e),i=t?.linkedCloudSourceKnown===!1&&!!e.headCommit;return o?a.push(o):i?a.push("upload required"):e.diverged?(e.ahead>0&&a.push(to("ahead",e.ahead)),e.behind>0&&a.push(to("behind",e.behind)),a.push("diverged")):(e.ahead>0&&a.push(to("ahead",e.ahead)),e.behind>0&&a.push(to("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 ES(e,t,n,a={}){const o=e?.linkedSandboxProject??null;if(!o?.projectId&&!t)return"upload required";if(o?.projectId&&a.cloudLinkTrusted===!1)return"uploaded to a different account";const i=o?.defaultBranch??t?.defaultBranch??"main",s=o?.manifestHash??null,l=e?.sandboxTemplate?.manifestHash??null,p=o?.syncedAt??t?.syncedAt??null,m=!!(s&&l&&s!==l),f=!!(o?.projectId&&n?.headCommit&&!o.lastUploadedCommit),S=eL(n);return S?`${i} / ${S}`:f?`${i} / upload required`:`${i} / ${m||!p?"needs sync":"setup ready"}`}function XD(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=[],o=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"),o>0&&a.push(MS(o)),t.linkedSourceHeadCommit&&t.headCommit&&t.linkedSourceHeadCommit!==t.headCommit&&t.linkedSourceComparisonError&&o===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 QD(e){return e.linkedSourceHeadCommit?e.divergedFromLinkedSource?"diverged":e.aheadOfLinkedSource>0?to("local ahead",e.aheadOfLinkedSource):e.behindLinkedSource>0?to("cloud ahead",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"sync unknown":null:null}function eL(e){return e?.linkedSourceHeadCommit?e.dirty?"local dirty files not in cloud":e.divergedFromLinkedSource?"diverged from local":e.aheadOfLinkedSource>0?to("cloud behind local",e.aheadOfLinkedSource):e.behindLinkedSource>0?to("cloud ahead local",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"source check unavailable":"synced":null}function to(e,t){return`${e} by ${MS(t)}`}function MS(e){return`${e} commit${e===1?"":"s"}`}function tL({size:e=14,className:t}){return b.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:[b.jsx("path",{d:"M12 13v8"}),b.jsx("path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242"}),b.jsx("path",{d:"m8 17 4-4 4 4"})]})}function jS({kind:e,linkedCloud:t=!1,open:n=!1,className:a,baseSize:o=15}){const i=e==="cloud"?"cloud":n?"folder-open":"folder";return b.jsx("span",{className:["project-kind-icon",e,t?"linked-cloud":"",a??""].filter(Boolean).join(" "),"aria-hidden":"true",children:b.jsxs("svg",{className:`lucide lucide-${i} project-kind-icon-svg`,xmlns:"http://www.w3.org/2000/svg",width:o,height:o,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e==="cloud"?b.jsx(oL,{}):n?b.jsx(aL,{}):b.jsx(nL,{}),t&&e==="local"?b.jsx(rL,{}):null]})})}function nL(){return b.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 aL(){return b.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 oL(){return b.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 rL(){return b.jsxs("g",{className:"project-kind-icon-cloud-badge",children:[b.jsx("circle",{cx:"18",cy:"17",r:"5"}),b.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 iL({session:e,onSave:t,onClose:n}){const[a,o]=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 b.jsx("div",{className:"git-dialog-backdrop rename-chat-backdrop",role:"presentation",onMouseDown:n,children:b.jsxs("section",{className:"git-dialog rename-chat-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"rename-chat-title",onMouseDown:p=>p.stopPropagation(),children:[b.jsx("h2",{id:"rename-chat-title",children:"Rename chat"}),b.jsx("textarea",{ref:i,className:"rename-chat-input",value:a,rows:1,maxLength:200,onChange:p=>o(p.target.value),onKeyDown:l,"aria-label":"Chat title"}),b.jsxs("div",{className:"git-dialog-footer",children:[b.jsx("button",{type:"button",className:"git-dialog-secondary",onClick:n,children:"Cancel"}),b.jsx("button",{type:"button",className:"git-dialog-primary",autoFocus:!0,onClick:s,disabled:!a.trim(),children:"Save"})]})]})})}const sL=24;function lL({title:e}){const t=g.useRef(e),[n,a]=g.useState(e);return g.useEffect(()=>{const o=t.current;if(t.current=e,!e){a("");return}if(o||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)},sL);return()=>window.clearInterval(l)},[e]),b.jsx("span",{className:`sidebar-task-title-text${e?"":" pending"}`,"aria-label":e||"Creating title",children:n||" "})}const cL=2650,dL=304,uL=260,mL=new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric"}),pL=new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit"}),fL=new Intl.DateTimeFormat("en-US",{dateStyle:"medium",timeStyle:"short"});function hL(){return{animationDelay:`${-(Date.now()%cL)}ms`}}function gL(e){const t=e.currentTarget,n=t.firstElementChild;if(!(n instanceof HTMLElement))return;const a=Math.max(0,n.scrollWidth-t.clientWidth),o=a>2;t.dataset.overflowing=String(o),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 Kh({label:e,actions:t,actionsVisible:n=!1,className:a,titleAccessory:o,children:i,collapsed:s=!1,titleActive:l=!1,onTitleClick:p,onToggleCollapsed:m}){return b.jsxs("section",{className:["sidebar-section",a,n?"actions-visible":""].filter(Boolean).join(" "),children:[b.jsxs("div",{className:"section-header",children:[b.jsxs("div",{className:"section-title-row",children:[p?b.jsxs("div",{className:"section-title-combo",children:[b.jsx("button",{type:"button",className:`section-title-link${l?" active":""}`,onClick:p,children:b.jsx("span",{children:e})}),m&&b.jsx("button",{type:"button",className:"section-chevron-button","aria-label":`${s?"Expand":"Collapse"} ${e}`,"aria-expanded":!s,onClick:m,children:s?b.jsx(qo,{size:13}):b.jsx(ro,{size:13})})]}):m?b.jsxs("button",{type:"button",className:"section-title-button","aria-label":`${s?"Expand":"Collapse"} ${e}`,"aria-expanded":!s,onClick:m,children:[b.jsx("span",{children:e}),s?b.jsx(qo,{size:13}):b.jsx(ro,{size:13})]}):b.jsx("span",{children:e}),o]}),t&&b.jsx("div",{className:"section-actions",children:t})]}),!s&&b.jsx("div",{className:"sidebar-section-body",children:i})]})}function Gh({children:e,expanded:t=!1,onClick:n}){return b.jsx("button",{type:"button",className:"sidebar-show-more",onClick:n,children:e??(t?"Show less":"Show more")})}function lu({session:e,selected:t,icon:n,archived:a=!1,hideIcon:o=!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:$=!1,onSelect:z,onToggleChildSessions:D,onTogglePin:x,onToggleSaveForLater:I,onDockRight:P,onArchive:O,onDragStart:T,onDragEnd:F,onDragOver:H,onDrop:L,onRename:V}){const[Y,ie]=g.useState(!1),_e=m?.status==="queued",fe=m?.tone==="active"&&!_e,J=(f?.activeCount??0)>0,Me=A>0&&!!D,Se=o&&!Me,ae=J||fe||!_e&&(p??e.status==="active"),xe=J&&f?f.label:fe&&m?vL(m):"Running",ee=k??(y?"hover-detail":"inline"),ue=ee==="hover-detail",ye=ee==="inline",We=["sidebar-task-row",cs(e)?"is-draft":"",P?"actions-4":I?"actions-3":"",ae?"has-running-dot":"",ue?"has-project-detail":""].filter(Boolean).join(" "),Pe=g.useMemo(hL,[]),re=b.jsxs("div",{className:`sidebar-row-actions${ue?" sidebar-task-inline-actions":""}`,children:[P?b.jsx(no,{label:"Open in right panel",onClick:P,children:b.jsx(em,{size:13})}):null,b.jsx(no,{label:e.pinned?"Unpin chat":"Pin chat",onClick:x,children:e.pinned?b.jsx(Mp,{size:13}):b.jsx(Ep,{size:13})}),I?b.jsx(no,{label:e.savedForLater?"Return to active":"Save for later",onClick:I,children:e.savedForLater?b.jsx(pS,{size:13}):b.jsx(mS,{size:13})}):null,b.jsx(no,{label:a?"Reopen":"Mark done",onClick:O,children:a?b.jsx(b$,{size:13}):b.jsx(Mo,{size:13})})]}),Ce=b.jsxs(Up,{selected:t,dataSessionId:e.id,dragging:s,iconless:Se,nested:i,placeholder:l,className:We||void 0,ariaExpanded:Me?$:void 0,ariaDescribedBy:R,onSelect:z,onDragStart:T,onDragEnd:F,onDragOver:H,onDrop:L,onDoubleClick:V?()=>ie(!0):void 0,children:[Se?null:Me?b.jsx("button",{type:"button",className:"sidebar-child-toggle","data-tooltip":$?"Hide subagent conversations":"Show subagent conversations","aria-label":`${$?"Hide":"Show"} ${A} subagent ${A===1?"conversation":"conversations"}`,"aria-expanded":$,onClick:Je=>{Je.stopPropagation(),D?.()},children:$?b.jsx(ro,{size:13}):b.jsx(qo,{size:13})}):n??b.jsx(dc,{size:15}),b.jsxs("span",{className:`row-label-shell${ue?" has-detail":""}`,children:[b.jsxs("span",{className:"sidebar-session-title-line",children:[b.jsx("span",{className:"row-label sidebar-task-title","data-overflowing":"false",onPointerEnter:gL,children:b.jsx(lL,{title:e.title})}),ye?b.jsx(rm,{value:e.updatedAt}):null]}),ue?b.jsxs("span",{className:"sidebar-session-detail-line",children:[b.jsx("span",{className:"sidebar-session-project-label",children:y}),re,b.jsx(rm,{value:e.updatedAt})]}):null]}),b.jsxs("div",{className:"row-meta",children:[b.jsxs("span",{className:"row-meta-status",children:[S?b.jsx(OS,{indicator:S}):null,ae?b.jsx("span",{className:`sidebar-running-dot${J?" subagent":fe?" goal":""}`,style:Pe,"aria-label":xe}):null]}),ue?null:re]})]}),De=Y&&V?b.jsx(iL,{session:e,onSave:Je=>V(e,Je),onClose:()=>ie(!1)}):null;return b.jsxs(b.Fragment,{children:[Ce,De]})}function bL({file:e,selected:t=!1,placeholder:n,onSelect:a,onTogglePin:o,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 b.jsxs(Up,{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?b.jsx(Pp,{size:15}):b.jsx(j$,{size:15}),b.jsx("span",{className:"row-label-shell",title:S,children:b.jsx("span",{className:"row-label",children:f})}),b.jsx("div",{className:"row-meta",children:b.jsxs("div",{className:"sidebar-row-actions",children:[b.jsx(no,{label:e.status==="pinned"?"Unpin file":"Pin file",onClick:o,children:e.status==="pinned"?b.jsx(Mp,{size:13}):b.jsx(Ep,{size:13})}),b.jsx(no,{label:e.status==="saved_for_later"?"Remove from Save for later":"Save file for later",onClick:i,children:e.status==="saved_for_later"?b.jsx(pS,{size:13}):b.jsx(mS,{size:13})})]})})]})}function vL(e){return e.actionLabel}function yL({kind:e="local",project:t,pinned:n=!1,selected:a,expanded:o=!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:$,onDragStart:z,onDragEnd:D,onDragOver:x,onDrop:I}){const[P,O]=g.useState(!1),T=g.useRef(null),[F,H]=g.useState({}),L=!!k||!!$,V=e==="local"&&l!==!1&&!!t.linkedSandboxProject?.projectId,Y=g.useCallback(()=>{if(typeof window>"u")return;const fe=T.current?.getBoundingClientRect();if(!fe)return;const J=Math.max(12,window.innerWidth-dL-12),Me=Math.max(12,window.innerHeight-uL),Se=Math.max(12,Math.min(fe.right+10,J)),ae=Math.max(12,Math.min(fe.top-4,Me)),xe={"--sidebar-project-locations-left":`${Math.round(Se)}px`,"--sidebar-project-locations-top":`${Math.round(ae)}px`};H(ee=>ee["--sidebar-project-locations-left"]===xe["--sidebar-project-locations-left"]&&ee["--sidebar-project-locations-top"]===xe["--sidebar-project-locations-top"]?ee:xe)},[]),ie=g.useCallback(()=>{Y(),S()},[S,Y]);function _e(){O(!1)}return b.jsxs("div",{ref:T,className:["sidebar-project-row-shell",P?"project-menu-open":""].filter(Boolean).join(" "),onFocusCapture:Y,onPointerEnter:Y,children:[b.jsxs(Up,{selected:a,placeholder:m,className:["sidebar-project-row",P?"project-menu-open":""].filter(Boolean).join(" "),ariaExpanded:i?o:void 0,onSelect:ie,onDragStart:z,onDragEnd:D,onDragOver:x,onDrop:I,children:[b.jsx(jS,{kind:e,linkedCloud:V,open:e==="local"&&o,className:"sidebar-row-icon",baseSize:15}),b.jsx("span",{className:"row-label-shell",children:b.jsxs("span",{className:"sidebar-project-title-line",children:[b.jsx("span",{className:"row-label",children:t.name}),b.jsx(rm,{value:t.updatedAt}),i?b.jsx("span",{className:"sidebar-project-caret","aria-hidden":"true",children:o?b.jsx(ro,{size:13}):b.jsx(qo,{size:13})}):null]})}),b.jsxs("div",{className:"row-meta",children:[b.jsx("span",{className:"row-meta-status",children:f?b.jsx(OS,{indicator:f}):null}),b.jsxs("div",{className:"sidebar-row-actions",children:[b.jsx(no,{label:n?"Unpin project":"Pin project",onClick:A,children:n?b.jsx(Mp,{size:13}):b.jsx(Ep,{size:13})}),L&&b.jsx(jL,{open:P,onToggleOpen:()=>O(fe=>!fe)}),b.jsx(no,{label:"New task",onClick:y,children:b.jsx(Op,{size:13})})]})]})]}),b.jsx(xL,{kind:e,project:t,workspaceState:s,cloudLinkTrusted:l,cloudLinkWarning:p,onWorkspaceTargetSelect:R,style:F}),P&&b.jsx(OL,{onClose:_e,onMoveToCloud:k?()=>{_e(),k()}:void 0,onRemove:()=>{_e(),$()}})]})}function rm({value:e}){const t=SL(e);if(!t||!e)return null;const n=new Date(e);return b.jsx("time",{className:"sidebar-row-updated-at",dateTime:e,title:`Last updated ${fL.format(n)}`,children:t})}function SL(e,t=new Date){if(!e)return null;const n=new Date(e);if(Number.isNaN(n.getTime()))return null;const a=pL.format(n);return n.getFullYear()===t.getFullYear()&&n.getMonth()===t.getMonth()&&n.getDate()===t.getDate()?a:`${mL.format(n)} ${a}`}function OS({indicator:e}){return b.jsx("span",{className:`sidebar-terminal-indicator ${e.status}`,"data-tooltip":e.label,"aria-label":e.label,title:e.label,children:b.jsx(vS,{size:13})})}function xL({kind:e,project:t,workspaceState:n,cloudLinkTrusted:a,cloudLinkWarning:o,onWorkspaceTargetSelect:i,style:s}){const l=_L(e,t,n,a,o);return b.jsxs("aside",{className:"sidebar-project-locations-popover","aria-label":`${t.name} status`,style:s,children:[b.jsx("div",{className:"sidebar-project-locations-title",children:t.name}),b.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=b.jsxs(b.Fragment,{children:[b.jsx("span",{className:["sidebar-project-location-icon",p.key].filter(Boolean).join(" "),"aria-hidden":"true",children:p.icon}),b.jsx("span",{className:"sidebar-project-location-copy",children:b.jsx(kL,{value:p.value})})]});return p.actionTarget?b.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):b.jsx("div",{className:m,children:f},p.key)})})]})}function kL({value:e}){const t=wL(e);return b.jsxs("span",{className:"sidebar-project-location-value","aria-label":e,children:[t.branch?b.jsxs(b.Fragment,{children:[b.jsx("span",{className:"sidebar-project-location-branch",children:t.branch}),b.jsx("span",{className:"sidebar-project-location-separator","aria-hidden":"true",children:"/"})]}):null,b.jsx("span",{className:"sidebar-project-location-status",children:t.status})]})}function wL(e){const n=e.indexOf(" / ");return n===-1?{branch:null,status:e}:{branch:e.slice(0,n),status:e.slice(n+3)}}function _L(e,t,n,a=!0,o=null){return e==="cloud"?CL(t):IL(t,n,a,o)}function IL(e,t,n=!0,a=null){const o=RL(e,t,n),i=AL(t),s=TL(e,n),l=n===!1&&a;return[{key:"local",value:o,tone:i?"attention":"local",icon:e.source==="git"?b.jsx(hS,{size:13}):b.jsx(F$,{size:13}),actionTarget:"local"},{key:"cloud",value:l||(s?EL(e,t,n):"not in cloud"),tone:l?"attention":"cloud",icon:b.jsx(cc,{size:13}),actionTarget:s?"cloud":"upload_cloud"}]}function CL(e){return[{key:"cloud",value:ML(e),tone:e.syncedAt?"cloud":"attention",icon:b.jsx(cc,{size:13}),actionTarget:"cloud"}]}function RL(e,t,n){const a=PL(e,t);return t?t.error?`${a} / status unavailable`:t.initialized?TS(t,{branch:e.linkedSandboxProject?.defaultBranch??null,linkedCloudSourceKnown:e.linkedSandboxProject?.projectId&&n?!!e.linkedSandboxProject.lastUploadedCommit||!t.headCommit:!0}):`${a} / not checked out`:`${a} / available`}function AL(e){return!!(e?.dirty||(e?.changedFilesCount??0)>0||(e?.untrackedFilesCount??0)>0)}function PL(e,t){return t?.currentBranch??t?.defaultBranch??e.linkedSandboxProject?.defaultBranch??"local"}function TL(e,t=!0){return!!(t&&e.linkedSandboxProject?.projectId||e.linkedOpenPondApp?.appId)}function EL(e,t,n){return ES(e,null,t,{cloudLinkTrusted:n})}function ML(e){const t=e.defaultBranch??"main",n=e.syncedAt?"setup ready":"needs setup";return`${t} / ${n}`}function jL({open:e,onToggleOpen:t}){return b.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:b.jsx(Tp,{size:13})})}function OL({onClose:e,onMoveToCloud:t,onRemove:n}){return b.jsxs(b.Fragment,{children:[b.jsx("button",{type:"button",className:"sidebar-project-menu-backdrop","aria-label":"Close project actions",onClick:a=>{a.stopPropagation(),e()}}),b.jsxs("div",{className:"section-menu-popover sidebar-project-row-popover",role:"menu",children:[t&&b.jsxs("button",{type:"button",role:"menuitem",onClick:a=>{a.stopPropagation(),t()},children:[b.jsx(tL,{size:13}),b.jsx("span",{children:"Move to Cloud"})]}),b.jsxs("button",{type:"button",role:"menuitem",onClick:a=>{a.stopPropagation(),n()},children:[b.jsx(ti,{size:13}),b.jsx("span",{children:"Remove from Projects"})]})]})]})}function Up({children:e,className:t,dataSessionId:n,dragging:a,iconless:o=!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 $=!!S;return b.jsx("div",{className:["sidebar-row",t??"",l?"selected":"",a?"dragging":"",o?"iconless":"",i?"nested":"",s?"placeholder":""].filter(Boolean).join(" "),draggable:$,"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 no({children:e,label:t,onClick:n}){return b.jsx("button",{type:"button",className:"sidebar-row-action","data-tooltip":t,"aria-label":t,onClick:a=>{a.stopPropagation(),n()},children:e})}function NL({filter:e,groupByProject:t,noun:n,onFilterChange:a,onGroupByProjectChange:o,onTasksetChange:i,onSortChange:s,openMenu:l,setOpenMenu:p,sort:m,selectedTasksetId:f,tasksets:S}){const[y,k]=g.useState(!1),A=S.find(D=>D.id===f)?.name??qh.find(D=>D.value===e)?.label??"Active",$=l==="tasks-filter",z=l==="chats";return b.jsxs(b.Fragment,{children:[b.jsxs("div",{className:"section-menu",children:[b.jsx("button",{type:"button",className:`section-icon ${z?"active":""}`,"aria-label":`Sort ${n}`,"aria-haspopup":"menu","aria-expanded":z,onClick:()=>p(D=>D==="chats"?null:"chats"),children:b.jsx(Tp,{size:14})}),z?b.jsxs("div",{className:"section-menu-popover",role:"menu","aria-label":`Sort ${n}`,children:[n==="tasks"?b.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":t,onClick:()=>o(!t),children:[b.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:t?b.jsx(Mo,{size:13}):null}),b.jsx("span",{children:"Group by project"})]}):null,HD.map(D=>b.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":m===D.value,onClick:()=>{s(D.value),p(null)},children:[b.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:m===D.value?b.jsx(Mo,{size:13}):null}),b.jsx("span",{children:D.label})]},D.value))]}):null]}),b.jsxs("div",{className:"section-menu",children:[b.jsx("button",{type:"button",className:`section-icon ${$||e!=="active"?"active":""}`,"aria-label":`Filter ${n}: ${A}`,"aria-haspopup":"menu","aria-expanded":$,onClick:()=>p(D=>D==="tasks-filter"?null:"tasks-filter"),children:b.jsx(X$,{size:14})}),$?b.jsx("div",{className:"section-menu-popover",role:"menu","aria-label":`Filter ${n}`,children:qh.map(D=>b.jsxs(g.Fragment,{children:[D.value==="tasksets"?b.jsxs("button",{type:"button",role:"menuitem","aria-expanded":y,onClick:()=>k(x=>!x),children:[b.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:y?b.jsx(ro,{size:13}):b.jsx(qo,{size:13})}),b.jsx("span",{children:D.label})]}):b.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":e===D.value,onClick:()=>{a(D.value),p(null)},children:[b.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e===D.value?b.jsx(Mo,{size:13}):null}),b.jsx("span",{children:D.label})]}),D.value==="tasksets"&&y?b.jsxs(b.Fragment,{children:[b.jsxs("button",{className:"section-menu-taskset-option",type:"button",role:"menuitemradio","aria-checked":e==="tasksets"&&!f,onClick:()=>{i(null),p(null)},children:[b.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&!f?b.jsx(Mo,{size:13}):null}),b.jsx("span",{children:"All Tasksets"})]}),S.map(x=>b.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:[b.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&f===x.id?b.jsx(Mo,{size:13}):null}),b.jsx("span",{children:x.name}),b.jsx("span",{className:"section-menu-option-count","aria-hidden":"true",children:x.chatCount})]},x.id))]}):null]},D.value))}):null]})]})}const $L=288,DL=112;function LL(e,t){const n=Math.max(12,t.width-$L-12),a=Math.max(12,t.height-DL-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 zL({detail:e,onClose:t}){if(g.useEffect(()=>{if(!e||typeof window>"u")return;const o=l=>{l.key==="Escape"&&t()};let i=!1;const s=window.requestAnimationFrame(()=>{window.addEventListener("scroll",t,!0),i=!0});return window.addEventListener("keydown",o),()=>{window.cancelAnimationFrame(s),window.removeEventListener("keydown",o),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 b.jsxs("aside",{id:e.descriptionId,className:"sidebar-task-detail-popover",style:e.style,"aria-label":`${e.title} details`,children:[b.jsx("div",{className:"sidebar-task-detail-title",children:e.title}),b.jsx("div",{className:"sidebar-task-detail-project",children:e.projectLabel}),b.jsx("time",{dateTime:e.updatedAt,children:a})]})}function UL({children:e,expanded:t,groupKey:n,kind:a,label:o,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"?Pp:dc,[y,k]=g.useState(!1),R=!!(s||l||p);return b.jsxs("section",{className:"sidebar-task-project-group",children:[b.jsxs("div",{className:`sidebar-task-project-group-header-shell${y?" menu-open":""}`,children:[b.jsxs("button",{type:"button",className:"sidebar-task-project-group-header","aria-controls":f,"aria-expanded":t,onClick:()=>{k(!1),i()},children:[m?b.jsx(jS,{kind:m.kind,linkedCloud:!!(m.kind==="local"&&m.project.linkedSandboxProject?.projectId),open:m.kind==="local"&&t,className:"sidebar-task-project-group-icon",baseSize:14}):b.jsx(S,{className:"sidebar-task-project-group-icon",size:14,"aria-hidden":"true"}),b.jsx("span",{className:"sidebar-task-project-group-name",children:o}),b.jsx("span",{className:"sidebar-task-project-group-caret","aria-hidden":"true",children:t?b.jsx(ro,{size:13}):b.jsx(qo,{size:13})})]}),m&&R?b.jsxs("div",{className:"sidebar-task-project-group-actions",children:[l||p?b.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:b.jsx(Tp,{size:13})}):null,s?b.jsx("button",{type:"button",className:"sidebar-row-action","data-tooltip":"New task","aria-label":"New task",onClick:s,children:b.jsx(Op,{size:13})}):null]}):null,y?b.jsxs(b.Fragment,{children:[b.jsx("button",{type:"button",className:"sidebar-task-project-group-menu-backdrop","aria-label":"Close project actions",onClick:()=>k(!1)}),b.jsxs("div",{className:"section-menu-popover sidebar-task-project-group-menu",role:"menu",children:[l?b.jsx("button",{type:"button",role:"menuitem",onClick:()=>{k(!1),l()},children:b.jsx("span",{children:"Open project"})}):null,p?b.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{k(!1),p()},children:[b.jsx(ti,{size:13}),b.jsx("span",{children:"Remove from Projects"})]}):null]})]}):null]}),t?b.jsx("div",{id:f,className:"sidebar-task-project-group-content",children:e}):null]})}const HL={},qL=new Map,BL=new Map;function FL(e,t){return Math.min(Math.max(e,Cn)+am,t)}function VL(e,t){const n=Math.max(Cn,Math.min(e,t));if(n<=Cn)return Cn;const a=Math.ceil((n-Cn)/am);return Math.max(Cn,Cn+(a-1)*am)}function WL(e,t){const n=new Map;for(const a of e){const o=t(a),i=n.get(o.key);i?i.sessions.push(a):n.set(o.key,{...o,sessions:[a]})}return[...n.values()]}function KL({activeSessions:e,archiveSession:t,archivedSessions:n,chatRowsVisibleCount:a,childSessionRowsByParentId:o={},cloudProjectRows:i,beginProjectChat:s,commitTaskDrop:l,commitTaskPreviewDrop:p,dockSessionRight:m,experience:f="work",goalRuntimeBySessionId:S=qL,localProjectRows:y,openSidebarFile:k,pinnedCollapsed:R,pinnedRows:A,previewTaskDrop:$,previewPinnedDrop:z,projectRows:D,renameSession:x,restoreSession:I,runningSessionIds:P,savedForLaterSessions:O,sectionMenuOpen:T,selectedProjectId:F,selectedSessionId:H,setChatRowsVisibleCount:L,setSectionMenuOpen:V,setSelectedAppId:Y,setSelectedProjectId:ie,setSelectedSessionId:_e,setView:fe,sidebarProjectIdBySessionId:J,startTaskDrag:Me,startPinnedDrag:Se,subagentRuntimeBySessionId:ae=BL,taskDragSessionId:xe,taskPreviewSessionIds:ee,terminalSummaries:ue=HL,toggleSessionPinned:ye,toggleSessionSavedForLater:We,view:Pe,clearTaskDrag:re,removeProject:Ce,toggleProjectPinned:De,onTogglePinnedCollapsed:Je,setSidebarFileStatus:et,commitPinnedDrop:rt,commitPinnedPreviewDrop:Be,clearSidebarDrag:He,dragItem:$e}){const[E,U]=g.useState("active"),[G,ce]=g.useState("recent"),[W,me]=g.useState(f!=="chat"),[he,Ze]=g.useState(null),[qe,it]=g.useState(()=>new Set),[nt,we]=g.useState(()=>new Map),[Oe,d]=g.useState(null),M=f==="chat"?"chats":"tasks",q=f==="chat"?"Chats":"Tasks",le=g.useMemo(()=>e.filter(te=>eo(te)===null),[e]),N=g.useMemo(()=>O.filter(te=>eo(te)===null),[O]),K=Math.max(0,le.length-N.length),w=qD({activeCount:K,filter:E,savedForLaterCount:N.length}),j=D??[...y,...i],oe=g.useMemo(()=>new Map(j.map(te=>[te.id,te.project.name])),[j]),X=g.useMemo(()=>new Map(j.map(te=>[te.id,te])),[j]),Q=g.useMemo(()=>{const te=new Set(P);for(const Ke of e){const Ge=S.get(Ke.id),St=ae.get(Ke.id);(Ge?.tone==="active"&&Ge.status!=="queued"||(St?.activeCount??0)>0||Xt(Ke.id)?.status==="running")&&te.add(Ke.id)}return te},[e,S,P,ae,ue]),pe=g.useMemo(()=>Bh({activeSessions:e,doneSessions:n,filter:"all",inProgressSessionIds:Q,sort:"manual"}),[e,n,Q]),de=g.useMemo(()=>Bh({activeSessions:e,doneSessions:n,filter:E,inProgressSessionIds:Q,selectedTasksetId:he,previewSessionIds:ee,sort:G}),[e,n,Q,he,E,ee,G]),ze=g.useMemo(()=>{const te=new Map;for(const Ke of[...e,...n]){const Ge=eo(Ke);if(!Ge)continue;const St=te.get(Ge.id);St?St.chatCount+=1:te.set(Ge.id,{...Ge,chatCount:1})}return[...te.values()].sort((Ke,Ge)=>Ke.name.localeCompare(Ge.name))},[e,n]),Te=g.useMemo(()=>de.filter(te=>!jl(te)).slice(0,Math.max(Cn,a)),[a,de]),Ne=g.useMemo(()=>WL(Te,te=>{if(cs(te))return{key:"draft",label:"Drafts",projectId:null,project:null,kind:"draft"};const Ke=J[te.id],Ge=xt(te)??"No project";return{key:Ke?`project:${Ke}`:`projectless:${Ge}`,label:Ge,projectId:Ke??null,project:Ke?X.get(Ke)??null:null,kind:Ke?"project":"projectless"}}),[oe,X,J,Te]),Ye=Te.length<de.length,Le=Te.length>Cn,ut=g.useMemo(()=>new Set(Ne.filter(te=>te.sessions.some(Ke=>Ke.id===H||Q.has(Ke.id))).map(te=>te.key)),[Ne,Q,H]),Vt=pe.filter(te=>!jl(te)).map(te=>te.id),dn=Te.map(te=>te.id),un=JSON.stringify(Object.entries(o).filter(([te,Ke])=>Ke.length>0&&(ae.get(te)?.activeCount??0)>0).flatMap(([te,Ke])=>Ke.map(Ge=>[te,Ge.id])).sort(([te,Ke],[Ge,St])=>te.localeCompare(Ge)||Ke.localeCompare(St)));g.useEffect(()=>{const te=JSON.parse(un);if(te.length===0)return;const Ke=new Set(te.map(([Ge])=>Ge));it(Ge=>[...Ke].every(St=>Ge.has(St))?Ge:new Set([...Ge,...Ke]))},[un]);function Xt(te){return JD(ue[PS({kind:"session",id:te})])}function xt(te){if(cs(te))return"Draft";const Ke=J[te.id];return Ke?oe.get(Ke)??te.workspaceName??"Project":DD(te)}function Wt(te){_e(te.id);const Ke=J[te.id]??null;Y(Ke?null:te.appId),ie(Ke),fe("chat")}function Pt(te){return o[te.id]??[]}function Rt(te,Ke){return qe.has(te.id)||Ke.some(Ge=>Ge.id===H)}function qn(te){it(Ke=>{const Ge=new Set(Ke);return Ge.has(te)?Ge.delete(te):Ge.add(te),Ge})}function jt(te){const Ke=Pt(te);return Ke.length===0||!Rt(te,Ke)?null:b.jsx("div",{className:"sidebar-child-session-group",children:Ke.map(Ge=>b.jsx(lu,{session:Ge,selected:Pe==="chat"&&H===Ge.id,hideIcon:!0,nested:!0,running:Q.has(Ge.id),goalRuntime:S.get(Ge.id)??null,subagentRuntime:ae.get(Ge.id)??null,terminalIndicator:Xt(Ge.id),projectLabel:xt(te),onSelect:()=>Wt(Ge),onTogglePin:()=>ye(Ge),onToggleSaveForLater:()=>We(Ge),onDockRight:()=>m(Ge),onArchive:()=>Ge.archived?I(Ge):t(Ge),onRename:x},Ge.id))})}function mn(te,Ke,Ge){typeof window>"u"||d({descriptionId:`sidebar-task-detail-${te.id}`,projectLabel:Ke,sessionId:te.id,title:te.title,updatedAt:te.updatedAt,style:LL(Ge.getBoundingClientRect(),{width:window.innerWidth,height:window.innerHeight})})}function Qt(te,Ke={}){const Ge=te.archived,St=xe===te.id,an=Pt(te),Ca="sidebar-session-group",kn=G==="manual"?{onDragStart:Dt=>Me(Dt,{allSessionIds:Vt,visibleSessionIds:dn,sessionId:te.id}),onDragEnd:re,onDragOver:Dt=>{St||$(Dt,te.id)},onDrop:Dt=>{St?p():l(Dt,te.id)}}:{};return b.jsxs("div",{className:Ca,onPointerEnter:Ke.metadataPresentation==="flyout"&&Ke.projectLabel?Dt=>mn(te,Ke.projectLabel,Dt.currentTarget):void 0,onPointerLeave:Ke.metadataPresentation==="flyout"?()=>d(null):void 0,onFocusCapture:Ke.metadataPresentation==="flyout"&&Ke.projectLabel?Dt=>mn(te,Ke.projectLabel,Dt.currentTarget):void 0,onBlurCapture:Ke.metadataPresentation==="flyout"?Dt=>{Dt.currentTarget.contains(Dt.relatedTarget)||d(null)}:void 0,children:[b.jsx(lu,{session:te,selected:!Ge&&Pe==="chat"&&H===te.id,archived:Ge,hideIcon:!0,placeholder:St,running:Q.has(te.id),goalRuntime:S.get(te.id)??null,subagentRuntime:ae.get(te.id)??null,terminalIndicator:Xt(te.id),projectLabel:Ke.projectLabel===void 0?xt(te):Ke.projectLabel,metadataPresentation:Ke.metadataPresentation,ariaDescribedBy:Ke.metadataPresentation==="flyout"&&Oe?.sessionId===te.id?Oe.descriptionId:void 0,childSessionCount:an.length,childSessionsExpanded:Rt(te,an),onToggleChildSessions:()=>qn(te.id),onSelect:()=>{d(null),Ge&&I(te),Wt(te)},onTogglePin:()=>ye(te),onToggleSaveForLater:()=>We(te),onDockRight:()=>m(te),onArchive:()=>Ge?I(te):t(te),onRename:x,...kn}),St?null:jt(te)]},te.id)}function ln(te){te!=="tasksets"&&Ze(null),U(te),L(Cn)}function Sn(te){Ze(te),U("tasksets"),L(Cn)}function Ia(te){ce(te),L(Cn)}function qt(){L(te=>FL(te,de.length))}function xn(){L(te=>VL(te,de.length))}function lt(te){const Ke={id:te.id,type:te.type};return{onDragStart:Ge=>Se(Ge,Ke),onDragEnd:He,onDragOver:Ge=>z(Ge,Ke),onDrop:Ge=>{$e?.id===te.id&&$e.type===te.type?Be():rt(Ge,Ke)}}}function Bt(te){const Ke=lt(te),Ge=$e?.id===te.id&&$e.type===te.type;if(te.type==="project"){const an=te.item;return b.jsx(yL,{kind:an.kind,project:an.project,pinned:!0,selected:Pe==="chat"&&F===an.id,expanded:!1,disclosure:!1,placeholder:Ge,onSelect:()=>{Y(null),ie(an.id),_e(null),fe("chat")},onNewChat:()=>s(an.id),onTogglePin:()=>De(an),onRemove:()=>Ce(an),...Ke},te.key)}if(te.type==="file")return b.jsx(bL,{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 St=te.session;return b.jsx(lu,{session:St,selected:Pe==="chat"&&H===St.id,hideIcon:!0,placeholder:Ge,running:Q.has(St.id),goalRuntime:S.get(St.id)??null,subagentRuntime:ae.get(St.id)??null,terminalIndicator:Xt(St.id),projectLabel:xt(St),metadataPresentation:"flyout",onSelect:()=>Wt(St),onTogglePin:()=>ye(St),onToggleSaveForLater:()=>We(St),onDockRight:()=>m(St),onArchive:()=>t(St),onRename:x,...Ke},te.key)}return b.jsxs("div",{className:"sidebar-scroll",children:[b.jsxs(Kh,{label:q,className:`sidebar-task-section${f!=="chat"?" development":""}`,titleAccessory:f!=="chat"?b.jsx("div",{className:"sidebar-task-mode-buttons",children:b.jsxs("button",{type:"button",className:`section-icon sidebar-task-count-bubble${E==="saved_for_later"?" active":""}`,"aria-label":`Show ${w.count} ${w.targetLabel} ${w.count===1?"task":"tasks"}`,onClick:()=>ln(w.targetFilter),children:[b.jsx("span",{children:w.label}),b.jsx("span",{className:"sidebar-task-count-badge","aria-hidden":"true",children:w.count>99?"99+":w.count})]})}):null,actionsVisible:T==="chats"||T==="tasks-filter",actions:b.jsx(NL,{filter:E,groupByProject:W,noun:M,onFilterChange:ln,onGroupByProjectChange:me,onTasksetChange:Sn,onSortChange:Ia,openMenu:T,setOpenMenu:V,sort:G,selectedTasksetId:he,tasksets:ze}),children:[A.length>0?b.jsx(Kh,{label:"Pinned",className:"sidebar-pinned-section",collapsed:R,onToggleCollapsed:Je,children:A.map(Bt)}):null,W&&f!=="chat"?Ne.map(te=>{const Ke=ut.has(te.key)||nt.get(te.key)!==!1;return b.jsx(UL,{expanded:Ke,groupKey:te.key,kind:te.kind,label:te.label,onToggle:()=>{we(Ge=>{const St=new Map(Ge);return St.set(te.key,!Ke),St})},onNewTask:te.project?()=>s(te.project.id):void 0,onOpenProject:te.project?()=>{Y(null),ie(te.project.id),_e(null),fe("chat")}:void 0,onRemoveProject:te.project?()=>Ce(te.project):void 0,project:te.project,children:te.sessions.map(Ge=>Qt(Ge,{metadataPresentation:"flyout",projectLabel:te.label}))},te.key)}):Te.map(te=>Qt(te)),de.length===0?b.jsx("div",{className:"empty-row",children:BD(E,M)}):null,de.length>Cn&&(Ye||Le)?b.jsxs("div",{className:"sidebar-pagination-controls","aria-label":`Showing ${Te.length} of ${de.length} ${M}`,children:[Ye?b.jsx(Gh,{onClick:qt,children:"Show more"}):null,Le?b.jsx(Gh,{onClick:xn,children:"Show less"}):null]}):null]}),b.jsx(zL,{detail:Oe,onClose:()=>d(null)})]})}const GL="./";function Dn(e){return`${GL}${e.replace(/^\.?\//,"")}`}const ZL=Dn("openpond-icon.png"),JL=Dn("openpond-wordlogo-white.png"),$3=Dn("tutorials/what-is-an-openpond-agent-poster.png"),D3=Dn("tutorials/what-is-an-openpond-agent.vtt"),L3=Dn("tutorials/how-to-make-an-agent-poster.png"),z3=Dn("tutorials/how-to-make-an-agent.vtt");function U3(e){return Dn(`tutorials/how-to-make-an-agent-${e}-poster.png`)}function H3(e){return Dn(`tutorials/how-to-make-an-agent-${e}.vtt`)}const Zh={github:Dn("connected-apps/github.svg"),google:Dn("connected-apps/google.svg"),microsoft_teams:Dn("connected-apps/microsoft.svg"),mcp:Dn("connected-apps/openpond-mcp.svg"),slack:Dn("connected-apps/slack.svg"),x:Dn("connected-apps/x.svg")};function q3(e){return Zh[e]??Zh.mcp}function YL({value:e,onChange:t}){const[n,a]=g.useState(!1),o=g.useRef(null),i=g.useRef(null),s=g.useRef(null),l=au.find(y=>y.value===e)??au[0];g.useEffect(()=>{if(!n)return;const y=R=>{R.target instanceof Node&&!o.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=Jh(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=Jh(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,$=R<0?0:(R+A+k.length)%k.length;k[$]?.focus()};return b.jsxs("div",{className:"sidebar-experience-menu",ref:o,children:[b.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:[b.jsx("img",{className:"sidebar-wordmark",src:JL,alt:""}),b.jsx("span",{className:"sidebar-experience-label",children:l.label}),b.jsx(ro,{size:13,"aria-hidden":"true"})]}),n?b.jsx("div",{ref:s,className:"sidebar-experience-popover",role:"menu","aria-label":"Choose product",onKeyDown:S,children:au.map(y=>{const k=y.value===e;return b.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:[b.jsxs("span",{children:[b.jsx("strong",{children:y.label}),b.jsx("small",{children:y.description})]}),k?b.jsx(Mo,{size:14,"aria-hidden":"true"}):null]},y.value)})}):null]})}function Jh(e){return e?Array.from(e.querySelectorAll('[role="menuitemradio"]')):[]}function XL(...e){for(const t of e){const n=t?.trim();if(n)return n}return null}function QL(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"?XL(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 ez({account:e,onOpenActivity:t,onOpenSettings:n}){const[a,o]=g.useState(!1),i=g.useRef(null),s=g.useMemo(()=>QL(e),[e]),l=s.label.trim().slice(0,1).toUpperCase();return g.useEffect(()=>{if(!a)return;function p(f){i.current?.contains(f.target)||o(!1)}function m(f){f.key==="Escape"&&o(!1)}return document.addEventListener("pointerdown",p),document.addEventListener("keydown",m),()=>{document.removeEventListener("pointerdown",p),document.removeEventListener("keydown",m)}},[a]),b.jsxs("div",{className:"user-auth-footer",ref:i,children:[b.jsxs("button",{type:"button",className:`user-auth-trigger ${a?"active":""}`,"aria-haspopup":"menu","aria-expanded":a,"aria-label":`${s.label} account menu`,onClick:()=>o(p=>!p),children:[b.jsx("span",{className:"user-auth-avatar","aria-hidden":"true",children:s.image?b.jsx("img",{src:s.image,alt:""}):l?b.jsx("span",{children:l}):b.jsx(bD,{size:16})}),b.jsx("span",{className:"user-auth-name",children:s.label})]}),a?b.jsxs("div",{className:"user-auth-menu",role:"menu","aria-label":"Account",children:[t?b.jsxs("a",{href:"/settings/usage",className:"user-auth-menu-link",role:"menuitem",onClick:p=>{p.preventDefault(),o(!1),t()},children:[b.jsx(Qu,{size:15}),b.jsx("span",{children:"Activity"})]}):null,b.jsxs("a",{href:"/settings",className:"user-auth-menu-link",role:"menuitem",onClick:p=>{p.preventDefault(),o(!1),n()},children:[b.jsx(jp,{size:15}),b.jsx("span",{children:"Settings"})]})]}):null]})}function Yh(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 tz(e,t){const n=Yh(e),a=Yh(t);if(!n||!a)return!1;for(let o=0;o<a.length;o+=1){if(a[o]>n[o])return!0;if(a[o]<n[o])return!1}return!1}function NS(e){const t=e?.toLowerCase()??"";return t==="darwin"||t.includes("mac")?"mac":t==="linux"||t.includes("linux")?"linux":null}function nz(e){const t=e?.toLowerCase()??"";return t==="arm64"||t==="aarch64"?"arm64":t==="x64"||t==="x86_64"||t==="amd64"?"x64":null}function az(e,t,n){const a=NS(t),o=nz(n);if(a==="mac"){const i=e.filter(s=>/-mac-.*\.zip$/i.test(s.name));return o==="arm64"?i.find(s=>/-mac-arm64\.zip$/i.test(s.name))??null:o==="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 o==="arm64"?i.find(s=>/(?:arm64|aarch64).*\.AppImage$/i.test(s.name))??null:o==="x64"?i.find(s=>/(?:x86_64|x64|amd64).*\.AppImage$/i.test(s.name))??i[0]??null:i[0]??null}return null}function oz(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(!tz(e.currentVersion,a))return null;const o=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=az(s,e.platform,e.arch);return!l||!o?null:{version:a,releaseUrl:o,assetName:l.name,downloadUrl:l.downloadUrl}}const rz=3600*1e3,iz="https://api.github.com/repos/openpond/openpond/releases/latest";function sz(e){const[t,n]=g.useState({status:"idle",update:null,lastCheckedAt:null}),a=e.currentVersion?.trim()??"",o=e.platform??"",i=e.arch??"",s=e.enabled&&!!a&&!!NS(o);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(iz,{headers:{Accept:"application/vnd.github+json"}});if(!f.ok)throw new Error(`GitHub release check failed: ${f.status}`);const S=await f.json(),y=oz({payload:S,currentVersion:a,platform:o,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()},rz);return()=>{l=!0,window.clearInterval(m)}},[i,a,s,o]),t}const $S="openpond.sidebar.continuous-learning.dismissed.v1";function lz(e=DS()){if(!e)return!1;try{return e.getItem($S)==="true"}catch{return!1}}function cz(e=DS()){if(e)try{e.setItem($S,"true")}catch{}}function DS(){return typeof window>"u"?null:window.localStorage}function dz({connection:e,onOpenSettings:t}){const[n,a]=g.useState(null),[o,i]=g.useState(lz),s=g.useCallback(async()=>{if(!e){a(null);return}try{a(await Z.harnessHistory(e))}catch{a(null)}},[e]);if(g.useEffect(()=>{s()},[s]),o||!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 b.jsxs("section",{className:"sidebar-learning-notice","aria-label":"Continuous learning",children:[b.jsxs("header",{children:[b.jsx("strong",{children:"Continuous learning"}),b.jsxs("div",{className:"sidebar-learning-notice-actions",children:[b.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Open Continuous learning settings",onClick:t,type:"button",children:b.jsx(jp,{size:14})}),b.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Close continuous learning",onClick:()=>{i(!0),cz()},type:"button",children:b.jsx(ti,{size:14})})]})]}),b.jsxs("div",{className:"sidebar-learning-status",children:[b.jsx("strong",{children:"Refiner"}),b.jsx("span",{children:n.backgroundReview.enabled?"On":"Off"})]}),b.jsxs("div",{className:"sidebar-learning-status",children:[b.jsx("strong",{children:"Continuous Review"}),b.jsx("span",{children:p})]})]})}function uz(e){const{beginNewChat:t,arch:n,currentVersion:a,experience:o,productArea:i,onProductAreaChange:s,onSidebarResizeStart:l,platform:p,setSectionMenuOpen:m,setSelectedAppId:f,setSelectedProjectId:S,setSelectedSessionId:y,setSidebarOpen:k,setSettingsSection:R,setView:A,view:$,modelProjects:z,modelTrainingActivityByProjectId:D}=e,x=sz({currentVersion:a,platform:p,arch:n,enabled:uc()}),I=x.status==="available"?x.update:null;return b.jsxs("aside",{className:"sidebar",children:[b.jsxs("div",{className:"sidebar-toolbar",children:[b.jsx("button",{className:"sidebar-icon","aria-label":"Hide sidebar",onClick:()=>k(!1),children:b.jsx(bS,{size:16})}),b.jsx(YL,{value:i,onChange:s}),I&&b.jsxs("button",{type:"button",className:"sidebar-update-pill",title:`Download OpenPond ${I.version}: ${I.assetName}`,"aria-label":`Download OpenPond ${I.version}`,onClick:()=>{mz(I.downloadUrl)},children:[b.jsx(L$,{size:14}),b.jsx("span",{children:"Update"})]})]}),b.jsx(CD,{productArea:i,experience:o,beginNewChat:t,setSectionMenuOpen:m,setSelectedAppId:f,setSelectedProjectId:S,setSelectedSessionId:y,setView:A,view:$,modelProjects:z,modelTrainingActivityByProjectId:D}),i==="models"?null:b.jsx(KL,{...e}),b.jsxs("div",{className:"sidebar-bottom-stack",children:[i==="models"?null:b.jsx(dz,{connection:e.connection,onOpenSettings:()=>{m(null),R("harness"),A("settings")}}),b.jsxs("div",{className:"sidebar-footer-row",children:[b.jsx(ez,{account:e.account,onOpenActivity:()=>{m(null),R("usage"),A("settings")},onOpenSettings:()=>{m(null),R("account"),A("settings")}}),b.jsx(RD,{setSectionMenuOpen:m,setSelectedAppId:f,setSelectedProjectId:S,setSelectedSessionId:y,setView:A,view:$})]})]}),b.jsx("div",{className:"sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",onPointerDown:l})]})}async function mz(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-update",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const pz=[/^(?:(?:type)?error:\s*)?failed to fetch\.?$/i,/^networkerror when attempting to fetch resource\.?$/i,/^load failed\.?$/i];function LS(e,t="Something went wrong."){const a=(e instanceof Error?e.message:String(e??"")).trim();return a?zS(a)?"Couldn’t connect to OpenPond.":a:t}function zS(e){const t=e.trim();return pz.some(n=>n.test(t))}const US=g.createContext(null);function Xh({children:e,showToast:t}){return b.jsx(US.Provider,{value:t,children:e})}function fz(){return g.useContext(US)}function Qh(e,t={}){const n=fz(),a=g.useRef(null),o=t.enabled??!0,i=t.fallback??"Something went wrong.",s=t.prefix?.trim()??"",l=e==null||e===""?null:`${s}${s?": ":""}${LS(e,i)}`;g.useEffect(()=>{if(!o||!l){a.current=null;return}a.current!==l&&(a.current=l,n?.(l,"error",{dismissible:!0}))},[o,l,n])}function hz({state:e,onClose:t,onOpenBrowserUrl:n,onStart:a}){if(Qh(e?.previewError,{prefix:"Upload preview"}),Qh(e?.error,{prefix:"Cloud setup"}),!e)return null;const o=e.status==="uploading",i=e.status==="ready",s=e.status==="error",l=e.projectKind==="cloud",p=e.preview??null;return b.jsx("div",{className:"git-dialog-backdrop",role:"presentation",children:b.jsxs("section",{className:"git-dialog cloud-setup-dialog",role:"dialog","aria-modal":"true","aria-label":"Set up Cloud coding",children:[b.jsx("button",{className:"git-dialog-close",disabled:o,type:"button",onClick:t,"aria-label":"Close Cloud setup",title:"Close",children:b.jsx(ti,{size:14})}),b.jsx("div",{className:"git-dialog-icon",children:i?b.jsx(fS,{size:18}):b.jsx(cc,{size:18})}),b.jsx("h2",{children:i?"Cloud repo ready":"Set up Cloud coding"}),b.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."}),b.jsxs("div",{className:"cloud-setup-summary",children:[b.jsxs("div",{className:"git-dialog-row",children:[b.jsx("span",{children:"Project"}),b.jsx("strong",{children:e.projectName})]}),b.jsxs("div",{className:"git-dialog-row",children:[b.jsx("span",{children:"Source"}),b.jsx("strong",{children:l?"OpenPond Git":"Local project upload"})]}),b.jsxs("div",{className:"git-dialog-row",children:[b.jsx("span",{children:"Branch"}),b.jsx("strong",{children:p?.branch??e.branch??"main"})]}),!l&&b.jsxs("div",{className:"git-dialog-row",children:[b.jsx("span",{children:"Cloud project"}),b.jsx("strong",{children:p?.targetProjectId??e.cloudProjectId??"New on upload"})]})]}),!i&&!l&&b.jsx("div",{className:"cloud-setup-upload-preview",role:"status","aria-live":"polite",children:e.previewLoading?b.jsxs(b.Fragment,{children:[b.jsx("strong",{children:"Calculating upload preview"}),b.jsx("span",{children:"Checking tracked and unignored files before anything is pushed."})]}):e.previewError?b.jsxs(b.Fragment,{children:[b.jsx("strong",{children:"Preview unavailable"}),b.jsx("span",{children:"Close and reopen setup to try the preview again."})]}):p?b.jsxs(b.Fragment,{children:[b.jsx("strong",{children:p.initializedEmptyProject?"Will initialize an empty project":`Will upload ${p.fileCount} files`}),b.jsx("span",{children:eg({byteCount:p.byteCount,skippedCount:p.skippedCount,headCommit:p.headCommit,targetProjectName:p.targetProjectName})})]}):b.jsxs(b.Fragment,{children:[b.jsx("strong",{children:"Upload preview pending"}),b.jsx("span",{children:"File count, byte count, and skipped files will appear here before upload."})]})}),o&&b.jsxs("div",{className:"cloud-setup-progress",role:"status","aria-live":"polite",children:[b.jsx(eD,{className:"cloud-setup-spinner",size:16}),b.jsx("span",{children:"Uploading source to OpenPond Git..."})]}),i&&e.upload&&b.jsxs("div",{className:"cloud-setup-upload-result",children:[b.jsx("strong",{children:e.upload.initializedEmptyProject?"Initialized empty project":`Uploaded ${e.upload.fileCount} files`}),b.jsx("span",{children:eg({byteCount:e.upload.byteCount,skippedCount:e.upload.skippedCount,headCommit:e.upload.headCommit,targetProjectName:e.upload.branch})})]}),i&&e.setupUrl&&b.jsxs("div",{className:"cloud-setup-next",children:[e.projectUrl?b.jsxs("span",{children:["Your repo is ready here:"," ",b.jsxs("a",{href:e.projectUrl,target:"_blank",rel:"noreferrer",onClick:m=>cu(m,e.projectUrl,n,{newTab:!0}),children:["Project page",b.jsx(tu,{size:13})]})]}):b.jsx("span",{children:"Your repo is ready. Next step:"}),b.jsxs("a",{href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:m=>cu(m,e.setupUrl,n),children:["Setup the Cloud sandbox",b.jsx(tu,{size:13})]})]}),b.jsxs("div",{className:"git-dialog-footer",children:[b.jsx("button",{className:"git-dialog-secondary",disabled:o,type:"button",onClick:t,children:i?"Done":"Cancel"}),i?e.setupUrl?b.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",b.jsx(tu,{size:13})]}):null:b.jsx("button",{className:"git-dialog-primary",disabled:o,type:"button",onClick:a,children:o?"Uploading":s?"Try again":l?"Show setup link":"Upload source"})]})]})})}function cu(e,t,n,a={}){!t||!n||(e.preventDefault(),n(t,a))}function gz(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 eg({byteCount:e,skippedCount:t,headCommit:n,targetProjectName:a}){const o=[gz(e),`${t} skipped`],i=bz(n);return i&&o.push(`local ${i}`),o.push(a),o.join(" · ")}function bz(e){const t=e?.trim();return t?t.slice(0,7):null}const vz=g.lazy(()=>Bo(()=>import("./CommandMenu-B5lGz8rG.js"),__vite__mapDeps([0,1,2,3]),import.meta.url).then(e=>({default:e.CommandMenu}))),yz=g.lazy(()=>Bo(()=>import("./SettingsView-CWTAUy2b.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}))),Sz=g.lazy(()=>Bo(()=>import("./NewProjectDialog-NuPVF2Y7.js"),__vite__mapDeps([27,1,2,8,16]),import.meta.url).then(e=>({default:e.NewProjectDialog}))),xz=g.lazy(()=>Bo(()=>import("./WorkspaceGitDialogs-BxU5Uhpz.js"),__vite__mapDeps([28,1,2,13,29,14,30,26]),import.meta.url).then(e=>({default:e.CommitDialog}))),kz=g.lazy(()=>Bo(()=>import("./WorkspaceGitDialogs-BxU5Uhpz.js"),__vite__mapDeps([28,1,2,13,29,14,30,26]),import.meta.url).then(e=>({default:e.BranchDialog})));function wz({payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:o,onError:i,onToast:s,onBack:l,onOpenSourceSession:p,onStartRefinerAuthoring:m,onAcceptEvaluationReview:f,onOpenSkill:S,onOpenExtension:y,teamChatCurrentUserId:k,teamChatEnabled:R,teamChatNotificationMode:A,teamChatThreads:$,onTeamChatNotificationModeChange:z,onTeamChatThreadMuteChange:D,diffPanelWidth:x,diffPanelResizing:I,diffPanelExpanded:P,onDiffPanelResizeStart:O,onDiffPanelExpandedChange:T}){return b.jsx(g.Suspense,{fallback:null,children:b.jsx(yz,{payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:o,onError:i,onToast:s,onBack:l,onOpenSourceSession:p,onStartRefinerAuthoring:m,onAcceptEvaluationReview:f,onOpenSkill:S,onOpenExtension:y,teamChatCurrentUserId:k,teamChatEnabled:R,teamChatNotificationMode:A,teamChatThreads:$,onTeamChatNotificationModeChange:z,onTeamChatThreadMuteChange:D,diffPanelWidth:x,diffPanelResizing:I,diffPanelExpanded:P,onDiffPanelResizeStart:O,onDiffPanelExpandedChange:T})})}function _z({activeSessions:e,branchDialogName:t,branchDialogOpen:n,commitDialogOpen:a,commitDraft:o,commitIncludeUnstaged:i,commitMessage:s,commitNextStep:l,canPublishOpenPondProject:p,expandProject:m,newProjectBusy:f,newProjectDialogOpen:S,newProjectDirectory:y,newProjectMode:k,newProjectName:R,newProjectPath:A,projectRows:$,query:z,searchOpen:D,visibleWorkspaceDiff:x,visibleWorkspaceState:I,workspaceBusy:P,appDispatch:O,beginNewChat:T,openDefaultsSettingsFromBranchDialog:F,setBranchDialogName:H,setBranchDialogOpen:L,setCommitDialogOpen:V,setCommitDraft:Y,setCommitIncludeUnstaged:ie,setCommitMessage:_e,setCommitNextStep:fe,setNewProjectDialogOpen:J,setNewProjectName:Me,setNewProjectPath:Se,setQuery:ae,setSearchOpen:xe,submitCommitDialog:ee,submitCreateWorkspaceBranch:ue,submitNewProjectDialog:ye}){return b.jsxs(b.Fragment,{children:[D&&b.jsx(g.Suspense,{fallback:null,children:b.jsx(vz,{open:D,query:z,projects:$,sessions:e,onQueryChange:ae,onClose:()=>{xe(!1),ae("")},onNewChat:()=>{xe(!1),ae(""),T()},onOpenProject:We=>{O({type:"selectProject",projectId:We.id}),O({type:"patch",patch:{searchOpen:!1,query:""}}),m(We.id)},onOpenSession:We=>{O({type:"selectSession",sessionId:We.id,appId:We.appId,projectId:We.workspaceKind==="local_project"&&We.workspaceId?gt("local",We.workspaceId):null}),O({type:"patch",patch:{searchOpen:!1,query:""}})}})}),S&&b.jsx(g.Suspense,{fallback:null,children:b.jsx(Sz,{open:S,mode:k,name:R,path:A,directory:y,busy:f,onNameChange:Me,onPathChange:Se,onClose:()=>{f||J(!1)},onSubmit:ye})}),a&&b.jsx(g.Suspense,{fallback:null,children:b.jsx(xz,{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:o,busy:P,canPush:!!I?.remoteUrl,canPublish:p,onMessageChange:_e,onIncludeUnstagedChange:ie,onNextStepChange:fe,onDraftChange:Y,onClose:()=>{P||V(!1)},onSubmit:ee})}),n&&b.jsx(g.Suspense,{fallback:null,children:b.jsx(kz,{open:n,branchName:t,busy:P,onBranchNameChange:H,onSetPrefix:F,onClose:()=>{P||L(!1)},onSubmit:ue})})]})}function HS({toast:e,onDismiss:t}){if(!e)return null;const n=!!(e.actionLabel&&e.onAction),a=!!(e.persistent||e.dismissible);return b.jsxs("div",{className:`app-toast ${e.tone} ${e.placement??"bottom-right"}`,role:e.tone==="error"?"alert":"status","aria-live":"polite",children:[b.jsx("span",{className:"app-toast-message",children:e.message}),(n||a)&&b.jsxs("div",{className:"app-toast-actions",children:[n&&b.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"?b.jsx(jp,{size:15}):e.actionLabel}),a&&b.jsx("button",{type:"button",className:"app-toast-close","aria-label":"Dismiss notification",onClick:t,children:b.jsx(ti,{size:14})})]})]})}async function Iz(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 Cz({activeView:e,onDiscoverCommunities:t,onOpenTeamChat:n}){return b.jsxs("div",{className:"titlebar-collaboration-actions",children:[b.jsx("button",{type:"button",className:`titlebar-icon${e==="team"?" active":""}`,"aria-label":"Team chat",title:"Team chat",onClick:n,children:b.jsx(dc,{size:16})}),b.jsx("button",{type:"button",className:`titlebar-icon${e==="community"?" active":""}`,"aria-label":"Discover communities",title:"Discover communities",onClick:t,children:b.jsx(gS,{size:16})})]})}const Rz=g.lazy(()=>Bo(()=>import("./WorkspaceEnvironmentMenu-Bp-9V7Jq.js"),__vite__mapDeps([31,1,2,29,22,32,10,33,14,6,30,34]),import.meta.url).then(e=>({default:e.WorkspaceEnvironmentMenu})));function Az({sidebarOpen:e,title:t,conversationId:n,breadcrumbs:a,backAction:o,workspaceName:i,workspaceId:s,busy:l,workspaceState:p,workspaceKind:m,selectedApp:f,selectedProject:S,workspaceDiff:y,managedWorkspace:k,workspaceBusy:R,defaultTeamId:A,showDiffControls:$,diffPanelOpen:z,terminalOpen:D,rightSidebarAvailable:x=!1,rightSidebarOpen:I=!1,onToggleDiffPanel:P,onToggleRightSidebar:O,onOpenSearch:T,onToggleTerminal:F,onRunTerminalCommand:H,onWorkspaceToolAction:L,onOpenCommitDialog:V,onWorkspaceBranchChange:Y,onWorkspaceBranchCreate:ie,connection:_e,onBootstrap:fe,onOpenSandboxWorkspace:J,onShowSidebar:Me,onOpenTeamChat:Se,onDiscoverCommunities:ae,collaborationView:xe=null,platform:ee,showWorkspaceControls:ue=!0}){const ye=y?.filesChanged??0,We=uc()&&!Np(ee),Pe=!!(Se||ae)||ue||x||We,[re,Ce]=g.useState(null);g.useEffect(()=>{if(!re)return;const et=()=>Ce(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)}},[re]);const De=et=>{et.preventDefault(),et.stopPropagation();const rt=190,Be=n?76:42;Ce({x:Math.min(et.clientX,window.innerWidth-rt-8),y:Math.min(et.clientY,window.innerHeight-Be-8)})},Je=et=>{Iz(et),Ce(null)};return b.jsxs("header",{className:"app-titlebar",children:[b.jsxs("div",{className:"titlebar-left",children:[!e&&b.jsx("button",{className:"titlebar-icon",title:"Show sidebar",onClick:Me,children:b.jsx(bS,{size:16})}),o?b.jsx("button",{className:"titlebar-icon",type:"button","aria-label":o.label,title:o.label,onClick:o.onSelect,children:b.jsx(y$,{size:16})}):null,a?.length?b.jsx("nav",{className:"titlebar-breadcrumbs","aria-label":"Breadcrumb",children:a.map((et,rt)=>{const Be=rt===a.length-1;return b.jsxs("div",{className:"titlebar-breadcrumb-item",children:[et.onSelect&&!Be?b.jsx("button",{type:"button",onClick:et.onSelect,children:et.label}):b.jsx("strong",{children:et.label}),!Be&&b.jsx(qo,{size:14})]},`${et.label}-${rt}`)})}):b.jsxs("div",{className:"titlebar-title",children:[b.jsx("strong",{className:"titlebar-copy-target",title:"Double-click to select; right-click for copy options",onContextMenu:De,children:t}),i&&b.jsx("span",{children:i})]})]}),Pe&&b.jsxs("div",{className:"titlebar-right",children:[b.jsx(Cz,{activeView:xe,onDiscoverCommunities:ae,onOpenTeamChat:Se}),ue&&b.jsxs("div",{className:"titlebar-actions",children:[b.jsx(g.Suspense,{fallback:null,children:b.jsx(Rz,{mode:"topbar",busy:l,workspaceState:p,workspaceId:s,workspaceKind:m,selectedApp:f,selectedProject:S,workspaceBusy:R,defaultTeamId:A,workspaceDiff:y,managedWorkspace:k,showDiffControls:$,diffPanelOpen:z,onToggleDiffPanel:P,onRunTerminalCommand:H,onWorkspaceToolAction:L,onOpenCommitDialog:V,onWorkspaceBranchChange:Y,onWorkspaceBranchCreate:ie,connection:_e,onBootstrap:fe,onOpenSandboxWorkspace:J})}),b.jsx("button",{type:"button",className:"titlebar-icon",title:"Search chats and projects","aria-label":"Search chats and projects",onClick:T,children:b.jsx(dD,{size:16})}),b.jsx("button",{type:"button",className:`titlebar-icon ${D?"active":""}`,title:`${D?"Hide":"Show"} terminal`,"aria-label":`${D?"Hide":"Show"} terminal`,"aria-pressed":D,onClick:F,children:b.jsx(vS,{size:16})}),$&&b.jsx("button",{type:"button",className:`topbar-diff-button ${I?"active":""}`,title:`${I?"Hide":"Show"} sidebar${ye?`, ${ye} changed files`:""}`,"aria-label":`${I?"Hide":"Show"} sidebar`,"aria-pressed":I,onClick:P,children:b.jsx(em,{size:16})})]}),x&&O&&!$?b.jsx("div",{className:"titlebar-actions",children:b.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:O,children:b.jsx(em,{size:16})})}):null,b.jsx(yD,{platform:ee})]}),re&&b.jsxs("div",{className:"titlebar-copy-menu",role:"menu","aria-label":"Conversation title actions",style:{left:re.x,top:re.y},onPointerDown:et=>et.stopPropagation(),children:[b.jsx("button",{type:"button",role:"menuitem",onClick:()=>Je(t),children:"Copy title"}),n&&b.jsx("button",{type:"button",role:"menuitem",onClick:()=>Je(n),children:"Copy conversation ID"})]})]})}function Pz(){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)}),[]),o=g.useCallback(i=>{const s=n.current;n.current=null,t(null),s?.resolve(i)},[]);return{confirmAction:a,confirmDialog:e,resolveConfirmDialog:o}}function Tz({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 o=e.tone==="danger"?"git-dialog-primary danger":"git-dialog-primary";return b.jsx("div",{className:"git-dialog-backdrop",role:"presentation",onMouseDown:()=>t(!1),children:b.jsxs("section",{className:"git-dialog project-confirm-dialog",role:"alertdialog","aria-modal":"true","aria-labelledby":n,"aria-describedby":a,onMouseDown:i=>i.stopPropagation(),children:[b.jsx("h2",{id:n,children:e.title}),b.jsx("p",{id:a,children:e.body}),b.jsxs("div",{className:"git-dialog-footer",children:[b.jsx("button",{type:"button",className:"git-dialog-secondary",onClick:()=>t(!1),children:e.cancelLabel}),b.jsx("button",{type:"button",className:o,autoFocus:!0,onClick:()=>t(!0),children:e.confirmLabel})]})]})})}function Ez(){const{confirmAction:e,confirmDialog:t,resolveConfirmDialog:n}=Pz();return{confirmProjectAction:g.useCallback(o=>e({tone:"danger",...o}),[e]),projectConfirmDialog:t,resolveProjectConfirmDialog:n}}function Mz({state:e,onResolve:t}){return b.jsx(Tz,{state:e,onResolve:t})}const Ol=new Map,jz=(e,t,n)=>{const a=Ol.get(e)??{commits:0,maxActualDurationMs:0,totalActualDurationMs:0};a.commits+=1,a.maxActualDurationMs=Math.max(a.maxActualDurationMs,n),a.totalActualDurationMs+=n,Ol.set(e,a)};function Oz({children:e,id:t}){return b.jsx(g.Profiler,{id:t,onRender:jz,children:e})}typeof window<"u"&&(window.__OPENPOND_RENDER_COMMITS__={get:()=>Object.fromEntries([...Ol.entries()].map(([e,t])=>[e,{...t}])),reset:()=>Ol.clear()});const Nz=g.lazy(()=>Bo(()=>import("./MainPane-DxVcMBFo.js").then(e=>e.M),__vite__mapDeps([35,1,2,13,5,36,32]),import.meta.url).then(e=>({default:e.MainPane})));function $z({className:e,style:t,sidebar:n,topBar:a,mainPane:o,cloudSetup:i,projectConfirm:s,lazyPanels:l,toast:p}){return b.jsxs("div",{className:e,style:t,children:[b.jsx(Oz,{id:"sidebar",children:b.jsx(uz,{...n})}),b.jsxs("div",{className:"content-shell",children:[b.jsx(Az,{...a}),b.jsx(g.Suspense,{fallback:b.jsx("main",{className:"main-pane","aria-busy":"true","aria-label":"Loading workspace"}),children:b.jsx(Nz,{...o})})]}),b.jsx(hz,{...i}),b.jsx(Mz,{...s}),b.jsx(_z,{...l}),b.jsx(HS,{...p})]})}function Dz({settings:e,toast:t}){return b.jsxs(b.Fragment,{children:[b.jsx(wz,{...e}),b.jsx(HS,{...t})]})}const bl="OpenPond".split("");function Lz({visibleLetterCount:e=bl.length}){const t=bl.slice(0,Math.max(0,Math.min(e,bl.length)));return b.jsxs("div",{className:"app-splash-lockup",children:[b.jsx("div",{className:"app-splash-mark",children:b.jsx("img",{alt:"OpenPond",className:"app-splash-logo",decoding:"async",src:ZL})}),b.jsx("span",{"aria-hidden":"true",className:`app-splash-wordmark${t.length>0?" is-visible":""}`,children:t.map((n,a)=>b.jsx("span",{className:"app-splash-letter",children:n},`${n}-${a}`))})]})}const du=bl.length,zz=520,Uz=240;function tg(){return typeof window>"u"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Hz({startup:e}){const[t,n]=g.useState(()=>tg()?du:0);return g.useEffect(()=>{if(tg()){n(du);return}const a=Array.from({length:du},(o,i)=>window.setTimeout(()=>n(i+1),zz+Uz*i));return()=>{a.forEach(o=>window.clearTimeout(o))}},[]),b.jsxs("main",{className:"app-splash","aria-busy":"true","aria-label":e.label,role:"status",children:[b.jsx(Lz,{visibleLetterCount:t}),b.jsx("span",{className:"app-splash-status",children:e.label})]})}const Hp=5e3;function Da(e,t){if(e.length===0)return t;if(t.length===0)return e;const n=new Set,a=[];for(const o of[...e,...t])n.has(o.id)||(n.add(o.id),a.push(o));return a}function Na(e,t,n=Hp){return vl(Da(e,t),n)}function vl(e,t=Hp){return e.length<=t?e:e.slice(e.length-t)}function qz(e,t,n){return n.length===0?e:{...e,[t]:Da(e[t]??[],n)}}function Bz(e,t){if(t.length===0)return vl(e);if(e.length===0)return vl(t);const n=new Map;let a=0;for(const o of[...e,...t])n.has(o.id)||n.set(o.id,{event:o,index:a}),a+=1;return vl([...n.values()].sort((o,i)=>Vz(o,i)).map(({event:o})=>o))}function Nl(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 Fz(e){let t=null;for(const n of e)n.sequence!==void 0&&(t===null||n.sequence<t)&&(t=n.sequence);return t}function Vz(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 o=Date.parse(e.event.timestamp),i=Date.parse(t.event.timestamp);if(Number.isFinite(o)&&Number.isFinite(i)){const s=o-i;if(s!==0)return s}return e.index-t.index}const Wz="codex_history_";function Mt(e){return!!e?.startsWith(Wz)}function qS(e){const t=[],n=new Set;for(const a of e)for(const o of[a.workspacePath,a.path]){const i=mc(o);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,o)=>o.path.length-a.path.length)}function Kz(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=BS(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"||!FS(e))return null;const o=mc(e.cwd);if(!o)return null;for(const i of n)if(qp(o,i.path))return i.projectId;return null}function ng(e,t,n,a=new Set){if(e.localProjectId&&t.has(e.localProjectId))return gt("local",e.localProjectId);if(e.workspaceKind==="local_project"&&e.workspaceId&&t.has(e.workspaceId))return gt("local",e.workspaceId);if(e.metadata?.workspaceTarget==="hybrid"&&e.cwd){const i=BS(e.cwd,n);if(i)return gt("local",i)}if(e.cloudProjectId&&a.has(e.cloudProjectId))return gt("cloud",e.cloudProjectId);if(!e.cwd||e.workspaceKind==="sandbox"||e.workspaceKind==="sandbox_template"||e.workspaceKind==="sandbox_app"||!FS(e))return null;const o=mc(e.cwd);if(!o)return null;for(const i of n)if(qp(o,i.path))return gt("local",i.projectId);return null}function BS(e,t){const n=mc(e);if(!n)return null;for(const a of t)if(qp(n,a.path))return a.projectId;return null}function FS(e){return e.workspaceKind==="local_project"||e.provider==="codex"||Mt(e.id)}function mc(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 qp(e,t){const n=ag(e),a=ag(t);return n===a||n.startsWith(`${a}/`)}function ag(e){return/^[A-Z]:\//.test(e)?e.toLowerCase():e}function og(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 Gz(e){return e===null?"unknown":e>=85?"high":e>=65?"medium":"low"}function rg(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 Zz(e){return e==="codex"}function Jz(e){return e==="openpond"}function VS(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="session.context.updated")continue;const a=mA.safeParse(n.data);if(a.success)return a.data}return null}function WS(e){if(e.snapshot&&e.snapshot.provider===e.provider){const n=e.snapshot.usedTokens,a=e.snapshot.maxContextTokens,o=Math.min(100,Math.round(e.snapshot.percentFull)),i=`${o}% full`,s=`${og(n)} / ${og(a)} tokens used`;return{usedTokens:n,maxTokens:a,percent:o,summary:i,tokensLabel:s,detail:rg(e.preferences,o),tooltip:`Context window: ${i} ${s}. ${rg(e.preferences,o)}`,tone:Gz(o)}}if(Zz(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(!Jz(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 Bp(e){let t=!1;const n=KS(e);for(let a=e.length-1;a>=0;a-=1){const o=e[a];if(Yz(o)){t=!0;continue}const i=Br(o?.data);if(!(o?.name!=="diagnostic"||!i)){if(i.kind==="thread_goal_cleared")return null;if(i.kind==="thread_goal"){const s=Fp(Br(i.goal),Nn(i.provider),n);if(s){const l=us(s);return t&&l.tone==="active"?null:l}}if(i.kind==="goal_context"){const s=ZS(o.output??"",Nn(i.provider)??"codex",n);if(s){const l=us(s);return t&&l.tone==="active"?null:l}}}}return null}function $l(e){const t=KS(e);for(let n=e.length-1;n>=0;n-=1){const a=e[n],o=Br(a?.data);if(!(a?.name!=="diagnostic"||!o)){if(o.kind==="thread_goal_cleared"&&o.synthetic!==!0)return null;if(o.kind==="thread_goal"){const i=Fp(Br(o.goal),Nn(o.provider),t);if(!i)continue;const s=us(i);return s.tone==="active"?s:null}if(o.kind==="goal_context"){const i=ZS(a.output??"",Nn(o.provider)??"codex",t);if(!i)continue;const s=us(i);return s.tone==="active"?s:null}}}return null}function uu(e){const t=Br(Br(e)?.codexGoalRuntime),n=Fp(t,Nn(t?.provider)??"codex");if(!n)return null;const a=us(n);return a.tone==="active"?a:null}function Yz(e){return e?.name==="turn.completed"||e?.name==="turn.interrupted"||e?.name==="turn.failed"}function us(e){const t=JS(e.status),n=QS(e.timeUsedSeconds),a=`Goal ${n}`,o=e.tokensUsed===null?null:e.tokenBudget===null?`${mu(e.tokensUsed)} tokens`:`${mu(e.tokensUsed)} / ${mu(e.tokenBudget)} tokens`,i=o?`${e.statusLabel} · ${o}`: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: ${ex(e.timeUsedSeconds)}. ${i}. ${e.objective}`,tone:t.tone,observedAt:e.observedAt}}function Xz(e,t){if(!e||e.tone!=="active"||!e.observedAt)return e;const n=GS(e.observedAt,t);if(n<=0)return e;const a=e.timeUsedSeconds+n,o=QS(a);return{...e,timeUsedSeconds:a,timeLabel:o,label:`Goal ${o}`,tooltip:`Goal runtime: ${ex(a)}. ${e.detail}. ${e.objective}`,observedAt:t}}function Fp(e,t=null,n=null){if(!e)return null;const a=Nn(e.objective)??"Active goal",o=Nn(e.status)??"active";if((im(t)??im(Nn(e.provider)))!=="codex")return null;const s=n??Nn(e.updatedAt)??Nn(e.updated_at)??null,l=kr(e.timeUsedSeconds)??kr(e.time_used_seconds)??0,p=Nn(e.activeSinceAt)??Nn(e.active_since_at),m=JS(o).tone==="active"?GS(p??Nn(e.createdAt)??Nn(e.created_at),s):0,f=p?l+m:Math.max(l,m),S=kr(e.tokensUsed)??kr(e.tokens_used),y=kr(e.tokenBudget)??kr(e.token_budget);return{objective:a,status:o,statusLabel:XS(o),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 KS(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 GS(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 ZS(e,t=null,n=null){if(!e.trim()||im(t)!=="codex")return null;const a=YS(e,"Status")??"active",o=qi(e,"Tokens used"),i=qi(e,"Token budget"),s=qi(e,"Time used seconds")??qi(e,"Time spent pursuing goal")??qi(e,"Elapsed seconds")??0;return{objective:ig(e,"objective")??ig(e,"untrusted_objective")??"Active goal",status:a,statusLabel:XS(a),timeUsedSeconds:Math.max(0,Math.floor(s)),tokensUsed:o,tokenBudget:i,observedAt:n}}function JS(e){switch(Qz(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 Qz(e){return e.trim().toLowerCase().replace(/[-\s]+/g,"_")}function YS(e,t){const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^\\s*-?\\s*${n}:\\s*(.+?)\\s*$`,"im").exec(e)?.[1]?.trim()||null}function qi(e,t){const n=YS(e,t);if(!n)return null;const a=n.replace(/,/g,""),o=/-?\d+(?:\.\d+)?/.exec(a);if(!o)return null;const i=Number(o[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 XS(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function QS(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 ex(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 mu(e){if(e<1e3)return String(e);if(e>=1e6){const n=e/1e6;return n<10?`${sg(n,2)}M`:n<100?`${sg(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 sg(e,t){return e.toFixed(t).replace(/\.?0+$/,"")}function Br(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Nn(e){return typeof e=="string"&&e.trim()?e.trim():null}function im(e){return e?.trim().toLowerCase()||null}function kr(e){return typeof e=="number"&&Number.isFinite(e)?e:null}const eU=new Set(["planning","applying_source","running_checks","evaluating","pushing_hosted","running_hosted_checks"]),tU=new Set(["awaiting_questions","awaiting_plan_approval","paused"]);function sm(e){const t=tx(e);return t?rU(t):null}function tx(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="create_improve.updated")continue;const a=oU(dU(n.data));if(a)return a}return null}function nU(e){if(e.events)return tx(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 aU(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 oU(e){const t=ys.safeParse(e?.createImproveRun);return t.success?t.data:null}function rU(e){const t=iU(e);if(!t)return null;const n=sU(e.createdAt,e.updatedAt),a=e.blockedReason??lU(e.state);return{objective:e.objective,status:e.state,timeUsedSeconds:n,tokensUsed:null,tokenBudget:null,actionLabel:t.actionLabel,timeLabel:cU(n),label:t.actionLabel,detail:a,tooltip:`${t.actionLabel}: ${a}. ${e.objective}`,tone:t.tone}}function iU(e){const t=e.state,n=e.target.kind==="agent"?"Agent":"Work";return eU.has(t)?{tone:"active",actionLabel:`${n} running`}:tU.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 sU(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 lU(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function cU(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 dU(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function nx(e,t){if(!t)return null;const n=new Map,a=[];for(const I of e){if(!I.name.startsWith("subagent."))continue;const P=pU(I);P&&a.push(P);const O=mU(I);O?.parentSessionId===t&&n.set(O.id,O)}if(n.size===0)return null;const o=[...n.values()].sort((I,P)=>Ir(P).localeCompare(Ir(I))),i=o.filter(I=>I.status==="queued"||I.status==="running"),s=o.filter(I=>I.status==="completed"),l=o.filter(I=>I.status==="failed"),p=o.filter(I=>I.status==="cancelled"),m=o.filter(I=>I.status==="needs_resume"),f=[...s,...l,...p].sort((I,P)=>Ir(P).localeCompare(Ir(I))),S=o.reduce((I,P)=>{const O=Fr(P.metadata?.usage);return I.totalTokens+=rl(O?.totalTokens),I.promptTokens+=rl(O?.promptTokens),I.completionTokens+=rl(O?.completionTokens),I.requestCount+=rl(O?.requestCount),I},{totalTokens:0,promptTokens:0,completionTokens:0,requestCount:0}),y=o.flatMap(I=>ax([...I.report?.blockers??[],I.error,I.progress.currentBlocker]).map(P=>({runId:I.id,roleId:I.roleId,status:I.status,message:P}))),k=o.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=>uU(I,a)),A=o[0]??null,$=A?{runId:A.id,roleId:A.roleId,status:A.status,message:A.progress.latestMeaningfulActivity||A.report?.summary||A.objective,updatedAt:Ir(A)}:null,z=i.length>0?`${i.length} ${i.length===1?"child":"children"} running`:`${f.length} ${f.length===1?"child":"children"} finished`,D=[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=$?`${gU($.roleId)}: ${$.message}`:"";return{sessionId:t,runs:o,activeRuns:i,completedRuns:s,failedRuns:l,cancelledRuns:p,needsResumeRuns:m,terminalRuns:f,latestRun:A,latestMeaningfulUpdate:$,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:o.reduce((I,P)=>I+P.progress.validationAttempts.length,0),label:z,tooltip:[D,x].filter(Boolean).join(". ")}}function uU(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:ax([...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:fU(e),updatedAt:Ir(e)}}function mU(e){const t=Fr(e.data),n=[t?.run,Fr(t?.message)?.run];for(const a of n){const o=nv.safeParse(a);if(o.success)return o.data}return null}function pU(e){const t=MC.safeParse(Fr(e.data)?.message);return t.success?t.data:null}function fU(e){const t=Fr(Fr(e.metadata?.workspaceHandoff)?.workspaceRetention);return t?.status!=="retained"?null:{status:"retained",reason:ol(t.reason),retainedAt:ol(t.retainedAt),expiresAt:ol(t.expiresAt),retentionDays:hU(t.retentionDays),trigger:ol(t.trigger),cleanupAfterExpiry:t.cleanupAfterExpiry===!0}}function Ir(e){return e.updatedAt??e.completedAt??e.startedAt??e.createdAt}function ax(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 Fr(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ol(e){return typeof e=="string"&&e.trim()?e.trim():null}function rl(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function hU(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function gU(e){return e.slice(0,1).toUpperCase()+e.slice(1).replace(/[-_]+/g," ")}const lm=[];function cm(e,t){return rx(e,t,null)}function rx(e,t,n){const a=n&&xU(n.events,e)?vU(n.indexes,n.events.length,e):bU(e),o=SU(t);return{...a,...o}}function bU(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 yU(t)}function vU(e,t,n){const a=new Map(e.eventsBySessionId),o=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)??lm,y=VS(S);y?o.set(f,y):o.delete(f);const k=sx(S);k?(i.set(f,k),k.tone==="active"?l.add(f):l.delete(f)):(i.delete(f),l.delete(f));const R=nx(S,f);R?(s.set(f,R),ix({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:o,latestGoalRuntimeBySessionId:i,latestSubagentRuntimeBySessionId:s,activeGoalSessionIds:l,activeSubagentSessionIds:p}}function yU(e){const t=new Map,n=new Map,a=new Map,o=new Set,i=new Set;for(const[s,l]of e){const p=VS(l);p&&t.set(s,p);const m=sx(l);m&&(n.set(s,m),m.tone==="active"&&o.add(s))}for(const[s,l]of e){const p=nx(l,s);p&&(a.set(s,p),ix({sessionEvents:l,sessionId:s,latestGoalRuntimeBySessionId:n,activeGoalSessionIds:o}),p.activeCount>0&&i.add(s))}return{eventsBySessionId:e,latestContextUsageBySessionId:t,latestGoalRuntimeBySessionId:n,latestSubagentRuntimeBySessionId:a,activeGoalSessionIds:o,activeSubagentSessionIds:i}}function ix(e){if(e.latestGoalRuntimeBySessionId.has(e.sessionId))return;const t=$l(e.sessionEvents);t&&(e.latestGoalRuntimeBySessionId.set(e.sessionId,t),t.tone==="active"&&e.activeGoalSessionIds.add(e.sessionId))}function sx(e){return sm(e)??Bp(e)??$l(e)}function SU(e){const t=new Map,n=new Map,a=new Map,o=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=o.get(i.sessionId);(!p||lg(i.createdAt)>lg(p.createdAt))&&o.set(i.sessionId,i)}return{approvalsById:t,approvalsByStatus:n,pendingApprovalsBySessionId:a,latestPendingApprovalBySessionId:o}}function xU(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 Ps(e,t){return t?e.eventsBySessionId.get(t)??lm:lm}function lx(e,t){return t?e.latestContextUsageBySessionId.get(t)??null:null}function cx(e,t){return t?e.latestGoalRuntimeBySessionId.get(t)??null:null}function kU(e,t){return t?e.latestSubagentRuntimeBySessionId.get(t)??null:null}function wU(e,t){return t?e.latestPendingApprovalBySessionId.get(t)??null:null}function lg(e){const t=Date.parse(e);return Number.isFinite(t)?t:Number.NEGATIVE_INFINITY}function _U(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("/"),o=a>=0?n.relativePath.slice(0,a):"";for(const i of n.resourceFiles)t.add(o?`${o}/${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 IU(e){return JSON.stringify([e.source,e.repositoryId,e.profileId])}function B3(e,t){return e.profiles.find(n=>IU(n.ref)===t)?.ref??null}function CU(e,t){return!!(e&&t&&e.source===t.source&&e.repositoryId===t.repositoryId&&e.profileId===t.profileId)}function F3(e,t){return e.profiles.find(n=>CU(n.ref,t))?.state??null}function RU(e,t){const n=new Map(CP.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 o of a.skills)o.validationStatus!=="valid"||n.has(o.name)||n.set(o.name,{name:o.name,description:o.description,path:o.relativePath,scope:"profile",enabled:!0,sourcePath:a.sourcePath,charCount:o.charCount,sourceHash:o.sourceHash,validationStatus:"valid",validationMessages:[],resourceFiles:o.resourceFiles});return[...n.values()].sort((a,o)=>a.name.localeCompare(o.name))}function AU(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 V3(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 dx="openpond:last-chat-task-mode";function PU(e,t){return e==="labs"?"models":"chat"}function TU(e){try{return e.getItem(dx)==="work"?"work":"chat"}catch{return"chat"}}function ux(){if(typeof window>"u")return"chat";try{return TU(window.localStorage)}catch{return"chat"}}function EU(e,t){try{e.setItem(dx,t==="chat"?"chat":"work")}catch{}}function MU(e){if(!(typeof window>"u"))try{EU(window.localStorage,e)}catch{}}const jU="uploaded to a different account";function mx(e,t){const n=e?.linkedSandboxProject??null;if(!n?.projectId||!n.teamId)return{state:"none",linked:null,cloudProject:null};const a=t?.find(o=>o.id===n.projectId&&o.teamId===n.teamId)??null;return a?{state:"confirmed",linked:n,cloudProject:a}:{state:"different_account",linked:n,cloudProject:null}}function aa(e,t){const n=mx(e,t);return n.state==="confirmed"?n.cloudProject:null}function OU(e,t){return mx(e,t).state==="different_account"?jU:null}function wa(e){return e==="sandbox"||e==="sandbox_template"||e==="sandbox_app"}function px(e={}){return{...e,workspaceTarget:"hybrid"}}function NU(e={}){return{...e,workspaceTarget:"local"}}function _a(e){return e?.metadata?.workspaceTarget==="hybrid"}function $U(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,o=e?aa(n,e):null,i=t?.id??o?.id??(e?null:a?.projectId??null),s=t?.teamId??o?.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??o?.name??a?.projectName??n?.name??"Hybrid workspace"}}function hx({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:px(),cwd:n.cwd,title:a}}function DU(e){return g.useEffect(()=>{const t=AS(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=LD(n);try{let o;const i=e.selectedSession;if(i&&cs(i))o=await Z.patchSession(e.connection,i.id,{title:a,metadata:su(i.metadata,n)}),e.setSessions(s=>s.map(l=>l.id===o.id?o: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:hs}:{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=hx({modelRef:p,provider:l,target:S,title:a});f={...y,experience:"work",metadata:su(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:su(m,n),title:a};o=await Z.createSession(e.connection,f),e.setSessions(S=>[o,...S])}return e.composerDraftStore.set(""),e.setMentionedAppId(null),e.setSelectedSessionId(null),e.setView("chat"),e.requestComposerFocus(),e.showToast("Task draft saved.","success"),!0}catch(o){return e.showToast(o instanceof Error?o.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 LU=[];function zU({primary:e,secondary:t}){const[n,a]=g.useState(!1),{composerDraftStore:o,appDispatch:i,pendingTerminalCommand:s,setPendingTerminalCommand:l,terminalTabs:p,setTerminalTabs:m,trainingDetailTasksetId:f,setTrainingDetailTasksetId:S,mentionedAppId:y,setMentionedAppId:k,cloudSetupDialog:R,setCloudSetupDialog:A,rightPanelTabRequest:$,workspaceDiffPanelViewState:z,mainComposerFocusRequestId:D,requestMainComposerFocus:x,projectConfirmDialog:I,resolveProjectConfirmDialog:P,query:O,searchOpen:T,archivedChatsOpen:F,sectionMenuOpen:H,cloudProjectsExpanded:L,sidebarOpen:V,view:Y,selectedAppId:ie,selectedProjectId:_e,selectedSessionId:fe,codexPermissionMode:J,codexReasoningEffort:Me,busy:Se,diffPanelOpen:ae,diffPanelExpanded:xe,rightPanelMode:ee,activeExperience:ue,changeNewExperience:ye,terminalOpen:We,settingsSection:Pe,newProjectDialogOpen:re,newProjectMode:Ce,newProjectName:De,newProjectPath:Je,newProjectBusy:et,commitDialogOpen:rt,commitMessage:Be,commitIncludeUnstaged:He,commitNextStep:$e,commitDraft:E,branchDialogOpen:U,branchDialogName:G,toast:ce,labDetailNavigation:W,setQuery:me,setSearchOpen:he,setArchivedChatsOpen:Ze,setSectionMenuOpen:qe,setCloudProjectsExpanded:it,setChatRowsVisibleCount:nt,setSidebarOpen:we,setView:Oe,setSelectedAppId:d,setSelectedProjectId:M,setSelectedSessionId:q,setPrompt:le,setDraftProvider:N,setDraftModel:K,setDraftExperience:w,setDiffPanelOpen:j,setDiffPanelExpanded:oe,setRightPanelMode:X,setTerminalOpen:Q,setSettingsSection:pe,setNewProjectDialogOpen:de,setNewProjectName:ze,setNewProjectPath:Te,setCommitDialogOpen:Ne,setCommitMessage:Ye,setCommitIncludeUnstaged:Le,setCommitNextStep:ut,setCommitDraft:Vt,setBranchDialogOpen:dn,setBranchDialogName:un,setError:Xt,showToast:xt,applyBootstrapPayload:Wt,bootstrap:Pt,connection:Rt,startup:qn,training:jt,pinnedCollapsed:mn,cloudProjectsCollapsed:Qt,chatsCollapsed:ln,savedForLaterCollapsed:Sn,sidebarWidth:Ia,sidebarResizing:qt,diffPanelWidth:xn,diffPanelResizing:lt,togglePinnedCollapsed:Bt,toggleCloudProjectsCollapsed:te,toggleChatsCollapsed:Ke,toggleSavedForLaterCollapsed:Ge,startSidebarResize:St,startDiffPanelResize:an,selectedApp:Ca,selectedCloudProject:kn,selectedProject:Dt,selectedProjectLinkedApp:kt,selectedSession:Lt,sidebarSessions:vt,runtimeIndexes:_t,runtimeEventStore:Tt,chatMentionApps:cn,connectedAppMentions:En,pendingApproval:Xe,pendingChatUserMessages:pn,account:mt,activeModel:Kt,activeProvider:wn,appDefaults:Bn,startMessage:po,teamChatOrganization:Fn,teamChatTeamId:Jn,teamChat:pt,publishTeamProfileAgent:ca,communitySidebar:fo,communityView:da,teamAiThreadId:ia,toggleTeamAiSidebar:Zo,activeOpenPondCommandAccessMode:ua,viewWorkspaceAppId:ho,viewWorkspaceId:Jo,viewWorkspaceKind:go,viewWorkspaceName:Yo,selectedActionCatalog:ni,expandedProjectIds:ai,expandProject:ma,toggleProjectExpanded:oi,changeCodexPermissionMode:Xo,changeCodexReasoningEffort:Qo,changeOpenPondCommandAccessMode:er,resolveApproval:ri,beginNewChat:Yn,beginNewChatWithTrainingModel:ii,dismissTrainingChatHandoff:si,trainingChatHandoff:li,selectTrainingChatTaskForComposer:ci,chatHistoryLoadStates:di,loadMoreSelectedChatHistory:tr,selectedPagedSessionEvents:nr,activeSessions:Ra,archivedSessions:ui,pinnedSessions:bo,savedForLaterSessions:Aa,savedForLaterFiles:Mn,sidebarFileBookmarks:mi,setSidebarFileStatus:ar,setSessions:Zt,projectRows:vo,localProjectRows:jn,cloudProjectRows:Pa,projectSessionRowsByProjectId:yo,childSessionRowsByParentId:pa,sidebarProjectIdBySessionId:So,chatRows:pi,visibleChatRows:fi,chatRowsVisibleCount:xo,sessionEvents:or,goalRuntime:ko,subagentRuntime:rr,visibleChatMessages:wo,activeTerminalScope:ir,terminalSummaries:Xn,runningSessionIds:Ka,selectedSessionRunning:_o,sidebarGoalRuntimeBySessionId:Ta,sidebarSubagentRuntimeBySessionId:sr,taskDragSessionId:fa,taskPreviewSessionIds:lr,startTaskDrag:hi,clearTaskDrag:Io,previewTaskDrop:cr,commitTaskDrop:dr,commitTaskPreviewDrop:ur,dragItem:gi,startPinnedDrag:mr,clearSidebarDrag:pr,previewPinnedDrop:Ga,commitPinnedDrop:ha,commitPinnedPreviewDrop:bi,commandProjectRows:vi,contextWindowStatus:fr,pinnedRows:yi,workspaceBusy:Qn,diffBusy:hr,visibleWorkspaceState:Ea,visibleWorkspaceDiff:Co,refreshVisibleWorkspaceDiff:Si,managedWorkspace:Vn,canSyncActiveWorkspace:xi,canPublishOpenPondProject:ki,projectTarget:wi,workspaceTarget:gr}=e,{title:yt,browserConversationId:Ot,handleWorkspaceDiffPanelViewStateChange:On,openSessionInChat:Jt,changeProjectTarget:Wn,submitNewProjectDialog:Kn,changeWorkspaceBranch:xc,openCommitDialog:kc,openCreateWorkspaceBranchDialog:wc,openDefaultsSettingsFromBranchDialog:_i,runWorkspaceTool:Ms,submitCommitDialog:_c,submitCreateWorkspaceBranch:Ic,syncWorkspaceLocally:Cc,answerCreateImproveQuestion:Rc,applyCreateImproveCandidate:Ac,approveCreateImproveRun:Pc,cancelCreateImproveRun:Tc,changeDraftProvider:js,openCreateImprovePullRequest:Ec,reconcileCreateImprovePullRequest:Mc,rejectCreateImproveCandidate:jc,pauseCreateImproveRun:Os,resumeCreateImproveRun:Oc,reviseCreateImproveRun:Nc,stopTurn:Ns,archiveSession:$s,restoreSession:Ds,renameSession:$c,toggleSessionPinned:Dc,toggleProjectPinned:Ii,toggleSessionSavedForLater:Ls,moveProjectToCloud:Lc,startCloudSetupUpload:Ci,changeWorkspaceTarget:zc,sendPromptFromMainComposer:zs,openSandboxWorkspace:Uc,openCloudProjectDialog:Ri,openUrlInBrowserPanel:Hc,showBrowserPanel:Us,showChangesPanel:qc,showGoalSidebarTab:Hs,rightChatTrainingLaunchRequest:Bc,setRightChatTrainingLaunchRequest:Fc,closeRightChatPanel:qs,openRightChatPanel:Ai,rightChatPanelViews:Vc,showRightChatPanel:Wc,showRightPanelDiffTab:Kc,submitRightChatPrompt:Gc,activateRightChatPanel:Za,updateRightChatModel:Bs,updateRightChatPrompt:Zc,updateRightChatProvider:Jc,updateRightChatScrollState:Yc,openProfileSettings:Xc,diagnosticEvents:Qc,toggleRightSidebar:Fs,removeProject:ed}=t,Vs=g.useCallback(Ee=>{d(null),M(Ee),q(null),Oe("chat"),ma(Ee),x()},[ma,x,d,M,q,Oe]),Pi=Jn??Bn.defaultTeamId??null,td=g.useMemo(()=>vo.filter(Ee=>Ee.kind==="local"||Pi!==null&&Ee.project.teamId===Pi),[vo,Pi]),nd=g.useMemo(()=>{const Ee={};for(const at of Ra){const ct=So[at.id];ct&&(Ee[ct]=(Ee[ct]??0)+1)}for(const at of jn){if(at.kind!=="local")continue;const ct=at.project.linkedSandboxProject?.projectId;if(!ct||!at.cloudLinkTrusted)continue;const on=gt("cloud",ct);Ee[at.id]=(Ee[at.id]??0)+(Ee[on]??0)}return Ee},[Ra,jn,So]),[Ti,Ei]=g.useState(null),[Mi,ji]=g.useState(null),ad=RU(Pt?.profile,Pt?.extensionCatalog),[Oi,Ni]=g.useState(null),[$i,Di]=g.useState(null),[Li,od]=g.useState(null),rd=g.useCallback(()=>{d(null),M(null),q(null),qe(null),Oe("team")},[qe,d,M,q,Oe]),id=g.useCallback(()=>{d(null),M(null),q(null),qe(null),fo.discoverCommunities()},[fo.discoverCommunities,qe,d,M,q]),of=DU({activeExperience:ue,activeModel:Kt,activeOpenPondCommandAccessMode:ua,activeProvider:wn,cloudProjects:Pt?.cloudProjects??LU,composerDraftStore:o,connection:Rt,requestComposerFocus:x,selectedCloudProject:kn,selectedProject:Dt,selectedSession:Lt,setMentionedAppId:k,setSelectedSessionId:q,setSessions:Zt,setView:Oe,showToast:xt,workspaceTarget:gr.value}),Ro=g.useCallback(async Ee=>{if(!Rt)throw new Error("OpenPond is not connected.");let at=wn,ct=Kt;at==="codex"&&(at=om(Pt?.providers,{enabledOnly:!0}).find(rn=>rn.value!=="codex")?.value??Uo,ct=Ml(at,Pt?.providers)??ns);const on=vt.find(rn=>rn.id===Ee.sourceSessionId),ga=await Z.createSession(Rt,{experience:Ee.target,provider:at,modelRef:{providerId:at,modelId:ct},openPondCommandAccessMode:ua,appId:null,appName:null,workspaceId:null,workspaceName:null,localProjectId:null,cloudProjectId:null,cloudTeamId:null,cwd:null,title:`Continue ${on?.title??"task"}`.slice(0,120),metadata:{experienceHandoff:AU({sourceTaskId:Ee.sourceSessionId,sourceExperience:on?.experience??null,targetExperience:Ee.target,sourceMessageIds:Ee.sourceMessageIds??[],sourceContext:Ee.sourceContext,output:Ee.output})}});return Zt(rn=>[ga,...rn]),w(Ee.target),N(at),K(ct),o.set(Ee.prompt),i({type:"selectSession",sessionId:ga.id,appId:null,projectId:null}),d(null),M(null),Q(!1),Oe("chat"),X("home"),j(Ee.target==="work"),oe(!1),ga},[Kt,ua,wn,i,Pt?.providers,o,Rt,oe,j,w,K,N,X,d,M,Zt,Q,Oe,vt]),Ws=g.useCallback(Ee=>{Ni(Ee),Di(null),Yn(null),we(!0)},[Yn,we]),Ks=g.useCallback(Ee=>{Yn(null),w("work"),o.set(`$openpond-refiner-authoring ${Ee}`),Oe("chat"),we(!0)},[Yn,o,w,we,Oe]),sd=g.useCallback(Ee=>{Di(_U(Ee)),Ni(null),Yn(null),we(!0)},[Yn,we]);g.useEffect(()=>{!Oi&&!$i||Y!=="chat"||fe||_e||ie||(Ei(Oi),ji($i),Ni(null),Di(null),X("home"),oe(!1),j(!0))},[Oi,$i,ie,_e,fe,oe,j,X,Y]),g.useEffect(()=>{!Ti&&!Mi||Y==="chat"&&ae&&ee==="home"||(Ei(null),ji(null))},[ae,Mi,Ti,ee,Y]);const zi=g.useCallback(()=>{Ei(null),ji(null),oe(!1),j(!1)},[oe,j]),ld=g.useCallback(Ee=>{if(Ee.workspaceKind==="local"){const at=gt("local",Ee.workspaceId);d(null),M(at),q(null),ma(at),Oe("chat")}else{const at=vt.find(ct=>ct.id===Ee.sourceSessionId||ct.workspaceId===Ee.workspaceId);if(!at){xt("This saved file's cloud chat is no longer available.","error");return}Jt(at.id)}X("changes"),j(!0),od({id:Date.now(),file:Ee}),Ee.available||xt(`File unavailable: ${Ee.path}`,"error")},[ma,Jt,j,X,d,M,q,Oe,xt,vt]);g.useEffect(()=>{if(!Li)return;const Ee=window.setTimeout(()=>{X("changes"),j(!0)},0);return()=>window.clearTimeout(Ee)},[_e,fe,j,X,Li]);const Gs=PU(Y),cd=g.useCallback(Ee=>{if(qe(null),d(null),M(null),q(null),Ee==="models"){Oe("labs");return}ye(ux())},[ye,qe,d,M,q,Oe]),Ao=g.useCallback(async(Ee,at)=>{const ct=await jt.actions.acceptHarnessReview(Ee,at,{providerId:wn,modelId:Kt},Me);return ct?(S(ct.materializedTasksetId??null),Oe("labs"),!0):(xt("Taskset review could not be opened.","error"),!1)},[Kt,wn,Me,S,Oe,xt,jt.actions]);if(!qn.ready)return b.jsx(Hz,{startup:qn});if(Y==="settings")return b.jsx(Xh,{showToast:xt,children:b.jsx(Dz,{settings:{payload:Pt,connection:Rt,diagnostics:Qc,initialSection:Pe,onPayload:Wt,onError:Xt,onToast:xt,onOpenSourceSession:Jt,onStartRefinerAuthoring:Ks,onAcceptEvaluationReview:Ao,onOpenSkill:Ws,onOpenExtension:sd,teamChatCurrentUserId:pt.currentUserId,teamChatEnabled:Jn!==null,teamChatNotificationMode:pt.notificationMode,teamChatThreads:pt.threads,onTeamChatNotificationModeChange:pt.setNotificationMode,onTeamChatThreadMuteChange:pt.setThreadMuted,diffPanelWidth:xn,diffPanelResizing:lt,diffPanelExpanded:xe,onDiffPanelResizeStart:an,onDiffPanelExpandedChange:oe,onBack:()=>{Oe("chat"),we(!0)}},toast:{toast:ce,onDismiss:()=>i({type:"field",key:"toast",value:null})}})});const dd=uc(),Ui=Rt?.platform??navigator.platform,ud=dd&&Np(Ui),Zs=ir,md=Ea?.initialized?Ea.repoPath:Lt?.cwd??null,pd={"--sidebar-width":`${Ia}px`,"--diff-panel-width":`${xn}px`},fd=Y==="chat"&&ue!=="chat"||Y==="labs"||Y==="scheduled"&&n||Y==="team"&&!!ia,Js=["app-shell",ud?"platform-macos":"",V?"sidebar-open":"sidebar-closed",qt?"sidebar-resizing":"",lt?"diff-panel-resizing":""].filter(Boolean).join(" "),br=fe?di[fe]:null,hd=fe?br?.cursorSequence??Fz(Na(nr,Ps(_t,fe))):null,gd=!!fe&&!!Rt&&(Mt(fe)?!0:!!Pt?.eventWindow?.hasMoreBefore&&!!hd)&&(br?.hasMore??!0),bd=!!br?.loading,ot=(()=>{const Ee=jt.payload;if(!Ee)return{};const at=new Map(Ee.plans.map(rn=>[rn.id,rn])),ct=new Set(["queued","starting","running","cancelling","reconciling"]),on={queued:"Queued",starting:"Starting",running:"Running",cancelling:"Cancelling",reconciling:"Reconciling"},ga={};for(const rn of[...Ee.modelRuns].sort((sa,vr)=>vr.updatedAt.localeCompare(sa.updatedAt))){if(rn.kind==="evaluation"||!["prepared","running"].includes(rn.status))continue;const sa=Ee.jobs.filter(vd=>vd.metadata.modelRunId===rn.id).sort((vd,wk)=>wk.updatedAt.localeCompare(vd.updatedAt))[0];if(sa&&!ct.has(sa.status))continue;const vr=sa?.status??(rn.status==="prepared"?"starting":"running");ga[rn.modelId]={label:on[vr]??"Running",status:vr}}for(const rn of[...Ee.jobs].sort((sa,vr)=>vr.updatedAt.localeCompare(sa.updatedAt))){if(!ct.has(rn.status))continue;const sa=at.get(rn.planId)?.modelId;!sa||ga[sa]||(ga[sa]={label:on[rn.status]??"Active",status:rn.status})}return ga})();return b.jsx(Xh,{showToast:xt,children:b.jsx($z,{className:Js,style:pd,sidebar:{productArea:Gs,modelProjects:(jt.payload?.modelProjects??[]).filter(Ee=>Ee.hosted===null||Ee.hosted.teamId===(Bn.defaultTeamId?.trim()??null)),modelTrainingActivityByProjectId:ot,onProductAreaChange:cd,experience:ue,view:Y,selectedAppId:ie,selectedProjectId:_e,selectedSessionId:fe,selectedTeamThreadId:pt.selectedThreadId,teamChatEnabled:Jn!==null,teamChatOrganization:Fn,teamChatLoading:pt.loading,currentUserId:pt.currentUserId,teamMembers:pt.members,teamThreads:pt.threads,...fo,account:mt,connection:Rt,profile:Pt?.profile,pinnedCollapsed:mn,cloudProjectsCollapsed:Qt,chatsCollapsed:ln,savedForLaterCollapsed:Sn,archivedChatsOpen:F,cloudProjectsExpanded:L,sectionMenuOpen:H,dragItem:gi,taskDragSessionId:fa,taskPreviewSessionIds:lr,activeSessions:Ra,archivedSessions:ui,pinnedRows:yi,pinnedSessions:bo,savedForLaterSessions:Aa,savedForLaterFiles:Mn,projectRows:vo,localProjectRows:jn,cloudProjectRows:Pa,projectSessionRowsByProjectId:yo,childSessionRowsByParentId:pa,sidebarProjectIdBySessionId:So,terminalSummaries:Xn,runningSessionIds:Ka,goalRuntimeBySessionId:Ta,subagentRuntimeBySessionId:sr,visibleChatRows:fi,chatRows:pi,chatRowsVisibleCount:xo,expandedProjectIds:ai,currentVersion:Pt?.server.version??null,platform:Ui,arch:Rt?.arch??null,onSidebarResizeStart:St,setSidebarOpen:we,setView:Oe,setSelectedAppId:d,setSelectedProjectId:M,setSelectedSessionId:q,setSearchOpen:he,setSectionMenuOpen:qe,setSettingsSection:pe,onTogglePinnedCollapsed:Bt,onToggleCloudProjectsCollapsed:te,onToggleChatsCollapsed:Ke,onToggleSavedForLaterCollapsed:Ge,setArchivedChatsOpen:Ze,setCloudProjectsExpanded:it,setChatRowsVisibleCount:nt,beginNewChat:Yn,beginProjectChat:Vs,dockSessionRight:Ai,selectTeamThread:Ee=>{Oe("team"),pt.selectThread(Ee)},openTeamDm:Ee=>{Oe("team"),pt.openDm(Ee)},toggleSessionPinned:Dc,toggleProjectPinned:Ii,toggleSessionSavedForLater:Ls,openSidebarFile:ld,setSidebarFileStatus:(Ee,at)=>{ar(Ee,at)},archiveSession:$s,restoreSession:Ds,renameSession:$c,removeProject:ed,expandProject:ma,toggleProjectExpanded:oi,startPinnedDrag:mr,clearSidebarDrag:pr,previewPinnedDrop:Ga,commitPinnedDrop:ha,commitPinnedPreviewDrop:bi,startTaskDrag:hi,clearTaskDrag:Io,previewTaskDrop:cr,commitTaskDrop:dr,commitTaskPreviewDrop:ur},topBar:{sidebarOpen:V,title:yt,backAction:W.backAction,breadcrumbs:W.breadcrumbs,conversationId:Y==="chat"?fe:null,workspaceName:Yo,workspaceId:Jo,busy:Se,workspaceState:Ea,workspaceKind:go,selectedApp:kt??Ca,selectedProject:Dt,workspaceDiff:Co,managedWorkspace:Vn,workspaceBusy:Qn,defaultTeamId:Bn.defaultTeamId,showDiffControls:Y==="chat"&&ue==="development",diffPanelOpen:ae,terminalOpen:We,rightSidebarAvailable:fd,rightSidebarOpen:Y==="scheduled"?n:ae,onToggleDiffPanel:Fs,onToggleRightSidebar:Y==="scheduled"?()=>a(Ee=>!Ee):Y==="team"&&ia?Zo:Fs,onOpenSearch:()=>{qe(null),he(!0)},onToggleTerminal:()=>Q(Ee=>!Ee),onRunTerminalCommand:Ee=>{l({id:Date.now(),scope:Zs,command:Ee}),Q(!0)},onWorkspaceToolAction:Ms,onOpenCommitDialog:kc,onWorkspaceBranchChange:xc,onWorkspaceBranchCreate:wc,connection:Rt,onBootstrap:Wt,onOpenSandboxWorkspace:Uc,onShowSidebar:()=>we(!0),onOpenTeamChat:rd,onDiscoverCommunities:id,collaborationView:Y==="team"||Y==="community"?Y:null,platform:Ui,showWorkspaceControls:Y!=="team"&&Y!=="community"&&Y!=="labs"&&Y!=="scheduled"&&Y!=="outputs"&&Y!=="projects"&&(ue==="development"||ue==="work"&&!!(Dt||Lt?.localProjectId||Lt?.cloudProjectId||Lt?.workspaceKind==="local_project"))},mainPane:{experience:ue,onNewExperienceChange:ye,view:Y,teamChat:{currentUserId:pt.currentUserId,members:pt.members,agents:pt.agents,profile:Pt?.profile??null,teamId:Jn,teamName:Fn?.displayName??null,detail:pt.detail,aiThread:pt.aiThread,agentConversation:pt.agentConversation,loading:pt.loading,busy:pt.busy,error:pt.error,connection:Rt,providerSettings:Pt?.providers??null,provider:wn,model:Kt,codexPermissionMode:J,codexReasoningEffort:Me,openPondCommandAccessMode:ua,contextWindowStatus:fr,showToast:xt,onProviderChange:js,onModelChange:K,onCodexPermissionModeChange:Xo,onCodexReasoningEffortChange:Qo,onOpenPondCommandAccessModeChange:er,onOpenProviderSettings:()=>{pe("providers"),Oe("settings")},onSendMessage:pt.sendMessage,onPublishProfileAgent:ca,onOpenAiThread:async Ee=>{await pt.openAiThread(Ee),X("chat"),j(!0)},onOpenAgentConversation:async Ee=>{await pt.openAgentConversation(Ee),X("chat"),j(!0)},onCloseAiThread:()=>j(!1),onCloseAgentConversation:()=>{pt.closeAgentConversation(),j(!1)},onSendAgentTurn:pt.sendAgentTurn,onSendAiTurn:pt.sendAiTurn,onStopAiTurn:pt.stopAiTurn,onEditMessage:pt.editMessage,onDeleteMessage:pt.deleteMessage,onRetryMessage:pt.retryMessage,onDismissFailedMessage:pt.dismissFailedMessage,onLoadMoreMessages:pt.loadMoreMessages,onRetryLoad:pt.refresh},community:da,bootstrap:Pt,runtimeEvents:or,chatMessages:wo,pendingUserMessage:fe?pn[fe]??null:null,contextWindowStatus:fr,goalRuntime:ko,subagentRuntime:rr,selectedSessionId:fe,composerDraftStore:o,mainComposerFocusRequestId:D,labCloseDetailRequestId:W.closeDetailRequestId,labCloseDetailKind:W.closeDetailKind,sideChatTrainingLaunchRequest:Bc,onSideChatTrainingLaunchHandled:Ee=>Fc(at=>at?.id===Ee?null:at),mentionApps:cn,connectedAppMentions:En,profileSkills:ad,selectedMentionAppId:y,busy:Se,turnRunning:_o,activeProvider:wn,activeModel:Kt,codexPermissionMode:J,codexReasoningEffort:Me,openPondCommandAccessMode:ua,pendingApproval:Xe,activeWorkspaceAppId:ho,activeWorkspaceId:Jo,activeWorkspaceKind:go,projectTarget:wi,actionCatalog:ni,workspaceTarget:gr,connection:Rt,workspaceName:Yo,workspaceState:Ea,workspaceDiff:Co,workspaceBusy:Qn,diffBusy:hr,forceChatThread:Mt(fe),diffPanelOpen:ae,diffPanelExpanded:xe,rightPanelMode:ee,rightPanelTabRequest:$,rightChatPanels:Vc,runtimeEventStore:Tt,nativeSkillSidebar:Ti,extensionSkillSidebar:Mi,workspaceDiffPanelViewState:z,sidebarFileOpenRequest:Li,sidebarFileBookmarks:mi,onSetSidebarFileStatus:(Ee,at)=>{ar(Ee,at)},browserConversationId:Ot,terminalScope:Zs,terminalTabs:p,terminalCwd:md,pendingTerminalCommand:s,terminalOpen:We,onToggleTerminal:()=>Q(Ee=>!Ee),onWorkspaceDiffPanelViewStateChange:On,training:jt,trainingSessions:vt,trainingChatHandoff:li,trainingDetailTasksetId:f,onTrainingDetailTasksetIdChange:S,onTrainingChatTaskSelect:ci,onTrainingChatHandoffDismiss:si,onOpenSession:Jt,onExperienceHandoff:Ro,cloudProjects:Pt?.cloudProjects??[],projects:td,projectsAccountBaseUrl:mt?.baseUrl??mt?.activeProfile?.baseUrl??null,projectsTeamName:Fn?.displayName??null,projectTaskCounts:nd,onNewCloudProject:Ri,onNewProjectTask:Ee=>Vs(Ee.id),onToggleProjectPinned:Ii,onUploadLocalProject:Lc,chatHistoryHasMore:gd,chatHistoryLoading:bd,onDiffPanelResizeStart:an,onToggleDiffPanelExpanded:()=>oe(Ee=>!Ee),onShowDiffPanel:qc,onShowBrowserPanel:Us,onShowFilesPanel:()=>Kc("files"),onShowGoalSidebarTab:Hs,onShowTrainingDraftPanel:()=>{X("training"),j(!0)},onShowRightChatPanel:Wc,onAddRightChat:()=>Ai(null),onOpenRightChatForSession:(Ee,at)=>{const ct=at??vt.find(on=>on.id===Ee)??null;ct&&Ai(ct,{preserveView:!0})},onLabDetailOpenChange:W.onDetailOpenChange,scheduledDetailOpen:n,onScheduledDetailOpenChange:a,onTerminalTabsChange:m,onCloseRightChatPanel:qs,onCloseNativeSkillSidebar:zi,onActivateRightChatPanel:Za,onRightChatModelChange:Bs,onRightChatPromptChange:Zc,onRightChatScrollStateChange:Yc,onRightChatProviderChange:Jc,onSubmitRightChat:Gc,onStopRightChat:Ee=>Ns(Ee),onCloseTerminal:()=>Q(!1),onLoadMoreChatHistory:tr,canSyncWorkspace:xi,startMessage:po,onPayload:Wt,onError:Xt,setView:Oe,onOpenProfileSettings:Xc,onOpenProviderSettings:()=>{pe("providers"),Oe("settings")},onOpenTrainingSettings:()=>{pe("training"),Oe("settings")},onOpenDatasetStorageSettings:()=>{pe("dataset-storage"),Oe("settings")},changeDraftProvider:js,changeProjectTarget:Wn,changeWorkspaceTarget:zc,setDraftProvider:N,setDraftModel:K,onBeginNewChatWithModel:ii,changeCodexPermissionMode:Xo,changeCodexReasoningEffort:Qo,changeOpenPondCommandAccessMode:er,resolveApproval:ri,answerCreateImproveQuestion:Rc,applyCreateImproveCandidate:Ac,approveCreateImproveRun:Pc,cancelCreateImproveRun:Tc,openCreateImprovePullRequest:Ec,reconcileCreateImprovePullRequest:Mc,rejectCreateImproveCandidate:jc,pauseCreateImproveRun:Os,resumeCreateImproveRun:Oc,reviseCreateImproveRun:Nc,setMentionedAppId:k,showToast:xt,onSaveTaskDraft:of,sendPrompt:zs,stopTurn:Ns,syncWorkspaceLocally:Cc,refreshWorkspaceDiff:Si},cloudSetup:{state:R,onClose:()=>A(null),onOpenBrowserUrl:Hc,onStart:()=>{Ci()}},projectConfirm:{state:I,onResolve:P},lazyPanels:{activeSessions:Ra,branchDialogName:G,branchDialogOpen:U,commitDialogOpen:rt,commitDraft:E,commitIncludeUnstaged:He,commitMessage:Be,commitNextStep:$e,canPublishOpenPondProject:ki,connection:Rt,expandProject:ma,newProjectBusy:et,newProjectDialogOpen:re,newProjectDirectory:Bn.defaultNewProjectDirectory,newProjectMode:Ce,newProjectName:De,newProjectPath:Je,projectRows:vi,query:O,searchOpen:T,visibleWorkspaceDiff:Co,visibleWorkspaceState:Ea,workspaceBusy:Qn,appDispatch:i,beginNewChat:()=>Yn(null),openDefaultsSettingsFromBranchDialog:_i,setBranchDialogName:un,setBranchDialogOpen:dn,setCommitDialogOpen:Ne,setCommitDraft:Vt,setCommitIncludeUnstaged:Le,setCommitMessage:Ye,setCommitNextStep:ut,setNewProjectDialogOpen:de,setNewProjectName:ze,setNewProjectPath:Te,setPrompt:le,setQuery:me,setSearchOpen:he,submitCommitDialog:_c,submitCreateWorkspaceBranch:Ic,submitNewProjectDialog:Kn},toast:{toast:ce,onDismiss:()=>i({type:"field",key:"toast",value:null})}})})}const Er=new Map,yl=new Map;function dm(e){if(!e||e.state!=="signed_in")return null;const t=e.accounts.find(o=>o.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 UU(e){const t=e?.trim();if(!t)return null;const n=Er.get(t);return n?.updatedAt?n.organizations:null}function HU(e,t){const n=e?.trim();if(n){Er.set(n,{organizations:t,promise:null,updatedAt:Date.now()});for(const a of yl.get(n)??[])a()}}function qU(e,t){const n=e?.trim();if(!n)return()=>{};const a=yl.get(n)??new Set;return a.add(t),yl.set(n,a),()=>{a.delete(t),a.size===0&&yl.delete(n)}}function cg(e){const t=e.accountKey?.trim();if(!t)return Promise.resolve([]);const n=Er.get(t);if(!e.force){if(n?.updatedAt)return Promise.resolve(n.organizations);if(n?.promise)return n.promise}const a=e.fetchOrganizations().then(o=>(HU(t,o),o)).catch(o=>{const i=Er.get(t);throw i?.promise===a&&Er.set(t,{organizations:i.organizations,promise:null,updatedAt:i.updatedAt}),o});return Er.set(t,{organizations:n?.organizations??[],promise:a,updatedAt:n?.updatedAt??0}),a}const W3="openpond.config.json";function K3(e,t,n){return t<=0?-1:n==="Home"?0:n==="End"?t-1:n==="ArrowRight"?(e+1)%t:(e-1+t)%t}function gx(){return{activeTab:"files",openFilePaths:[],selectedPath:null}}function pu(e){return{activeTab:e.activeTab,openFilePaths:[...e.openFilePaths],selectedPath:e.selectedPath}}function G3(e,t=null){const n=FU(e.openFilePaths.map(o=>ug(o,t)).filter(Boolean)),a=e.selectedPath&&ug(e.selectedPath,t)||null;return{activeTab:e.activeTab==="file"&&!a?"files":e.activeTab,openFilePaths:n,selectedPath:a}}function dg(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 ug(e,t=null){let n=BU(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 o=a.split("/").filter(Boolean).at(-1);return o&&n.startsWith(`${o}/`)&&(n=n.slice(o.length+1)),n}function Z3(e){return e.startsWith("/")||/^[A-Za-z]:\//.test(e)}function J3(e){return{path:e,status:"unchanged",additions:0,deletions:0,patch:"",content:null}}function Y3(e,t){const n=mg(e.path);return!n||e.path.endsWith("/")||e.content==null&&/Could not access .+\/null['"]?/.test(e.patch)?!0:t.some(a=>{const o=mg(a);return!!(o&&o.startsWith(`${n}/`))})}function X3(e){return/\.(?:md|markdown|mdx)$/i.test(e)||/(?:^|\/)readme$/i.test(e)}function Q3(e){return/\.(?:doc|docx)$/i.test(e)}function BU(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 FU(e){return Array.from(new Set(e))}function mg(e){const n=e.replace(/\\/g,"/").replace(/^\.\/+/,"").split("/").filter(Boolean);return n.length===0?null:n.join("/")}function VU(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",o=e.activeProfile?.baseUrl??t?.baseUrl??e.baseUrl??"",i=e.apiBaseUrl??t?.apiBaseUrl??"",s=e.chatApiBaseUrl??t?.chatApiBaseUrl??"";return[n?`profile:${n}`:"profile:unknown",a,o,i,s].join("|")}function bx(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"cloud-project"}function WU(e){const t=new TextEncoder().encode(e);let n="";for(const a of t)n+=String.fromCharCode(a);return btoa(n)}function pc(e){const t=e,n=t.teamId||t.id||"";if(!n)return null;const a=t.displayName||t.name||n,o=t.workspaceKind==="personal"||t.isPersonalDefault===!0||t.kind==="personal_default"||t.name?.trim().toLowerCase()==="personal";return{teamId:n,slug:t.slug||bx(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:o?"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:o,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 KU(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 GU(e,t){const n=e.filter(o=>o.status==="active"&&o.workspaceKind==="shared"),a=t?.trim()??"";if(a){const o=n.find(i=>i.teamId===a);if(o)return o}return n.find(o=>o.role==="owner")??n.find(o=>o.role==="admin")??n[0]??null}function ZU(...e){for(const t of e){const n=t?.trim();if(n)return n}return""}function JU({draftProvider:e,hasSelectedCloudProject:t,selectedSessionHybridWorkspace:n}){return t&&!n?"openpond":e}const YU=[{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 XU(...e){return ZU(...e.map(t=>{const n=t?.trim();return n&&!n.includes("@")?n:null}))}function QU(e){if(e?.state!=="signed_in")return"";const t=e.accounts.find(n=>n.isActive)??null;return XU(e.profile?.name,e.label,t?.displayLabel,e.profile?.handle,t?.handle,e.activeProfile?.handle)}function eH({bootstrap:e,draftModel:t,draftProvider:n,selectedApp:a,selectedAppId:o,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?wa(l.workspaceKind):!1,k=_a(l),R=l?$U(l):!1,A=l?.cwd&&(!y||k)?Pv(l.cwd):null,$=e?.providers??null,z=aa(s,e?.cloudProjects??[]),D=JU({draftProvider:n,hasSelectedCloudProject:!!i,selectedSessionHybridWorkspace:k}),x=uo(D,t,$),I=Zn(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":o?"sandbox_app":null,O=S?null:l?y&&!k||R?null:f||(l.workspaceId??l.appId??A):i?null:s?.id??o,T=S?null:l?y?l.workspaceId??null:R?null:f??l.workspaceId??l.appId??A:i?null:s?.id??o,F=e?.account??null,H=!e||F?.state==="loading"||F?.state==="switching",L=!H&&F?.state==="signed_out",V=H?null:L?"Sign in":F?.label??F?.activeProfile?.handle??"Account",Y=QU(F),ie=Y?`Welcome, ${Y}`:"Welcome",_e=l?.workspaceName??l?.appName??i?.name??s?.name??a?.name??null,fe=wa(P)?"cloud":"local",J=s?.name??m?.name??(l?.workspaceKind==="local_project"?l.workspaceName:null)??"Local workspace",Me=(fe==="cloud"?_e:null)??i?.name??z?.name??s?.name??"Cloud workspace",Se=!!(i?.id||z?.id||l?.cloudProjectId||fe==="cloud");return{account:F,accountLabel:V,accountPending:H,accountSignedOut:L,activeModel:x,activeProvider:D,activeWorkspaceAppId:O,activeWorkspaceId:T,activeWorkspaceKind:P,activeWorkspaceLocation:fe,appDefaults:I,cloudLinked:Se,cloudTargetName:Me,localTargetName:J,selectedCodexHistoryPending:S,selectedSessionCloudWorkspace:y,selectedSessionLocalPathWorkspaceId:A,selectedSessionPendingCloudStart:R,selectedSessionProjectId:f,startMessage:ie,workspaceName:_e}}function tH({accountPending:e,accountSignedOut:t,activeWorkspaceLocation:n,bootstrap:a,busy:o,cloudLinked:i,selectedCloudProject:s,selectedProject:l,selectedSession:p,pendingWorkspaceTarget:m,workspaceStates:f,workspaceBusy:S}){const y=aa(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"})),H=l?`local:${l.id}`:s?`cloud:${s.id}`:"none",L=[...T,...F].find(V=>V.value===H)??null;return{value:H,label:L?.label??"Select Project",detail:L?.detail??"Choose a project for local or cloud work",busy:S||o,options:[...T,...F,...YU,{value:"none",label:"Don't work in a project",detail:"General chat without project files",kind:"none"}]}},[a?.cloudProjects,a?.localProjects,o,s,l,S]),$=!!(i||l),z=!!(s?.id||y?.id||p?.cloudProjectId||_a(p)),D=l?f[l.id]??null:null,x=TS(D,{branch:l?.linkedSandboxProject?.defaultBranch??null,path:l?.workspacePath??p?.cwd??null,linkedCloudSourceKnown:l?.linkedSandboxProject?.projectId&&R?!!l.linkedSandboxProject.lastUploadedCommit||!D?.headCommit:!0}),I=ES(l,s??y,D,{cloudLinkTrusted:R}),P=XD(l,D,{cloudLinkTrusted:R}),O=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."},H={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},L={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",Y=V==="local"?T:H;let ie=n==="cloud"?H:T;return m==="cloud"?ie=H:m==="local"?ie=T:(_a(p)||m==="hybrid")&&(ie=F),{value:ie.value,label:ie.label,detail:ie.stateNote||ie.detail,busy:S,action:{...Y,label:V==="cloud"?"Hosted":l?"Local checkout":"Check out locally"},uploadAction:l?L:null,options:[T,F,H]}},[n,e,t,i,$,I,z,x,m,l,p,P,S]);return{projectTarget:A,workspaceTarget:O}}function bn(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")}function vx(e){return bn(e.name||e.gitRepo||e.id)}function eV(e){return`@${vx(e)}`}function yx(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>bn(t[1]??"")).filter(Boolean)}function nH(e,t){const n=yx(e);if(n.length===0)return!1;const a=new Set([bn(t.id),vx(t),t.gitRepo?bn(t.gitRepo):""].filter(Boolean));return n.some(o=>a.has(o))}function Sx(e){return e.filter(t=>t.sandbox)}function aH(e,t){const n=yx(e);if(n.length===0)return null;const a=new Map;for(const o of n){const i=t.find(s=>{const l=bn(s.id),p=bn(s.name),m=s.gitRepo?bn(s.gitRepo):"";return o===l||o===p||o===m});i&&a.set(i.id,i)}return a.size===1?Array.from(a.values())[0]??null:null}function tV(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 o=n.slice(a.index).indexOf("@");return o<0?null:{query:bn(a[1]??""),start:a.index+o}}function oH(e){return new Set(e.map(t=>t.id))}function pg(e,t){const n=e?.linkedOpenPondApp??null;return n?.appId&&t.has(n.appId)?n:null}function rH({bootstrap:e,codexHistorySessions:t,selectedProjectId:n,selectedSessionId:a,selectedAppId:o,sessions:i}){const s=g.useMemo(()=>e?.apps.find(L=>L.id===o)??null,[e?.apps,o]),l=g.useMemo(()=>new Map((e?.localProjects??[]).map(L=>[L.id,L])),[e?.localProjects]),p=g.useMemo(()=>new Map((e?.cloudProjects??[]).map(L=>[L.id,L])),[e?.cloudProjects]),m=g.useMemo(()=>wS(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(()=>oH(e?.apps??[]),[e?.apps]),k=g.useMemo(()=>Sx(e?.apps??[]),[e?.apps]),R=g.useMemo(()=>{const L=[];for(const V of e?.localProjects??[]){const Y=pg(V,y);Y&&L.push([Y.appId,V.id])}return new Map(L)},[e?.localProjects,y]),A=g.useMemo(()=>new Set((e?.localProjects??[]).map(L=>L.id)),[e?.localProjects]),$=g.useMemo(()=>qS(e?.localProjects??[]),[e?.localProjects]),z=g.useRef([]),D=g.useMemo(()=>iH(i,t,z.current),[t,i]),x=g.useMemo(()=>D.find(L=>L.id===a)??null,[D,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 L=Kz(x,A,$);if(L)return l.get(L)??null;if(!x.appId)return null;const V=R.get(x.appId);return V?l.get(V)??null:null},[R,l,A,$,x]),P=g.useMemo(()=>x?.cloudProjectId?p.get(x.cloudProjectId)??null:null,[p,x]),O=f??I,T=S??P,F=g.useMemo(()=>pg(O,y),[y,O]),H=g.useMemo(()=>F?e?.apps.find(L=>L.id===F.appId)??null:null,[e?.apps,F]);return{cloudProjectById:p,currentAppIds:y,linkedProjectByAppId:R,localProjectById:l,mentionableSandboxApps:k,selectedApp:s,selectedCloudProject:T,selectedProject:O,selectedProjectLinkedApp:H,selectedProjectLinkedOpenPondApp:F,selectedSession:x,selectedSessionLinkedProject:I,sidebarSessions:D}}function iH(e,t,n){const a=new Map;for(const m of e){const f=fg(m);a.set(f,m)}for(const m of t){const f=fg(m),S=a.get(f);a.set(f,S?sH(S,m):m)}const o=Array.from(a.entries());if(!n)return o.sort((m,f)=>hg(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=[...o.filter(([m])=>!s.has(m)).sort((m,f)=>hg(m[1],f[1])),...i];return n.splice(0,n.length,...p.map(([m])=>m)),p.map(m=>m[1])}function sH(e,t){return{...e,metadata:lH(e.metadata,t.metadata),status:e.status==="active"||t.status==="active"?"active":e.status,updatedAt:cH(e.updatedAt,t.updatedAt)}}function fg(e){return e.codexThreadId?`codex:${e.codexThreadId}`:`session:${e.id}`}function hg(e,t){const n=gg(t)-gg(e);return n!==0?n:e.title.localeCompare(t.title)}function lH(e,t){const n={...e??{},...t??{}};return Object.keys(n).length>0?n:void 0}function cH(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 gg(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 dH(e){return!!(e&&wa(e.workspaceKind)&&!_a(e)&&e.provider!=="openpond")}function uH(e,t){const n=CS(e,t);return`${e.id}\0${n.provider}\0${n.model}`}function mH({activeWorkspaceId:e,activeWorkspaceKind:t,appDispatch:n,connection:a,expandProject:o,linkedProjectByAppId:i,providerSettings:s,selectedAppId:l,selectedSession:p,selectedSessionId:m,selectedSessionProjectId:f,setDiffPanelExpanded:S,setDraftModel:y,setDraftProvider:k,setError:R,setSelectedAppId:A,setSelectedProjectId:$,setSessions:z,setTerminalOpen:D,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 O=gt("local",P);A(null),$(O),o(O)},[o,i,l,m,f,A,$]),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(O){(O.metaKey||O.ctrlKey)&&O.key==="`"&&(O.preventDefault(),D(T=>!T))}return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[D]),g.useEffect(()=>{S(!1)},[e,t,S]),g.useEffect(()=>{if(!m){I.current=null;return}if(!p||p.id!==m)return;const P=uH(p,s);if(I.current===P)return;I.current=P;const O=CS(p,s);k(O.provider),y(O.model)},[s,p,m,y,k]),g.useEffect(()=>{!a||!p||!dH(p)||Z.patchSession(a,p.id,{provider:"openpond"}).then(P=>{z(O=>O.map(T=>T.id===P.id?P:T)),k("openpond"),y(O=>uo("openpond",O))}).catch(P=>{R(P instanceof Error?P.message:String(P))})},[a,p,y,k,R,z])}function pH({connection:e,setError:t}){return g.useCallback(async(n,a)=>{if(!e){const o=new Error("OpenPond App server is not connected.");throw t(o.message),o}t(null);try{await Z.resolveApproval(e,n,{decision:a})}catch(o){const i=o instanceof Error?o.message:String(o);throw t(i),o}},[e,t])}function fH({activeProvider:e,contextCompaction:t,contextUsage:n,pinnedItems:a,pinnedPreviewKeys:o,pinnedProjects:i,projectRows:s,visibleProjectRows:l}){const p=g.useMemo(()=>ED(a,o),[a,o]),m=g.useMemo(()=>WS({provider:e,snapshot:n,preferences:t}),[e,t,n]),f=g.useMemo(()=>Array.from(new Set([...i,...l].filter($p).map(y=>y.project.id))),[i,l]);return{commandProjectRows:g.useMemo(()=>s,[s]),contextWindowStatus:m,pinnedRows:p,sidebarWorkspaceAppIds:f}}function hH({appDispatch:e,expandProject:t,linkedProjectByAppId:n,requestComposerFocus:a,onBeginNewChat:o,setMentionedAppId:i}){return g.useCallback((s=null)=>{o?.();const l=s?.id?n.get(s.id)??null:null;if(l){const p=gt("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,o,a,i])}const xx={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 nV(e){return`@${e.token}`}function gH(e){return`@${xH(e)}`}function bH(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 o=a[0],i=Cr(a.flatMap(S=>S.capabilities.map(y=>y.id))),s=Cr(a.flatMap(S=>S.capabilityLabels)),l=Cr(a.flatMap(S=>S.connections.map(y=>y.id).filter(wH))),p=Cr(a.map(S=>S.id)),m=Cr(a.map(S=>S.setupSurface)),f=SH(n);return{provider:n,label:o.providerLabel,detail:s.length>0?s.slice(0,4).join(", "):o.description,token:f,tokens:yH(a),ref:{kind:"integration",provider:n,appIds:p,setupSurfaces:m,...l.length>0?{connectionIds:l}:{},...i.length>0?{capabilities:i}:{}}}})}function aV(e,t){const n=bn(t);return e.filter(a=>n?a.tokens.some(o=>o.includes(n)):!0).slice(0,8)}function vH(e,t){const n=kH(e);if(n.length===0)return[];const a=new Map;for(const o of n){const i=t.find(s=>s.tokens.includes(o));i&&a.set(i.provider,i)}return Array.from(a.values())}function oV(e,t){if(t.length===0)return[];const n=[];for(const a of e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)){const o=a[1]??"",i=bn(o);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=`@${o}`;n.push({detail:s.detail,displayText:gH(s),end:m+f.length,label:s.label,provider:s.provider,start:m,text:f})}return n}function yH(e){return Cr(e.flatMap(t=>[...xx[t.providerFamily],t.providerFamily,t.id,t.label,t.shortLabel]).map(bn).filter(Boolean))}function SH(e){return bn(xx[e][0]??e)}function xH(e){return e.provider==="github"?"GitHub":e.provider==="x"?"X":e.provider==="mcp"?"MCP":e.label}function kH(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>bn(t[1]??"")).filter(Boolean)}function Cr(e){return Array.from(new Set(e))}function wH(e){return typeof e=="string"&&e.length>0}function _H({bootstrap:e,connectedAppRows:t,mentionableSandboxApps:n,runtimeIndexes:a,selectedApp:o,selectedCloudProject:i,selectedProject:s,selectedSession:l,selectedSessionId:p}){const m=g.useMemo(()=>{const R=new Map;for(const A of e?.cloudProjects??[]){const $=R.get(A.teamId)??[];$.push(A.id),R.set(A.teamId,$)}return R},[e?.cloudProjects]),S=!!(l||o||s||i)?[]:n,y=g.useMemo(()=>bH(t),[t]),k=g.useMemo(()=>wU(a,p),[a,p]);return{chatMentionApps:S,cloudProjectIdsByTeam:m,connectedAppMentions:y,pendingApproval:k}}const kx="openpond.codexPermissionMode",wx="openpond.codexReasoningEffort";function Ts(){if(typeof window>"u")return null;try{return window.localStorage}catch{return null}}function IH(e){return e==="default"||e==="auto-review"||e==="full-access"?e:null}function CH(e){return e==="low"||e==="medium"||e==="high"||e==="xhigh"?e:null}function _x(e=Ts()){if(!e)return{};const t=IH(e.getItem(kx)),n=CH(e.getItem(wx));return{...t?{codexPermissionMode:t}:{},...n?{codexReasoningEffort:n}:{}}}function RH(e,t=Ts()){try{t?.setItem(kx,e)}catch{}}function AH(e,t=Ts()){try{t?.setItem(wx,e)}catch{}}function bg(e,t=Ts()){const n=Zn(e),a=_x(t);return{codexPermissionMode:a.codexPermissionMode??n.codexPermissionMode??Kl,codexReasoningEffort:a.codexReasoningEffort??n.codexReasoningEffort??Gl}}function PH(e,t=Ts()){const n=Zn(e),a=_x(t),o={};return a.codexPermissionMode&&a.codexPermissionMode!==n.codexPermissionMode&&(o.codexPermissionMode=a.codexPermissionMode),a.codexReasoningEffort&&a.codexReasoningEffort!==n.codexReasoningEffort&&(o.codexReasoningEffort=a.codexReasoningEffort),o}function TH({connection:e,setBootstrap:t,setCodexPermissionMode:n,setCodexReasoningEffort:a,setError:o}){const i=g.useCallback(l=>{n(l),RH(l),e&&Z.savePreferences(e,{codexPermissionMode:l}).then(()=>{t(p=>p&&{...p,preferences:{...p.preferences,codexPermissionMode:l}})}).catch(p=>{o(p instanceof Error?p.message:String(p))})},[e,t,n,o]),s=g.useCallback(l=>{a(l),AH(l),e&&Z.savePreferences(e,{codexReasoningEffort:l}).then(()=>{t(p=>p&&{...p,preferences:{...p.preferences,codexReasoningEffort:l}})}).catch(p=>{o(p instanceof Error?p.message:String(p))})},[e,t,a,o]);return{changeCodexPermissionMode:i,changeCodexReasoningEffort:s}}const EH=6e4;function Vp(e,t){if(!e)return t;const n=jH(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 Cx(e,n)?e:n}function MH(e,t){const n=Vp(e,t),a=e?{...n,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order,updatedAt:e.updatedAt}:n;return e&&Cx(e,a)?e:a}function Gi(e,t){let n=!1,a=!1;const o=e.map(i=>{if(i.id!==t.id)return i;n=!0;const s=Vp(i,t);return s!==i&&(a=!0),s});return n?a?o:e:[t,...e]}function fc(e,t){let n=!1,a=!1;const o=e.map(i=>{if(i.id!==t.id)return i;n=!0;const s=MH(i,t);return s!==i&&(a=!0),s});return n?a?o:e:[t,...e]}function um(e,t,n,a=Date.now()){const o=new Map(e.map(i=>[i.id,i]));return t.map(i=>{const s=o.get(i.id);if(s&&n){const l=NH(s,i,n,a);if(l)return l}return Vp(s,i)})}function vg(e,t,n,a=Date.now()){const o=new Map(e.map(m=>[m.id,m])),i=new Map(um(e,t,n,a).map(m=>[m.id,m])),s=new Set(o.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||(Ix(m,t)?m:null)}).filter(m=>!!m);return[...l,...p]}function Ix(e,t){const n=Date.parse(e.updatedAt);if(!Number.isFinite(n))return!1;const a=OH(t);return a===null||n>=a}function yg(e,t,n,a=Date.now()){const o=new Map(t.map(i=>[i.id,i]));for(const i of n){const s=o.get(i.id);s&&(Rx(s,i)||(e[i.id]=a))}}function jH(e,t){const n=Date.parse(e),a=Date.parse(t);return Number.isFinite(n)&&Number.isFinite(a)&&n>a}function Cx(e,t){return JSON.stringify(e)===JSON.stringify(t)}function OH(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 NH(e,t,n,a){const o=n[t.id];return o===void 0?null:a-o>EH||Rx(e,t)?(delete n[t.id],null):{...t,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order}}function Rx(e,t){return e.pinned===t.pinned&&e.savedForLater===t.savedForLater&&e.archived===t.archived&&e.order===t.order}const Ax=800,$H=5e3,Sg=5e4,DH=16,LH=3e4,$n=new Map;function zH(e,t){return $n.get(Tx(e,t))?.payload??null}async function Px(e,t,n={}){const a=Tx(e,t),o=$n.get(a),i=n.limit??Ax,s=n.tail??!0;if(o?.promise)return o.promise;if(!n.force&&s&&o?.payload&&Date.now()-o.fetchedAt<=LH)return xg(a,o),o.payload;const l=!!(n.force&&s&&o?.payload),p=l?o?.payload?.events.at(-1)?.id:void 0,m=Z.codexHistoryThreadIncremental(e,t,{afterEventId:p,limit:i,revision:l?o?.revision:void 0,tail:s}).then(f=>{const S=$n.get(a)?.payload??o?.payload;if(f.unchanged){if(!S)throw new Error("Codex history revision matched without a cached thread.");return $n.set(a,{fetchedAt:Date.now(),payload:S,revision:f.revision}),xg(a,$n.get(a)),S}const y={session:f.session,events:f.events},k=s&&S&&!f.reset?{...y,events:UH(S.events,y.events)}:y;return $n.set(a,{fetchedAt:Date.now(),payload:k,revision:f.revision}),kg(),k}).catch(f=>{throw $n.get(a)?.promise===m&&$n.delete(a),f});return $n.set(a,{fetchedAt:o?.fetchedAt??0,payload:o?.payload,promise:m,revision:o?.revision}),kg(),m}function Tx(e,t){return`${e.serverUrl}
132
- ${e.token}
133
- ${t}`}function xg(e,t){$n.delete(e),$n.set(e,t)}function kg(){for(;$n.size>DH;){const e=$n.keys().next().value;if(!e)return;$n.delete(e)}}function UH(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 HH=500,qH=2500,BH=15e3;function FH(e){return e.active?HH:e.surface==="thread"?qH:BH}function Wp(e,t){return!t||e.session.status==="active"?e:{...e,session:{...e.session,status:"active"}}}function VH(e={}){const t={cachedPayload:e.cachedPayload??zH,clearTimer:e.clearTimer??(m=>globalThis.clearTimeout(m)),loadPayload:e.loadPayload??Px,now:e.now??Date.now,setTimer:e.setTimer??((m,f)=>globalThis.setTimeout(m,f))},n=new Map;let a=1;function o(m){const f=KH(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"||Bp(m.latestPayload?.events??[])?.tone==="active",y=f.some(k=>k.surface==="thread")?"thread":"sidebar";return FH({active:S,surface:y})}function p(m){m.timer&&t.clearTimer(m.timer),m.timer=null,m.nextRefreshAt=null}return{subscribe:o}}const WH=VH();function Kp(e){return WH.subscribe(e)}function KH(e,t){return`${e.serverUrl}
134
- ${e.token}
135
- ${t}`}function GH({connection:e,selectedSessionId:t,selectedSessionLocallyActive:n,selectedSessionStatus:a,setCodexHistorySessions:o,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 Kp({connection:e,locallyActive:S,onError:k=>i(k instanceof Error?k.message:String(k)),onPayload:k=>{const R=Wp(k,S);l(A=>A.sessionId!==p?{events:R.events,sessionId:p}:{events:Na(A.events,R.events),sessionId:p}),i(A=>A==="Session not found"?null:A),o(A=>fc(A,R.session))},reportedActive:a==="active",sessionId:p,surface:"thread"})},[e,p,n,a,o,i]),{codexHistoryEvents:m,setCodexHistoryEvents:f}}function Ex(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 ZH({connection:e,appPreferences:t,sessions:n,pinnedItems:a,setAppPreferences:o,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 $(O,T){O.dataTransfer.effectAllowed="move",O.dataTransfer.setData("text/plain",`${T.type}:${T.id}`),Ex(O);const F=a.map(H=>H.key);R.current=T,A.current=F,S(T),k(F)}function z(){R.current=null,A.current=null,S(null),k(null)}function D(O,T){const F=R.current;if(!F)return;const H=Tl(O),L=A.current??a.map(Y=>Y.key),V=El(L,$o(F),$o(T),H);Uh(L,V)||(A.current=V,k(V))}function x(O){if(!e)return;const T=a.map(fe=>fe.key),F=new Set(T),H=[...O.filter(fe=>F.has(fe)),...T.filter(fe=>!O.includes(fe))];if(Uh(T,H))return;const L=t,V=new Map(n.map(fe=>[fe.id,fe])),Y=l,ie=new Map(a.map(fe=>[fe.key,fe]));o(fe=>{const J={...fe};return H.forEach((Me,Se)=>{const ae=ie.get(Me);ae?.type==="project"&&(J[ae.id]={...J[ae.id]??{},pinned:!0,archived:!1,order:Se})}),J});const _e=fe=>{const J=new Map(fe.map(ae=>[ae.id,ae])),Me=H.map((ae,xe)=>{const ee=ie.get(ae),ue=ee?.type==="session"?J.get(ee.id):null;return ue?{...ue,order:xe}:null}).filter(ae=>!!ae),Se=new Map(Me.map(ae=>[ae.id,ae]));return fe.map(ae=>Se.get(ae.id)??ae)};s(_e),i(_e),p(fe=>{const J=new Map;return H.forEach((Me,Se)=>{const ae=ie.get(Me);ae?.type==="file"&&J.set(ae.id,Se)}),fe.map(Me=>{const Se=J.get(Me.id);return Se===void 0?Me:{...Me,order:Se}})}),Promise.all(H.map((fe,J)=>{const Me=ie.get(fe);return Me?Me.type==="project"?Z.patchSidebarAppPreference(e,Me.id,{pinned:!0,archived:!1,order:J}):Me.type==="session"?Z.patchSession(e,Me.id,{order:J}):Z.patchSidebarFile(e,{workspaceKind:Me.file.workspaceKind,workspaceId:Me.file.workspaceId,workspaceName:Me.file.workspaceName,path:Me.file.path,status:"pinned",order:J,sourceSessionId:Me.file.sourceSessionId}):Promise.resolve(null)})).catch(fe=>{m(fe instanceof Error?fe.message:String(fe)),o(L);const J=Me=>Me.map(Se=>V.get(Se.id)??Se);s(J),i(J),p(Y)})}function I(O,T){const F=R.current;if(F){const H=A.current??a.map(V=>V.key),L=El(H,$o(F),$o(T),Tl(O));x(L)}z()}function P(){R.current&&x(A.current??a.map(T=>T.key)),z()}return{dragItem:f,pinnedPreviewKeys:y,startPinnedDrag:$,clearSidebarDrag:z,previewPinnedDrop:D,commitPinnedDrop:I,commitPinnedPreviewDrop:P}}function JH({connection:e,sessions:t,setCodexHistorySessions:n,setError:a,setSessions:o}){const[i,s]=g.useState(null),[l,p]=g.useState(null),m=g.useRef(null),f=g.useRef(null);function S(z,D){z.dataTransfer.effectAllowed="move",z.dataTransfer.setData("text/plain",`session:${D.sessionId}`),Ex(z),m.current=D,f.current=D.visibleSessionIds,s(D.sessionId),p(D.visibleSessionIds)}function y(z,D){const x=m.current;if(!x)return;const I=f.current??x.visibleSessionIds,P=El(I,x.sessionId,D,Tl(z));YH(I,P)||(f.current=P,p(P))}function k(){m.current=null,f.current=null,s(null),p(null)}function R(z,D){const x=m.current;if(!x){k();return}const I=f.current??x.visibleSessionIds,P=El(I,x.sessionId,D,Tl(z));$(Vh(x.allSessionIds,x.visibleSessionIds,P)),k()}function A(){const z=m.current;z&&$(Vh(z.allSessionIds,z.visibleSessionIds,f.current??z.visibleSessionIds)),k()}function $(z){const D=new Map(z.map((O,T)=>[O,T])),x=new Map(t.map(O=>[O.id,O.order])),I=z.filter((O,T)=>x.get(O)!==T);if(I.length===0)return;const P=O=>O.map(T=>{const F=D.get(T.id);return F===void 0||F===T.order?T:{...T,order:F}});o(P),n(P),e&&Promise.all(I.map(O=>Z.patchSession(e,O,{order:D.get(O)}))).catch(O=>{const T=F=>F.map(H=>{const L=x.get(H.id);return L===void 0||L===H.order?H:{...H,order:L}});o(T),n(T),a(O instanceof Error?O.message:String(O))})}return{clearTaskDrag:k,commitTaskDrop:R,commitTaskPreviewDrop:A,previewTaskDrop:y,startTaskDrag:S,taskDragSessionId:i,taskPreviewSessionIds:l}}function YH(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function wg({afterMessageId:e=null,attachments:t,content:n,sessionId:a}){const o=new Date().toISOString(),i=`pending_user_${a}_${o}_${Math.random().toString(36).slice(2,8)}`,s=XH(t);return{id:i,role:"user",content:n,sessionId:a,afterMessageId:e,timestamp:o,turnId:i,...s.length>0?{attachments:s}:{}}}function Mx(e,t){return!t||jx(e,t)?e:[...e,t]}function jx(e,t){const n=t.afterMessageId?e.findIndex(i=>i.id===t.afterMessageId):-1,a=n>=0?n+1:0,o=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(o)||!Number.isFinite(l)||l>=o)return!0}return!1}function XH(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 mo(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 qa(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];if(t(a))return a}return null}function QH(e,t,n){if(t.name==="workspace_action_result"){const a=qa(e,o=>o.role==="assistant"&&o.turnId===t.turnId&&o.actionRun?.actionName===n.actionName);if(a?.actionRun){a.id=t.id,a.timestamp=t.timestamp,a.actionRun={...a.actionRun,...n,refs:mm([...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 eq(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"])??fu(t)??fu(Ae(t?.run))??fu(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=mm([...Oa("artifact",t?.artifactRefs,"Artifact"),...Oa("artifact",p?.artifactRefs,"Artifact"),...Oa("artifact",l?.artifactRefs,"Artifact"),...Oa("artifact",m?.artifactRefs,"Artifact"),...Oa("trace",t?.traceArtifactRefs,"Trace"),...Oa("trace",S?.artifactRefs,"Trace"),...Oa("eval",t?.evalResultArtifactRefs,"Eval"),...Oa("eval",y?.artifactRefs,"Eval"),...Oa("output",t?.outputRefs,"Output")]),R=be(f,["sourceRef","ref"]);return R&&k.push({id:pm("source",R),kind:"source",label:"Source",target:R}),{actionName:a,title:be(p,["label","title","name"])??be(s,["selectedActionLabel"])??iq(a),status:tq(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:mm(k),childCalls:aq(t,i,s)}}function fu(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 tq(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 o=be(n,["status"]);return o==="failed"?"failed":o==="succeeded"||o==="completed"?"completed":o==="queued"||o==="running"||o==="runtime_created"?"running":e.status==="pending"?"pending":e.status==="started"||e.name==="workspace_action"?"running":"unknown"}function Oa(e,t,n){return(Array.isArray(t)?t:t?[t]:[]).flatMap(o=>{const i=nq(e,o,n);return i?[i]:[]})}function nq(e,t,n){if(typeof t=="string"&&t.trim()){const s=t.trim();return{id:pm(e,s),kind:e,label:n,target:s}}const a=Ae(t);if(!a)return null;const o=be(a,["url","webUrl","artifactPath","path","ref"])??be(Ae(a.artifact),["url","webUrl","path","ref"]);if(!o)return null;const i=be(a,["label","title","name","type","kind"])??n;return{id:pm(e,o),kind:e,label:i,target:o}}function mm(e){const t=new Set,n=[];for(const a of e){const o=`${a.kind}:${a.target}`;t.has(o)||(t.add(o),n.push(a))}return n}function pm(e,t){return`${e}:${t}`}function aq(e,t,n){return[e?.childCalls,e?.childRuns,e?.implementationCalls,t?.childCalls,t?.childRuns,n?.childCalls,n?.childRuns].flatMap(o=>oq(o)).slice(0,6)}function oq(e){return(Array.isArray(e)?e:e?[e]:[]).flatMap((n,a)=>{const o=Ae(n);if(!o)return[];const i=be(o,["id","runId","callId"])??`child_${a+1}`,s=be(o,["label","title","actionName","name","tool"])??be(Ae(o.action),["label","name"])??"Implementation call",l=be(o,["detail","summary","runId","sandboxId","runtimeId"])??null;return[{id:i,label:s,status:rq(o),detail:l}]})}function rq(e){const t=be(e,["status","state"]);return t==="running"||t==="completed"||t==="failed"||t==="pending"?t:t==="succeeded"?"completed":"unknown"}function iq(e){const t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e}const sq=new Set([".avif",".gif",".jpeg",".jpg",".png",".webp"]);function Ox(e){if(!e)return!1;const t=e.split("?")[0]?.split("#")[0]??e,n=t.lastIndexOf(".");return n<0?!1:sq.has(t.slice(n).toLowerCase())}function Nx(e){return e.split("/").filter(Boolean).pop()??e}function lq(e){if(!hm(e))return;const t=Ae(e.data),a=(typeof t?.openpondImagePreviewPath=="string"?t.openpondImagePreviewPath:null)??Do(e.data)??Do(e.args)??Do(e.output);if(!(!a||!Ox(a)))return{path:a,appId:e.appId??null,title:Nx(a)}}function cq(e){if(e.name!=="tool.completed"&&e.name!=="workspace_action_result")return[];const t=[],n=new Set;return fm(e.data,t,n),t.slice(0,12)}function fm(e,t,n,a=0){if(a>7||e==null)return;if(Array.isArray(e)){for(const l of e)fm(l,t,n,a+1);return}const o=Ae(e);if(!o)return;const i=be(o,["path","artifactRef"]),s=be(o,["contentType","mimeType"]);i&&s&&!n.has(i)&&(n.add(i),t.push({path:i,title:be(o,["title","name"])??Nx(i),contentType:s,sizeBytes:typeof o.sizeBytes=="number"?o.sizeBytes:null}));for(const l of Object.values(o))fm(l,t,n,a+1)}function hm(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 Do(e,t=0,n=""){if(t>5||e==null)return null;if(typeof e=="string"){if(hu(n)&&Ox(e.trim()))return e.trim();const o=mo(e);if(o!==null){const i=Do(o,t+1,n);if(i)return i}return dq(e)}if(Array.isArray(e)){for(const o of e){const i=Do(o,t+1,n);if(i)return i}return null}const a=Ae(e);if(!a)return null;for(const[o,i]of Object.entries(a)){if(!hu(o))continue;const s=Do(i,t+1,o);if(s)return s}for(const[o,i]of Object.entries(a)){if(hu(o))continue;const s=Do(i,t+1,o);if(s)return s}return null}function hu(e){return/^(path|filePath|filepath|imagePath|image|localPath|uri|url)$/i.test(e)}function dq(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 uq(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=pq(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 mq(e){if(e.action!=="connected_app_search"&&e.action!=="connected_app_read"&&e.action!=="connected_app_write")return null;const t=$x(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 pq(e){return $x(e).providerLabel}function $x(e){const t=Ae(e.args),n=Ae(e.data),a=Ae(n?.result),o=Wl(be(t,["provider"])??be(a,["provider"])??be(n,["provider"])??void 0),i=be(a,["providerLabel"])??be(n,["providerLabel"])??(o?Um(o)?.label:null)??"connected app",s=be(t,["operation"]),l=be(a,["operation"])??be(n,["operation"]),p=gu(t?.capabilityIds)||gu(a?.capabilityIds)||gu(n?.capabilityIds);return{providerLabel:i,providerOperation:s,operation:l,capabilityCount:p}}function gu(e){return Array.isArray(e)?e.length:0}function Dx(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()||bu(a)}}return t==="<turn_aborted>"?{kind:"turn_aborted",text:bu("turn_aborted")}:t==="<goal_context>"?{kind:"goal_context",text:bu("goal_context")}:null}function bu(e){return e==="turn_aborted"?"The previous turn was interrupted.":"Goal context updated."}function hc(e){return e.name==="diagnostic"&&Ae(e.data)?.kind==="goal_context"}function fq(e,t){if(!t.turnId)return;yq(e,t.turnId);const n=hq(t);if(!n)return;const a=vq(e,t.turnId);if(a){a.refinerActivity=n;return}const o={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,o):e.push(o)}function hq(e){const t=Ae(e.data),n=Ae(t?.activity);return n?gq(n,e):bq(e,t)}function rV(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 · ${wq(e.route??"external")} issue routed`;const t=e.result==="applied"?"Applied":"Needs review";return`Refiner · ${e.summary} — ${t}`}function gq(e,t){const n=xa(e.state,["running","completed","failed"]);if(!n)return null;const a=n==="failed"?"failed":xa(e.result,["no_action","routed","applied","retained"]),o=Rn(e.reason)??t.output??t.error??null;return{state:n,visibility:xa(e.visibility,["always","material_only"])??"material_only",result:n==="running"?null:a,workspaceId:Rn(e.workspaceId),decision:xa(e.decision,["no_action","route","propose"]),route:Rn(e.route),operation:xa(e.operation,["create","update","delete"]),target:Rn(e.target),summary:Rn(e.summary)??Lx(n,a),expectedOutcome:Rn(e.expectedOutcome),reason:o,evidenceBasis:Sq(e.evidenceBasis),critiqueStatus:xa(e.critiqueStatus,["not_applicable","pending","passed","rejected","failed"])??(n==="running"?"pending":"not_applicable"),validationStatus:xa(e.validationStatus,["not_applicable","pending","passed","failed"])??(n==="running"?"pending":"not_applicable"),validations:xq(e.validationReceipts),edits:kq(e.edits),refs:{trigger:Sa(e.trigger),outcome:Sa(e.outcome),proposal:Sa(e.proposal),applyReceipt:Sa(e.applyReceipt),advanceReceipt:Sa(e.advanceReceipt),inputHarness:Sa(e.inputHarness),outputHarness:Sa(e.outputHarness)}}}function bq(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",o=Ae(t?.outcome),i=Ae(t?.proposal),s=o?.routed===!0,l=Rn(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:Rn(o?.route),operation:null,target:null,summary:Lx(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:Sa(t?.trigger),outcome:Sa(o),proposal:Sa(i),applyReceipt:null,advanceReceipt:null,inputHarness:null,outputHarness:null}}}function vq(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(o=>o.subagentMessage))return a}return null}function yq(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 Sq(e){const t=Ae(e),n=xa(t?.kind,["single_deterministic","recurrent_independent"]);return!t||!n?null:{kind:n,supportingEvidenceIds:_g(t.supportingEvidenceIds),counterevidence:_g(t.counterevidence)}}function xq(e){return Array.isArray(e)?e.flatMap(t=>{const n=Ae(t),a=Rn(n?.id),o=xa(n?.status,["passed","failed","blocked","skipped"]),i=Rn(n?.summary);return a&&o&&i?[{id:a,status:o,summary:i}]:[]}):[]}function kq(e){return Array.isArray(e)?e.flatMap(t=>{const n=Ae(t),a=Rn(n?.id),o=xa(n?.operation,["create","update","delete"]),i=Rn(n?.target),s=Rn(n?.summary);return!a||!o||!i||!s?[]:[{id:a,operation:o,target:i,summary:s,content:typeof n?.content=="string"?n.content:null}]}):[]}function Sa(e){const t=Ae(e),n=Rn(t?.id),a=Rn(t?.contentHash);return n&&a?`${n} · ${a.slice(0,12)}`:null}function _g(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()):[]}function Rn(e){return typeof e=="string"&&e.trim()?e.trim():null}function xa(e,t){return typeof e=="string"&&t.includes(e)?e:null}function Lx(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 wq(e){return e.length>0?`${e[0].toUpperCase()}${e.slice(1)}`:e}const Ig=64*1024,Cg=8*1024;function Rg(e,t){const n=zx(t);if(n.subagentMessage){e.push({id:t.id,role:"activity_group",activities:[n],timestamp:t.timestamp,turnId:t.turnId});return}const a=_q(e,t.turnId);if(a){a.activities=Rq(a.activities??[],t,n),a.timestamp=t.timestamp;return}Sl(e,t),e.push({id:t.id,role:"activity_group",activities:[n],timestamp:t.timestamp,turnId:t.turnId,traceState:"running",traceStartedAt:t.timestamp})}function Sl(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];a.role!=="activity_group"||a.activities?.some(o=>o.subagentMessage)||a.traceState==="running"&&(a.traceState="settled",a.traceCompletedAt=t.timestamp)}}function _q(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(o=>o.subagentMessage))return a}return null}function gm(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)),o=a.filter(l=>l.traceState==="running"),i=o.length>0?o: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 Iq(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 o=a.activities?.filter(i=>i.controlKind!=="turn_aborted")??[];o.length!==a.activities?.length&&(o.length===0?e.splice(n,1):a.activities=o)}gm(e,t,"interrupted"),e.push({id:t.id,role:"status_divider",content:Cq(t),timestamp:t.timestamp,turnId:t.turnId,statusKind:"interruption",statusState:"failed",statusTone:"danger"})}function Cq(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 Rq(e,t,n=zx(t)){const a=[...e];return Dq(a,t,n)||Oq(a,t,n)||Nq(a,t,n)||$q(a,t,n)?a:[...a,n]}function Aq(e){return e.name==="session.compaction.started"||e.name==="session.compaction.completed"||e.name==="session.compaction.failed"}function Pq(e,t){const n={id:t.id,role:"status_divider",content:Tq(t),timestamp:t.timestamp,turnId:t.turnId,statusKind:"compaction",statusState:Eq(t),statusTone:Mq(t)};if(t.name!=="session.compaction.started"){const a=qa(e,o=>o.role==="status_divider"&&o.statusKind==="compaction"&&o.statusState==="running"&&o.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 Tq(e){const t=jq(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 Eq(e){return e.name==="session.compaction.started"?"running":e.name==="session.compaction.completed"?"completed":"failed"}function Mq(e){return e.name==="session.compaction.failed"?"danger":e.name==="session.compaction.completed"?"success":"info"}function jq(e){return Ae(e.data)?.reason==="auto"?"auto":"manual"}function zx(e){const t=lq(e),n=e.name==="assistant.reasoning.delta"?"reasoning":Kq(e),a=Gq(e),o=Yq(e),i=Jq(e),s=Xq(e),l=Qq(e),p=cq(e);return{id:e.id,label:l?l.direction==="received"?"Child message received":"Child message sent":Uq(e),content:l?.summary??qq(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:Gp(e)??void 0}:{},...n&&e.name==="command.output"?{detail:bm(e)}:{},...n==="command"?{terminal:rB(e)}:{},...i?{meta:i}:{},...o?{receipt:o}:{},...s?{openSession:s}:{},...l?{subagentMessage:l}:{},state:zq(e),...t?{imagePreview:t}:{},...p.length>0?{artifacts:p}:{}}}function Oq(e,t,n){if(t.name==="tool.completed"){const a=Ag(e,t);if(!a)return!1;const o=iB(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,...o!==null?{durationMs:o}:{}};const i=bm(t);return i&&i!==a.content&&(a.detail=Dl(a.detail,i)),!0}if(t.name==="command.output"){const a=Ag(e,t);if(!a)return!1;const o=bm(t);return o&&(a.detail=Dl(a.detail,o)),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 Nq(e,t,n){if(t.name!=="tool.completed"||n.kind==="command")return!1;const a=Gp(t),o=qa(e,s=>s.state==="running"&&s.kind!=="command"&&(a?s.callId===a:!!t.action&&s.action===t.action));if(!o)return!1;const i=n.content.trim();return o.id=n.id,o.label=n.label,o.timestamp=n.timestamp,o.state=n.state,i&&i!==o.content.trim()&&(o.content.trim()===o.action?o.content=i:o.detail=Dl(o.detail,i)),n.detail&&(o.detail=Dl(o.detail,n.detail)),o.meta=n.meta,o.receipt=n.receipt,o.imagePreview=n.imagePreview??o.imagePreview,o.artifacts=n.artifacts,!0}function $q(e,t,n){if(t.name!=="workspace_action_result")return!1;const a=Lq(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 Dq(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 Ag(e,t){const n=Gp(t);if(n){const a=qa(e,o=>o.kind==="command"&&o.callId===n);if(a)return a}return qa(e,a=>a.kind==="command")}function Lq(e,t){const n=t.action??"",a=Ux[n]??{started:"Running workspace action"};return qa(e,o=>o.state==="running"&&o.label===a.started&&o.kind!=="command"&&!o.controlKind)}function zq(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 Uq(e){if(e.name==="assistant.reasoning.delta")return be(Ae(e.data),["kind"])==="commentary"?"Update":"Reasoning";if(hc(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(hm(e)&&e.name==="tool.started")return"Reading image";if(hm(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=uq(e);if(t)return t;const n=Fq(e);if(n)return n;const a=Bq(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"?Hq(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 Ux={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 Hq(e){const t=e.action??"",n=Ux[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 qq(e,t){if(e.name==="assistant.reasoning.delta")return e.output??"";if(t)return t.path;const n=Dx(e.output??"");if(n)return n.text;if(hc(e)||e.name==="turn.interrupted")return e.output??e.error??"";const a=Vq(e);if(a)return a;const o=Wq(e);if(o)return o;const i=mq(e);if(i)return i;const s=Hx(e);if(s)return s;if(e.name==="command.output")return Bx(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 Bq(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 Fq(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 Vq(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(mo(e.output??"")),o=be(a,["output"]);if(o)return o;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 Wq(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(mo(e.output??"")),o=be(a,["output"]);if(o)return o;const i=Ae(e.args),s=be(i,["reason"]);if(s)return s;const l=be(i,["objective"]);return l||(e.error??null)}function Kq(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"||Hx(e)||a&&/(^|[._-])exec_command$/i.test(a))return"command"}function Gq(e){if(e.name==="turn.interrupted")return"turn_aborted";if(hc(e))return"goal_context"}function Hx(e){const t=Ae(e.data),n=be(t,["type"]),a=be(t,["tool","toolName","tool_name","name","functionName","function_name"]),o=Ae(t?.result),i=Ae(mo(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"])??Zq(be(t,["arguments","args","input"]))??be(Ae(e.args),["command","cmd"])??be(o,["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 Zq(e){if(!e)return null;const t=mo(e),n=Ae(t);return be(n,["command","cmd"])}function Gp(e){const t=Ae(e.data);return be(t,["callId","call_id","toolCallId","tool_call_id","id","itemId","item_id"])}function Jq(e){const t=Ae(e.data);if(!t)return null;const n=[],a=Ae(t.workspaceToolTiming),o=typeof a?.durationMs=="number"?a.durationMs:null;o!==null&&n.push(nB(o));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?` ${Pg(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 ${oB(m)}`:"checkpoint saved")}else n.push("checkpoint clean");const p=qx(t);return p&&(n.push(`receipt ${Pg(p.id)}`),n.push(`${aB(p.totalUsd)} ${p.status}`)),n.length>0?n.join(" · "):null}function Yq(e){const t=qx(Ae(e.data));return t?{id:t.id,status:t.status,totalUsd:t.totalUsd}:void 0}function Xq(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 o=be(n,["roleId"])??be(t,["roleId"]),i=be(n,["status"])??be(t,["status"]);return{sessionId:a,label:"Open conversation",...o?{roleId:o}:{},...i?{status:i}:{}}}function Qq(e){if(e.name!=="subagent.message")return;const t=Ae(e.data),n=Ae(t?.message);if(!n)return;const a=be(n,["id"]),o=be(n,["kind"]),i=be(n,["fromRunId"]),s=be(n,["body"]);if(!a||!o||!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),$=be(A,["kind"]),z=be(A,["id"]),D=be(A,["label"]);return $&&z&&D?[{kind:$,id:z,label:D}]:[]}):[];return{direction:y,summary:eB(s),body:s,messageId:a,kind:o,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 eB(e){const t=e.replace(/\s+/g," ").trim();if(!t)return"No message body";const n=/^(.*?[.!?])(?:\s|$)/.exec(t)?.[1]??t;return tB(n,96)}function tB(e,t){if(e.length<=t)return e;const n=e.slice(0,t-1),a=n.lastIndexOf(" "),o=a>=Math.floor(t*.55)?a:t-1;return`${n.slice(0,o).trimEnd()}...`}function qx(e){const t=Ae(e?.sandbox),n=Array.isArray(t?.receipts)?t.receipts:[];for(let a=n.length-1;a>=0;a-=1){const o=Ae(n[a]),i=be(o,["id"]),s=be(o,["status"]),l=be(o,["totalUsd","retailTotalUsd"]);if(i&&s&&l)return{id:i,status:s,totalUsd:l}}return null}function nB(e){return e<1e3?`${Math.max(0,Math.round(e))} ms`:e<1e4?`${(e/1e3).toFixed(1)} s`:`${Math.round(e/1e3)} s`}function aB(e){const t=e.trim();return t.startsWith("$")?t:`$${t}`}function oB(e){return e.length>12?e.slice(0,12):e}function Pg(e){const t=e.trim();return t.length<=14?t:`${t.slice(0,6)}...${t.slice(-4)}`}function Bx(e){let t=e.replace(/\r\n/g,`
136
- `).trim();if(!t)return"";const n=sB(t);if(n!==null)return Dr(n);const a=`
137
- Output:
138
- `,o=t.indexOf(a);return o>=0&&lB(t.slice(0,o))&&(t=t.slice(o+a.length).trim()),t=t.replace(/^Total output lines: \d+\n\n/,""),Dr(t.trim())}function bm(e){const t=Bx(e.output??"");if(t)return t;const n=Ae(Ae(e.data)?.result);return n?Dr(Fx(n)):""}function rB(e){const t=Ae(e.data),n=Ae(t?.result),a=Ae(mo(e.output??"")),o=Ae(a?.data),i=Ae(t?.workspaceToolTiming),s=[n?.exitCode,o?.exitCode,t?.exitCode].find(p=>typeof p=="number"),l=i?.durationMs;return{...typeof s=="number"?{exitCode:s}:{},...typeof l=="number"?{durationMs:l}:{}}}function iB(e,t){const n=Date.parse(t)-Date.parse(e);return Number.isFinite(n)&&n>0?n:null}function sB(e){const t=Ae(mo(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?Fx(a,be(t,["output"])):typeof t.output=="string"?t.output.trim():""}function Fx(e,t=null){const n=be(e,["stdout"])?.replace(/\r\n/g,`
139
- `).trimEnd()??"",a=be(e,["stderr"])?.replace(/\r\n/g,`
140
- `).trimEnd()??"",o=[n,a].filter(Boolean);return o.length>0?o.join(`
141
- `):t?.replace(/\r\n/g,`
142
- `).trim()??""}function lB(e){return/^(Chunk ID|Exit code):/m.test(e)&&/Wall time:/m.test(e)}function Dl(e,t){const n=e??"";if(!n)return Dr(t);if(n===t||n.includes(t))return n;if(t.includes(n))return Dr(t);const a=n.endsWith(`
143
- `)||t.startsWith(`
144
- `)?"":`
145
- `;return Dr(`${n}${a}${t}`)}function Dr(e){if(e.length<=Ig)return e;const t=`
146
-
147
- … output omitted from live view; full output remains in task history …
148
-
149
- `,n=Math.max(0,Ig-Cg-t.length);return`${e.slice(0,Cg)}${t}${e.slice(-n)}`}const cB=/\bopenpond\s+opchat\b/i,dB=/\b(?:50[0-9]|52[0-9]|53[0-9])\b|bad\s+gateway|gateway\s+timeout|service\s+unavailable/i;function Vx(e){const t=e?.trim()||"Turn failed";return cB.test(t)&&dB.test(t)?"Server connection lost. Retry your message.":t}function uB(e,t){if((il(t,"code")??il(t,"errorCode"))==="opchat_quota_exceeded")return"opchat_quota_exceeded";const a=t&&typeof t=="object"?t.error:null;if(a&&typeof a=="object"&&(il(a,"code")??il(a,"errorCode"))==="opchat_quota_exceeded")return"opchat_quota_exceeded";const o=e??"";return/\bopchat_quota_exceeded\b/i.test(o)||/OpChat token allowance is exhausted/i.test(o)?"opchat_quota_exceeded":null}function il(e,t){if(!e||typeof e!="object")return null;const a=e[t];return typeof a=="string"&&a.trim()?a.trim():null}function mB(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 o=pB(a.activities??[]);if(o.length===0){a.deliverables=void 0;continue}const i=t.get(a.turnId)??"",s=i?fB(o,i):[];if(s.length>0){a.deliverables=s;continue}a.deliverables=n.has(a.turnId)?[o[o.length-1]]:void 0}}function pB(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 o of a.artifacts??[])t.has(o.path)||(n.delete(o.path),n.set(o.path,o));return[...n.values()]}function fB(e,t){const n=Wx(t);return e.filter(a=>hB(a).some(o=>t.includes(o)||n.includes(o)))}function hB(e){const t=new Set;for(const n of[e.path,e.title,gB(e.path)]){const a=n.trim();a&&(t.add(a),t.add(Wx(a)))}return[...t]}function gB(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).at(-1)??e}function Wx(e){try{return decodeURIComponent(e)}catch{return e}}const Kx=8;function bB(e){if(e.name!=="tool.completed"||e.status==="failed")return[];if(e.action!=="web_search"&&e.action!=="web_fetch")return[];const t=ym(e.data),n=e.output?ym(mo(e.output)):null;return vB(t??n)}function vm(e,t){if(t.length===0)return e;const n=[],a=new Set;for(const o of[...e??[],...t]){const i=Gx(o.url);if(!(!i||a.has(i))&&(a.add(i),n.push(o),n.length>=Kx))break}return n.length>0?n:void 0}function ym(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 o of["result","data","output"]){const i=ym(n[o],t+1);if(i)return i}return null}function vB(e){if(!e)return[];const t=[],n=new Set;for(let a=0;a<e.results.length;a+=1){const o=yB(e.results[a],a,e.provider);if(!o)continue;const i=Gx(o.url);if(!(!i||n.has(i))&&(n.add(i),t.push(o),t.length>=Kx))break}return t}function yB(e,t,n){const a=Ae(e);if(!a)return null;const o=be(a,["url","href"]);if(!o||!SB(o))return null;const i=be(a,["title"])??Tg(o)??`Source ${t+1}`;return{id:be(a,["id"])??`source_${t+1}`,title:i,url:o,sourceName:be(a,["sourceName","source_name","source"])??Tg(o),snippet:be(a,["snippet","description"]),provider:n,faviconUrl:xB(be(a,["faviconUrl","favicon_url","iconUrl","icon_url"]))??kB(o),publishedAt:be(a,["publishedAt","published_at"]),updatedAt:be(a,["updatedAt","updated_at"])}}function SB(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function Gx(e){try{const t=new URL(e);return t.hash="",t.toString()}catch{return null}}function xB(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 kB(e){try{return new URL("/favicon.ico",e).toString()}catch{return null}}function Tg(e){try{return new URL(e).hostname.replace(/^www\./i,"")}catch{return null}}const Eg=new WeakMap;function gc(e){const t=Eg.get(e);if(t)return t;const n=wB(e);return Eg.set(e,n),n}function wB(e){const t=[],n=new Map;for(const a of e){if(a.name==="turn.started"){Sl(t,a);const o=RB(a.args);if(o){const i=Dx(o);if(i){Rg(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:o,attachments:AB(a.args),timestamp:a.timestamp,turnId:a.turnId});const s=jg(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 o=jg(a.data);if(!o)continue;const i=qa(t,s=>s.turnId===a.turnId&&!!s.createImproveRun);i?(i.createImproveRun=o,i.timestamp=a.timestamp):t.push({id:`${a.id}:create-improve`,role:"assistant",timestamp:a.timestamp,turnId:a.turnId,createImproveRun:o});continue}if(a.name==="assistant.delta"){const o=a.output??"";if(!o)continue;Sl(t,a);const i=t[t.length-1];if(i?.role==="assistant"&&i.turnId===a.turnId&&!i.createImproveRun)i.content=`${i.content??""}${o}`,i.timestamp=a.timestamp,i.sources=vm(i.sources,Mg(n,a.turnId)??[]);else{const s=Mg(n,a.turnId);t.push({id:a.id,role:"assistant",content:o,timestamp:a.timestamp,turnId:a.turnId,...s?.length?{sources:s}:{}})}continue}if(a.name==="assistant.reasoning.delta"){const o=a.output??"";if(!o)continue;Sl(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}${o}`,i.timestamp=a.timestamp):i?.role==="assistant"&&i.turnId===a.turnId&&!i.reasoningContent&&!i.createImproveRun?(i.reasoningContent=o,i.timestamp=a.timestamp):t.push({id:a.id,role:"assistant",reasoningContent:o,timestamp:a.timestamp,turnId:a.turnId});continue}if(a.name==="user_question.asked"){const o=Ae(a.data),i=DC.safeParse(o?.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 o=Ae(a.data),i=LC.safeParse(o?.resolution);if(!i.success)continue;const s=qa(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"){gm(t,a,"completed");continue}if(a.name==="turn.failed"){gm(t,a,"failed");const o=a.error??"Turn failed",i=uB(o,a.data);t.push({id:a.id,role:"error",content:Vx(o),...i?{errorKind:i}:{},timestamp:a.timestamp,turnId:a.turnId});continue}if(a.name==="turn.interrupted"){Iq(t,a);continue}if(Aq(a)){Pq(t,a);continue}if(a.name.startsWith("harness.refiner.")){fq(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.")||hc(a)){if(IB(a))continue;const o=eq(a);if(o){QH(t,a,o);continue}const i=bB(a);i.length>0&&_B(t,n,a.turnId,i),Rg(t,a)}if(a.name==="workspace.diff"){const o=CB(a.data);if(!o||o.filesChanged===0)continue;const i=qa(t,s=>s.role==="assistant"&&s.turnId===a.turnId);i&&(i.changeSummary=o,i.timestamp=a.timestamp)}}return mB(t),t}function _B(e,t,n,a){if(!n)return;const o=e[e.length-1];if(o?.role!=="assistant"||o.turnId!==n){t.set(n,vm(t.get(n),a));return}o.sources=vm(o.sources,a)}function Mg(e,t){if(!t)return;const n=e.get(t);return n&&e.delete(t),n}function IB(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 CB(e){const t=YR.safeParse(e);return t.success?t.data:null}function RB(e){if(!e||typeof e!="object"||!("prompt"in e))return"";const t=e.prompt;return typeof t=="string"?t:""}function AB(e){if(!e||typeof e!="object"||!("attachments"in e))return;const t=eT.array().safeParse(e.attachments);return t.success&&t.data.length>0?t.data:void 0}function jg(e){const t=Ae(e);if(!t)return null;const n=ys.safeParse(t.createImproveRun);return n.success?n.data:null}function iV(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 o=Math.floor(a/60);return o<48?`${o}h`:`${Math.floor(o/24)}d`}function sV(e){const t=Zx(e);return t?t.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):""}function lV(e){const t=Zx(e);return t?t.toLocaleString():""}function Zx(e){if(!e)return null;const t=new Date(e);return Number.isNaN(t.getTime())?null:t}function PB(e){const{chatMessages:t,runtimeIndexes:n,selectedSessionId:a}=e,[o,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=gc(Ps(n,f));jx(y,S)&&(m===p&&(m={...p}),delete m[f])}return m})},[n]);const l=g.useMemo(()=>Mx(t,a?o[a]:null),[t,o,a]);return{pendingChatUserMessages:o,recordPendingChatUserMessage:s,visibleChatMessages:l}}const Jx="openpond.commandAccessMode";function bc(){if(typeof window>"u")return null;try{return window.localStorage}catch{return null}}function TB(e){return e==="ask"||e==="full-access"||e==="disabled"?e:null}function Yx(e=bc()){if(!e)return{};const t=TB(e.getItem(Jx));return{...t?{openPondCommandAccessMode:t}:{}}}function EB(e,t=bc()){try{t?.setItem(Jx,e)}catch{}}function MB(e,t=bc()){const n=Zn(e);return{openPondCommandAccessMode:Yx(t).openPondCommandAccessMode??n.openPondCommandAccessMode??gs}}function jB(e,t=bc()){const n=Zn(e),a=Yx(t),o={};return a.openPondCommandAccessMode&&a.openPondCommandAccessMode!==n.openPondCommandAccessMode&&(o.openPondCommandAccessMode=a.openPondCommandAccessMode),o}function OB({connection:e,selectedSession:t,setBootstrap:n,setError:a,setOpenPondCommandAccessMode:o,setSessions:i}){return{changeOpenPondCommandAccessMode:g.useCallback((l,p=t)=>{o(l),EB(l);const m=p?.provider==="codex"?null:p;m&&i(f=>f.map(S=>S.id===m.id?{...S,openPondCommandAccessMode:l}:S)),e&&(Z.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&&Z.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,o,i])}}function NB({localProjects:e,cloudProjects:t,sessions:n,runtimeIndexes:a,appPreferences:o,selectedSessionId:i,selectedProjectId:s,archivedChatsOpen:l,projectsExpanded:p,chatRowsVisibleCount:m,sidebarFileBookmarks:f=[]}){const S=g.useMemo(()=>e.filter(re=>!re.hiddenFromDefaultSidebar),[e]),y=g.useMemo(()=>n.filter(re=>!re.archived&&Og(re)),[n]),k=g.useMemo(()=>y.filter(re=>re.pinned),[y]),R=g.useMemo(()=>y.filter(re=>!!re.savedForLater),[y]),A=g.useMemo(()=>n.filter(re=>re.archived&&Og(re)),[n]),$=g.useMemo(()=>new Set(e.map(re=>re.id)),[e]),z=g.useMemo(()=>new Set(t.map(re=>re.id)),[t]),D=g.useMemo(()=>qS(e),[e]),x=g.useMemo(()=>{const re={};for(const Ce of[...y,...A]){const De=ng(Ce,$,D,z);De&&(re[Ce.id]=De)}return re},[y,A,z,$,D]),I=g.useMemo(()=>y.filter(re=>!re.pinned&&!re.savedForLater&&!re.appId&&!x[re.id]),[y,x]),P=g.useMemo(()=>A.filter(re=>!re.appId&&!ng(re,$,D,z)),[A,z,$,D]),O=g.useMemo(()=>{const re={};for(const Ce of y){if(Ce.pinned||Ce.savedForLater)continue;const De=x[Ce.id];if(!De)continue;const Je=re[De];Je?Je.push(Ce):re[De]=[Ce]}return re},[y,x]),T=g.useMemo(()=>{const re={};for(const Ce of n){if(Ce.archived||!Xx(Ce))continue;const De=re[Ce.parentSessionId];De?De.push(Ce):re[Ce.parentSessionId]=[Ce]}for(const Ce of Object.values(re))Ce.sort((De,Je)=>Date.parse(Je.updatedAt)-Date.parse(De.updatedAt));return re},[n]),F=g.useMemo(()=>S.map((re,Ce)=>{const De=gt("local",re.id),Je=OU(re,t);return{id:De,kind:"local",project:re,pinned:!!o[De]?.pinned,order:o[De]?.order??Ce,cloudLinkTrusted:!Je,cloudLinkWarning:Je}}).sort(vu),[o,t,S]),H=g.useMemo(()=>t.map((re,Ce)=>{const De=gt("cloud",re.id);return{id:De,kind:"cloud",project:re,pinned:!!o[De]?.pinned,order:o[De]?.order??Ce,cloudLinkTrusted:!0,cloudLinkWarning:null}}).sort(vu),[o,t]),L=g.useMemo(()=>new Set(S.map(re=>aa(re,t)?.id??null).filter(re=>!!re)),[t,S]),V=g.useMemo(()=>H.filter(re=>!L.has(re.project.id)),[H,L]),Y=g.useMemo(()=>[...F,...V].sort(vu),[V,F]),ie=g.useMemo(()=>Y.filter(re=>re.pinned),[Y]),_e=g.useMemo(()=>f.filter(re=>re.status==="pinned"),[f]),fe=g.useMemo(()=>f.filter(re=>re.status==="saved_for_later"),[f]),J=Y,Me=g.useMemo(()=>$B(J,p,s),[J,p,s]),Se=g.useMemo(()=>[...ie.map(re=>({type:"project",key:$o({type:"project",id:re.id}),id:re.id,item:re,order:re.order})),...k.map(re=>({type:"session",key:$o({type:"session",id:re.id}),id:re.id,session:re,order:re.order})),..._e.map((re,Ce)=>({type:"file",key:$o({type:"file",id:re.id}),id:re.id,file:re,order:re.order??ie.length+k.length+Ce}))].sort((re,Ce)=>{if(re.order!==Ce.order)return re.order-Ce.order;if(re.type!==Ce.type){const et={project:0,session:1,file:2};return et[re.type]-et[Ce.type]}const De=re.type==="project"?re.item.project.name:re.type==="session"?re.session.title:re.file.path,Je=Ce.type==="project"?Ce.item.project.name:Ce.type==="session"?Ce.session.title:Ce.file.path;return De.localeCompare(Je)}),[_e,ie,k]),ae=g.useMemo(()=>l?[...I,...P]:I,[l,P,I]),xe=g.useMemo(()=>ae.slice(0,Math.max(Cn,m)),[ae,m]),ee=g.useMemo(()=>Ps(a,i),[a,i]),ue=g.useMemo(()=>gc(ee),[ee]),ye=lx(a,i),We=cx(a,i),Pe=kU(a,i);return{activeSessions:y,pinnedSessions:k,savedForLaterSessions:R,pinnedFiles:_e,savedForLaterFiles:fe,chatSessions:I,archivedSessions:A,pinnedProjects:ie,pinnedItems:Se,projectRows:J,localProjectRows:F,visibleProjectRows:Me,cloudProjectRows:V,projectSessionRowsByProjectId:O,childSessionRowsByParentId:T,sidebarProjectIdBySessionId:x,chatRows:ae,visibleChatRows:xe,sessionEvents:ee,chatMessages:ue,contextUsage:ye,goalRuntime:We,subagentRuntime:Pe}}function Og(e){return Xx(e)?!1:e.hiddenFromDefaultSidebar?e.metadata?.benchmarkRuntime==="desktop_local_work":!0}function Xx(e){return!!(e.parentSessionId&&e.subagentRunId)}function vu(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 $B(e,t,n){if(t||e.length<=gl)return e;const a=e.slice(0,gl);if(!n||a.some(i=>i.id===n))return a;const o=e.find(i=>i.id===n);return o?[...a.slice(0,gl-1),o]:a}function DB(e){return e.name==="turn.completed"||e.name==="turn.failed"||e.name==="turn.interrupted"}function Qx(e){let t=-1,n=null;for(let a=e.length-1;a>=0;a-=1){const o=e[a];if(o?.name==="turn.started"){t=a,n=o.turnId??null;break}}if(t===-1)return"none";for(let a=e.length-1;a>t;a-=1){const o=e[a];if(!(!o||!DB(o))&&!(n&&o.turnId&&o.turnId!==n))return o.name==="turn.completed"?"completed":"blocked"}return"pending"}function Ng(e,t){if(e.systemKind)return!1;const n=Ps(t,e.id);if(n.length===0)return!1;const a=Qx(n);return a==="pending"||a==="none"&&ek(n)==="pending"}function $g(e,t){if(e.systemKind||e.status!=="active")return!1;const n=Ps(t,e.id);if(n.length===0)return!0;const a=Qx(n);return a==="pending"||a==="none"&&ek(n)!=="terminal"}function ek(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 LB({goalRuntime:e,goalRuntimeBySessionId:t,runtimeIndexes:n,selectedSession:a,selectedSessionId:o,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 o&&!a?.systemKind&&e?.tone==="active"&&y.add(o),y},[e,t,n,a,o,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||Ng(k,n)&&y.add(k.id);return a&&Ng(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)$g(k,n)&&y.add(k.id);return a&&$g(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 zB=1e3;function UB(e){const[t,n]=g.useState(()=>new Date().toISOString());return g.useEffect(()=>{if(!e)return;const a=()=>n(new Date().toISOString());a();const o=window.setInterval(a,zB);return()=>window.clearInterval(o)},[e]),t}function HB(e){const{codexHistoryEvents:t,codexHistorySessions:n,connection:a,expandedProjectIds:o,goalRuntime:i,locallyActiveCodexHistorySessionIds:s,pinnedSessions:l,savedForLaterSessions:p,projectSessionRowsByProjectId:m,rightChatHistoryEvents:f,runtimeIndexes:S,selectedSession:y,selectedSessionId:k,serverId:R,setCodexHistorySessions:A,sidebarSessions:$,subagentRuntime:z,visibleChatRows:D,visibleProjectRows:x}=e,[I,P]=g.useState({});g.useEffect(()=>{P({})},[R]);const O=g.useMemo(()=>{const ae=[],xe=new Set,ee=ye=>{!ye||ye.id===k||!Mt(ye.id)||xe.has(ye.id)||(xe.add(ye.id),ae.push(ye.id))};for(const ye of n)(ye.status==="active"||s.has(ye.id))&&ee(ye);const ue=ae.length;for(const ye of x)for(const We of(m[ye.id]??[]).slice(0,2))ee(We);for(const ye of o)for(const We of(m[ye]??[]).slice(0,gl))ee(We);for(const ye of l)ee(ye);for(const ye of p)ee(ye);for(const ye of D)ee(ye);return[...ae.slice(0,ue),...ae.slice(ue,ue+8)].join(`
150
- `)},[n,o,s,l,p,m,k,D,x]),T=g.useCallback(ae=>{P(xe=>xe[ae.session.id]===ae.events?xe:{...xe,[ae.session.id]:ae.events}),A(xe=>fc(xe,ae.session))},[A]),F=g.useMemo(()=>{if(!O)return"";const ae=new Set(O.split(`
151
- `).filter(Boolean));return $.filter(xe=>ae.has(xe.id)&&xe.status==="active").map(xe=>xe.id).join(`
152
- `)},[O,$]),H=g.useMemo(()=>O?O.split(`
153
- `).filter(ae=>s.has(ae)).join(`
154
- `):"",[O,s]);g.useEffect(()=>{!y||!k||!Mt(k)||t.length===0||T({session:y,events:t})},[T,t,y,k]),g.useEffect(()=>{if(!a||!O)return;const ae=a,xe=O.split(`
155
- `).filter(Boolean),ee=new Set(F.split(`
156
- `).filter(Boolean)),ue=new Set(H.split(`
157
- `).filter(Boolean)),ye=xe.map(We=>Kp({connection:ae,locallyActive:ue.has(We),onPayload:Pe=>T(Wp(Pe,ue.has(We))),reportedActive:ee.has(We),sessionId:We,surface:"sidebar"}));return()=>ye.forEach(We=>We())},[T,F,H,O,a]);const L=g.useMemo(()=>new Map($.map(ae=>[ae.id,ae])),[$]),V=g.useMemo(()=>{const ae=new Map(S.latestGoalRuntimeBySessionId);for(const xe of $){const ee=xe.status==="active"?uu(xe.metadata):null;ee&&ae.set(xe.id,ee)}for(const xe of[I,f])for(const[ee,ue]of Object.entries(xe)){const ye=L.get(ee),We=ye?.status==="active"?uu(ye.metadata):null,Pe=sm(ue)??Bp(ue)??(ye?.status==="active"?$l(ue)??We:null);Pe?ae.set(ee,Pe):ae.delete(ee)}if(k)if(i)ae.set(k,i);else if(y?.status==="active"&&t.length>0){const xe=sm(t)??$l(t)??uu(y.metadata);xe?ae.set(k,xe):ae.delete(k)}else(!Mt(k)||t.length>0)&&ae.delete(k);return ae},[t.length,I,i,f,S.latestGoalRuntimeBySessionId,y?.status,y?.metadata,k,L,$]),Y=g.useMemo(()=>[...V.values()].some(ae=>ae.tone==="active"&&!!ae.observedAt),[V]),ie=UB(Y),_e=g.useMemo(()=>Y?new Map([...V].map(([ae,xe])=>[ae,Xz(xe,ie)??xe])):V,[V,ie,Y]),fe=k?_e.get(k)??i:i,J=g.useMemo(()=>{const ae=new Map(S.latestSubagentRuntimeBySessionId);return k&&(z?ae.set(k,z):ae.delete(k)),ae},[S.latestSubagentRuntimeBySessionId,k,z]),{runningSessionIds:Me,selectedSessionRunning:Se}=LB({goalRuntime:fe,goalRuntimeBySessionId:_e,runtimeIndexes:S,selectedSession:y,selectedSessionId:k,sidebarSessions:$,subagentRuntimeBySessionId:J});return{goalRuntime:fe,runningSessionIds:Me,selectedSessionRunning:Se,sidebarGoalRuntimeBySessionId:_e,sidebarSubagentRuntimeBySessionId:J}}function qB({searchOpen:e,sectionMenuOpen:t,setSectionMenuOpen:n,setSearchOpen:a,setQuery:o}){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),o(""),n(null);return}s.key==="Escape"&&t&&(s.preventDefault(),n(null))};return document.addEventListener("keydown",i),()=>document.removeEventListener("keydown",i)},[e,t,o,a,n])}function BB({afterSequence:e,appendEvents:t,connection:n,setApprovals:a,setSessions:o,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 $(){p!==null&&(window.clearTimeout(p),p=null)}function z(){i(L=>L==="Event stream disconnected"?null:L)}function D(){f=null;const L=m;if(m=[],L.length===0)return;R=Date.now(),t(L);const V=FB(L);V.length>0&&o(Y=>V.reduce(Gi,Y)),a(Y=>{let ie=Y;for(const _e of L)if(_e.name==="approval.requested"&&_e.data&&(ie=[_e.data,...ie]),_e.name==="approval.resolved"&&_e.data&&typeof _e.data=="object"){const fe=_e.data;fe.approvalId&&(ie=ie.filter(J=>J.id!==fe.approvalId))}return ie})}function x(){const L=Date.now()-R;if(L>=A){f!==null&&(window.clearTimeout(f),f=null),D();return}f===null&&(f=window.setTimeout(D,A-L))}function I(L){P(L),m.push(L),x()}function P(L){if(!(!L.sessionId||!L.name.startsWith("harness.refiner."))){if(L.name==="harness.refiner.completed"||L.name==="harness.refiner.failed"){k.delete(L.sessionId);return}(L.name==="harness.refiner.queued"||L.name==="harness.refiner.started")&&(k.set(L.sessionId,typeof L.sequence=="number"?L.sequence:0),O())}}function O(){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([L,V])=>{const Y=await Z.runtimeEventsPage(l,{sessionId:L,afterSequence:V,limit:100});for(const ie of Y.events){const _e=ie.event;k.set(L,Math.max(k.get(L)??0,ie.sequence)),I(_e)}}))}catch{}finally{y=!1,O()}}}function F(){f!==null&&(window.clearTimeout(f),f=null),D()}document.addEventListener("visibilitychange",F);const H=FN(n,L=>{$(),z(),I(L)},()=>{$(),p=window.setTimeout(()=>{H.isOpen()||(i("Event stream disconnected"),s?.())},2e3)},()=>{$(),z()},{afterSequence:e});return()=>{$(),f!==null&&window.clearTimeout(f),S!==null&&window.clearTimeout(S),f=null,S=null,m=[],document.removeEventListener("visibilitychange",F),H.close()}},[e,t,n,s,a,i,o])}function FB(e){const t=new Map;for(const n of e){const a=n.data;if(!a||typeof a!="object"||Array.isArray(a))continue;const o=n.name==="session.started"||n.name==="session.title.updated"?"session":n.name==="subagent.started"||n.name==="subagent.failed"?"childSession":null;if(!o)continue;const i=Bu.safeParse(a[o]);i.success&&t.set(i.data.id,i.data)}return[...t.values()]}function yu(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function VB(e){return typeof e=="string"&&e.trim()?e.trim():null}function WB(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n.name!=="create_improve.updated")continue;const a=yu(n.data),o=yu(a?.createImproveRun);if(o?.state!=="ready_local"&&o?.state!=="released"||yu(o.adapter)?.kind!=="local")continue;const s=VB(o.id)??n.id;return[n.sessionId??"global",n.turnId??"turn",s].join(":")}return null}const KB=332,Dg=244,Lg=560,GB=560,zg=320,Ug=2400,ZB=440;function Su(e){const t=typeof window>"u"?Lg:Math.min(Lg,Math.max(Dg,window.innerWidth-420));return Math.min(t,Math.max(Dg,Math.round(e)))}function xu(e){const t=typeof window>"u"?Ug:Math.min(Ug,Math.max(zg,window.innerWidth-ZB));return Math.min(t,Math.max(zg,Math.round(e)))}function JB(e,t){return!!(e&&e.serverUrl===t.serverUrl&&e.token===t.token&&e.platform===t.platform)}const Mr=new Map;function Zp(e,t){const n=e?.trim();return n?`${t?.trim()||"global"}|${n}`:null}function tk(e,t){const n=Zp(e,t);if(!n)return null;const a=Mr.get(n);return a?.updatedAt?a.agents:null}function YB(e,t,n){const a=Zp(e,n);a&&Mr.set(a,{agents:t,promise:null,updatedAt:Date.now()})}function Jp(e){const t=e.teamId?.trim();if(!t)return Promise.resolve([]);const n=Zp(t,e.accountKey);if(!n)return Promise.resolve([]);const a=Mr.get(n);if(!e.force){if(a?.updatedAt)return Promise.resolve(a.agents);if(a?.promise)return a.promise}const o=e.fetchAgents(t).then(i=>(YB(t,i,e.accountKey),i)).catch(i=>{const s=Mr.get(n);throw s?.promise===o&&Mr.set(n,{agents:s.agents,promise:null,updatedAt:s.updatedAt}),i});return Mr.set(n,{agents:a?.agents??[],promise:o,updatedAt:a?.updatedAt??0}),o}const XB=6e4,QB=6e4,eF=6e4,Yp=["pinned","projects","cloudProjects","chats","savedForLater"];function tF(e,t,n,a=Date.now()){for(const o of rF(t,n))nk(t[o],n[o])||(e[o]=a)}function nF(e,t,n,a=Date.now()){const o={...t};for(const[i,s]of Object.entries(n)){if(a-s>XB){delete n[i];continue}const l=sF(e,i),p=e[i];!l||nk(p,t[i])||(o[i]=p)}return o}function aF(e,t,n,a=Date.now()){for(const o of Yp)t[o]!==n[o]&&(e[o]=a)}function oF(e,t,n,a=Date.now()){const o={...t};for(const i of Yp){const s=n[i];if(s!==void 0){if(a-s>QB){delete n[i];continue}if(e[i]===t[i]){delete n[i];continue}o[i]=e[i]}}return iF(e,o)?e:o}function Hg(e,t,n=Date.now()){return e===t?null:{value:t,changedAt:n}}function qg(e,t,n=Date.now()){return t?n-t.changedAt>eF?{value:e,localChange:null}:e===t.value?{value:e,localChange:t}:{value:t.value,localChange:t}:{value:e,localChange:null}}function rF(e,t){return new Set([...Object.keys(e),...Object.keys(t)])}function nk(e,t){return e?.pinned===t?.pinned&&e?.archived===t?.archived&&e?.order===t?.order}function iF(e,t){return Yp.every(n=>e[n]===t[n])}function sF(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const lF=5e4,Xa="\0openpond-unscoped-runtime-events",ya=[];class cF{perSessionLimit;totalLimit;entries=new Map;eventKeyById=new Map;listenersByKey=new Map;allListeners=new Set;summaryListeners=new Set;retainedKeys=new Set;allEventsSnapshot=ya;summaryEventsSnapshot=ya;clock=0;eventCount=0;constructor(t={}){if(this.perSessionLimit=Vg(t.perSessionLimit??Hp,"perSessionLimit"),this.totalLimit=Vg(t.totalLimit??lF,"totalLimit"),this.totalLimit<this.perSessionLimit)throw new Error("totalLimit must be greater than or equal to perSessionLimit")}append(t){if(t.length===0)return Fg();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||Xa,S=n.get(f);S?S.push(m):n.set(f,[m]),this.eventKeyById.set(m.id,f)}if(n.size===0)return{...Fg(),duplicateEventCount:a};const o=new Set;let i=0,s=0,l=!1;for(const[m,f]of n){f.some(Wg)&&(l=!0);const S=this.entries.get(m),y=S?.snapshot.events??ya,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),$=A.length===0?R:[...A,...R],z=y.slice(0,y.length-A.length);z.some(Wg)&&(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($.map(I=>I.id)),lastTouched:++this.clock,retained:S?.retained??this.retainedKeys.has(m),snapshot:{events:$,latestSequence:Nl($),revision:(S?.snapshot.revision??0)+1}};this.entries.set(m,x),this.eventCount+=$.length-y.length,i+=R.length,s+=z.length+f.length-R.length,o.add(m)}const p=this.enforceTotalLimit(o);return s+=p,this.publish(o,l||p>0),uF({acceptedEventCount:i,duplicateEventCount:a,evictedEventCount:s,changedKeys:o})}mergeBootstrap(t){const n=dF(t),a=new Set([...this.entries.keys(),...n.keys()]),o=[];for(const i of a){const s=n.get(i)??ya,l=this.entries.get(i)?.snapshot.events??ya;o.push(...Bz(s,l))}return this.replace(o)}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=ya,this.summaryEventsSnapshot=ya;const o=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),{...o,evictedEventCount:o.evictedEventCount+s,changedSessionIds:new Set([...o.changedSessionIds,...[...l].filter(p=>p!==Xa)]),unscopedEventsChanged:o.unscopedEventsChanged||l.has(Xa)}}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=ya,this.summaryEventsSnapshot=ya,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??Bg:Bg;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(mF),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!==Xa&&a.retained&&(t+=1);return{eventCount:this.eventCount,retainedSessionCount:t,sessionCount:this.entries.size-(this.entries.has(Xa)?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[o,i]=a,s=this.eventCount-this.totalLimit;if(!i.retained||i.snapshot.events.length<=s){n+=i.snapshot.events.length,this.removeEntry(o),t.add(o);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:Nl(p),revision:i.snapshot.revision+1},this.eventCount-=l.length,n+=l.length,t.add(o)}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 o of this.listenersByKey.get(a)??[])o();for(const a of this.allListeners)a();if(n)for(const a of this.summaryListeners)a()}}}const Bg=Object.freeze({events:ya,latestSequence:null,revision:0});function dF(e){const t=new Map;for(const n of e){const a=n.sessionId||Xa,o=t.get(a);o?o.push(n):t.set(a,[n])}return t}function uF(e){return{acceptedEventCount:e.acceptedEventCount,duplicateEventCount:e.duplicateEventCount,evictedEventCount:e.evictedEventCount,changedSessionIds:new Set([...e.changedKeys].filter(t=>t!==Xa)),unscopedEventsChanged:e.changedKeys.has(Xa)}}function Fg(){return{acceptedEventCount:0,duplicateEventCount:0,evictedEventCount:0,changedSessionIds:new Set,unscopedEventsChanged:!1}}function mF(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 Vg(e,t){if(!Number.isInteger(e)||e<=0)throw new Error(`${t} must be a positive integer`);return e}function Wg(e){return e.name!=="assistant.delta"&&e.name!=="assistant.reasoning.delta"&&e.name!=="command.output"}const pF=256,fF=15e3,hF=5e3,gF=3e4;class bF{constructor(t={}){this.options=t}options;entries=new Map;connection=null;accountScope=null;generation=0;activateConnection(t){vF(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,yF(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 o=this.now(),i=this.entries.get(t);if(i?.state==="loading"&&!this.expired(i,o))return i.promise;if(i?.state==="failed"&&!this.expired(i,o))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??hF),lastAccessedAt:p}),this.prune(),null});return this.entries.set(t,{state:"loading",promise:l,expiresAt:o+(this.options.loadingTtlMs??gF),lastAccessedAt:o}),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,o]of this.entries)this.expired(o,t)&&this.entries.delete(a);const n=this.options.maxEntries??pF;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??fF:0;return t.expiresAt<=n+a}now(){return(this.options.now??Date.now)()}}const Kg=new bF;function cV(e,t,...n){return[t,e.serverUrl,...n].join("\0")}function vF(e,t){return e?.serverUrl===t?.serverUrl&&e?.token===t?.token&&e?.platform===t?.platform}function yF(e,t,n){e.delete(t),e.set(t,n)}const SF={connecting:"Connecting to OpenPond",account:"Loading account",team:"Loading default team",ready:"Ready"};function xF(e){return{label:SF[e],ready:e==="ready",stage:e}}const kF=650,wF=1200,_F=6e4;function IF(e){const{setDraftModel:t,setDraftProvider:n,setCodexPermissionMode:a,setCodexReasoningEffort:o,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 cF),A=g.useSyncExternalStore(R.subscribeSummary,R.getSummaryEvents,R.getSummaryEvents),$=g.useCallback(W=>{const me=R.getAllEvents(),he=typeof W=="function"?W(me):W;he!==me&&R.replace(he)},[R]),z=g.useCallback(W=>{R.append(W)},[R]),[D,x]=g.useState(null),[I,P]=g.useState([]),[O,T]=g.useState([]),[F,H]=g.useState([]),[L,V]=g.useState({}),[Y,ie]=g.useState("connecting"),_e=dm(y?.account),fe=g.useRef({}),J=g.useRef({}),Me=g.useRef({}),Se=g.useRef([]),ae=g.useRef([]),xe=g.useRef(null),ee=g.useRef(null),ue=g.useRef(null),ye=g.useRef(null),We=g.useRef(""),Pe=g.useRef(!1),re=g.useRef(Date.now()),Ce=g.useRef(null),De=g.useRef(null);g.useEffect(()=>{Kg.activateConnection(f),Kg.activateAccountScope(_e)},[f,_e]);const Je=g.useCallback(W=>{Pe.current||ie(W)},[]),et=g.useCallback(W=>{V(me=>{const he=typeof W=="function"?W(me):W;return tF(fe.current,me,he),he})},[]),rt=g.useCallback(W=>{P(me=>{const he=typeof W=="function"?W(me):W;return yg(J.current,me,he),Se.current=he,he})},[]),Be=g.useCallback(W=>{T(me=>{const he=typeof W=="function"?W(me):W;return yg(Me.current,me,he),ae.current=he,he})},[]),He=g.useCallback(()=>{if(Pe.current||Ce.current!==null)return;const W=()=>{Ce.current=null,!Pe.current&&(Pe.current=!0,ie("ready"))},me=Date.now()-re.current,he=CF(me);if(he===0){W();return}Ce.current=window.setTimeout(W,he)},[]);g.useEffect(()=>()=>{Ce.current!==null&&window.clearTimeout(Ce.current)},[]);const $e=g.useCallback(W=>{const me=xe.current,he=!me||me===W.server.id;xe.current=W.server.id,x(Ze=>Ze?.serverId===W.server.id?Ze:{afterSequence:W.eventWindow?.latestSequence??Nl(W.events)??0,serverId:W.server.id}),We.current=W.preferences.defaultTeamId?.trim()??"",k(W),he?R.mergeBootstrap(W.events):R.replace(W.events),P(Ze=>{const qe=he?vg(Ze,W.sessions,J.current):um(Ze,W.sessions,J.current);return Se.current=qe,qe}),T(Ze=>{const qe=he?vg(Ze,W.codexHistorySessions??[],Me.current):um(Ze,W.codexHistorySessions??[],Me.current);return ae.current=qe,qe}),H(W.approvals),V(Ze=>nF(Ze,W.sidebarAppPreferences,fe.current)),l(Ze=>Ze&&W.apps.some(qe=>qe.id===Ze)?Ze:null),p(Ze=>{if(!Ze)return null;const qe=wS(Ze);return qe?.kind==="local"&&W.localProjects.some(it=>it.id===qe.id)?gt("local",qe.id):qe?.kind==="cloud"&&(W.cloudProjects??[]).some(it=>it.id===qe.id)?gt("cloud",qe.id):W.localProjects.some(it=>it.id===Ze)?gt("local",Ze):(W.cloudProjects??[]).some(it=>it.id===Ze)?gt("cloud",Ze):null}),m(Ze=>{if(!Ze)return null;const qe=[...W.sessions,...W.codexHistorySessions??[]];if(qe.some(nt=>nt.id===Ze&&!nt.archived))return Ze;if(!he)return null;const it=Se.current.find(nt=>nt.id===Ze)??ae.current.find(nt=>nt.id===Ze)??null;return it&&!it.archived&&Ix(it,qe)?Ze:null})},[R,l,p,m]),E=g.useCallback(W=>{We.current=W.preferences.defaultTeamId?.trim()??"",k(me=>me&&{...me,preferences:W.preferences})},[]);g.useEffect(()=>{const W=Zn(y?.preferences);n(W.defaultChatProvider),t(W.defaultChatModel)},[y?.preferences.defaultChatProvider,y?.preferences.defaultChatModel,t,n]),g.useEffect(()=>{a(bg(y?.preferences).codexPermissionMode)},[y?.preferences.codexPermissionMode,a]),g.useEffect(()=>{o(bg(y?.preferences).codexReasoningEffort)},[y?.preferences.codexReasoningEffort,o]),g.useEffect(()=>{i(MB(y?.preferences).openPondCommandAccessMode)},[y?.preferences.openPondCommandAccessMode,i]),g.useEffect(()=>{if(!f||!y)return;const W=PH(y.preferences),me=JSON.stringify(W);if(me==="{}"){ee.current=null;return}ee.current!==me&&(ee.current=me,Z.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=jB(y.preferences),me=JSON.stringify(W);if(me==="{}"){ue.current=null;return}ue.current!==me&&(ue.current=me,Z.savePreferences(f,W).then(E).catch(he=>{ue.current=null,s(he instanceof Error?he.message:String(he))}))},[E,y,y?.preferences.openPondCommandAccessMode,f,s]),g.useEffect(()=>{if(!f||!y){ye.current=null;return}if(y.account.state!=="signed_in"){ye.current=null,He();return}const W=dm(y.account);if(!W){ye.current=null,He();return}He(),Je("team");const me=y.preferences.defaultTeamId?.trim()??"",he=Zg(W,me,y.accountMeta.asOf??"initial");if(ye.current===he)return;ye.current=he;let Ze=!1;const qe=it=>Jp({teamId:it,accountKey:W,fetchAgents:async nt=>(await Z.listSandboxAgents(f,{teamId:nt})).agents}).catch(()=>{!Ze&&ye.current===he&&(ye.current=null)});return cg({accountKey:W,force:!0,fetchOrganizations:()=>Gg(f)}).then(async it=>{if(Ze)return;if(it.length===0){He();return}if(!!me&&it.some(le=>le.teamId===me)){await qe(me),He();return}const we=KU(it)?.teamId;if(!we){He();return}const Oe=We.current;if(Oe&&Oe!==me){He();return}const d=qe(we);ye.current=Zg(W,we,y.accountMeta.asOf??"initial");const M=await Z.savePreferences(f,{defaultTeamId:we});await d;const q=We.current;if(Ze){q&&q!==we&&Z.savePreferences(f,{defaultTeamId:q}).then(E).catch(le=>{s(le instanceof Error?le.message:String(le))});return}if(q&&q!==we){E(await Z.savePreferences(f,{defaultTeamId:q})),He();return}Ze||(E(M),He())}).catch(it=>{Ze||(ye.current=null,s(it instanceof Error?it.message:String(it)),He())}),()=>{Ze=!0}},[$e,E,y?.account,y?.accountMeta.asOf,y?.preferences.defaultTeamId,He,f,Je,s]),g.useEffect(()=>{if(!f||!_e)return;let W=!1;const me=()=>{W||(W=!0,cg({accountKey:_e,force:!0,fetchOrganizations:()=>Gg(f)}).catch(()=>{}).finally(()=>{W=!1}))},he=()=>{document.visibilityState==="visible"&&me()},Ze=window.setInterval(me,_F);return window.addEventListener("focus",me),document.addEventListener("visibilitychange",he),()=>{window.clearInterval(Ze),window.removeEventListener("focus",me),document.removeEventListener("visibilitychange",he)}},[f,_e]);const U=g.useCallback(async()=>{Je("connecting"),x(null);const W=await d$();S(he=>JB(he,W)?he:W),Je("account");const me=await Z.bootstrap(W);$e(me),He(),s(he=>he&&(zS(he)||he==="Event stream disconnected")?null:he)},[$e,He,Je,s]);g.useEffect(()=>{let W=!1,me=null;const he=async Ze=>{try{await U()}catch(qe){if(W)return;s(qe instanceof Error?qe.message:String(qe));const it=Math.min(5e3,750+Ze*750);me=window.setTimeout(()=>{he(Ze+1)},it)}};return he(0),()=>{W=!0,me!==null&&window.clearTimeout(me)}},[U,s]);const G=g.useCallback(()=>{U().catch(()=>{})},[U]);BB({afterSequence:D?.afterSequence??null,appendEvents:z,connection:f,setApprovals:H,setSessions:rt,setError:s,onDisconnected:G}),g.useEffect(()=>{if(!f||!y){De.current=null;return}const W=WB(A);!W||De.current===W||(De.current=W,Z.profileCurrent(f).then(me=>{k(he=>he&&{...he,profile:me})}).catch(me=>{De.current=null,s(me instanceof Error?me.message:String(me))}))},[y,f,A,s]);const ce=g.useCallback(()=>{f&&Z.refreshOpenPondAccount(f).then(({account:W,accountMeta:me})=>{k(he=>he&&{...he,account:W,accountMeta:me})}).catch(W=>s(W instanceof Error?W.message:String(W)))},[f,s]);return{appPreferences:L,applyBootstrapPayload:$e,approvals:F,bootstrap:y,codexHistorySessions:O,connection:f,events:A,runtimeEventStore:R,refreshOpenPondAccount:ce,sessions:I,startup:xF(Y),setAppPreferences:et,setBootstrap:k,setCodexHistorySessions:Be,setEvents:$,setSessions:rt}}async function Gg(e){return(await Z.organizations(e)).organizations.map(pc).filter(n=>!!n).filter(n=>n.status==="active")}function CF(e){return e>=wF?0:Math.max(0,kF-e)}function Zg(e,t,n){return`${e}::${t||"none"}::${n}`}function RF({appDispatch:e,error:t,setErrorState:n}){const a=g.useRef(null),o=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=o.current,y=typeof f=="function"?f(S):f;if(Object.is(S,y))return;if(o.current=y,n(y),!y){i.current!==null&&(e({type:"clearToast",toastId:i.current}),i.current=null);return}i.current=l(AF(y),"error",{actionLabel:"Open diagnostics settings",actionIcon:"settings",onAction:p,dismissible:!0});const k=a.current;k&&Z.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(()=>{o.current=t,!(t||i.current===null)&&(e({type:"clearToast",toastId:i.current}),i.current=null)},[e,t]),{connectionRef:a,setError:m,showToast:l}}function AF(e){return LS(e)}const PF={query:"",searchOpen:!1,archivedChatsOpen:!1,sectionMenuOpen:null,projectsExpanded:!1,cloudProjectsExpanded:!1,chatRowsVisibleCount:Cn,sidebarOpen:!0,view:"chat",selectedAppId:null,selectedProjectId:null,selectedSessionId:null,prompt:"",promptDrafts:{},draftProvider:Uo,draftModel:ns,draftExperience:"chat",codexPermissionMode:Kl,codexReasoningEffort:Gl,openPondCommandAccessMode:gs,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 Xp(e){return e.selectedSessionId?`session:${e.selectedSessionId}`:e.selectedProjectId?`project:${e.selectedProjectId}`:e.selectedAppId?`app:${e.selectedAppId}`:`new-${e.draftExperience}`}function Ll(e,t,n){if(!n){if(!(t in e))return e;const{[t]:a,...o}=e;return o}return e[t]===n?e:{...e,[t]:n}}function TF(e){return Ll(e.promptDrafts,Xp(e),e.prompt)}function Bi(e,t,n={}){const a={...e,...t},o=Xp(a),i=TF(e),s=n.clearSelectedDraft?Ll(i,o,""):n.preserveCurrentPrompt?Ll(i,o,e.prompt):i;return{...e,...t,promptDrafts:s,prompt:n.clearSelectedDraft?"":n.preserveCurrentPrompt?e.prompt:s[o]??""}}function EF(e){return e==="draftExperience"||e==="selectedAppId"||e==="selectedProjectId"||e==="selectedSessionId"}function MF(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 o=String(a);return{...e,prompt:o,promptDrafts:Ll(e.promptDrafts,Xp(e),o)}}return EF(t.key)?Bi(e,{[t.key]:a}):{...e,[t.key]:a}}case"patch":return{...e,...t.patch};case"selectApp":return Bi(e,{selectedAppId:t.appId,selectedProjectId:null,selectedSessionId:null,view:"chat"});case"selectProject":return Bi(e,{selectedAppId:null,selectedProjectId:t.projectId,selectedSessionId:null,view:"chat"},{preserveCurrentPrompt:!0});case"selectSession":{const n=t.projectId??null;return Bi(e,{selectedSessionId:t.sessionId,selectedAppId:n?null:t.appId??null,selectedProjectId:n,view:"chat"})}case"beginNewChat":return Bi(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 ft(e,t){return n=>e({type:"field",key:t,value:n})}function jF(e){return{setQuery:ft(e,"query"),setSearchOpen:ft(e,"searchOpen"),setArchivedChatsOpen:ft(e,"archivedChatsOpen"),setSectionMenuOpen:ft(e,"sectionMenuOpen"),setProjectsExpanded:ft(e,"projectsExpanded"),setCloudProjectsExpanded:ft(e,"cloudProjectsExpanded"),setChatRowsVisibleCount:ft(e,"chatRowsVisibleCount"),setSidebarOpen:ft(e,"sidebarOpen"),setView:ft(e,"view"),setSelectedAppId:ft(e,"selectedAppId"),setSelectedProjectId:ft(e,"selectedProjectId"),setSelectedSessionId:ft(e,"selectedSessionId"),setPrompt:ft(e,"prompt"),setDraftProvider:ft(e,"draftProvider"),setDraftModel:ft(e,"draftModel"),setDraftExperience:ft(e,"draftExperience"),setCodexPermissionMode:ft(e,"codexPermissionMode"),setCodexReasoningEffort:ft(e,"codexReasoningEffort"),setOpenPondCommandAccessMode:ft(e,"openPondCommandAccessMode"),setBusy:ft(e,"busy"),setDiffPanelOpen:ft(e,"diffPanelOpen"),setDiffPanelExpanded:ft(e,"diffPanelExpanded"),setRightPanelMode:ft(e,"rightPanelMode"),setRightChatPanels:ft(e,"rightChatPanels"),setTerminalOpen:ft(e,"terminalOpen"),setSyncingWorkspaceAppId:ft(e,"syncingWorkspaceAppId"),setSettingsSection:ft(e,"settingsSection"),setNewProjectDialogOpen:ft(e,"newProjectDialogOpen"),setNewProjectMode:ft(e,"newProjectMode"),setNewProjectName:ft(e,"newProjectName"),setNewProjectPath:ft(e,"newProjectPath"),setNewProjectBusy:ft(e,"newProjectBusy"),setCommitDialogOpen:ft(e,"commitDialogOpen"),setCommitMessage:ft(e,"commitMessage"),setCommitIncludeUnstaged:ft(e,"commitIncludeUnstaged"),setCommitNextStep:ft(e,"commitNextStep"),setCommitDraft:ft(e,"commitDraft"),setBranchDialogOpen:ft(e,"branchDialogOpen"),setBranchDialogName:ft(e,"branchDialogName"),setToast:ft(e,"toast"),setError:ft(e,"error")}}function ku(e){return e.selectedSessionId?`session:${e.selectedSessionId}`:e.selectedProjectId?`project:${e.selectedProjectId}`:e.selectedAppId?`app:${e.selectedAppId}`:"new-chat"}function OF(e={selectedAppId:null,selectedProjectId:null,selectedSessionId:null}){let t=e,n="";const a=new Map,o=new Set,i=m=>{if(!Object.is(n,m)){n=m;for(const f of o)f()}},s=()=>{const m=ku(t);n?a.set(m,n):a.delete(m)},l=(m,f={})=>{const S=n;s(),t={...t,...m};const y=ku(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 o.add(m),()=>o.delete(m)},set(m){const f=typeof m=="function"?m(n):m;if(Object.is(n,f))return;const S=ku(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 dV(e){return g.useSyncExternalStore(e.subscribe,e.getSnapshot,e.getSnapshot)}function NF(e){return{...e,draftExperience:ux()}}function $F(){const[e,t]=g.useReducer(MF,PF,NF),[n]=g.useState(()=>OF()),a=g.useCallback(i=>{n.applyAppAction(i),t(i)},[n]),o=g.useMemo(()=>({...jF(a),setPrompt:n.set}),[n,a]);return{composerDraftStore:n,dispatch:a,setters:o,state:e}}function DF(e){return!!(e&&e.includes("Git is required for OpenPond app workspaces")&&e.includes("Command Line Tools"))}function LF(e){const{connection:t,events:n,showToast:a}=e,o=g.useRef(new Set),i=g.useCallback(async()=>{if(t)try{const l=await Z.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 Z.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(o.current.has(l.id))continue;const p=l.error??l.output??null;l.name==="workspace_action_result"&&l.status==="failed"&&DF(p)&&(o.current.add(l.id),s("OpenPond needs Git before it can update this project."))}},[n,s])}function zF({connection:e,preferences:t,sidebarOpen:n,diffPanelExpanded:a,setBootstrap:o,setError:i}){const[s,l]=g.useState(()=>Zn().sidebarSectionsCollapsed),p=g.useRef(s),m=g.useRef({}),f=g.useRef(null),S=g.useRef(null),[y,k]=g.useState(KB),[R,A]=g.useState(!1),[$,z]=g.useState(GB),[D,x]=g.useState(!1),{pinned:I,projects:P,cloudProjects:O,chats:T,savedForLater:F}=s;g.useEffect(()=>{if(R)return;const ee=Su(Zn(t).sidebarWidth),ue=qg(ee,f.current);f.current=ue.localChange,k(ue.value)},[t,R]),g.useEffect(()=>{if(D)return;const ee=xu(Zn(t).diffPanelWidth),ue=qg(ee,S.current);S.current=ue.localChange,z(ue.value)},[D,t]),g.useEffect(()=>{const ee=Zn(t).sidebarSectionsCollapsed;l(ue=>{const ye=oF(ue,ee,m.current);return p.current=ye,ye})},[t]);const H=g.useCallback(ee=>{o(ue=>ue&&{...ue,preferences:ee.preferences})},[o]),L=g.useCallback(async ee=>{if(e&&Su(Zn(t).sidebarWidth)!==ee)try{H(await Z.savePreferences(e,{sidebarWidth:ee}))}catch(ue){i(ue instanceof Error?ue.message:String(ue))}},[e,t,i,H]),V=g.useCallback(async ee=>{if(e&&xu(Zn(t).diffPanelWidth)!==ee)try{H(await Z.savePreferences(e,{diffPanelWidth:ee}))}catch(ue){i(ue instanceof Error?ue.message:String(ue))}},[e,t,i,H]),Y=g.useCallback(async ee=>{if(!e)return;const ue=Zn(t).sidebarSectionsCollapsed;if(!UF(ue,ee))try{H(await Z.savePreferences(e,{sidebarSectionsCollapsed:ee}))}catch(ye){i(ye instanceof Error?ye.message:String(ye))}},[e,t,i,H]),ie=g.useCallback(ee=>{const ue=p.current;aF(m.current,ue,ee),p.current=ee,l(ee),Y(ee)},[Y]),_e=g.useCallback(()=>{const ee=p.current;ie({...ee,pinned:!ee.pinned})},[ie]),fe=g.useCallback(()=>{const ee=p.current;ie({...ee,projects:!ee.projects})},[ie]),J=g.useCallback(()=>{const ee=p.current;ie({...ee,cloudProjects:!ee.cloudProjects})},[ie]),Me=g.useCallback(()=>{const ee=p.current;ie({...ee,chats:!ee.chats})},[ie]),Se=g.useCallback(()=>{const ee=p.current;ie({...ee,savedForLater:!ee.savedForLater})},[ie]),ae=g.useCallback(ee=>{if(!n)return;ee.preventDefault();const ue=ee.clientX,ye=y;let We=ye;A(!0);function Pe(Ce){We=Su(ye+Ce.clientX-ue),k(We)}function re(){window.removeEventListener("pointermove",Pe),window.removeEventListener("pointerup",re);const Ce=Hg(ye,We);Ce&&(f.current=Ce),A(!1),L(We)}window.addEventListener("pointermove",Pe),window.addEventListener("pointerup",re,{once:!0})},[L,n,y]),xe=g.useCallback(ee=>{if(a)return;ee.preventDefault();const ue=ee.clientX,ye=$;let We=ye;x(!0);function Pe(Ce){We=xu(ye-(Ce.clientX-ue)),z(We)}function re(){window.removeEventListener("pointermove",Pe),window.removeEventListener("pointerup",re);const Ce=Hg(ye,We);Ce&&(S.current=Ce),x(!1),V(We)}window.addEventListener("pointermove",Pe),window.addEventListener("pointerup",re,{once:!0})},[a,$,V]);return{pinnedCollapsed:I,projectsCollapsed:P,cloudProjectsCollapsed:O,chatsCollapsed:T,savedForLaterCollapsed:F,sidebarWidth:y,sidebarResizing:R,diffPanelWidth:$,diffPanelResizing:D,togglePinnedCollapsed:_e,toggleProjectsCollapsed:fe,toggleCloudProjectsCollapsed:J,toggleChatsCollapsed:Me,toggleSavedForLaterCollapsed:Se,startSidebarResize:ae,startDiffPanelResize:xe}}function UF(e,t){return e.pinned===t.pinned&&e.projects===t.projects&&e.cloudProjects===t.cloudProjects&&e.chats===t.chats&&e.savedForLater===t.savedForLater}function HF(e){const[t,n]=g.useState({id:0,kind:null}),[a,o]=g.useState(null),i=g.useCallback((m=null)=>{n(f=>({id:f.id+1,kind:m}))},[]),s=g.useCallback(m=>{o(m)},[]),l=null,p=g.useMemo(()=>{if(e)return qF(a,i)},[e,a,i]);return{backAction:l,breadcrumbs:p,closeDetailKind:t.kind,closeDetailRequestId:t.id,onDetailOpenChange:s}}function qF(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 BF(e){const{connection:t,profileId:n}=e,[a,o]=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=Z.trainingState(t,n).then(I=>(y.current=I.activityRevision??null,o(I),f(null),I)).catch(I=>(f(Po(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,O="POST",T={})=>{if(!t)return null;T.silent||p(x);try{const F=await Z.trainingRequest(t,I,P,O);return await R(),T.silent||f(null),F}catch(F){return T.silent||f(Po(F)),null}finally{T.silent||p(null)}},[t,R]);g.useEffect(()=>{if(y.current=null,!t){o(null);return}k()},[t,n,k]);const $=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=$?500:3e4,O=async()=>{let T=P;try{const F=await Z.trainingActivity(t,n);T=F.active?500:3e4,(y.current===null||y.current!==F.revision)&&await k()}catch(F){f(Po(F))}x&&(I=window.setTimeout(()=>{O()},T))};return I=window.setTimeout(()=>{O()},P),()=>{x=!1,I!==null&&window.clearTimeout(I)}},[t,$,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`,{}),saveModelRunDraft:x=>A("save-model-run-draft","/model-run-drafts",x,"PUT"),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 Z.trainingRequest(t,`/taskset-drafts/${encodeURIComponent(x)}/workspace`,{},"GET")}catch(I){return f(Po(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"),deleteModelRunDraft:x=>A("delete-model-run-draft",`/model-run-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 O of I.columns??[])P.append("column",O);return Z.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?Z.trainingRequest(t,"/sources/estimate",{sessionIds:x}):Promise.resolve([]),searchChats:(x,I,P=0,O=20)=>t?Z.trainingRequest(t,"/sources/search",{query:x,candidates:I,offset:P,limit:O}):Promise.resolve({schemaVersion:"openpond.trainingChatSearchResult.v1",query:x,offset:P,limit:O,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,O)=>A(`run-benchmark-${I}`,`/tasksets/${encodeURIComponent(x)}/benchmark-runs`,{phase:I,model:P,reasoningEffort:O,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,O=null)=>A("accept-harness-review","/harness-reviews/accept",{profileId:n,workspaceId:x,reviewRef:I,analysisModel:P,analysisReasoningEffort:O}),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(Po(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,O)=>A("create-candidate",`/candidates/${encodeURIComponent(x)}/create`,{mode:I,analysisModel:P??null,analysisReasoningEffort:O??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?Z.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?Z.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 O=new URLSearchParams({reviewerKey:I});return P&&O.set("comparisonReleaseId",P),Z.trainingRequest(t,`/tasksets/${encodeURIComponent(x)}/preference-comparisons/calibration/status?${O}`,{},"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-runs/${encodeURIComponent(x)}/prepare`,I),startModelRun:(x,I)=>A("start-model-run",`/model-runs/${encodeURIComponent(x)}/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")??"",O=/filename="([^"]+)"/.exec(P)?.[1]??"openpond-model-artifact",T=URL.createObjectURL(await I.blob()),F=document.createElement("a");return F.href=T,F.download=O,F.click(),URL.revokeObjectURL(T),!0}catch(I){return f(Po(I)),!1}finally{p(null)}},downloadModelPackage:async x=>D(`/models/${encodeURIComponent(x)}/download`,`${x}.openpond-lora.tar`),downloadBundle:async x=>D(`/bundles/${encodeURIComponent(x)}/download`,"openpond-model-improvement-bundle.json")}),[t,A,n,k]);async function D(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 O=P.headers.get("content-disposition")??"",T=/filename="([^"]+)"/.exec(O)?.[1]??I,F=URL.createObjectURL(await P.blob()),H=document.createElement("a");return H.href=F,H.download=T,H.click(),URL.revokeObjectURL(F),!0}catch(P){return f(Po(P)),!1}finally{p(null)}}return{connection:t,payload:a,loading:i,busyAction:l,error:m,refresh:k,actions:z}}function Po(e){return e instanceof Error?e.message:String(e)}function uV({modelId:e,taskset:t}){const n=t.metadata.toolContractHash===ws?"cross_system":t.environment.kind==="stateful_harness"&&t.environment.actionBindings?.length?"harness":null,a=n?KF(t,n):[];return{model:{providerId:"openpond",modelId:e},tasksetId:t.id,tasksetName:t.name,taskRuntime:n,sourceProjectId:GF(t),tasks:a,selectedTaskIndex:0,sessionId:null}}function Rr(e){return e?.tasks.length?e.tasks[rk(e,e.selectedTaskIndex)]??null:null}function ak(e,t){return{...e,selectedTaskIndex:rk(e,t)}}function FF(e){return ak(e,e.selectedTaskIndex+1)}function VF(e,t,n){if(!e||ok(e,n))return null;const a=Rr(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 WF({model:e,connection:t,loadBootstrap:n,applyBootstrap:a}){e.providerId!=="openpond"||!t||a(await n(t))}function KF(e,t){const n=new Set;return e.tasks.flatMap(a=>{const o=t==="cross_system"?a.metadata.taskId:a.metadata.caseId,i=typeof o=="string"?o.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 GF(e){const t=new Set(e.sourceRefs.filter(ME).flatMap(n=>{const a=n.workspaceId?.trim();return a?[a]:[]}));return t.size===1?t.values().next().value??null:null}function rk(e,t){return e.tasks.length?Math.max(0,Math.min(Math.trunc(t),e.tasks.length-1)):0}function ZF({activeModel:e,activeProvider:t,applyBootstrapPayload:n,beginNewChat:a,composerDraftStore:o,connection:i,requestComposerFocus:s,selectedLocalProjectId:l,selectedSessionId:p,selectLocalProject:m,setDraftModel:f,setDraftProvider:S,setError:y,view:k}){const[R,A]=g.useState(null),$=g.useCallback(T=>{T.sourceProjectId?m(T.sourceProjectId):a(null)},[a,m]),z=g.useCallback(T=>{if(!R)return;const F={...ak(R,T),sessionId:R.sessionId?null:R.sessionId},H=Rr(F);A(F),H&&(R.sessionId&&$(F),o.set(H.prompt),s())},[$,o,R,s]),D=g.useCallback(()=>{const T=Rr(R);T&&o.getSnapshot().trim()===T.prompt.trim()&&o.set(""),A(null)},[o,R]),x=g.useCallback(T=>{const F=T.model;WF({model:F,connection:i,loadBootstrap:Z.bootstrap,applyBootstrap:n}).then(()=>{const H={...T,selectedTaskIndex:0,sessionId:null};S(F.providerId),f(F.modelId),A(H.tasks.length?H:null),$(H);const L=Rr(H);L&&o.set(L.prompt)}).catch(y)},[n,$,o,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?VF(R,T,l):null}},[e,t,R,l]),P=g.useCallback(T=>{A(F=>F&&{...F,sessionId:T})},[]),O=g.useCallback(()=>{if(!R)return;const T={...FF(R),sessionId:null},F=Rr(T);A(T),F&&($(T),o.set(F.prompt),s())},[$,o,R,s]);return g.useEffect(()=>{const T=Rr(R);!T||k!=="chat"||p||o.set(F=>F.trim()?F:T.prompt)},[o,R,l,p,k]),g.useEffect(()=>{R&&p&&R.sessionId!==p&&A(null)},[R?.sessionId,p]),{advanceAfterTurn:O,begin:x,bindSession:P,dismiss:D,handoff:R,prepareTurn:I,selectTask:z}}const Fi=[],wu=500;function JF(e){const{approvals:t,codexHistoryEvents:n,connection:a,latestServerSequence:o,runtimeIndexes:i,runtimeEventStore:s,selectedSessionId:l,serverId:p,setCodexHistoryEvents:m,setCodexHistorySessions:f,setError:S}=e,[y,k]=g.useState({}),[R,A]=g.useState({}),$=g.useRef(new Set);g.useEffect(()=>{k({}),A({}),$.current.clear()},[p]);const z=g.useCallback(async()=>{if(!a||!l||$.current.has(l))return!1;const O=R[l];if(O?.hasMore===!1)return!1;if(Mt(l)){const H=Math.max(O?.totalMatchingEvents??0,n.length,Ax),L=Math.min(Sg,Math.max($H,H*2));$.current.add(l),A(V=>({...V,[l]:{cursorSequence:null,hasMore:!0,loading:!0,totalMatchingEvents:V[l]?.totalMatchingEvents??n.length}}));try{const V=await Px(a,l,{force:!0,limit:L,tail:!1});return m(V.events),f(Y=>fc(Y,V.session)),A(Y=>({...Y,[l]:{cursorSequence:null,hasMore:V.events.length>=L&&L<Sg,loading:!1,totalMatchingEvents:L}})),V.events.length>n.length}catch(V){return S(V instanceof Error?V.message:String(V)),A(Y=>({...Y,[l]:{cursorSequence:null,hasMore:Y[l]?.hasMore??!0,loading:!1,totalMatchingEvents:Y[l]?.totalMatchingEvents??n.length}})),!1}finally{$.current.delete(l)}}const T=Da(y[l]??Fi,s.getSessionEvents(l)),F=O?.cursorSequence??YF(T);if(!F)return!1;$.current.add(l),A(H=>({...H,[l]:{cursorSequence:H[l]?.cursorSequence??F,hasMore:H[l]?.hasMore??!0,loading:!0,totalMatchingEvents:H[l]?.totalMatchingEvents??null}}));try{const H=await Z.runtimeEventsPage(a,{sessionId:l,beforeSequence:F,limit:wu}),L=H.events.map(V=>V.event);return k(V=>({...V,[l]:Da(L,V[l]??Fi)})),A(V=>({...V,[l]:{cursorSequence:H.previousSequence,hasMore:H.hasMore,loading:!1,totalMatchingEvents:H.totalMatchingEvents}})),L.length>0}catch(H){return S(H instanceof Error?H.message:String(H)),A(L=>({...L,[l]:{cursorSequence:L[l]?.cursorSequence??F,hasMore:L[l]?.hasMore??!0,loading:!1,totalMatchingEvents:L[l]?.totalMatchingEvents??null}})),!1}finally{$.current.delete(l)}},[R,n.length,a,y,s,l,m,f,S]),D=l?y[l]??Fi:Fi,x=g.useMemo(()=>s.getSessionEvents(l).length,[s,l]),I=g.useRef(null);g.useEffect(()=>{if(!a||!l||Mt(l)||$.current.has(l)||D.length>0||x>0)return;const O=o;if(!O)return;const T=l,F=O+1;$.current.add(T),A(H=>({...H,[T]:{cursorSequence:H[T]?.cursorSequence??F,hasMore:H[T]?.hasMore??!0,loading:!0,totalMatchingEvents:H[T]?.totalMatchingEvents??null}})),Z.runtimeEventsPage(a,{sessionId:T,beforeSequence:F,limit:wu}).then(H=>{const L=H.events.map(V=>V.event);k(V=>({...V,[T]:Da(L,V[T]??Fi)})),A(V=>({...V,[T]:{cursorSequence:H.previousSequence,hasMore:H.hasMore,loading:!1,totalMatchingEvents:H.totalMatchingEvents}}))}).catch(H=>{S(H instanceof Error?H.message:String(H)),A(L=>({...L,[T]:{cursorSequence:L[T]?.cursorSequence??F,hasMore:L[T]?.hasMore??!0,loading:!1,totalMatchingEvents:L[T]?.totalMatchingEvents??null}}))}).finally(()=>{$.current.delete(T)})},[o,a,D.length,x,l,S]),g.useEffect(()=>{if(!a||!l||Mt(l)||$.current.has(l)||!o)return;const O=Da(D,s.getSessionEvents(l)),T=Nl(O);if(!T||T>=o)return;const F=`${l}:${T}:${o}`;if(I.current===F)return;I.current=F;let H=!1;return Z.runtimeEventsPage(a,{sessionId:l,afterSequence:T,limit:wu}).then(L=>{if(H)return;const V=L.events.map(Y=>Y.event);V.length!==0&&k(Y=>qz(Y,l,V))}).catch(L=>{H||(I.current=null,S(L instanceof Error?L.message:String(L)))}),()=>{H=!0}},[o,a,s,D,l,S]);const P=g.useMemo(()=>Mt(l)?cm(n,[]):!l||D.length===0?i:cm(Da(D,s.getSessionEvents(l)),t),[t,n,i,D,l]);return{chatHistoryLoadStates:R,loadMoreSelectedChatHistory:z,selectedPagedSessionEvents:D,selectedRuntimeIndexes:P}}function YF(e){let t=null;for(const n of e)n.sequence!==void 0&&(t===null||n.sequence<t)&&(t=n.sequence);return t}function XF(e,t){const n=g.useRef(null);return g.useMemo(()=>{const a=rx(e,t,n.current);return n.current={events:e,indexes:a},a},[t,e])}function jr(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function _u(e){return Array.isArray(e)?e.filter(t=>!!jr(t)):[]}function Eo(e){return typeof e=="string"&&e.trim()?e.trim():null}function Jg(e){return Eo(e)??jr(e)}function QF(e){if(!e)return[];const t=jr(e.sandboxActionRegistry),n=jr(e.sandboxManifest),a=new Map;for(const o of[..._u(n?.actionCatalog),..._u(t?.actions),..._u(n?.actions)]){const i=Eo(o.id)??Eo(o.name);if(!i)continue;const s=a.get(i);a.set(i,{id:i,name:Eo(o.name)??s?.name??i,label:Eo(o.label)??s?.label??e5(i),description:Eo(o.description)??s?.description??null,visibility:Eo(o.visibility)??s?.visibility??"default",inputSchema:Jg(o.inputSchema)??s?.inputSchema??null,outputSchema:Jg(o.outputSchema)??s?.outputSchema??null,implementation:jr(o.implementation)??s?.implementation??null,mcp:jr(o.mcp)??s?.mcp??null,invokesModel:typeof o.invokesModel=="boolean"?o.invokesModel:s?.invokesModel})}return Array.from(a.values()).filter(o=>o.visibility!=="internal"&&o.visibility!=="debug")}function e5(e){const t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e}function ik(e){if(e.selectedCloudProject)return{id:e.selectedCloudProject.id,teamId:e.selectedCloudProject.teamId,name:e.selectedCloudProject.name,selectionKey:gt("cloud",e.selectedCloudProject.id),localProjectId:null};const t=e.selectedProject?.linkedSandboxProject??null;if(!t?.projectId||!t.teamId)return null;const n=e.cloudProjects?aa(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:gt("cloud",n?.id??t.projectId),localProjectId:e.selectedProject?.id??null}}const sk="openpond-agent",lk="openpond-profile-action";function vc(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function La(e){return typeof e=="string"&&e.trim()?e.trim():null}function Qp(e){return e.displayPrompt&&/(?:^|\s)@[A-Za-z0-9_-]+/.test(e.displayPrompt)?"mention":"slash"}function t5(e){const t=vc(e),n=La(t?.scope);return n!=="entire_manifest"&&n!=="start"&&n!=="action"&&n!=="service"&&n!=="schedule"?null:{scope:n,name:La(t?.name)}}function n5(e){const t=La(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 a5(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:sk,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 o5(e){const t=vc(e.implementation);if(t?.type!==sk)return null;const n=La(t.agentId),a=La(t.teamId),o=La(t.projectId),i=t5(t.selectedEntrypoint),s=n5(t.workflowMode);return!n||!a||!o||!i||!s?null:{agentId:n,agentName:La(t.agentName)??e.label??e.name??e.id,teamId:a,projectId:o,projectName:La(t.projectName),selectedEntrypoint:i,workflowMode:s}}function r5(e,t={}){const n=t.agentName?.trim()||null;return{...e,implementation:{...vc(e.implementation)??{},type:lk,actionId:e.id,...n?{agentName:n}:{}},invokesModel:e.invokesModel??!0}}function i5(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=>r5(n,{agentName:n.agentId?t.get(n.agentId):null}))}function mV(e){return!!(e&&ef(e))}function pV(e){return!!(e&&ef(e)&&e.sourceActionId==="chat")}function ef(e){const t=vc(e.implementation);if(t?.type!==lk)return null;const n=La(t.actionId)??e.id;return n?{actionId:n,actionLabel:e.label??e.name??n}:null}function s5({action:e,attachments:t=[],displayPrompt:n,prompt:a,sessionId:o}){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:Qp({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{},...o?{sessionId:o}:{}}}}function l5({action:e,attachments:t=[],displayPrompt:n,prompt:a,teamId:o}){return{teamId:o,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:Qp({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{}}}}function c5({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:Qp({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{}},workflowMode:e.workflowMode}}const Or=new Map;function tf(e,t){const n=e?.trim();return n?`${t?.trim()||"global"}|${n}`:null}function d5(e,t){const n=tf(e,t);if(!n)return null;const a=Or.get(n);return a?.updatedAt?a.projects:null}function u5(e,t,n){const a=tf(e,n);a&&Or.set(a,{projects:t,promise:null,updatedAt:Date.now()})}function m5(e){const t=e.teamId?.trim();if(!t)return Promise.resolve([]);const n=tf(t,e.accountKey);if(!n)return Promise.resolve([]);const a=Or.get(n);if(!e.force){if(a?.updatedAt)return Promise.resolve(a.projects);if(a?.promise)return a.promise}const o=e.fetchProjects(t).then(i=>(u5(t,i,e.accountKey),i)).catch(i=>{const s=Or.get(n);throw s?.promise===o&&Or.set(n,{projects:s.projects,promise:null,updatedAt:s.updatedAt}),i});return Or.set(n,{projects:a?.projects??[],promise:o,updatedAt:a?.updatedAt??0}),o}function Iu(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 p5({cloudProjectById:e,cloudProjects:t,connection:n,defaultTeamId:a,accountScopeKey:o,localProjects:i,profile:s,selectedCloudProject:l,selectedProject:p,reportError:m}){const[f,S]=g.useState(null),[y,k]=g.useState([]),[R,A]=g.useState([]),$=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 H=t.find(L=>L.id===F.linkedSandboxProject?.projectId&&L.teamId===F.linkedSandboxProject?.teamId);H?.teamId&&T.add(H.teamId)}return[...T].sort()},[t,a,i]),z=$.join("\0"),D=g.useMemo(()=>ik({cloudProjects:t,selectedCloudProject:l,selectedProject:p}),[t,l,p]);g.useEffect(()=>{if(!n||$.length===0){A([]);return}let T=!1;const F=$.flatMap(H=>tk(H,o)??[]);return A(Iu(F)),Promise.all($.map(H=>Jp({teamId:H,accountKey:o,fetchAgents:async L=>(await Z.listSandboxAgents(n,{teamId:L})).agents}))).then(H=>{T||A(Iu(H.flat()))}).catch(()=>{T||A(Iu(F))}),()=>{T=!0}},[o,n,z]),g.useEffect(()=>{if(!n||!D){S(null);return}const T=d5(D.teamId,o);T&&S(T.find(H=>H.id===D.id)??null);let F=!1;return m5({teamId:D.teamId,accountKey:o,fetchProjects:async H=>(await Z.listSandboxProjects(n,{teamId:H})).projects}).then(H=>{F||S(H.find(L=>L.id===D.id)??null)}).catch(()=>{F||S(null)}),()=>{F=!0}},[o,n,D?.id,D?.teamId]),g.useEffect(()=>{if(!n||!p){k([]);return}let T=!1;return Z.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 QF(f))T.set(F.id,F);for(const F of y)T.set(F.id,F);return[...T.values()]},[y,f]),I=g.useMemo(()=>i5(s),[s]),P=g.useMemo(()=>[...R.map(T=>a5(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 f5({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})},[]),o=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:o,setExpandedProjectIds:n}}function h5(){const e=new Map;function t(o,i){const s=e.get(o);if(s)return s.consumers+=1,n(o,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(o)===p&&e.delete(o)})};return e.set(o,p),n(o,p,!1)}function n(o,i,s){let l=!1;return{key:o,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 o of e.values())o.consumers=0,o.settled||o.controller.abort()}return{request:t,cancelAll:a,inFlightCount:()=>e.size}}function Cu(e,t,n){return`workspace-status:${e.serverUrl}:${t}:${n?"ensure":"read"}`}function g5(e,t){return`workspace-diff:${e.serverUrl}:${t}`}function Ru(e){return e instanceof Error&&e.name==="AbortError"}function b5({connection:e,activeWorkspaceAppId:t,view:n,shouldLoadWorkspaceDiff:a,sidebarWorkspaceAppIds:o,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),$=g.useRef(new Set),z=g.useRef(new Set),D=g.useRef(h5()),x=t?p[t]??(s?.appId===t?s:null):null,I=f?.appId===t?f:null,P=n==="chat"||n==="labs",O=g.useCallback(H=>{$.current.add(H.appId),l(H),m(L=>({...L,[H.appId]:H}))},[]),T=g.useCallback(async(H,L=!1)=>{if(!e||!H)return l(null),null;k(!0);const V=D.current.request(Cu(e,H,L),Y=>Z.workspaceStatus(e,H,L,{signal:Y}));try{const Y=await V.promise;return O(Y),L&&Y.error?i(`Workspace sync failed: ${Y.error}`):L&&i(null),Y}catch(Y){return Ru(Y)||(l(null),i(Y instanceof Error?Y.message:String(Y))),null}finally{V.release(),k(!1)}},[e,O,i]),F=g.useCallback(async(H=t,L={})=>{if(!e||!H)return S(null),null;L.silent||A(!0);const V=D.current.request(g5(e,H),Y=>Z.workspaceDiff(e,H,{signal:Y}));try{const Y=await V.promise;return S(Y),Y}catch(Y){return Ru(Y)||(S(null),i(Y instanceof Error?Y.message:String(Y))),null}finally{V.release(),L.silent||A(!1)}},[t,e,i]);return g.useEffect(()=>{if(!e||!t||!P){l(null),S(null),k(!1);return}let H=!1;const L=D.current.request(Cu(e,t,!1),V=>Z.workspaceStatus(e,t,!1,{signal:V}));return k(!0),L.promise.then(V=>{H||(O(V),V.initialized||S(Y=>Y?.appId===V.appId?null:Y))}).catch(V=>{Ru(V)||H||(l(null),i(V instanceof Error?V.message:String(V)))}).finally(()=>{L.release(),H||k(!1)}),()=>{H=!0,L.release()}},[t,e,O,i,P]),g.useEffect(()=>{if(!e||!t||!P){S(null);return}if(!x?.initialized){x&&!x.initialized&&S(H=>H?.appId===t?null:H);return}a&&F(t)},[t,e,F,a,P,x?.dirty,x?.initialized]),g.useEffect(()=>{if(!e||o.length===0)return;const H=o.filter(Y=>!$.current.has(Y)&&!z.current.has(Y));if(H.length===0)return;H.forEach(Y=>z.current.add(Y));let L=!1;const V=H.map(Y=>({appId:Y,request:D.current.request(Cu(e,Y,!1),ie=>Z.workspaceStatus(e,Y,!1,{signal:ie}))}));return Promise.all(V.map(({appId:Y,request:ie})=>ie.promise.then(_e=>({appId:Y,state:_e})).catch(()=>({appId:Y,state:null})).finally(()=>{ie.release(),z.current.delete(Y)}))).then(Y=>{if(!L)for(const ie of Y)ie.state&&O(ie.state)}),()=>{L=!0,V.forEach(({appId:Y,request:ie})=>{ie.release(),z.current.delete(Y)})}},[e,O,o]),g.useEffect(()=>()=>D.current.cancelAll(),[]),{workspaceState:s,workspaceStates:p,workspaceDiff:f,workspaceBusy:y,diffBusy:R,visibleWorkspaceState:x,visibleWorkspaceDiff:I,rememberWorkspaceState:O,refreshWorkspace:T,refreshWorkspaceDiff:F,setWorkspaceBusy:k}}const v5=1,y5=15e3,S5=15e3,ck=5*6e4,x5=5e3,k5=1e4;function dk(e,t=(a,o)=>new WebSocket(a,o),n={}){const a=new w5(e,t,n.reconnectDelayMs??_5);return a.open(),{close:()=>a.close()}}class w5{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=ck;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===v5)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-${I5(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."))},y5))},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 o=typeof a.type=="string"?a.type:"";if(o==="connection_ack"){this.connectionAckTimer&&clearTimeout(this.connectionAckTimer),this.connectionAckTimer=null,this.keepAliveTimeoutMs=R5(a.connectionTimeoutMs),this.lastKeepAliveAt=Date.now(),this.startKeepAliveMonitor(),this.subscribe(t);return}if(o==="ka"){this.lastKeepAliveAt=Date.now();return}if(o==="subscribe_success"){const i=typeof a.id=="string"?a.id:"";if(!this.subscriptionChannels.has(i))return;this.acknowledgedSubscriptions.add(i),this.markReadyWhenSubscribed();return}if(o==="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(o==="connection_error"||o==="subscribe_error"){const i=A5(a);if(this.reportError(i),o==="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 o=C5();this.subscriptionChannels.set(o,a),t.send(JSON.stringify({type:"subscribe",id:o,channel:a,authorization:n}))}this.subscriptionAckTimer=setTimeout(()=>{this.failConnection(new Error("Team chat realtime subscription acknowledgement timed out."))},S5)}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."))},x5)}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 _5(e){const t=Math.min(k5,500*2**Math.min(e,5));return Math.max(100,Math.floor(Math.random()*t))}function I5(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 C5(){return globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random().toString(36).slice(2)}`}function R5(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:ck}function A5(e){const n=(Array.isArray(e.errors)?e.errors:[])[0];if(n&&typeof n=="object"){const a=n,o=typeof a.errorType=="string"?a.errorType:"RealtimeError",i=typeof a.message=="string"?a.message:"Request failed";return new Error(`${o}: ${i}`)}return new Error("Team chat realtime request failed.")}function P5(e,t,n){const a=[`/team-chat/users/${e.session.userId}/${e.session.teamId}`,...Array.from(new Set(e.threadIds)).map(o=>`/team-chat/threads/${o}`)];return dk({realtimeUrl:e.session.realtimeUrl,httpUrl:e.session.httpUrl,authorizationToken:e.session.token,channels:a,onEvent:o=>{const i=g0.safeParse(o);i.success&&e.onEvent(i.data)},onReady:e.onReady,onError:e.onError},t,n)}function T5(e){return e.refs.find(t=>t.refType==="message_reply")??null}function E5(e){return{id:e.id,authorType:e.authorType,authorUserId:e.authorUserId,authorAgentId:e.authorAgentId,body:e.body,deleted:!!e.deletedAt}}function fV(e,t){const n=T5(e);if(!n)return null;const a=t.get(n.refId);return a?E5(a):j5(n)}function M5(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 hV(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 gV(e){return e.deleted?"Message deleted":e.body.replace(/\s+/g," ").trim()||"Attachment"}function j5(e){const t=e.preview;return{id:e.refId,authorType:O5(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 O5(e){return e==="agent"||e==="system"?e:"user"}function Yg(e,t,n){return n===t.conversationId?{...e,aiThread:t}:e}function N5(e,t){return!e||e.thread.id!==t.thread.id?t:{...t,messages:Es([...e.messages,...t.messages]),hasMoreBefore:e.messages.length>t.messages.length?e.hasMoreBefore:t.hasMoreBefore}}function Au(e,t){const n=Array.from(t.values()).filter(o=>o.threadId===e.thread.id);if(n.length===0)return e;let a=e.thread;for(const o of n)a=Vr(a,o,"message.created",!0,o.authorUserId);return{...e,thread:a,messages:Es([...e.messages,...n])}}function $5(e,t){const n=new Set(e.map(o=>o.lastMessage?.clientRequestId).filter(o=>!!o)),a=new Map;for(const o of t.values()){if(o.clientRequestId&&n.has(o.clientRequestId))continue;const i=a.get(o.threadId)??[];i.push(o),a.set(o.threadId,i)}return e.map(o=>{let i=o;for(const s of a.get(o.id)??[])i=Vr(i,s,"message.created",!0,s.authorUserId);return i}).sort((o,i)=>i.lastMessageAt.localeCompare(o.lastMessageAt))}function Pu(e,t,n){for(const a of e)!a.clientRequestId||a.id.startsWith("pending:")||(t.delete(a.clientRequestId),n.delete(a.clientRequestId))}function Tu(e,t,n){const a=e.get(t);a&&e.set(t,{...a,metadata:{...a.metadata,deliveryStatus:n}})}function Xg(e,t,n){const a=e.get(t);a&&e.set(t,{...a,metadata:{...a.metadata,uploadProgress:n}})}function Es(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,o)=>a.sequence!==o.sequence?a.sequence-o.sequence:a.createdAt.localeCompare(o.createdAt))}function uk(e){return e.type!=="message.created"&&e.type!=="message.updated"&&e.type!=="message.deleted"?null:Xm.safeParse(e.payload.message).data??null}function mk(e,t,n){const a=uk(t);if(a){const o=e.selectedThreadId===a.threadId,i=e.detail?.thread.id===a.threadId?{...e.detail,thread:Vr(e.detail.thread,a,t.type,o,n),messages:Es([...e.detail.messages,a])}:e.detail,l=e.threads.some(p=>p.id===a.threadId)?e.threads.map(p=>p.id===a.threadId?Vr(p,a,t.type,o,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 o=typeof t.payload.userId=="string"?t.payload.userId:null,i=Number(t.payload.sequence);if(!o||!Number.isSafeInteger(i)||i<0)return e;const s=l=>({...l,participants:l.participants.map(p=>p.userId===o?{...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 Vr(e,t,n,a,o){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===o?0:i?e.unreadCount+1:e.unreadCount}}function D5(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:M5(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 L5(e,t){const n=e.detail?.thread.id===t.threadId?{...e.detail,thread:Vr(e.detail.thread,t,"message.created",!0,t.authorUserId),messages:Es([...e.detail.messages,t])}:e.detail;return{...e,detail:n,threads:e.threads.map(a=>a.id===t.threadId?Vr(a,t,"message.created",!0,t.authorUserId):a).sort((a,o)=>o.lastMessageAt.localeCompare(a.lastMessageAt)),error:null}}function Qg(e,t,n){return mk(e,{teamId:t.teamId,threadId:t.threadId,type:"message.created",payload:{message:t},createdAt:t.createdAt},n)}function z5(e,t){return Sm(e,t,"failed")}function Sm(e,t,n){const a=o=>o.clientRequestId===t&&o.id.startsWith("pending:")?{...o,metadata:{...o.metadata,deliveryStatus:n}}:o;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(o=>({...o,lastMessage:o.lastMessage?a(o.lastMessage):null}))}}function eb(e,t,n){const a=o=>o.clientRequestId===t&&o.id.startsWith("pending:")?{...o,metadata:{...o.metadata,uploadProgress:n}}:o;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(o=>({...o,lastMessage:o.lastMessage?a(o.lastMessage):null}))}}function U5(e,t){const n=e.detail?.messages.filter(i=>i.id!==t)??[],a=n.at(-1)??null,o=e.detail?{...e.detail,thread:e.detail.thread.lastMessageId===t?tb(e.detail.thread,a):e.detail.thread,messages:n}:null;return{...e,detail:o,threads:e.threads.map(i=>i.lastMessageId===t?tb(i,a):i)}}function H5(e){if(e.length>Oo.maxAttachments)return null;const t=[];for(const n of e){if(n.kind!=="image"||!q5(n.mediaType)||!n.contentsBase64||n.sizeBytes<=0||n.sizeBytes>Oo.maxAttachmentBytes)return null;t.push({...n,kind:"image",mediaType:n.mediaType,contentsBase64:n.contentsBase64})}return t}function tb(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 q5(e){return e==="image/png"||e==="image/jpeg"||e==="image/webp"||e==="image/gif"}const B5={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 F5(e){const t=e instanceof Error?e.message:String(e),n=t.trim().toLowerCase();for(const[a,o]of Object.entries(B5))if(n.includes(a))return o;return n.includes("event stream ended")?"Team chat realtime disconnected. Messages will continue to refresh automatically.":Vx(t)}const pk="openpond.team-chat.notification-mode";function fk(){try{return typeof window>"u"?null:window.localStorage}catch{return null}}function V5(e=fk()){const t=e?.getItem(pk);return t==="direct_mentions"||t==="none"?t:"all"}function W5(e,t=fk()){try{t?.setItem(pk,e)}catch{}}function K5(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 G5(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 nb={members:[],agents:[],threads:[],selectedThreadId:null,detail:null,aiThread:null,agentConversation:null,loading:!1,busy:!1,error:null};function sl(e,t){return e.map(n=>n.id===t&&n.unreadCount!==0?{...n,unreadCount:0}:n)}function ll(e){return!e||e.thread.unreadCount===0?e:{...e,thread:{...e.thread,unreadCount:0}}}function Z5(e){return{teamId:e.teamId,body:e.body.trim(),clientRequestId:e.clientRequestId,selectedAgentId:e.conversation.agent.id,conversationId:e.conversation.conversationId}}function J5(e){return{teamId:e.teamId,body:e.body.trim(),clientRequestId:e.clientRequestId,selectedActionKey:e.selectedActionKey,approvalId:e.approvalId??null}}async function ab(e,t=Z.markTeamChatRead){return e.lastMessageSequence<=0?!1:t(e.connection,e.threadId,e.teamId,e.lastMessageSequence).then(()=>!0,()=>!1)}function Y5(e){const[t,n]=g.useState(nb),a=g.useRef(t);a.current=t;const[o,i]=g.useState(V5),[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),$=g.useRef(new Set),z=g.useRef(0),D=g.useRef(!1),x=g.useRef(new Map),I=g.useRef(new Map),[P,O]=g.useState(null),[T,F]=g.useState(null),H=g.useCallback(E=>{i(E),W5(E)},[]),L=g.useCallback(E=>{l(U=>U?.eventId===E?null:U)},[]),V=g.useCallback(async()=>{if(!e.connection||!e.teamId)return[];const E=await Z.teamChatThreads(e.connection,e.teamId),U=$5(E.threads,x.current);return n(G=>({...G,threads:U})),U},[e.connection,e.teamId]),Y=g.useCallback(async()=>{if(!e.connection||!e.teamId)return{members:[],agents:[]};const[E,U]=await Promise.all([Z.teamChatMembers(e.connection,e.teamId),Z.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]),ie=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 ce=await Z.teamChatThread(e.connection,e.teamId,U);Pu(ce.messages,x.current,I.current);const W=Au(ce,x.current);return y.current.get(U)!==G||(n(me=>me.selectedThreadId===U?{...me,threads:sl(me.threads,U),detail:ll(N5(me.detail,W))}:me),p.current===U&&W.thread.lastMessageSequence>0&&await Z.markTeamChatRead(e.connection,U,e.teamId,W.thread.lastMessageSequence).catch(()=>{})),W},[e.connection,e.teamId]),_e=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 ce=await Z.teamChatAiThread(e.connection,e.teamId,U);return S.current.get(U)===G&&m.current===U&&n(W=>Yg(W,ce,m.current)),ce},[e.connection,e.teamId]),fe=g.useCallback(async E=>{const U=E??R.current;if(!e.connection||!e.teamId||!U)return null;const G=await Z.teamChatAgentConversation(e.connection,e.teamId,U);return n(ce=>ce.agentConversation?.run.id===U?{...ce,agentConversation:G}:ce),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(()=>{fe().catch(G=>{n(ce=>({...ce,error:tn(G)}))})},2500);return()=>window.clearInterval(U)},[fe,t.agentConversation?.run.status]),g.useEffect(()=>{if(!e.connection||!e.teamId||!e.currentUserId){n(nb),O(null),F(null),I.current.clear(),x.current.clear(),y.current.clear(),S.current.clear(),k.current+=1,l(null),$.current.clear(),z.current=0,A.current=0;return}let E=!1;return m.current=null,f.current+=1,k.current+=1,O(null),F(null),I.current.clear(),x.current.clear(),$.current.clear(),z.current=0,n(U=>({...U,aiThread:null,agentConversation:null,loading:!0,error:null})),(async()=>{try{const U=await Z.teamChatEvents(e.connection,e.teamId);if(E)return;A.current=U.cursor;const G=Z.teamChatMembers(e.connection,e.teamId),ce=Z.teamChatAgents(e.connection,e.teamId),W=await Z.teamChatGeneral(e.connection,e.teamId),[me,he,Ze]=await Promise.all([G,ce,Z.teamChatThreads(e.connection,e.teamId)]);if(E)return;const qe=p.current&&Ze.threads.some(we=>we.id===p.current)?p.current:W.thread.id,it=qe===W.thread.id?W:await Z.teamChatThread(e.connection,e.teamId,qe);if(E)return;const nt=ll(it);n(we=>({...we,members:me.members,agents:he.agents,threads:sl(Ze.threads,qe),selectedThreadId:qe,detail:nt,loading:!1,error:null})),ab({connection:e.connection,teamId:e.teamId,threadId:qe,lastMessageSequence:nt?.thread.lastMessageSequence??0}),F(e.teamId)}catch(U){if(E)return;n(G=>({...G,loading:!1,error:tn(U)}))}})(),()=>{E=!0}},[e.connection,e.currentUserId,e.refreshToken,e.teamId]);const J=g.useCallback(E=>{if($.current.has(E.id))return;if($.current.add(E.id),$.current.size>2e3){const G=$.current.values().next().value;typeof G=="number"&&$.current.delete(G)}const U=uk(E);if(U&&E.type==="message.created"){const G=a.current,ce=G.threads.find(me=>me.id===U.threadId)??(G.detail?.thread.id===U.threadId?G.detail.thread:null),W=me=>{E.id<=z.current||K5({mode:o,currentUserId:e.currentUserId,message:U,thread:me})&&(z.current=E.id,l(G5({eventId:E.id,message:U,thread:me,members:G.members})))};ce?W(ce):V().then(me=>{const he=me.find(Ze=>Ze.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=>mk(G,E,e.currentUserId)),E.type==="thread.created"&&V().catch(G=>{n(ce=>({...ce,error:tn(G)}))}),(E.type==="ai_thread.created"||E.type==="ai_turn.updated")&&(ie(E.threadId).catch(G=>{n(ce=>({...ce,error:tn(G)}))}),E.conversationId===m.current&&_e(E.conversationId).catch(G=>{n(ce=>({...ce,error:tn(G)}))})),U&&E.type==="message.created"&&p.current===U.threadId&&U.authorUserId!==e.currentUserId&&e.connection&&e.teamId&&Z.markTeamChatRead(e.connection,U.threadId,e.teamId,U.sequence).catch(()=>{})},[e.connection,e.currentUserId,e.teamId,o,_e,ie,V]),Me=g.useCallback(async()=>{if(!(!e.connection||!e.teamId||D.current)){D.current=!0;try{let E=!0;for(;E;){const U=await Z.teamChatEvents(e.connection,e.teamId,{after:A.current,limit:250});for(const G of U.events)J(G);A.current=U.cursor,E=U.hasMore}}finally{D.current=!1}}},[J,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 ce=await Z.teamChatRealtimeSession(e.connection,e.teamId);if(E||(await Me(),E))return;O(ce);const W=Math.max(3e4,new Date(ce.expiresAt).getTime()-Date.now()-3e4);U=window.setTimeout(()=>{G()},W)}catch{E||(Me().catch(()=>{}),U=window.setTimeout(()=>{G()},1e4))}};return G(),()=>{E=!0,U!==null&&window.clearTimeout(U),O(null)}},[Me,e.connection,e.teamId,T]);const Se=t.threads.map(E=>E.id).sort().join(",");g.useEffect(()=>{if(!P)return;const E=P5({session:P,threadIds:Se?Se.split(","):[],onEvent:J,onReady:()=>{Me().catch(U=>{n(G=>({...G,error:tn(U)}))})},onError:()=>{Me().catch(()=>{})}});return()=>{E.close()}},[J,Me,P,Se]),g.useEffect(()=>{if(!e.connection||!e.teamId||T!==e.teamId)return;const E=window.setInterval(()=>{Me().catch(()=>{})},15e3);return()=>window.clearInterval(E)},[Me,e.connection,e.teamId,T]);const ae=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(ce=>({...ce,threads:sl(ce.threads,E),selectedThreadId:E,detail:ce.detail?.thread.id===E?ll(ce.detail):null,aiThread:G?null:ce.aiThread,agentConversation:G?null:ce.agentConversation,loading:!0,error:null}));try{const ce=await Z.teamChatThread(e.connection,e.teamId,E);if(k.current!==U||p.current!==E)return;Pu(ce.messages,x.current,I.current);const W=Au(ce,x.current);n(me=>({...me,threads:sl(me.threads,E),detail:ll(W),loading:!1})),await Z.markTeamChatRead(e.connection,E,e.teamId,W.thread.lastMessageSequence).catch(()=>{})}catch(ce){if(k.current!==U)return;n(W=>({...W,loading:!1,error:tn(ce)}))}},[e.connection,e.teamId]),xe=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 Z.teamChatDm(e.connection,e.teamId,E);if(k.current!==U)return null;Pu(G.messages,x.current,I.current);const ce=Au(G,x.current),W=p.current!==ce.thread.id;return p.current=ce.thread.id,W&&(f.current+=1,m.current=null),n(me=>({...me,selectedThreadId:ce.thread.id,detail:ce,aiThread:W?null:me.aiThread,agentConversation:W?null:me.agentConversation,busy:!1})),await ab({connection:e.connection,teamId:e.teamId,threadId:ce.thread.id,lastMessageSequence:ce.thread.lastMessageSequence}),await V(),ce}catch(G){return k.current!==U||n(ce=>({...ce,busy:!1,error:tn(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 Z.teamChatThread(e.connection,e.teamId,E.thread.id,{beforeSequence:U,limit:50});return n(ce=>{if(ce.detail?.thread.id!==E.thread.id)return ce;const W=[...G.messages,...ce.detail.messages];return{...ce,loading:!1,detail:{...ce.detail,messages:Es(W),hasMoreBefore:G.hasMoreBefore}}}),!0}catch(G){return n(ce=>({...ce,loading:!1,error:tn(G)})),!1}},[e.connection,e.teamId,t.detail]),ue=g.useCallback(async E=>{const U=p.current,G=H5(E.attachments??[]);if(!G)return n(me=>({...me,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(me=>({...me,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 me=f.current;n(he=>({...he,busy:!0,error:null}));try{const he=await Z.createTeamChatAiThread(e.connection,U,{teamId:e.teamId,body:E.body.trim(),clientRequestId:crypto.randomUUID(),providerId:E.providerId,modelId:E.modelId}),Ze=f.current===me&&p.current===U;return Ze&&(f.current+=1,m.current=he.conversationId),n(qe=>({...qe,aiThread:Ze?he:qe.aiThread})),he.activeTurn&&await Z.executeTeamChatAiTurn(e.connection,he.activeTurn.id,e.teamId),await Promise.all([ie(U),V()]),n(qe=>({...qe,busy:!1})),!0}catch(he){return n(Ze=>({...Ze,busy:!1,error:tn(he)})),!1}}const ce=crypto.randomUUID();if(E.selectedActionKey){if(G.length>0)return n(me=>({...me,error:"Agent invocations do not support image attachments yet."})),!1;n(me=>({...me,busy:!0,error:null}));try{return await Z.createTeamChatAgentRun(e.connection,U,J5({teamId:e.teamId,body:E.body,clientRequestId:ce,selectedActionKey:E.selectedActionKey,approvalId:E.approvalId})),await Promise.all([ie(U),V()]),n(me=>({...me,busy:!1})),!0}catch(me){return n(he=>({...he,busy:!1,error:tn(me)})),!1}}I.current.set(ce,{inputs:G,uploaded:null});const W=D5({clientRequestId:ce,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(ce,W),n(me=>L5(me,W));try{const me=[];for(const[qe,it]of G.entries())me.push(await Z.uploadTeamChatAttachment(e.connection,U,{teamId:e.teamId,attachment:it})),Xg(x.current,ce,`${qe+1} of ${G.length}`),n(nt=>eb(nt,ce,`${qe+1} of ${G.length}`));const he=I.current.get(ce);he&&(he.uploaded=me);const Ze=await Z.sendTeamChatMessage(e.connection,U,{teamId:e.teamId,body:E.body.trim(),clientRequestId:ce,mentionUserIds:E.mentionUserIds,attachmentIds:me.map(qe=>qe.id),replyToMessageId:E.replyToMessage?.id??null});return I.current.delete(ce),x.current.delete(ce),n(qe=>Qg(qe,Ze,e.currentUserId)),!0}catch(me){return Tu(x.current,ce,"failed"),n(he=>({...z5(he,ce),error:tn(me)})),!1}},[e.connection,e.currentUserId,e.teamId,ie,V,t.detail?.thread.lastMessageSequence]),ye=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 Z.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:tn(U)}))}}},[e.connection,e.teamId]),We=g.useCallback(async E=>{if(!(!e.connection||!e.teamId)){R.current=E,n(U=>({...U,busy:!0,error:null}));try{const U=await Z.teamChatAgentConversation(e.connection,e.teamId,E);n(G=>({...G,agentConversation:U,busy:!1}))}catch(U){n(G=>({...G,busy:!1,error:tn(U)}))}}},[e.connection,e.teamId]),Pe=g.useCallback(()=>{R.current=null,n(E=>({...E,agentConversation:null}))},[]),re=g.useCallback(async E=>{const U=p.current,G=t.agentConversation;if(!e.connection||!e.teamId||!U||!G||!E.body.trim())return!1;n(ce=>({...ce,busy:!0,error:null}));try{const ce=await Z.createTeamChatAgentRun(e.connection,U,Z5({teamId:e.teamId,body:E.body,clientRequestId:E.clientRequestId,conversation:G}));R.current=ce.run.id;const[W]=await Promise.all([Z.teamChatAgentConversation(e.connection,e.teamId,ce.run.id),ie(U),V()]);return n(me=>({...me,agentConversation:W,busy:!1})),!0}catch(ce){return n(W=>({...W,busy:!1,error:tn(ce)})),!1}},[e.connection,e.teamId,ie,V,t.agentConversation]),Ce=g.useCallback(()=>{f.current+=1,m.current=null,n(E=>({...E,aiThread:null}))},[]),De=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 Z.sendTeamChatAiTurn(e.connection,U,{teamId:e.teamId,body:E.body.trim(),clientRequestId:crypto.randomUUID(),providerId:E.providerId,modelId:E.modelId});return n(ce=>({...Yg(ce,G,m.current),busy:!1})),G.activeTurn&&await Z.executeTeamChatAiTurn(e.connection,G.activeTurn.id,e.teamId),!0}catch(G){return n(ce=>({...ce,busy:!1,error:tn(G)})),!1}},[e.connection,e.teamId]),Je=g.useCallback(async()=>{const E=t.aiThread?.activeTurn?.id;return!e.connection||!e.teamId||!E?!1:(await Z.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 Z.editTeamChatMessage(e.connection,E.threadId,E.id,{teamId:e.teamId,body:U}),await ie(E.threadId),!0}catch(G){return n(ce=>({...ce,error:tn(G)})),!1}},[e.connection,e.teamId,ie]),rt=g.useCallback(async E=>{if(!e.connection||!e.teamId)return!1;try{return await Z.deleteTeamChatMessage(e.connection,E.threadId,E.id,e.teamId),await ie(E.threadId),!0}catch(U){return n(G=>({...G,error:tn(U)})),!1}},[e.connection,e.teamId,ie]),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),ce=E.refs.find(W=>W.refType==="message_reply");Tu(x.current,E.clientRequestId,"sending"),n(W=>Sm(W,E.clientRequestId,"sending"));try{let W=G?.uploaded??[];if(G&&!G.uploaded){W=[];for(const[he,Ze]of G.inputs.entries())W.push(await Z.uploadTeamChatAttachment(e.connection,E.threadId,{teamId:e.teamId,attachment:Ze})),Xg(x.current,E.clientRequestId,`${he+1} of ${G.inputs.length}`),n(qe=>eb(qe,E.clientRequestId,`${he+1} of ${G.inputs.length}`));G.uploaded=W}const me=await Z.sendTeamChatMessage(e.connection,E.threadId,{teamId:e.teamId,body:E.body,clientRequestId:E.clientRequestId,mentionUserIds:U,attachmentIds:W.map(he=>he.id),replyToMessageId:ce?.refId??null});return I.current.delete(E.clientRequestId),x.current.delete(E.clientRequestId),n(he=>Qg(he,me,e.currentUserId)),!0}catch(W){return Tu(x.current,E.clientRequestId,"failed"),n(me=>({...Sm(me,E.clientRequestId,"failed"),error:tn(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=>U5(U,E.id)))},[]),$e=g.useCallback(async(E,U)=>{if(!e.connection||!e.teamId)return!1;try{const G=await Z.setTeamChatThreadMuted(e.connection,E,e.teamId,U),ce=W=>W.id===G.threadId?{...W,mutedAt:G.mutedAt}:W;return n(W=>({...W,threads:W.threads.map(ce),detail:W.detail?.thread.id===G.threadId?{...W.detail,thread:ce(W.detail.thread)}:W.detail,error:null})),!0}catch(G){return n(ce=>({...ce,error:tn(G)})),!1}},[e.connection,e.teamId]);return{...t,currentUserId:e.currentUserId,notificationMode:o,incomingNotification:s,setNotificationMode:H,dismissIncomingNotification:L,setThreadMuted:$e,selectThread:ae,openDm:xe,loadMoreMessages:ee,sendMessage:ue,openAiThread:ye,openAgentConversation:We,closeAgentConversation:Pe,sendAgentTurn:re,closeAiThread:Ce,sendAiTurn:De,stopAiTurn:Je,editMessage:et,deleteMessage:rt,retryMessage:Be,dismissFailedMessage:He,refreshDirectory:Y,refresh:async()=>{await Promise.all([Y(),V(),ie(),_e(),fe()])}}}function tn(e){return F5(e)}const hk="local-profile-agent";function bV(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?[]:[jo(l.agentName),jo(s.name),jo(s.label)].filter(Boolean)})),a=t.hosted?.teamId===e.teamId?t.hosted.hostedSourceMaterialization:null,o=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&&o.has(a.runtimeAgentId))||n.has(jo(s.name))||n.has(jo(s.id))?[]:[e4(t,s)]:[]);return[...e.hostedActions,...i]}function vV(e){return e?.implementation?.type===hk}function yV(e){const t=e.implementation?.profileAgentId;return typeof t=="string"&&t.trim()?t.trim():null}function X5(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 Q5(e,t){const n=t.runtimeAgentId?.trim()??"",a=t.profileName?.trim()??"",o=jo(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&&o&&[s.agentName,i.name,i.label].some(l=>jo(l)===o))})??null}function e4(e,t){return{id:`local-profile:${e.activeProfile??"default"}:${t.id}:chat`,name:t.name,label:t.name,description:t4(e),approvalPolicy:{required:!1,risk:"write"},setupRequirements:e.setupGate.blockingRequirements,invokesModel:!0,implementation:{type:hk,profileAgentId:t.id,profileName:e.activeProfile??"default"}}}function t4(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 jo(e){return typeof e=="string"?e.trim().toLowerCase().replace(/[^a-z0-9]+/g,""):""}const ob=5;function n4(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 Z.profileCheck(e.connection,{kind:"all"}),a=X5(n,t);if(a)throw new Error(a);const o=n?.agents.find(m=>m.id===t);if(!o)throw new Error(`Profile agent not found: ${t}`);const s=(await Z.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 Z.bootstrap(e.connection));let p=null;for(let m=0;m<ob;m+=1){const f=await e.refreshDirectory();if(p=Q5(f.agents,{runtimeAgentId:l,profileName:n.activeProfile,agentName:o.name}),p)break;m<ob-1&&await a4(200*(m+1))}if(!p)throw new Error(`${o.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 a4(e){return new Promise(t=>{setTimeout(t,e)})}function o4(e){g.useEffect(()=>{if(!e.notification)return;const{eventId:t,threadId:n,title:a,body:o}=e.notification;e.showToast(`${a}: ${o}`,"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 r4(e){const{connection:t,refreshToken:n=null}=e,[a,o]=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,$]=g.useState(!1),[z,D]=g.useState(null),[x,I]=g.useState(null),[P,O]=g.useState(null),[T,F]=g.useState(0),H=g.useRef(0),L=g.useMemo(()=>a.find(ee=>ee.id===l)??null,[a,l]),V=g.useCallback(async()=>{if(!t)return!1;y(!0),D(null);try{const ee=await Z.communities(t);return o(ee.items),s(ee.nextCursor),p(ue=>ue&&ee.items.some(ye=>ye.id===ue)?ue:null),!0}catch(ee){return D(xl(ee)),!1}finally{y(!1)}},[t]),Y=g.useCallback(async()=>{if(!t||!i||S)return!1;y(!0),D(null);try{const ee=await Z.communities(t,i);return o(ue=>i4(ue,ee.items)),s(ee.nextCursor),!0}catch(ee){return D(xl(ee)),!1}finally{y(!1)}},[t,S,i]),ie=g.useCallback(async ee=>{if(!t)return null;const ue=++H.current;R(!0),I(null);try{const ye=await Z.communityPreview(t,ee.slug);return H.current===ue&&f(ye),ye}catch(ye){return H.current===ue&&I(xl(ye)),null}finally{H.current===ue&&R(!1)}},[t]),_e=g.useCallback(ee=>{const ue=a.find(ye=>ye.id===ee);ue&&(p(ue.id),f(ye=>ye?.id===ue.id?ye:null),O(null),ie(ue))},[a,ie]),fe=g.useCallback(()=>{H.current+=1,p(null),f(null),I(null),O(null)},[]);g.useEffect(()=>{if(!t){o([]),f(null),p(null);return}V()},[t,V,n]),g.useEffect(()=>{!L||m?.id===L.id||k||ie(L)},[ie,m?.id,k,L]);const J=g.useCallback(async()=>{const ee=L;await V(),ee&&await ie(ee)},[ie,V,L]),Me=g.useCallback(async()=>{if(!t||!m?.currentRules||A)return!1;$(!0),O(null);try{return await Z.joinCommunity(t,m.id,m.currentRules.id),F(ee=>ee+1),await J(),!0}catch(ee){const ue=cl(ee);return O(ue),ue.kind==="rules_stale"&&await J(),!1}finally{$(!1)}},[t,A,m,J]),Se=g.useCallback(async()=>{if(!t||!m?.currentRules||A)return!1;$(!0),O(null);try{return await Z.acceptCommunityRules(t,m.id,m.currentRules.id),F(ee=>ee+1),await J(),!0}catch(ee){const ue=cl(ee);return O(ue),ue.kind==="rules_stale"&&await J(),!1}finally{$(!1)}},[t,A,m,J]),ae=g.useCallback(async()=>{if(!t||!m||A)return!1;$(!0),O(null);try{return await Z.leaveCommunity(t,m.id),F(ee=>ee+1),await J(),!0}catch(ee){return O(cl(ee)),!1}finally{$(!1)}},[t,A,m,J]),xe=g.useCallback(async ee=>{if(!t||!m||A)return!1;$(!0),O(null);try{return await Z.updateCommunityNotifications(t,m.id,ee),o(ue=>ue.map(ye=>ye.id===m.id&&ye.membership?{...ye,membership:{...ye.membership,notificationMode:ee}}:ye)),f(ue=>ue?.id===m.id&&ue.membership?{...ue,membership:{...ue.membership,notificationMode:ee}}:ue),!0}catch(ue){return O(cl(ue)),!1}finally{$(!1)}},[t,A,m]);return{items:a,nextCursor:i,selectedCommunityId:l,selectedSummary:L,preview:m,discoveryLoading:S,previewLoading:k,membershipBusy:A,discoveryError:z,previewError:x,membershipError:P,membershipVersion:T,refresh:V,loadMore:Y,showDiscovery:fe,selectCommunity:_e,join:Me,acceptRules:Se,leave:ae,updateNotifications:xe,clearMembershipError:()=>O(null)}}function i4(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 xl(e){return e instanceof Error?e.message:String(e)}function cl(e){const t=xl(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 s4(e,t,n){return dk({realtimeUrl:e.session.realtimeUrl,httpUrl:e.session.httpUrl,authorizationToken:e.session.token,channels:[e.session.channel],onEvent:a=>{const o=I0.safeParse(a);o.success&&e.onEvent(o.data)},onReady:e.onReady,onError:e.onError},t,n)}function l4(e){const{connection:t,preview:n,currentUserId:a,membershipVersion:o}=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([]),[$,z]=g.useState(!1),[D,x]=g.useState(!1),[I,P]=g.useState(!1),[O,T]=g.useState(!1),[F,H]=g.useState(null),[L,V]=g.useState(null),[Y,ie]=g.useState(null),[_e,fe]=g.useState(null),[J,Me]=g.useState(!1),[Se,ae]=g.useState(null),[xe,ee]=g.useState(null),ue=g.useRef(null),ye=g.useRef([]),We=g.useRef("mentions"),Pe=g.useRef(0),re=g.useRef({}),Ce=g.useRef(new Set),De=g.useMemo(()=>p.find(we=>we.id===f)??null,[p,f]),Je=f?y[f]??null:null;g.useEffect(()=>{ue.current=f},[f]),g.useEffect(()=>{ye.current=p},[p]),g.useEffect(()=>{We.current=n?.membership?.notificationMode??"mentions"},[n?.membership?.notificationMode]);const et=g.useCallback(async()=>{if(!t||!i)return!1;z(!0),H(null);try{const we=await Z.communityChannels(t,i);return m(we.channels),S(Oe=>Oe&&we.channels.some(d=>d.id===Oe)?Oe:we.channels.find(d=>d.isDefault)?.id??we.channels[0]?.id??null),Me(!1),!0}catch(we){const Oe=Gn(we);return H(Oe),Vi(Oe)&&Me(!0),!1}finally{z(!1)}},[i,t]),rt=g.useCallback(async we=>{if(!t||!i)return!1;const Oe=++Pe.current;x(!0),V(null);try{const d=await Z.communityMessages(t,i,we,{limit:50});return Oe!==Pe.current?!1:(k(M=>({...M,[we]:{items:d.messages,hasMoreBefore:d.hasMoreBefore,preview:d.preview}})),Me(!1),!0)}catch(d){if(Oe!==Pe.current)return!1;const M=Gn(d);return V(M),Vi(M)&&Me(!0),!1}finally{Oe===Pe.current&&x(!1)}},[i,t]);g.useEffect(()=>{m(n?.channels??[]),k({}),S(n?.channels.find(we=>we.isDefault)?.id??n?.channels[0]?.id??null),H(null),V(null),ie(null),Me(!1),Ce.current.clear(),i&&et()},[i,et,o]),g.useEffect(()=>{f&&rt(f)},[rt,f]);const Be=g.useCallback(async(we,Oe)=>{if(!t||!i||!s||!l||Oe<=0)return!1;if((re.current[we]??0)>=Oe)return!0;re.current[we]=Oe;try{const d=await Z.markCommunityRead(t,i,we,Oe);return m(M=>M.map(q=>q.id===we?{...q,unreadCount:0,readState:q.readState?{...q.readState,lastReadSequence:d.sequence,lastReadAt:new Date().toISOString()}:{lastReadSequence:d.sequence,lastReadAt:new Date().toISOString(),mutedAt:null,pinnedAt:null}}:q)),!0}catch(d){const M=Gn(d);return Vi(M)&&Me(!0),!1}},[i,t,s,l]);g.useEffect(()=>{const we=Je?.items.at(-1)?.sequence??0;f&&we>0&&Be(f,we)},[Be,f,Je?.items]);const He=g.useCallback(we=>{if(we.communityId!==i||Ce.current.has(we.id))return;Ce.current.add(we.id);const Oe=_0.safeParse(we.payload.message);if(Oe.success&&we.type!=="read.updated"){const d=Oe.data;if(k(M=>{const q=M[we.channelId];if(!q)return M;const N=q.items.some(K=>K.id===d.id)?q.items.map(K=>K.id===d.id?d:K):[...q.items,d].sort((K,w)=>K.sequence-w.sequence);return{...M,[we.channelId]:{...q,items:N}}}),m(M=>M.map(q=>q.id===we.channelId?{...q,lastMessageSequence:Math.max(q.lastMessageSequence,d.sequence),unreadCount:ue.current===we.channelId||d.authorUserId===a?0:Math.max(q.unreadCount+(we.type==="message.created"?1:0),0)}:q)),we.type==="message.created"&&d.authorUserId!==a){const M=ye.current.find(N=>N.id===we.channelId),q=c4(d).includes(a??""),le=We.current;!M?.readState?.mutedAt&&(le==="all"||le==="mentions"&&q)&&ee({communityId:we.communityId,channelId:we.channelId,message:d})}ue.current===we.channelId&&Be(we.channelId,d.sequence);return}we.type==="read.updated"&&we.payload.userId===a&&et()},[i,a,et,Be]);g.useEffect(()=>{if(!t||!i||!s||!l)return;let we=!1,Oe=null;return ie(null),Promise.all([Z.communityRealtimeSession(t,i),Z.communityEvents(t,i)]).then(async([d,M])=>{if(we)return;const q=async()=>{let N=M.cursor;for(;;){const K=await Z.communityEvents(t,i,{after:N,limit:200});if(we)return;for(const w of K.events)He(w);if(N=K.cursor,!K.hasMore)return}},le=s4({session:d,onEvent:He,onReady:()=>{ie(null),q().catch(N=>ie(Gn(N)))},onError:N=>ie(Gn(N))});Oe=()=>le.close(),await q()}).catch(d=>{if(!we){const M=Gn(d);ie(M),Vi(M)&&Me(!0)}}),()=>{we=!0,Oe?.()}},[He,i,t,s,o,l]);const $e=g.useCallback(async()=>{if(!t||!i||!f||I)return!1;const we=y[f],Oe=we?.items[0]?.sequence;if(!we?.hasMoreBefore||Oe==null)return!1;P(!0),V(null);try{const d=await Z.communityMessages(t,i,f,{beforeSequence:Oe,limit:50});return k(M=>{const q=M[f]??we,le=new Set(q.items.map(N=>N.id));return{...M,[f]:{...q,items:[...d.messages.filter(N=>!le.has(N.id)),...q.items],hasMoreBefore:d.hasMoreBefore}}}),!0}catch(d){return V(Gn(d)),!1}finally{P(!1)}},[i,t,y,I,f]),E=g.useCallback(async we=>{if(!t||!i||!f||O)return!1;T(!0),fe(null),ae(null);try{const Oe=await Promise.all(we.attachments.map(M=>Z.uploadCommunityAttachment(t,i,f,M))),d=await Z.sendCommunityMessage(t,i,f,{body:we.body,clientRequestId:we.clientRequestId,mentionUserIds:we.mentionUserIds,attachmentIds:Oe.map(M=>M.id),replyToMessageId:we.replyToMessageId});return k(M=>{const q=M[f]??{items:[],hasMoreBefore:!1,preview:!1};return q.items.some(le=>le.id===d.id)?M:{...M,[f]:{...q,items:[...q.items,d]}}}),await Be(f,d.sequence),!0}catch(Oe){const d=Gn(Oe);return fe(d),ae({...we,message:d}),Vi(d)&&Me(!0),!1}finally{T(!1)}},[i,t,Be,f,O]),U=g.useCallback(we=>E({body:we.body,clientRequestId:crypto.randomUUID(),mentionUserIds:we.mentionUserIds??[],attachments:we.attachments??[],replyToMessageId:we.replyToMessageId??null}),[E]),G=g.useCallback(async(we,Oe)=>{if(!t||!i||!f)return!1;fe(null);try{const d=await Z.editCommunityMessage(t,i,f,we,Oe);return rb(k,f,d),!0}catch(d){return fe(Gn(d)),!1}},[i,t,f]),ce=g.useCallback(async we=>{if(!t||!i||!f)return!1;fe(null);try{const Oe=await Z.deleteCommunityMessage(t,i,f,we);return rb(k,f,Oe),!0}catch(Oe){return fe(Gn(Oe)),!1}},[i,t,f]),W=g.useCallback(async(we,Oe)=>{if(!t||!i)return!1;fe(null);try{const d=await Z.setCommunityChannelMuted(t,i,we,Oe);return m(M=>M.map(q=>q.id===we&&q.readState?{...q,readState:{...q.readState,mutedAt:d.mutedAt}}:q)),!0}catch(d){return fe(Gn(d)),!1}},[i,t]),me=g.useCallback(async(we="")=>{if(!t||!i||!s)return[];try{const Oe=await Z.searchCommunityMembers(t,i,{query:we,limit:50});return A(d=>d4(d,Oe.items)),Oe.items}catch(Oe){return fe(Gn(Oe)),[]}},[i,t,s]);g.useEffect(()=>{s&&l?me():A([])},[s,l,me]);const he=g.useCallback(async we=>{if(!t||!i||!f)return!1;try{const Oe=await Z.communityAttachmentDownload(t,i,f,we);return window.open(Oe.url,"_blank","noopener,noreferrer"),!0}catch(Oe){return fe(Gn(Oe)),!1}},[i,t,f]),Ze=g.useCallback(()=>f?rt(f):Promise.resolve(!1),[rt,f]),qe=g.useCallback(()=>Se?E(Se):Promise.resolve(!1),[Se,E]),it=g.useCallback(()=>ae(null),[]),nt=g.useCallback(()=>ee(null),[]);return{channels:p,selectedChannelId:f,selectedChannel:De,messages:Je?.items??[],hasMoreBefore:Je?.hasMoreBefore??!1,previewMode:Je?.preview??!s,members:R,channelsLoading:$,messagesLoading:D,olderMessagesLoading:I,sending:O,channelsError:F,messagesError:L,realtimeError:Y,actionError:_e,lostMembership:J,failedSend:Se,incomingNotification:xe,selectChannel:S,loadChannels:et,loadMessages:Ze,loadOlder:$e,sendMessage:U,retrySend:qe,dismissFailedSend:it,editMessage:G,deleteMessage:ce,setMuted:W,searchMembers:me,downloadAttachment:he,dismissIncomingNotification:nt}}function rb(e,t,n){e(a=>{const o=a[t];return o?{...a,[t]:{...o,items:o.items.map(i=>i.id===n.id?n:i)}}:a})}function c4(e){const t=e.metadata.mentionUserIds;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function d4(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 Vi(e){return e.includes("community_membership_required")||e.includes("community_rules")}function Gn(e){return e instanceof Error?e.message:String(e)}function u4(e){const t=r4({connection:e.connection,refreshToken:e.refreshToken}),n=l4({connection:e.connection,preview:t.preview,currentUserId:e.currentUserId,membershipVersion:t.membershipVersion}),a=n.incomingNotification,o=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=o.find($=>$.id===a.communityId),A=i.find($=>$.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,o,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 m4=[];function p4(e){const t=g.useCallback(a=>qU(e,a),[e]),n=g.useCallback(()=>UU(e)??m4,[e]);return g.useSyncExternalStore(t,n,n)}function f4(e){const[t,n]=g.useState(()=>Zd());return g.useEffect(()=>{let a=!0;return e?(Z.connectedAppStatus(e,{status:"all"}).then(o=>{a&&n(o.apps)}).catch(o=>{console.warn("Unable to load connected app mention status.",o),a&&n(Zd())}),()=>{a=!1}):(n(Zd()),()=>{a=!1})},[e]),t}function h4(){const{composerDraftStore:e,dispatch:t,setters:n,state:a}=$F(),[o,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),[$,z]=g.useState(null),[D,x]=g.useState(gx),[I,P]=g.useState({}),[O,T]=g.useState(()=>new Set),F=g.useCallback((ot,Ee)=>{T(at=>{if(at.has(ot)===Ee)return at;const ct=new Set(at);return Ee?ct.add(ot):ct.delete(ot),ct})},[]),[H,L]=g.useState(0),[V,Y]=g.useState(null),ie=g.useRef(null),{confirmProjectAction:_e,projectConfirmDialog:fe,resolveProjectConfirmDialog:J}=Ez(),{query:Me,searchOpen:Se,archivedChatsOpen:ae,sectionMenuOpen:xe,projectsExpanded:ee,cloudProjectsExpanded:ue,chatRowsVisibleCount:ye,sidebarOpen:We,view:Pe,selectedAppId:re,selectedProjectId:Ce,selectedSessionId:De,draftProvider:Je,draftModel:et,draftExperience:rt,codexPermissionMode:Be,codexReasoningEffort:He,openPondCommandAccessMode:$e,busy:E,diffPanelOpen:U,diffPanelExpanded:G,rightPanelMode:ce,rightChatPanels:W,terminalOpen:me,settingsSection:he,newProjectDialogOpen:Ze,newProjectMode:qe,newProjectName:it,newProjectPath:nt,newProjectBusy:we,commitDialogOpen:Oe,commitMessage:d,commitIncludeUnstaged:M,commitNextStep:q,commitDraft:le,branchDialogOpen:N,branchDialogName:K,toast:w,error:j}=a,oe=HF(Pe==="labs"),{setQuery:X,setSearchOpen:Q,setArchivedChatsOpen:pe,setSectionMenuOpen:de,setProjectsExpanded:ze,setCloudProjectsExpanded:Te,setChatRowsVisibleCount:Ne,setSidebarOpen:Ye,setView:Le,setSelectedAppId:ut,setSelectedProjectId:Vt,setSelectedSessionId:dn,setPrompt:un,setDraftProvider:Xt,setDraftModel:xt,setDraftExperience:Wt,setCodexPermissionMode:Pt,setCodexReasoningEffort:Rt,setOpenPondCommandAccessMode:qn,setDiffPanelOpen:jt,setDiffPanelExpanded:mn,setRightPanelMode:Qt,setRightChatPanels:ln,setTerminalOpen:Sn,setSyncingWorkspaceAppId:Ia,setSettingsSection:qt,setNewProjectDialogOpen:xn,setNewProjectMode:lt,setNewProjectName:Bt,setNewProjectPath:te,setNewProjectBusy:Ke,setCommitDialogOpen:Ge,setCommitMessage:St,setCommitIncludeUnstaged:an,setCommitNextStep:Ca,setCommitDraft:kn,setBranchDialogOpen:Dt,setBranchDialogName:kt,setError:Lt}=n,{connectionRef:vt,setError:_t,showToast:Tt}=RF({appDispatch:t,error:j,setErrorState:Lt}),{appPreferences:cn,applyBootstrapPayload:En,bootstrap:Xe,codexHistorySessions:pn,connection:mt,events:Kt,runtimeEventStore:wn,approvals:Bn,sessions:po,startup:Fn,setAppPreferences:Jn,setBootstrap:pt,setCodexHistorySessions:ca,setEvents:fo,setSessions:da}=IF({setDraftModel:xt,setDraftProvider:Xt,setCodexPermissionMode:Pt,setCodexReasoningEffort:Rt,setOpenPondCommandAccessMode:qn,setError:_t,setSelectedAppId:ut,setSelectedProjectId:Vt,setSelectedSessionId:dn});vt.current=mt,g.useEffect(()=>{Xe&&k(Xe.sidebarFileBookmarks??[])},[Xe?.sidebarFileBookmarks]);const ia=g.useMemo(()=>[...Kt].reverse().find(ot=>ot.name==="tool.completed"&&ot.action==="manage_sidebar_file")??null,[Kt]),Zo=g.useRef(null);g.useEffect(()=>{!mt||!ia||Zo.current===ia.id||(Zo.current=ia.id,Z.sidebarFiles(mt).then(ot=>k(ot.items)).catch(ot=>_t(ot instanceof Error?ot.message:String(ot))))},[mt,ia,_t]);const ua=g.useCallback(async(ot,Ee)=>{if(!mt)return;const at=y;k(ct=>Ee==="none"?ct.filter(on=>on.id!==ot.id):ct.some(on=>on.id===ot.id)?ct.map(on=>on.id===ot.id?{...on,status:Ee}:on):[...ct,{...ot,status:Ee}]);try{const ct=await Z.patchSidebarFile(mt,{workspaceKind:ot.workspaceKind,workspaceId:ot.workspaceId,workspaceName:ot.workspaceName,path:ot.path,status:Ee,sourceSessionId:ot.sourceSessionId});k(ct.items)}catch(ct){k(at),_t(ct instanceof Error?ct.message:String(ct))}},[mt,_t,y]),ho=f4(mt),Jo=BF({connection:mt,profileId:Xe?.profile?.activeProfile??"default"}),{pinnedCollapsed:go,projectsCollapsed:Yo,cloudProjectsCollapsed:ni,chatsCollapsed:ai,savedForLaterCollapsed:ma,sidebarWidth:oi,sidebarResizing:Xo,diffPanelWidth:Qo,diffPanelResizing:er,togglePinnedCollapsed:ri,toggleProjectsCollapsed:Yn,toggleCloudProjectsCollapsed:ii,toggleChatsCollapsed:si,toggleSavedForLaterCollapsed:li,startSidebarResize:ci,startDiffPanelResize:di}=zF({connection:mt,preferences:Xe?.preferences,sidebarOpen:We,diffPanelExpanded:G,setBootstrap:pt,setError:_t}),{cloudProjectById:tr,linkedProjectByAppId:nr,localProjectById:Ra,mentionableSandboxApps:ui,selectedApp:bo,selectedCloudProject:Aa,selectedProject:Mn,selectedProjectLinkedApp:mi,selectedProjectLinkedOpenPondApp:ar,selectedSession:Zt,selectedSessionLinkedProject:vo,sidebarSessions:jn}=rH({bootstrap:Xe,codexHistorySessions:pn,selectedAppId:re,selectedProjectId:Ce,selectedSessionId:De,sessions:po}),Pa=Zt?.experience??rt;g.useEffect(()=>{MU(Pa)},[Pa]);const yo=g.useMemo(()=>$D(jn,Pa),[Pa,jn]),pa=XF(Kt,Bn),{chatMentionApps:So,connectedAppMentions:pi,pendingApproval:fi}=_H({bootstrap:Xe,connectedAppRows:ho,mentionableSandboxApps:ui,runtimeIndexes:pa,selectedApp:bo,selectedCloudProject:Aa,selectedProject:Mn,selectedSession:Zt,selectedSessionId:De}),{codexHistoryEvents:xo,setCodexHistoryEvents:or}=GH({connection:mt,selectedSessionId:De,selectedSessionLocallyActive:!!(De&&O.has(De)),selectedSessionStatus:Zt?.status,setCodexHistorySessions:ca,setError:_t}),{account:ko,accountPending:rr,accountSignedOut:wo,activeModel:ir,activeProvider:Xn,activeWorkspaceAppId:Ka,activeWorkspaceId:_o,activeWorkspaceKind:Ta,activeWorkspaceLocation:sr,appDefaults:fa,cloudLinked:lr,selectedCodexHistoryPending:hi,selectedSessionProjectId:Io,startMessage:cr,workspaceName:dr}=eH({bootstrap:Xe,draftModel:et,draftProvider:Je,selectedApp:bo,selectedAppId:re,selectedCloudProject:Aa,selectedProject:Mn,selectedSession:Zt,selectedSessionId:De,selectedSessionLinkedProject:vo}),ur=g.useMemo(()=>VU(Xe?.account??null),[Xe?.account]),gi=g.useMemo(()=>dm(Xe?.account??null),[Xe?.account]),mr=p4(gi),pr=g.useMemo(()=>GU(mr,fa.defaultTeamId),[fa.defaultTeamId,mr]),Ga=pr?.teamId??null,ha=Y5({connection:mt,teamId:Ga,currentUserId:ko?.profile?.id??null,refreshToken:Xe?.accountMeta.asOf??null}),bi=n4({connection:mt,teamId:Ga,applyBootstrapPayload:En,refreshDirectory:ha.refreshDirectory});o4({notification:ha.incomingNotification,dismiss:ha.dismissIncomingNotification,selectThread:ha.selectThread,setView:Le,showToast:Tt});const{communities:vi,sidebar:fr,view:yi}=u4({connection:mt,currentUserId:ko?.profile?.id??null,refreshToken:Xe?.accountMeta.asOf??null,setView:Le,showToast:Tt}),Qn=ha.aiThread?.conversationId??null,hr=Pe==="team"&&!!Qn&&U&&ce==="chat";g.useEffect(()=>{if(Pe==="team"){if(Qn){Qt("chat"),jt(!0);return}ce==="chat"&&jt(!1)}},[ce,jt,Qt,Qn,Pe]);const Ea=g.useCallback(()=>{if(Qn){if(hr){jt(!1);return}Qt("chat"),jt(!0)}},[jt,Qt,hr,Qn]),Co=g.useMemo(()=>aa(Mn,Xe?.cloudProjects??[]),[Xe?.cloudProjects,Mn]),Si=Zt?.provider==="codex"?$e:Zt?.openPondCommandAccessMode??$e,Vn=Ka,xi=_o,ki=Ta,wi=dr,{openPondActionCatalog:gr,selectedActionCatalog:yt}=p5({cloudProjectById:tr,cloudProjects:Xe?.cloudProjects??[],connection:mt,defaultTeamId:fa.defaultTeamId,accountScopeKey:ur,localProjects:Xe?.localProjects??[],profile:Xe?.profile,selectedCloudProject:Aa,selectedProject:Mn,reportError:_t}),{expandedProjectIds:Ot,expandProject:On,toggleProjectExpanded:Jt,setExpandedProjectIds:Wn}=f5({selectedProjectId:Ce});mH({activeWorkspaceId:_o,activeWorkspaceKind:Ta,appDispatch:t,connection:mt,expandProject:On,linkedProjectByAppId:nr,providerSettings:Xe?.providers??null,selectedAppId:re,selectedSession:Zt,selectedSessionId:De,selectedSessionProjectId:Io,setDiffPanelExpanded:mn,setDraftModel:xt,setDraftProvider:Xt,setError:_t,setSelectedAppId:ut,setSelectedProjectId:Vt,setSessions:da,setTerminalOpen:Sn,toast:w});const{changeCodexPermissionMode:Kn,changeCodexReasoningEffort:xc}=TH({connection:mt,setBootstrap:pt,setCodexPermissionMode:Pt,setCodexReasoningEffort:Rt,setError:_t}),{changeOpenPondCommandAccessMode:kc}=OB({connection:mt,selectedSession:Zt,setBootstrap:pt,setError:_t,setOpenPondCommandAccessMode:qn,setSessions:da}),wc=pH({connection:mt,setError:_t}),_i=g.useCallback(()=>{L(ot=>ot+1)},[]),Ms=hH({appDispatch:t,expandProject:On,linkedProjectByAppId:nr,requestComposerFocus:_i,onBeginNewChat:()=>{Y(null),Wt(ot=>ot==="development"?"work":ot)},setMentionedAppId:S}),_c=g.useCallback(ot=>{const Ee=gt("local",ot);t({type:"selectProject",projectId:Ee}),On(Ee)},[t,On]),{advanceAfterTurn:Ic,begin:Cc,bindSession:Rc,dismiss:Ac,handoff:Pc,prepareTurn:Tc,selectTask:js}=ZF({activeModel:ir,activeProvider:Xn,applyBootstrapPayload:En,beginNewChat:Ms,composerDraftStore:e,connection:mt,requestComposerFocus:_i,selectedLocalProjectId:Mn?.id??null,selectedSessionId:De,selectLocalProject:_c,setDraftModel:xt,setDraftProvider:Xt,setError:_t,view:Pe});LF({connection:mt,events:Kt,showToast:Tt}),qB({searchOpen:Se,sectionMenuOpen:xe,setSectionMenuOpen:de,setSearchOpen:Q,setQuery:X}),g.useEffect(()=>{P({})},[Xe?.server.id]);const{chatHistoryLoadStates:Ec,loadMoreSelectedChatHistory:Mc,selectedPagedSessionEvents:jc,selectedRuntimeIndexes:Os}=JF({approvals:Bn,codexHistoryEvents:xo,connection:mt,latestServerSequence:Xe?.eventWindow?.latestSequence,runtimeIndexes:pa,runtimeEventStore:wn,selectedSessionId:De,serverId:Xe?.server.id,setCodexHistoryEvents:or,setCodexHistorySessions:ca,setError:_t}),{activeSessions:Oc,archivedSessions:Nc,pinnedProjects:Ns,pinnedSessions:$s,savedForLaterSessions:Ds,pinnedFiles:$c,savedForLaterFiles:Dc,pinnedItems:Ii,projectRows:Ls,localProjectRows:Lc,visibleProjectRows:Ci,cloudProjectRows:zc,projectSessionRowsByProjectId:zs,childSessionRowsByParentId:Uc,sidebarProjectIdBySessionId:Ri,chatRows:Hc,visibleChatRows:Us,sessionEvents:qc,chatMessages:Hs,contextUsage:Bc,goalRuntime:Fc,subagentRuntime:qs}=NB({localProjects:Xe?.localProjects??[],cloudProjects:Xe?.cloudProjects??[],sessions:yo,runtimeIndexes:Os,appPreferences:cn,selectedSessionId:De,selectedProjectId:Ce,archivedChatsOpen:ae,projectsExpanded:ee,chatRowsVisibleCount:ye,sidebarFileBookmarks:y}),Ai=g.useCallback(ot=>{Wt(ot);const Ee=[...yo].filter(at=>ot==="work"?at.experience==="work"||at.experience==="development":at.experience===ot).sort((at,ct)=>ct.updatedAt.localeCompare(at.updatedAt))[0]??[...jn].filter(at=>at.experience===ot).sort((at,ct)=>ct.updatedAt.localeCompare(at.updatedAt))[0]??null;if(Ee)t({type:"selectSession",sessionId:Ee.id,appId:ot!=="chat"?Ee.appId:null,projectId:ot!=="chat"?Ri[Ee.id]??null:null});else if(t({type:"beginNewChat",appId:null}),ot==="chat"&&Xn==="codex"){const at=om(Xe?.providers,{enabledOnly:!0}).find(ct=>ct.value!=="codex")?.value??Uo;Xt(at),xt(Ml(at,Xe?.providers)??ns)}ot==="chat"&&(Sn(!1),mn(!1),Qt("home")),Le("chat")},[t,Xn,Xe?.providers,yo,mn,Wt,xt,Xt,Qt,Sn,Le,Ri,jn]),Vc=g.useCallback(ot=>{const Ee=e.getSnapshot();if(Wt(ot),(De||re||Ce)&&(t({type:"beginNewChat",appId:null}),Ee&&e.set(Ee)),ot==="chat"&&Xn==="codex"){const at=om(Xe?.providers,{enabledOnly:!0}).find(ct=>ct.value!=="codex")?.value??Uo;Xt(at),xt(Ml(at,Xe?.providers)??ns)}ot==="chat"&&(Sn(!1),mn(!1),Qt("home")),Le("chat")},[Xn,t,Xe?.providers,e,re,Ce,De,mn,Wt,xt,Xt,Qt,Sn,Le]),{pendingChatUserMessages:Wc,recordPendingChatUserMessage:Kc,visibleChatMessages:Gc}=PB({chatMessages:Hs,runtimeIndexes:Os,selectedSessionId:De}),Za=g.useMemo(()=>KD({selectedAppId:re,selectedProjectId:Ce,selectedSessionId:De}),[re,Ce,De]),Bs=g.useRef(null);g.useEffect(()=>{const ot=Bs.current;Bs.current=Za,!(!ot||ot.kind!=="draft"||Za.kind!=="session")&&(ds(ot,Za)||l(Ee=>{const at=GD({tabs:Ee,previousScope:ot,activeScope:Za});return at.some((on,ga)=>on!==Ee[ga])?at:Ee}))},[Za]);const Zc=g.useMemo(()=>ZD(s),[s]),{goalRuntime:Jc,runningSessionIds:Yc,selectedSessionRunning:Xc,sidebarGoalRuntimeBySessionId:Qc,sidebarSubagentRuntimeBySessionId:Fs}=HB({codexHistoryEvents:xo,codexHistorySessions:pn,connection:mt,expandedProjectIds:Ot,goalRuntime:Fc,locallyActiveCodexHistorySessionIds:O,pinnedSessions:$s,savedForLaterSessions:Ds,projectSessionRowsByProjectId:zs,rightChatHistoryEvents:I,runtimeIndexes:pa,selectedSession:Zt,selectedSessionId:De,serverId:Xe?.server.id,setCodexHistorySessions:ca,sidebarSessions:jn,subagentRuntime:qs,visibleChatRows:Us,visibleProjectRows:Ci}),{dragItem:ed,pinnedPreviewKeys:Vs,startPinnedDrag:Pi,clearSidebarDrag:td,previewPinnedDrop:nd,commitPinnedDrop:Ti,commitPinnedPreviewDrop:Ei}=ZH({connection:mt,appPreferences:cn,sessions:jn,pinnedItems:Ii,setAppPreferences:Jn,setCodexHistorySessions:ca,setSessions:da,sidebarFileBookmarks:y,setSidebarFileBookmarks:k,setError:_t}),{clearTaskDrag:Mi,commitTaskDrop:ji,commitTaskPreviewDrop:ad,previewTaskDrop:Oi,startTaskDrag:Ni,taskDragSessionId:$i,taskPreviewSessionIds:Di}=JH({connection:mt,sessions:jn,setCodexHistorySessions:ca,setError:_t,setSessions:da}),{commandProjectRows:Li,contextWindowStatus:od,pinnedRows:rd,sidebarWorkspaceAppIds:id}=fH({activeProvider:Xn,contextCompaction:fa.contextCompaction,contextUsage:Bc,pinnedItems:Ii,pinnedPreviewKeys:Vs??[],pinnedProjects:Ns,projectRows:Ls,visibleProjectRows:Ci}),Ro=!!(Vn&&(Pe==="chat"||Pe==="labs")&&(Oe||U&&(ce==="changes"||ce==="goal"))),{workspaceStates:Ws,workspaceBusy:Ks,diffBusy:sd,visibleWorkspaceState:zi,visibleWorkspaceDiff:ld,rememberWorkspaceState:Gs,refreshWorkspace:cd,refreshWorkspaceDiff:Ao,setWorkspaceBusy:dd}=b5({connection:mt,activeWorkspaceAppId:Vn,view:Pe,shouldLoadWorkspaceDiff:Ro,sidebarWorkspaceAppIds:id,setError:_t});ie.current=Gs;const Ui=g.useCallback((ot=Vn)=>!ot||ot!==Vn||!Ro?Promise.resolve(null):Ao(ot),[Ao,Ro,Vn]),ud=g.useCallback(async(ot={})=>{!Vn||!Ro||await Ao(Vn,ot)},[Ao,Ro,Vn]),Zs=!1,md=!!(Zt?.provider==="codex"&&Zt.cwd&&!wa(Zt.workspaceKind)),pd=!!(zi&&!zi.initialized&&Ta!=="local_project"&&Xn!=="codex"&&!md&&!hi),fd=Ta==="local_project"&&!!Mn?.sandboxTemplate?.detected&&!Mn?.linkedOpenPondApp?.appId,[Js,br]=g.useState(null),[hd,rf]=g.useState(null),{projectTarget:gd,workspaceTarget:bd}=tH({accountPending:rr,accountSignedOut:wo,activeWorkspaceLocation:sr,bootstrap:Xe,busy:E,cloudLinked:lr,selectedCloudProject:Aa,selectedProject:Mn,selectedSession:Zt,pendingWorkspaceTarget:Js,workspaceStates:Ws,workspaceBusy:Ks});return g.useEffect(()=>{br(null)},[Zt?.id]),{composerDraftStore:e,appDispatch:t,pendingTerminalCommand:o,setPendingTerminalCommand:i,terminalTabs:s,setTerminalTabs:l,trainingDetailTasksetId:p,setTrainingDetailTasksetId:m,mentionedAppId:f,setMentionedAppId:S,cloudSetupDialog:R,setCloudSetupDialog:A,rightPanelTabRequest:$,setRightPanelTabRequest:z,workspaceDiffPanelViewState:D,setWorkspaceDiffPanelViewState:x,rightChatHistoryEvents:I,setRightChatHistoryEvents:P,locallyActiveCodexHistorySessionIds:O,setCodexHistoryTurnLocallyActive:F,mainComposerFocusRequestId:H,requestMainComposerFocus:_i,draftSubagentDelegationMode:V,setDraftSubagentDelegationMode:Y,confirmProjectAction:_e,projectConfirmDialog:fe,resolveProjectConfirmDialog:J,query:Me,searchOpen:Se,archivedChatsOpen:ae,sectionMenuOpen:xe,projectsExpanded:ee,cloudProjectsExpanded:ue,sidebarOpen:We,view:Pe,selectedAppId:re,selectedProjectId:Ce,selectedSessionId:De,draftProvider:Je,draftModel:et,draftExperience:rt,activeExperience:Pa,changeExperience:Ai,changeNewExperience:Vc,codexPermissionMode:Be,codexReasoningEffort:He,openPondCommandAccessMode:$e,busy:E,diffPanelOpen:U,diffPanelExpanded:G,rightPanelMode:ce,rightChatPanels:W,terminalOpen:me,settingsSection:he,newProjectDialogOpen:Ze,newProjectMode:qe,newProjectName:it,newProjectPath:nt,newProjectBusy:we,commitDialogOpen:Oe,commitMessage:d,commitIncludeUnstaged:M,commitNextStep:q,commitDraft:le,branchDialogOpen:N,branchDialogName:K,toast:w,error:j,labDetailNavigation:oe,setQuery:X,setSearchOpen:Q,setArchivedChatsOpen:pe,setSectionMenuOpen:de,setProjectsExpanded:ze,setCloudProjectsExpanded:Te,setChatRowsVisibleCount:Ne,setSidebarOpen:Ye,setView:Le,setSelectedAppId:ut,setSelectedProjectId:Vt,setSelectedSessionId:dn,setPrompt:un,setDraftProvider:Xt,setDraftModel:xt,setDraftExperience:Wt,setDiffPanelOpen:jt,setDiffPanelExpanded:mn,setRightPanelMode:Qt,setRightChatPanels:ln,setTerminalOpen:Sn,setSyncingWorkspaceAppId:Ia,setSettingsSection:qt,setNewProjectDialogOpen:xn,setNewProjectMode:lt,setNewProjectName:Bt,setNewProjectPath:te,setNewProjectBusy:Ke,setCommitDialogOpen:Ge,setCommitMessage:St,setCommitIncludeUnstaged:an,setCommitNextStep:Ca,setCommitDraft:kn,setBranchDialogOpen:Dt,setBranchDialogName:kt,setError:_t,showToast:Tt,appPreferences:cn,applyBootstrapPayload:En,approvals:Bn,bootstrap:Xe,connection:mt,events:Kt,runtimeEventStore:wn,sessions:po,startup:Fn,setAppPreferences:Jn,setCodexHistorySessions:ca,setEvents:fo,setSessions:da,training:Jo,pinnedCollapsed:go,projectsCollapsed:Yo,cloudProjectsCollapsed:ni,chatsCollapsed:ai,savedForLaterCollapsed:ma,sidebarWidth:oi,sidebarResizing:Xo,diffPanelWidth:Qo,diffPanelResizing:er,togglePinnedCollapsed:ri,toggleProjectsCollapsed:Yn,toggleCloudProjectsCollapsed:ii,toggleChatsCollapsed:si,toggleSavedForLaterCollapsed:li,startSidebarResize:ci,startDiffPanelResize:di,cloudProjectById:tr,localProjectById:Ra,selectedApp:bo,selectedCloudProject:Aa,selectedProject:Mn,selectedProjectLinkedApp:mi,selectedProjectLinkedOpenPondApp:ar,selectedSession:Zt,sidebarSessions:jn,runtimeIndexes:pa,chatMentionApps:So,connectedAppMentions:pi,pendingApproval:fi,codexHistoryEvents:xo,setCodexHistoryEvents:or,account:ko,accountPending:rr,accountSignedOut:wo,activeModel:ir,activeProvider:Xn,activeWorkspaceAppId:Ka,activeWorkspaceId:_o,activeWorkspaceKind:Ta,activeWorkspaceLocation:sr,appDefaults:fa,selectedSessionProjectId:Io,startMessage:cr,workspaceName:dr,accountScopeKey:ur,teamChatOrganization:pr,teamChatTeamId:Ga,teamChat:ha,publishTeamProfileAgent:bi,communities:vi,communitySidebar:fr,communityView:yi,teamAiThreadId:Qn,toggleTeamAiSidebar:Ea,selectedProjectConfirmedCloudProject:Co,activeOpenPondCommandAccessMode:Si,viewWorkspaceAppId:Vn,viewWorkspaceId:xi,viewWorkspaceKind:ki,viewWorkspaceName:wi,openPondActionCatalog:gr,selectedActionCatalog:yt,expandedProjectIds:Ot,expandProject:On,toggleProjectExpanded:Jt,setExpandedProjectIds:Wn,changeCodexPermissionMode:Kn,changeCodexReasoningEffort:xc,changeOpenPondCommandAccessMode:kc,resolveApproval:wc,beginNewChat:Ms,advanceTrainingModelChatAfterTurn:Ic,beginNewChatWithTrainingModel:Cc,bindTrainingModelChatSession:Rc,dismissTrainingChatHandoff:Ac,trainingChatHandoff:Pc,prepareTrainingModelChatTurn:Tc,selectTrainingChatTaskForComposer:js,chatHistoryLoadStates:Ec,loadMoreSelectedChatHistory:Mc,selectedPagedSessionEvents:jc,activeSessions:Oc,archivedSessions:Nc,pinnedSessions:$s,savedForLaterSessions:Ds,pinnedFiles:$c,savedForLaterFiles:Dc,sidebarFileBookmarks:y,setSidebarFileStatus:ua,projectRows:Ls,localProjectRows:Lc,visibleProjectRows:Ci,cloudProjectRows:zc,projectSessionRowsByProjectId:zs,childSessionRowsByParentId:Uc,sidebarProjectIdBySessionId:Ri,chatRows:Hc,visibleChatRows:Us,chatRowsVisibleCount:ye,sessionEvents:qc,chatMessages:Hs,goalRuntime:Jc,subagentRuntime:qs,pendingChatUserMessages:Wc,recordPendingChatUserMessage:Kc,visibleChatMessages:Gc,activeTerminalScope:Za,terminalSummaries:Zc,runningSessionIds:Yc,selectedSessionRunning:Xc,sidebarGoalRuntimeBySessionId:Qc,sidebarSubagentRuntimeBySessionId:Fs,taskDragSessionId:$i,taskPreviewSessionIds:Di,startTaskDrag:Ni,clearTaskDrag:Mi,previewTaskDrop:Oi,commitTaskDrop:ji,commitTaskPreviewDrop:ad,dragItem:ed,startPinnedDrag:Pi,clearSidebarDrag:td,previewPinnedDrop:nd,commitPinnedDrop:Ti,commitPinnedPreviewDrop:Ei,commandProjectRows:Li,contextWindowStatus:od,pinnedRows:rd,workspaceStates:Ws,workspaceBusy:Ks,diffBusy:sd,visibleWorkspaceState:zi,visibleWorkspaceDiff:ld,rememberWorkspaceState:Gs,refreshWorkspace:cd,refreshWorkspaceDiff:Ao,setWorkspaceBusy:dd,refreshWorkspaceDiffWhenNeeded:Ui,refreshVisibleWorkspaceDiff:ud,managedWorkspace:Zs,canSyncActiveWorkspace:pd,canPublishOpenPondProject:fd,pendingWorkspaceTarget:Js,setPendingWorkspaceTarget:br,pendingSidebarWorkspaceTarget:hd,setPendingSidebarWorkspaceTarget:rf,projectTarget:gd,workspaceTarget:bd}}const g4=/^(localhost|\[::1\]|127(?:\.\d{1,3}){3})(?::\d+)?(?:[/?#].*)?$/i,b4=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+(?:[:/?#].*)?$/i;function v4(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)?dl(n,new Set(["http:","https:"])):/^file:\/\//i.test(n)?t.explicitFile?dl(n,new Set(["file:"])):null:g4.test(n)?dl(`http://${n}`,new Set(["http:"])):b4.test(n)?dl(`https://${n}`,new Set(["https:"])):null}function dl(e,t){try{const n=new URL(e);return t.has(n.protocol)?n.toString():null}catch{return null}}async function y4(e){const t=v4(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 S4="openpond-coding-core-v1",x4="feature";function xm(e){const t=new URL("/sandboxes",nf(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",x4),t.searchParams.set("runtimeProfileId",S4),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 SV(e){const t=e.organizationSlug?.trim(),n=t?`/sandboxes/${encodeURIComponent(t)}/billing`:"/sandboxes/billing",a=new URL(n,nf(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)}`,nf(e.accountBaseUrl)).toString()}function nf(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 k4({account:e,browserConversationId:t,cloudProjectById:n,cloudProjects:a,diffPanelOpen:o,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(o&&i==="changes"){l(!1);return}y()},[o,i,l,y]),R=g.useCallback(()=>{S("browser"),l(!0)},[l,S]),A=g.useCallback(()=>{S("goal"),l(!0)},[l,S]),$=g.useCallback((I,P)=>{y4({conversationId:t,href:I,explicitFile:P?.explicitFile,newTab:P?.newTab}).then(O=>{O&&R()})},[t,R]),z=g.useCallback(()=>{m("cloud"),f(""),p(!0)},[p,m,f]),D=g.useCallback(I=>{const P=n.get(I);P&&$(xm({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,$]);return{createCloudEnvironmentFromSidebar:g.useCallback(()=>{const I=s?.startsWith("cloud:")?s.slice(6):a[0]?.id??null;if(I){D(I);return}z()},[a,z,s,D]),openCloudProjectDialog:z,openUrlInBrowserPanel:$,showBrowserPanel:R,showChangesPanel:y,showGoalSidebarTab:A,toggleChangesPanel:k}}function w4(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 _4({browserConversationId:e,sessionIds:t,onOpenSession:n,onShowBrowserPanel:a}){g.useEffect(()=>window.openpond?.browser?.onRevealRequest?.(i=>{const s=w4({currentConversationId:e,requestConversationId:i.conversationId,sessionIds:t});s.reveal&&(s.sessionIdToOpen&&n(s.sessionIdToOpen),a())}),[e,n,a,t])}const I4="chat",C4=["help me","please","can you","could you","make","create","build"],R4=new Set(["a","an","and","for","from","i","me","my","of","our","please","produce","summary","the","to","with"]);function sb(e){const t=Eu(e.label);if(t&&!km(t))return lb(t);const n=Eu(e.name);if(n&&!km(n))return lb(n);const a=Eu(e.actionId)?.replace(/\.chat$/i,"")??"";return A4(a||t||"Profile Agent")}function km(e){return e.trim().toLowerCase()===I4}function A4(e){const t=P4(e.replace(/\.chat$/i,"").replace(/[._-]+/g," ").replace(/\s+/g," ").trim()),a=t.toLowerCase().split(/\s+/).map(o=>o.replace(/[^a-z0-9]/g,"")).filter(o=>o&&!R4.has(o)).slice(0,3);return gk(a.length?a.join(" "):t||e)}function lb(e){return gk(e).split(/\s+/).slice(0,4).join(" ")}function P4(e){let t=e.trim();for(const n of C4)if(t.toLowerCase().startsWith(`${n} `)){t=t.slice(n.length).trim();break}return t}function Eu(e){return typeof e=="string"&&e.trim()?e.trim():null}function gk(e){return e.replace(/[._-]+/g," ").replace(/\s+/g," ").trim().replace(/\b[a-z0-9]/gi,t=>t.toUpperCase())}const T4="openpond-profile-action";function E4(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ul(e){return typeof e=="string"&&e.trim()?e.trim():null}function M4(e){const t=E4(e.implementation);if(t?.type!==T4)return null;const n=ul(t.actionId)??e.id;if(e.sourceActionId!=="chat"&&n!=="chat"&&!n.endsWith(".chat"))return null;const a=ul(e.label);if(a&&!km(a))return sb({label:a,description:e.description});const o=ul(t.agentName)??ul(e.name);return sb({actionId:n,description:e.description,name:o})}function j4(e){const t=M4(e);return t||e.label?.trim()||e.name?.trim()||e.id}function bk(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 O4=new Set(["action","agent","chat","customer","default","filter","items","open","openpond","profile","run","summarize","track","workflow"]);function vk(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Wr(e){return typeof e=="string"&&e.trim()?e.trim():null}function Nr(e,t,n={}){const a=Wr(t)?bn(String(t)):"";a&&(!n.generic&&O4.has(a)||e.add(a))}function ml(e,t){const n=Wr(t);if(n)for(const a of n.split(/[.:/\\\s]+/g))Nr(e,a)}function N4(e,t){const n=Wr(t);if(n)for(const a of n.split(/[^A-Za-z0-9_-]+/g))a.length<4||Nr(e,a)}function yk(e){const t=new Set,n=vk(e.implementation),a=Wr(n?.actionId);return Nr(t,e.id,{generic:!0}),ml(t,e.id),Nr(t,a,{generic:!0}),ml(t,a),Nr(t,e.name,{generic:!0}),ml(t,e.name),Nr(t,e.label,{generic:!0}),ml(t,e.label),N4(t,e.description),t}function $4(e){const t=vk(e.implementation);return[e.id,e.name??"",e.label??"",e.description??"",Wr(t?.actionId)??"",Wr(t?.agentName)??"",bk(e),...Array.from(yk(e))].join(" ").toLowerCase()}function xV(e,t,n=8){const a=bn(t);return e.length===0?[]:e.filter(o=>a?$4(o).includes(a):!0).slice(0,n)}function D4(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>bn(t[1]??"")).filter(Boolean)}function L4(e,t){const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return e.replace(new RegExp(`(^|\\s)@${n}(?=\\s|$)`,"g"),"$1").replace(/\s+/g," ").trim()}function z4(e,t){const n=D4(e);if(n.length===0||t.length===0)return null;const a=new Map;for(const i of n)for(const s of t)yk(s).has(i)&&a.set(s.id,{action:s,mention:i});if(a.size!==1)return null;const o=Array.from(a.values())[0];return{action:o.action,mention:o.mention,prompt:L4(e,o.mention)}}function kV(e){return j4(e)}function wV(e){return e.description||bk(e)}const af=[{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 U4(e){return af.filter(t=>t.id!=="goal"||e==="codex")}function Sk(e,t){return t==="work"?e.id==="submit-issue":t==="chat"?e.id!=="sync-cloud":!0}function _V(e,t){return U4(e).filter(n=>Sk(n,t))}const H4=new Set(af.map(e=>e.id));function IV(e){return e.subcommands?.length?e.subcommands.join(", "):e.description}function q4(e){return[e.id,e.command,e.label,e.description].join(" ")}function B4(e){return(e.subcommands??[]).flatMap(t=>[t,`${e.id} ${t}`,`${e.command} ${t}`]).join(" ")}function F4(e){const t=/^\/([a-z][a-z0-9_-]*)(?:\s+([\s\S]*))?$/.exec(e.trim());if(!t)return null;const n=t[1];return H4.has(n)?{command:n,args:t[2]?.trim()??""}:null}function V4(e){const t=e.trim();if(!t.startsWith("!"))return null;const n=t.slice(1).trim();return n?{command:n}:null}function CV({commands:e=af,prompt:t,limit:n=10}){if(!t.startsWith("/"))return[];const a=t.slice(1).trim().toLowerCase();if(!a)return e.slice(0,n);const o=e.filter(l=>l.id.startsWith(a));if(o.length>0)return o.slice(0,n);const i=e.filter(l=>q4(l).toLowerCase().includes(a));return(i.length>0?i:e.filter(l=>B4(l).toLowerCase().includes(a))).slice(0,n)}function RV(e){return e==="owner"?"Owner":e==="admin"?"Admin":"Member"}function yc(e){return e?.role==="owner"||e?.role==="admin"}function AV(e){const t=Sc(e.organizations,e.defaultTeamId),n=yc(t),a=e.localProject??null;if(!a)return W4("Open a local project to set up an Agent.");const o=K4(a,e.projects),i=G4(a,o,e.agents),s=!!a.sandboxTemplate?.detected,l=t&&!n?"Ask an owner or admin to connect this project.":null;return s?o?Z4(a,o)?pl({state:"needs_sync",actionLabel:"Sync Project",project:o,agent:i,canManage:n,actionBlockedReason:l}):i?{state:"ready",actionLabel:"Run Agent",canAct:!0,reason:null,project:o,agent:i}:pl({state:"needs_agent",actionLabel:"Create Agent",project:o,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:o,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 W4(e){return{state:"blocked",actionLabel:"Ask admin",canAct:!1,reason:e,project:null,agent:null}}function Sc(e,t){if(e.length===0)return null;const n=t?.trim()??"";if(n){const a=e.find(o=>o.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 K4(e,t){const n=e.linkedSandboxProject;return n?.projectId?t.find(a=>a.id===n.projectId)??null:null}function G4(e,t,n){if(!t)return null;const a=e.preferredSandboxAgentId;if(a){const o=n.find(i=>i.id===a&&i.projectId===t.id);if(o)return o}return n.find(o=>o.projectId===t.id)??null}function Z4(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 To=e=>e.slice(0,2e4);function J4({model:e,provider:t,providerSettings:n}){return{model:Lp(t,e,n),modelRef:la(t,e,n)}}function Y4(e,t){return e.some(n=>n.id===t.id)?e:[...e,t]}function X4(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 Q4(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 cb({action:e,prompt:t,runPayload:n,sessionId:a}){const o=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:o,source:"chat_action",args:{prompt:t}},{id:`${i}_result`,sessionId:a,turnId:i,name:"workspace_action_result",timestamp:n.run.updatedAt??o,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 e6({applyBootstrapPayload:e,connection:t,codexPermissionMode:n,codexReasoningEffort:a,openPondCommandAccessMode:o,draftModel:i,draftProvider:s,experience:l,expandProject:p,ensureCloudSessionReady:m,getPrompt:f,bootstrap:S,chatMessages:y,apps:k,connectedAppMentions:R,mentionedAppId:A,refreshWorkspace:$,refreshWorkspaceDiff:z,selectedApp:D,selectedActionCatalog:x,openPondActionCatalog:I,cloudProjects:P,accountScopeKey:O,selectedCloudProject:T,selectedProject:F,selectedProjectLinkedOpenPondApp:H,selectedSession:L,workspaceTarget:V,subagentDelegationMode:Y,setDraftModel:ie,setDraftProvider:_e,setError:fe,setPrompt:J,setMentionedAppId:Me,setCodexHistoryEvents:Se,setCodexHistorySessions:ae,onCodexHistoryTurnActivityChange:xe,onCodexHistoryTurnPayload:ee,onPendingUserMessage:ue,setEvents:ye,setSelectedAppId:We,setSelectedProjectId:Pe,setSelectedSessionId:re,setSessions:Ce,setView:De,setWorkspaceBusy:Je}){const et=g.useRef(new Set),rt=S?.providers??null;function Be(N,K){return N==="codex"?void 0:K}function He(N){return!!(N&&N.provider!=="codex"&&(N.workspaceKind==="local_project"&&N.cwd?.trim()||(N.workspaceKind==="sandbox"||N.workspaceKind==="sandbox_template"||N.workspaceKind==="sandbox_app")&&N.workspaceId))}function $e(N){_e(N),ie(K=>uo(N,K,rt)),De("chat")}async function E(N,K){return(tk(K,O)??await Jp({teamId:K,accountKey:O,fetchAgents:async oe=>(await Z.listSandboxAgents(t,{teamId:oe})).agents})).find(oe=>oe.projectId===N)??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 N=await Z.organizations(t),K=Sc(N.organizations.map(pc).filter(w=>!!w).filter(w=>w.status==="active"),S?.preferences.defaultTeamId??null);if(!K)throw new Error("Add an OpenPond account before syncing a Project to Cloud.");if(!yc(K))throw new Error(`You need owner or admin access to create projects in ${K.displayName}.`);return K}async function G(N){if(!t)return!1;const K=F;if(!K)throw new Error("Select a local Project before using /sync-cloud.");const w=await U(),j=K.linkedSandboxProject?.defaultBranch?.trim()||"main",oe=gt("local",K.id),X=aa(K,P),Q=await Z.createSession(t,{provider:"openpond",modelRef:la("openpond",hs,rt),openPondCommandAccessMode:Be("openpond",o),appId:null,appName:null,workspaceKind:"local_project",workspaceId:K.id,workspaceName:K.name,localProjectId:K.id,cloudProjectId:X?.id??null,cloudTeamId:X?.teamId??null,cwd:K.workspacePath,title:`Sync ${K.name} to Cloud`});Ce(pe=>[Q,...pe]),N.onSessionCreated?.(Q),N.selectSession&&(re(Q.id),Pe(oe),We(null),De("chat"),p(oe)),N.clearPromptForTurn(),Je(!0);try{const pe=await Z.uploadLocalProjectCloudSource(t,K.id,{teamId:w.teamId,projectName:K.name,branch:j,chatSessionId:Q.id,displayPrompt:N.displayPrompt});return e(pe.bootstrap),p(oe),p(gt("cloud",pe.project.id)),!0}catch(pe){const de=await Z.bootstrap(t).catch(()=>null);throw de&&e(de),pe}finally{Je(!1)}}async function ce(N){if(!t||N.providerForTurn==="codex"||N.selectedSessionForTurn?.provider==="codex")return!1;let K=He(N.selectedSessionForTurn)?N.selectedSessionForTurn:null;if(!K&&N.selectedSessionForTurn)throw new Error("Select a project to use this.");if(!K)if(T){const j=gt("cloud",T.id),oe=N.providerForTurn;K=await Z.createSession(t,{provider:oe,modelRef:la(oe,N.modelForTurnValue,rt),openPondCommandAccessMode:Be(oe,N.openPondCommandAccessModeForTurn),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:T.id,workspaceName:T.name,localProjectId:null,cloudProjectId:T.id,cloudTeamId:T.teamId,cwd:null,autoTitlePrompt:To(N.command)}),Ce(X=>[K,...X]),N.onSessionCreated?.(K),N.selectSession&&(re(K.id),Pe(j),We(null),De("chat"),p(j))}else{const j=F;if(!j)throw new Error("Select a project to use this.");const oe=aa(j,P),X=gt("local",j.id),Q=N.providerForTurn;K=await Z.createSession(t,{provider:Q,modelRef:la(Q,N.modelForTurnValue,rt),openPondCommandAccessMode:Be(Q,N.openPondCommandAccessModeForTurn),appId:null,appName:null,workspaceKind:"local_project",workspaceId:j.id,workspaceName:j.name,localProjectId:j.id,cloudProjectId:oe?.id??null,cloudTeamId:oe?.teamId??null,cwd:j.workspacePath,autoTitlePrompt:To(N.command)}),Ce(pe=>[K,...pe]),N.onSessionCreated?.(K),N.selectSession&&(re(K.id),Pe(X),We(null),De("chat"),p(X))}if(!K)throw new Error("Select a project to use this.");N.clearPromptForTurn();const w=await Z.runSessionCommand(t,K.id,{command:N.command,cwd:K.cwd});return Ce(j=>Gi(j,w.session)),ye(j=>Na(j,w.events)),!0}async function W(N=[],K=null,w,j={}){const oe=w??f();let X=oe.trim()||(N.length>0?"Please review the attached files.":"");if(!t||!X)return!1;const Q=j.displayPrompt?.trim()||X,pe=j.provider??s,de=j.model??i,ze=j.openPondCommandAccessMode??o,Te=j.session!==void 0,Ne=Te?j.session??null:L,Ye=j.experience??Ne?.experience??l,Le=Ye==="development"||Ye==="work"&&(Ne?.workspaceKind==="local_project"||!!Ne?.localProjectId||!!Ne?.cloudProjectId||!Te&&!!(F||T||D||V==="hybrid"||V==="local")),ut=Te||!Le?null:D,Vt=Te||!Le?null:F,dn=Te||!Le?null:T,un=Te||!Le?null:H,Xt=!Te&&Le&&V==="hybrid",xt=j.selectSession??!0,Wt=j.chatMessages??y,Pt=j.session!==void 0?null:A,Rt=j.clearPrompt===void 0?()=>{J(""),Me(null)}:j.clearPrompt,qn=K?null:z4(X,x),jt=K??qn?.action??null,mn=qn?.prompt||X,Qt=Le&&!jt?V4(X):null,ln=jt||Qt?null:F4(X),Sn=ln&&!Sk({id:ln.command},Ye)?ln:null,Ia=j.usageAttribution??(ln?{surface:"chat",workflowKind:"slash_command",commandName:`/${ln.command}`,commandSource:"prompt_parse"}:void 0);fe(null);let qt=null,xn=null;try{if(!Le&&pe==="codex")throw new Error("The Codex provider requires repository-aware Work.");if(Sn)throw new Error(`/${Sn.command} isn't available in ${Ye}.`);if(Qt&&pe!=="codex"&&Ne?.provider!=="codex"){if(N.length>0)throw new Error("Direct commands do not accept attachments.");return await ce({command:Qt.command,clearPromptForTurn:Rt,modelForTurnValue:de,onSessionCreated:j.onSessionCreated,openPondCommandAccessModeForTurn:ze,providerForTurn:pe,selectedSessionForTurn:Ne,selectSession:xt})}if(!Te&&ln?.command==="sync-cloud")return await G({clearPromptForTurn:Rt,displayPrompt:Q,onSessionCreated:j.onSessionCreated,selectSession:xt});if(jt){const kt=o5(jt);if(kt){let Xe=Ne;if(!Xe||Xe.cloudProjectId!==kt.projectId){Xe=await Z.createSession(t,{provider:"openpond",modelRef:la("openpond",de,rt),openPondCommandAccessMode:Be("openpond",ze),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:kt.projectId,workspaceName:kt.projectName??kt.agentName,localProjectId:null,cloudProjectId:kt.projectId,cloudTeamId:kt.teamId,cwd:null,autoTitlePrompt:To(Q)}),Ce(wn=>[Xe,...wn]),j.onSessionCreated?.(Xe),xt&&re(Xe.id);const Kt=gt("cloud",kt.projectId);xt&&Pe(Kt),xt&&p(Kt)}const pn=await Z.runSandboxAgent(t,kt.agentId,c5({agent:kt,attachments:N,displayPrompt:Q,prompt:mn})),mt=await Z.bootstrap(t);return e(mt),Rt(),ye(Kt=>Na(Kt,cb({action:jt,prompt:Q,runPayload:pn,sessionId:Xe.id}))),!0}const Lt=ef(jt);if(Lt){let Xe=Ne;(!Xe||Xe.provider!=="openpond")&&(Xe=await Z.createSession(t,{provider:"openpond",modelRef:la("openpond",de,rt),openPondCommandAccessMode:Be("openpond",ze),appId:null,appName:null,workspaceId:null,workspaceName:"OpenPond profile",localProjectId:null,cloudProjectId:null,cloudTeamId:null,cwd:null,autoTitlePrompt:To(Q)}),Ce(mt=>[Xe,...mt]),j.onSessionCreated?.(Xe),xt&&re(Xe.id)),await Z.runProfileAction(t,s5({action:Lt,attachments:N,displayPrompt:Q,prompt:mn,sessionId:Xe.id}));const pn=await Z.bootstrap(t);return e(pn),Rt(),!0}const vt=ik({cloudProjects:P,selectedCloudProject:T,selectedProject:F});if(!vt)throw new Error("Select a Project linked to an OpenPond Cloud Project before running an action.");let _t=Ne;(!_t||_t.cloudProjectId!==vt.id)&&(_t=await Z.createSession(t,{provider:"openpond",modelRef:la("openpond",de,rt),openPondCommandAccessMode:Be("openpond",ze),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:vt.id,workspaceName:vt.name,localProjectId:vt.localProjectId,cloudProjectId:vt.id,cloudTeamId:vt.teamId,cwd:null,autoTitlePrompt:To(Q)}),Ce(Xe=>[_t,...Xe]),j.onSessionCreated?.(_t),xt&&(re(_t.id),Pe(vt.selectionKey),p(vt.selectionKey)));const Tt=await E(vt.id,vt.teamId);if(!Tt)throw new Error("No OpenPond Agent is available for this Project.");Rt();const cn=await Z.runSandboxAgent(t,Tt.id,l5({action:jt,attachments:N,displayPrompt:Q,prompt:mn,teamId:vt.teamId})),En=await Z.bootstrap(t);return e(En),ye(Xe=>Na(Xe,cb({action:jt,prompt:Q,runPayload:cn,sessionId:_t.id}))),!0}let lt=Ne;if(lt&&Mt(lt.id)){xn=wg({afterMessageId:Wt.at(-1)?.id??null,attachments:N,content:X,sessionId:lt.id}),Rt(),qt=lt.id,et.current.add(qt),ue?.(xn),xe?.(qt,!0);const kt=X4(lt.id,X),Lt=Tt=>{(!Te||L?.id===lt.id)&&Se(cn=>Y4(cn,Tt)),j.onCodexHistoryOptimisticEvent?.(Tt)};Lt(kt),ae(Tt=>Tt.map(cn=>cn.id===lt.id?{...cn,status:"active"}:cn));const vt=await Z.sendCodexHistoryTurn(t,lt.id,{prompt:X,attachments:N.length>0?N:void 0,model:Lp("codex",de,rt),modelRef:la("codex",de,rt),...Hh(n),codexPermissionMode:n,codexReasoningEffort:a}).catch(Tt=>{throw Lt(Q4(kt,Tt)),Tt});(!Te||L?.id===lt.id)&&Se(Tt=>Na(Tt,vt.events)),ae(Tt=>Gi(Tt,vt.session)),ee?.(vt);const _t=await Z.bootstrap(t);return e(_t),!0}const te=(Pt?k.find(kt=>kt.id===Pt&&nH(oe,kt)&&kt.sandbox)??null:null)??aH(oe,Sx(k)),Ke=Ye==="chat"?[]:vH(oe,R).map(kt=>kt.ref);if(!lt){const kt=un?.appId??ut?.id??null,Lt=un?.appName??ut?.name??null,vt=dn,_t=Te?null:aa(Vt,P),Tt=Xt?fx({cloudProjects:P,selectedCloudProject:vt,selectedProject:Vt}):null;if(Tt?.kind==="missing_cloud_project")throw new Error(Tt.message);const cn=Tt?.kind==="ready",En=cn?pe:vt?"openpond":pe,Xe=la(En,de,rt),pn=Be(En,ze),mt=cn?hx({modelRef:Xe,provider:En,target:Tt,title:X.slice(0,64)}):null;lt=await Z.createSession(t,mt?{...mt,subagentDelegationMode:Y,metadata:{...mt.metadata,...j.sessionMetadata??{}},...pn?{openPondCommandAccessMode:pn}:{},autoTitlePrompt:To(X)}:{experience:Ye,provider:En,modelRef:Xe,subagentDelegationMode:Y,...pn?{openPondCommandAccessMode:pn}:{},appId:kt,appName:Lt,workspaceKind:vt?"sandbox":Vt?"local_project":ut?"sandbox_app":void 0,workspaceId:Vt?.id??(ut?kt:void 0),workspaceName:vt?.name??Vt?.name??Lt,localProjectId:Vt?.id??null,cloudProjectId:vt?.id??_t?.id??null,cloudTeamId:vt?.teamId??_t?.teamId??null,...!vt&&!Vt&&!ut&&V==="local"?{metadata:{...NU(),...j.sessionMetadata??{}}}:{cwd:Vt?Vt.workspacePath:null,...j.sessionMetadata?{metadata:j.sessionMetadata}:{}},autoTitlePrompt:To(X)}),Ce(Kt=>[lt,...Kt]),j.onSessionCreated?.(lt),xt&&(re(lt.id),vt&&Pe(gt("cloud",vt.id)),lt.workspaceKind==="local_project"&&lt.workspaceId&&p(gt("local",lt.workspaceId)),vt&&p(gt("cloud",vt.id)))}if(db(lt)&&wa(lt.workspaceKind)&&lt.provider!=="openpond"&&!_a(lt))throw new Error("Cloud workspaces use OpenPond Chat. Switch to Local to use local providers.");if(db(lt)&&wa(lt.workspaceKind)&&m)try{lt=await m(lt)}catch(kt){const Lt=kt instanceof Error?kt.message:String(kt);throw await Z.recordPreflightTurnFailure(t,lt.id,{prompt:X,error:Lt,target:_a(lt)?"hybrid_sandbox":"cloud_workspace"}).then(e).catch(()=>{}),kt}xn=wg({afterMessageId:Wt.at(-1)?.id??null,attachments:N,content:X,sessionId:lt.id}),Rt(),qt=lt.id,et.current.add(qt),ue?.(xn),Ce(kt=>kt.map(Lt=>Lt.id===qt?{...Lt,status:"active"}:Lt));const Ge=pe,St=J4({provider:Ge,model:de,providerSettings:rt}),an=ND(Ge,St.model??de,rt),Ca=Ge==="codex"?Hh(n):{approvalPolicy:"on-request",sandbox:"workspace-write"};await Z.sendTurn(t,lt.id,{prompt:X,metadata:j.turnMetadata,attachments:N.length>0?N:void 0,mentionedAppIds:te?[te.id]:void 0,mentionedConnectedApps:Ke.length>0?Ke:void 0,openPondActionCatalog:I.length>0?I:void 0,usageAttribution:Ia,...St,...Ca,codexPermissionMode:Ge==="codex"?n:"default",codexReasoningEffort:an?a:void 0});const kn=await Z.bootstrap(t);e(kn);const Dt=lt.workspaceId??lt.appId;return Dt&&lt.workspaceKind!=="sandbox"&&lt.workspaceKind!=="sandbox_template"&&$(Dt,!1).then(kt=>{kt?.initialized&&z(Dt)}),!0}catch(lt){return fe(lt instanceof Error?lt.message:String(lt)),!1}finally{qt&&et.current.delete(qt),qt&&Mt(qt)&&xe?.(qt,!1),qt&&(Mt(qt)?ae(lt=>lt.map(Bt=>Bt.id===qt&&Bt.status==="active"?{...Bt,status:"idle"}:Bt)):Ce(lt=>lt.map(Bt=>Bt.id===qt&&Bt.status==="active"?{...Bt,status:"idle"}:Bt)))}}async function me(N){const K=et.current.values().next().value??null,w=N??L?.id??K;if(!t||!w)return!1;if(fe(null),Mt(w))try{const j=await Z.interruptCodexHistoryTurn(t,w);if(!j.interrupted){if(j.reason==="no_active_openpond_turn"){const X=await Z.codexHistoryThread(t,w,{tail:!0}),Q={...X.session,status:"idle"};return L?.id===w&&Se(pe=>Na(pe,X.events)),ae(pe=>Gi(pe,Q)),fe("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 fe("This Codex history turn is still starting. Try stopping it again in a moment."),!1}const oe=await Z.codexHistoryThread(t,w,{tail:!0});return L?.id===w&&Se(X=>Na(X,oe.events)),ae(X=>Gi(X,oe.session)),!0}catch(j){const oe=j instanceof Error?j.message:String(j);return fe(oe==="Not found"?"OpenPond could not find this Codex history session, so it cannot interrupt it here.":oe),!1}try{await Z.interruptTurn(t,w);const j=await Z.bootstrap(t);return e(j),!0}catch(j){return fe(j instanceof Error?j.message:String(j)),!1}}async function he(N,K){if(!t){fe("OpenPond App server is not connected.");return}fe(null),await Z.applyCreateImproveAction(t,N.id,{...K,runId:N.id,expectedRevision:N.revision,actionId:`web:${K.type}:${crypto.randomUUID()}`});const w=await Z.bootstrap(t);e(w)}async function Ze(N){await he(N.run,{type:"approve_plan"})}async function qe(N){await he(N.run,{type:"cancel",reason:null})}async function it(N,K){await he(N.run,{type:"revise_plan",revision:K})}async function nt(N,K,w){await he(N.run,{type:"answer_question",questionId:K,value:w})}async function we(N){await he(N.run,{type:"pause"})}async function Oe(N){await he(N.run,{type:"resume"})}async function d(N,K){await he(N.run,{type:"open_pull_request",candidateId:K})}async function M(N,K){await he(N.run,{type:"apply_candidate",candidateId:K})}async function q(N,K){await he(N.run,{type:"reject_candidate",candidateId:K,reason:null})}async function le(N,K){await he(N.run,{type:"reconcile_pull_request",candidateId:K})}return{answerCreateImproveQuestion:nt,approveCreateImproveRun:Ze,applyCreateImproveCandidate:M,cancelCreateImproveRun:qe,changeDraftProvider:$e,openCreateImprovePullRequest:d,pauseCreateImproveRun:we,reconcileCreateImprovePullRequest:le,rejectCreateImproveCandidate:q,resumeCreateImproveRun:Oe,reviseCreateImproveRun:it,sendPrompt:W,stopTurn:me}}function db(e){return e.experience==="development"||e.experience==="work"&&(e.workspaceKind==="local_project"||!!e.localProjectId||!!e.cloudProjectId||e.metadata?.workspaceTarget==="local")}async function t6({branch:e,connection:t,session:n}){if(!wa(n.workspaceKind))return{sandbox:null,session:n,status:"already_running"};const a=await Z.ensureCloudWorkspaceReady(t,n.id,{branch:e,surface:"desktop"});return{bootstrap:await Z.bootstrap(t),output:a.output,sandbox:null,session:a.session,status:a.status}}function n6(e){return _a(e)?"Preparing Hybrid sandbox...":"Starting Cloud workspace..."}function a6(e,t){if(e==="already_running")return null;const n=_a(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 o6(e,t){return!e.cloudProjectId||!e.cloudTeamId?!0:t.some(n=>n.id===e.cloudProjectId&&n.teamId===e.cloudTeamId)}function r6({applyBootstrapPayload:e,cloudProjects:t,connection:n,localProjectById:a,selectedCloudProject:o,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&&!o6(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(n6(m),"info"),s(!0);try{const S=await t6({branch:i?.linkedSandboxProject?.defaultBranch??o?.defaultBranch??p?.currentBranch??null,connection:n,localProject:f,session:m,source:_a(m)?"openpond-app-hybrid-chat-preflight":"openpond-app-cloud-chat-preflight"});S.bootstrap&&e(S.bootstrap);const y=a6(S.status,m);return y&&l(y,"success"),S.session}finally{s(!1)}},[e,t,n,a,o,i,s,l,p?.currentBranch])}function i6(){return{diffPanelOpen:!1,diffPanelExpanded:!1,rightPanelMode:"changes",rightChatPanels:[]}}function s6(e){return e.keepOpen?l6():i6()}function l6(){return{diffPanelOpen:!0,diffPanelExpanded:!1,rightPanelMode:"home",rightChatPanels:[]}}function c6(e){return{diffPanelOpen:e.diffPanelOpen,diffPanelExpanded:e.diffPanelExpanded,rightPanelMode:e.rightPanelMode,rightChatPanels:e.rightChatPanels}}function ub(e){return{...e,rightChatPanels:e.rightChatPanels.map(t=>({...t}))}}function d6(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 o=t.rightChatPanels[a];return!!(o&&n.id===o.id&&n.activationVersion===o.activationVersion&&n.sessionId===o.sessionId&&n.prompt===o.prompt&&n.provider===o.provider&&n.model===o.model&&n.scrollTop===o.scrollTop&&n.stickyToBottom===o.stickyToBottom)})}function u6(e){return`${e.conversationId}\0${e.workspaceSourceKey||"none"}`}function m6(e){const{appDispatch:t,diffPanelExpanded:n,diffPanelOpen:a,rightChatPanels:o,rightPanelMode:i,selectedAppId:s,selectedCloudProject:l,selectedProjectId:p,selectedSession:m,selectedSessionId:f,setWorkspaceDiffPanelViewState:S,view:y,viewWorkspaceAppId:k,viewWorkspaceId:R,viewWorkspaceKind:A,workspaceDiffPanelViewState:$}=e,z=g.useRef(new Map),D=g.useRef(new Map),x=g.useRef(null),I=g.useRef(null),P=f??`draft:${p??s??l?.id??"general"}`,O=g.useMemo(()=>R?`${A??"workspace"}:${R}`:k?`app:${k}`:m?.cwd&&!wa(m.workspaceKind)?`cwd:${m.cwd}`:"none",[m?.cwd,m?.workspaceKind,y,k,R,A]),T=u6({conversationId:P,workspaceSourceKey:O}),F=g.useMemo(()=>c6({diffPanelExpanded:n,diffPanelOpen:a,rightChatPanels:o,rightPanelMode:i}),[n,a,o,i]);g.useEffect(()=>{const L=x.current;L&&z.current.set(L,ub(F))},[P,F]),g.useEffect(()=>{if(x.current===P)return;x.current=P;const V=z.current.get(P)??s6({keepOpen:F.diffPanelOpen});d6(F,V)||t({type:"patch",patch:ub(V)})},[P,F]),g.useEffect(()=>{const L=I.current;L&&D.current.set(L,pu($))},[T,$]),g.useEffect(()=>{if(I.current===T)return;I.current=T;const V=D.current.get(T)??gx();S(Y=>dg(Y,V)?Y:pu(V))},[T]);const H=g.useCallback(L=>{S(V=>dg(V,L)?V:pu(L))},[]);return{browserConversationId:P,handleWorkspaceDiffPanelViewStateChange:H}}function p6({account:e,accountPending:t,accountSignedOut:n,activeWorkspaceKind:a,activeWorkspaceLocation:o,appDispatch:i,applyBootstrapPayload:s,busy:l,cloudSetupDialog:p,cloudProjects:m,connection:f,defaultTeamId:S,expandProject:y,localProjectById:k,selectedCloudProject:R,selectedProject:A,selectedSession:$,selectedSessionProjectId:z,setCloudSetupDialog:D,setDiffPanelOpen:x,setError:I,setSessions:P,setWorkspaceBusy:O,showToast:T,visibleWorkspaceState:F,workspaceBusy:H}){const L=e?.baseUrl??e?.activeProfile?.baseUrl??null,V=g.useCallback(async(J,Me)=>{if(f)try{const Se=await Z.previewLocalProjectCloudSource(f,J.id,{branch:Me});D(ae=>!ae||ae.status!=="confirm"||ae.localProjectId!==J.id||ae.branch!==Me?ae:{...ae,branch:Se.preview.branch,cloudProjectId:Se.preview.targetProjectId,preview:Se.preview,previewLoading:!1,previewError:null})}catch(Se){const ae=Se instanceof Error?Se.message:String(Se);D(xe=>!xe||xe.status!=="confirm"||xe.localProjectId!==J.id||xe.branch!==Me?xe:{...xe,preview:null,previewLoading:!1,previewError:ae})}},[f,D]),Y=g.useCallback(async()=>{const J=p;if(!J||J.status==="uploading")return;if(J.projectKind==="cloud"){D(xe=>xe&&{...xe,status:"ready",error:null});return}if(!f){D(xe=>xe&&{...xe,status:"error",error:"OpenPond App server is not connected."});return}const Me=J.localProjectId??"",Se=k.get(Me);if(!Se){D(xe=>xe&&{...xe,status:"error",error:"Project is no longer available."});return}O(!0);const ae=aa(Se,m);D(xe=>xe&&{...xe,status:"uploading",error:null,previewLoading:!1});try{const xe=await Z.organizations(f),ee=Sc(xe.organizations.map(pc).filter(De=>!!De).filter(De=>De.status==="active"),S);if(!ee)throw new Error("Add an OpenPond account before creating a Cloud environment.");if(!yc(ee))throw new Error(`You need owner or admin access to create projects in ${ee.displayName}.`);const ue=J.branch||Se.linkedSandboxProject?.defaultBranch||"main",ye=gt("local",Se.id),We=await Z.createSession(f,{provider:"openpond",appId:null,appName:null,workspaceKind:"local_project",workspaceId:Se.id,workspaceName:Se.name,localProjectId:Se.id,cloudProjectId:ae?.id??null,cloudTeamId:ae?.teamId??null,cwd:Se.workspacePath,title:`Sync ${Se.name} to Cloud`});P(De=>[We,...De]),i({type:"selectSession",sessionId:We.id,projectId:ye}),y(ye);const Pe=await Z.uploadLocalProjectCloudSource(f,Se.id,{teamId:ee.teamId,projectName:Se.name,branch:ue,chatSessionId:We.id,displayPrompt:`/sync-cloud ${Se.name}`});s(Pe.bootstrap),y(ye),y(gt("cloud",Pe.project.id));const re=xm({accountBaseUrl:L,teamId:Pe.project.teamId,projectId:Pe.project.id,projectName:Pe.project.name,baseBranch:Pe.upload.branch,localProjectId:Se.id,source:"openpond-app"}),Ce=ib({accountBaseUrl:L,organizationSlug:Pe.project.organizationSlug,projectSlug:Pe.project.slug});D({status:"ready",localProjectId:Se.id,cloudProjectId:Pe.project.id,teamId:Pe.project.teamId,projectName:Pe.project.name,projectKind:"local",projectUrl:Ce,setupUrl:re,branch:Pe.upload.branch,preview:J.preview??null,previewLoading:!1,previewError:null,upload:{branch:Pe.upload.branch,headCommit:Pe.upload.headCommit,fileCount:Pe.upload.fileCount,byteCount:Pe.upload.byteCount,skippedCount:Pe.upload.skippedCount,initializedEmptyProject:Pe.upload.initializedEmptyProject},error:null}),T("Source uploaded to OpenPond Git. Cloud setup link is ready.","success")}catch(xe){const ee=xe instanceof Error?xe.message:String(xe),ue=f?await Z.bootstrap(f).catch(()=>null):null;ue&&s(ue),I(ee),D(ye=>ye&&{...ye,status:"error",error:ee})}finally{O(!1)}},[L,i,s,p,m,f,S,y,k,D,I,P,O,T]),ie=g.useCallback((J,Me)=>{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 Se=Me||J.linkedSandboxProject?.defaultBranch||"main";D({status:"confirm",localProjectId:J.id,projectName:J.name,projectKind:"local",projectUrl:null,setupUrl:null,branch:Se,preview:null,previewLoading:!0,previewError:null,upload:null,error:null}),V(J,Se)},[t,n,f,V,D,T]),_e=g.useCallback(async J=>{if(J===o||H||l)return;if(I(null),J==="upload_cloud"){if(!A){T("Select a local Project before uploading source.","error");return}ie(A,F?.currentBranch??null);return}if(J==="local"){const ae=$?.localProjectId??A?.id??z??null,xe=ae?k.get(ae)??null:null;if(!xe){T("No linked local workspace for this Cloud chat.","error");return}if(wa(a)&&!window.confirm("Switch to Local? Cloud changes will stay in the hosted workspace until you preserve or export them."))return;const ee=gt("local",xe.id);i({type:"selectProject",projectId:ee}),y(ee),x(!1),T(`Switched to Local: ${xe.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){D({status:"ready",cloudProjectId:R.id,teamId:R.teamId,projectName:R.name,projectKind:"cloud",projectUrl:ib({accountBaseUrl:L,organizationSlug:R.organizationSlug,projectSlug:R.slug}),setupUrl:xm({accountBaseUrl:L,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 Me=A;if(!Me){T("Select a Project before Cloud coding.","error");return}const Se=F?.currentBranch||Me.linkedSandboxProject?.defaultBranch||"main";ie(Me,Se)},[L,t,n,a,o,i,l,f,m,y,k,ie,R,A,$,z,D,x,I,T,F?.currentBranch,H]),fe=g.useCallback(J=>{$p(J)&&ie(J.project)},[ie]);return{changeWorkspaceTarget:_e,moveProjectToCloud:fe,openCloudSetupForLocalProject:ie,startCloudSetupUpload:Y}}function f6({advanceTrainingTurn:e,bindTrainingSession:t,composerDraftStore:n,onSessionCreated:a,onSubmitted:o,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:$=>{a($),R.metadata&&t($.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 o?.(),A&&R.metadata&&e(),A},[e,t,n,a,o,i,s,l,p])}function h6({appDispatch:e,connection:t,sessions:n,setDiffPanelOpen:a,setRightPanelMode:o,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}),o("changes"),a(!0),s("chat");return}const m=l.name??`Sandbox ${l.sandboxId.slice(0,8)}`,f=await Z.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}),o("changes"),a(!0),s("chat")},[e,t,n,a,o,i,s])}function g6({connection:e,defaultTeamId:t,sessions:n,selectedProjectId:a,confirmProjectAction:o,openExistingProjectDialog:i,applyBootstrapPayload:s,expandProject:l,setExpandedProjectIds:p,setSelectedAppId:m,setSelectedProjectId:f,setSelectedSessionId:S,setError:y,setView:k,showToast:R}){function A(P){const O=gt("local",P.id);m(null),f(O),S(null),k("chat"),l(O)}async function $(P){if(!e)return!1;y(null);const O=P.trim();if(!O)return!1;try{const T=await Z.createLocalProject(e,{path:O});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 $(P.path);return}i()}}async function D(P){if(!e)return!1;const O=P.trim();if(!O)return!1;y(null);try{const T=await Z.createLocalProject(e,{createNew:!0,name:O});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 O=P.trim();if(!O)return!1;y(null);try{const T=await Z.organizations(e),F=Sc(T.organizations.map(pc).filter(ie=>!!ie).filter(ie=>ie.status==="active"),t);if(!F)throw new Error("Add an OpenPond account before creating a Cloud Project.");if(!yc(F))throw new Error(`You need owner or admin access to create projects in ${F.displayName}.`);const H=`${bx(O)}-${Date.now().toString(36)}`;let L=(await Z.upsertSandboxProject(e,{teamId:F.teamId,name:O,sourceType:"internal_repo",normalizedSourceIdentity:H,internalRepoPath:H,defaultBranch:"main",sourceConfig:{sourceType:"internal_repo",sourceValue:H},metadata:{source:"openpond-app-new-cloud-project"}})).project;L=(await Z.uploadSandboxProjectSource(e,L.id,{teamId:F.teamId,branch:"main",commitMessage:"Initialize cloud project",entries:[{path:"README.md",type:"file",contentsBase64:WU(`# ${O}
158
-
159
- Created in OpenPond Cloud.
160
- `)}]})).project;const V=await Z.bootstrap(e);s(V);const Y=gt("cloud",L.id);return m(null),f(Y),S(null),k("chat"),l(Y),R(`Created Cloud Project: ${L.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(TD(P)){const H=`Archive ${P.project.name} in OpenPond Cloud?`;if(!(o?await o({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(H)))return;y(null);try{await Z.archiveSandboxProject(e,P.project.id,{teamId:P.project.teamId}),s(await Z.bootstrap(e)),p(V=>{const Y=new Set(V);return Y.delete(P.id),Y}),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(!$p(P))return;const O=P.project,T=`Remove ${O.name} from Projects? The folder will not be deleted.`;if(o?await o({title:"Remove Project",body:`${O.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 H=await Z.deleteLocalProject(e,O.id);s(H),p(L=>{const V=new Set(L);return V.delete(P.id),V}),a===P.id&&(f(null),S(L=>{const V=n.find(Y=>Y.id===L);return V?.workspaceKind==="local_project"&&V.workspaceId===O.id?null:L})),R(`Removed ${O.name}`,"success")}catch(H){y(H instanceof Error?H.message:String(H)),R("Project could not be removed","error")}}}return{addProjectFolder:z,addProjectFolderPath:$,createCloudProjectFromScratch:x,createProjectFromScratch:D,removeProject:I}}function b6({addProjectFolder:e,addProjectFolderPath:t,appDispatch:n,busy:a,cloudProjectById:o,createCloudProjectFromScratch:i,createProjectFromScratch:s,expandProject:l,localProjectById:p,onCreateCloudEnvironment:m,onNewCloudProject:f,onNewLocalProject:S,onUseExistingFolderPath:y,newProjectBusy:k,newProjectMode:R,newProjectName:A,newProjectPath:$,projectTargetValue:z,setDiffPanelOpen:D,setDraftModel:x,setDraftProvider:I,setError:P,setNewProjectBusy:O,setNewProjectDialogOpen:T,setNewProjectName:F,setNewProjectPath:H,showToast:L,workspaceBusy:V}){const Y=g.useCallback(_e=>{if(_e===z||a||V)return;if(P(null),_e==="action:new-local-project"){S();return}if(_e==="action:add-local-project"){e();return}if(_e==="action:add-local-project-path"){y();return}if(_e==="action:new-cloud-project"){f();return}if(_e==="action:create-cloud-environment"){m();return}if(_e==="none"){n({type:"selectProject",projectId:null}),D(!1),L("Started a chat without project files.","info");return}const fe=_e.indexOf(":"),J=fe>=0?_e.slice(0,fe):"",Me=fe>=0?_e.slice(fe+1):"";if(J==="local"){const Se=p.get(Me);if(!Se){L("Project is no longer available.","error");return}const ae=gt("local",Se.id);n({type:"selectProject",projectId:ae}),l(ae),D(!1);return}if(J==="cloud"){const Se=o.get(Me);if(!Se){L("Cloud Project is no longer available.","error");return}const ae=gt("cloud",Se.id);n({type:"selectProject",projectId:ae}),l(ae),I("openpond"),x(xe=>uo("openpond",xe)),D(!1)}},[e,n,a,o,l,p,m,f,S,y,z,D,x,I,P,L,V]),ie=g.useCallback(async()=>{const _e=A.trim(),fe=$.trim();if(!k&&!(R==="existing-local"?!fe:!_e)){O(!0);try{(R==="cloud"?await i(_e):R==="existing-local"?await t(fe):await s(_e))&&(T(!1),F(""),H(""))}finally{O(!1)}}},[t,i,s,k,R,A,$,O,T,F,H]);return{changeProjectTarget:Y,submitNewProjectDialog:ie}}function v6(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 PV(e){return e.reduce((t,n)=>!t||n.activationVersion>=t.activationVersion?n:t,null)}function y6(e,t){const n=Math.max(0,...e.map(i=>i.activationVersion))+1;let a=!1;const o=e.map(i=>i.id!==t?i:(a=!0,{...i,activationVersion:n}));return a?o:[...e]}function S6(e,t){const n=Math.max(0,...e.map(i=>i.activationVersion))+1;let a=!1;const o=e.map(i=>i.sessionId!==t.sessionId?i:(a=!0,{...i,activationVersion:n,prompt:t.prompt??i.prompt}));return a?o:[...e]}function xk(e){return!!(e.parentSessionId&&e.subagentRunId)}function x6(e){const t=e.sessions.filter(xk);return{knownSessionIds:new Set(t.map(n=>n.id)),newSessions:t.filter(n=>!e.knownSessionIds.has(n.id))}}function k6(e,t){const n=new Set(e.map(o=>o.sessionId).filter(Boolean)),a=t.filter(xk).filter(o=>!n.has(o.id)).map(o=>({id:`right-subagent-${o.id}`,activationVersion:1,sessionId:o.id,prompt:"",provider:o.provider,model:o.modelRef?.modelId??"",scrollTop:0,stickyToBottom:!0}));return a.length>0?[...e,...a]:e}const mb="openpond/openpond",w6="github.issue.write";function _6(e){return e.some(t=>t.provider==="github"&&(t.ref.capabilities??[]).includes(w6))}function TV(e){return[`Title: ${e.title.trim()}`,"","Description:",e.description.trim()].join(`
161
- `)}function I6(e){const t=e.trim();return[`@github Submit this request as a new GitHub issue in ${mb}.`,`Use the GitHub connected app write operation github.issue.create with input.repo set to ${mb}, 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 C6(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:I6(n),requiresInstructions:!0};case"sync-cloud":return{kind:"send_prompt",prompt:`/sync-cloud ${n}`,requiresInstructions:!1}}}const pb=[];function R6(e){const{approvals:t,codexHistoryEvents:n,contextCompaction:a,pendingChatUserMessages:o,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=A6(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:pb):pb,$=cm(A,[]),z=y.sessionId?S.get(y.sessionId)??null:null,D=!!(k&&l.has(k.id)),x=R?nU({events:A}):null,I=k?.cwd??null,P=k?.appId??k?.localProjectId??(k?.workspaceKind==="local_project"?k.workspaceId??null:null)??(k?.cwd&&!wa(k.workspaceKind)?Pv(k.cwd):null),O=y.sessionId?o[y.sessionId]??null:null;return{...y,session:k,title:aU(x,k?.title??"New task"),messages:R?Mx(gc(A),O):[],createImproveRun:x,contextWindowStatus:WS({provider:y.provider,snapshot:lx($,y.sessionId),preferences:a}),goalRuntime:cx($,y.sessionId),pendingApproval:z,running:D,workspaceRootPath:I,activeWorkspaceAppId:P,pendingUserMessage:O,runtimeSource:R?"history":"live"}})},[t,n,a,o,i,s,l,p,m])}function A6(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 P6(e){const{applyPayload:t,connection:n,locallyActiveSessionIds:a,panels:o,sessions:i,setError:s}=e,l=g.useMemo(()=>{const f=new Set,S=[];for(const y of o)!Mt(y.sessionId)||!y.sessionId||f.has(y.sessionId)||(f.add(y.sessionId),S.push(y.sessionId));return S.join(`
164
- `)},[o]),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=>Kp({connection:n,locallyActive:y.has(R),onError:A=>s(A instanceof Error?A.message:String(A)),onPayload:A=>t(Wp(A,y.has(R))),reportedActive:S.has(R),sessionId:R,surface:"thread"}));return()=>k.forEach(R=>R())},[p,t,n,m,l,s])}const fb=[];function T6(e){const{activeModel:t,activeProvider:n,approvals:a,applyRightCodexHistoryPayload:o,codexHistoryEvents:i,connectedAppMentions:s,connection:l,contextCompaction:p,openLabTraining:m,locallyActiveCodexHistorySessionIds:f,openPondCommandAccessMode:S,pendingChatUserMessages:y,providerSettings:k,rightChatHistoryEvents:R,rightChatPanels:A,rightPanelMode:$,runtimeIndexes:z,runtimeEventStore:D,runningSessionIds:x,selectedSession:I,selectedSessionId:P,sendPrompt:O,setDiffPanelOpen:T,setError:F,setRightChatHistoryEvents:H,setRightChatPanels:L,setRightPanelMode:V,setRightPanelTabRequest:Y,setView:ie,showChangesPanel:_e,showToast:fe,sidebarSessions:J,startupReady:Me}=e,Se=g.useRef(null),ae=g.useRef(new Map),xe=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)||xe.current.has(He)||(xe.current.add(He),Z.runtimeEventsPage(l,{sessionId:He,beforeSequence:Number.MAX_SAFE_INTEGER,limit:500}).then($e=>{const E=$e.events.map(U=>U.event);H(U=>({...U,[He]:Da(U[He]??fb,E)}))}).catch($e=>{F($e instanceof Error?$e.message:String($e))}).finally(()=>{xe.current.delete(He)}))},[l,R,A,F,H]);const ee=g.useCallback(Be=>{Y(He=>({id:(He?.id??0)+1,tab:Be})),_e()},[_e]),ue=g.useCallback((Be=null,He={})=>{const $e=Be?.id?A.find(U=>U.sessionId===Be.id)??null:null;if($e)return L(U=>S6(U,{sessionId:Be.id,prompt:He.prompt})),T(!0),V("chat"),He.preserveView||ie("chat"),$e.id;const E=v6({sessionId:Be?.id??null,provider:Be?.provider??n,model:Be?.modelRef?.modelId??t,prompt:He.prompt});return L(U=>[...U,E]),T(!0),V("chat"),He.preserveView||ie("chat"),E.id},[t,n,A,T,L,V,ie]);g.useEffect(()=>{if(!Me)return;const Be=Se.current;if(!Be){Se.current=new Set(J.filter(U=>!!(U.parentSessionId&&U.subagentRunId)).map(U=>U.id));return}const He=x6({sessions:J,knownSessionIds:Be});Se.current=He.knownSessionIds;for(const U of He.newSessions)ae.current.set(U.id,U);const $e=I?.parentSessionId??I?.id??null;if(!$e)return;const E=[...ae.current.values()].filter(U=>U.parentSessionId===$e);if(E.length!==0){for(const U of E)ae.current.delete(U.id);L(U=>k6(U,E)),T(!0),V("chat")}},[I?.id,I?.parentSessionId,T,L,V,J,Me]);const ye=g.useCallback(()=>{if(A.length===0){ue(null);return}T(!0),V("chat"),ie("chat")},[ue,A.length,T,V,ie]),We=g.useCallback(Be=>{const He=A.length<=1&&A.some(E=>E.id===Be),$e=()=>{L(E=>E.filter(U=>U.id!==Be))};if(He&&$==="chat"){if(ee("files"),typeof window>"u"){$e();return}window.requestAnimationFrame($e);return}$e()},[A,$,L,ee]),Pe=g.useCallback((Be,He)=>{L($e=>$e.map(E=>E.id===Be?{...E,prompt:He}:E))},[L]),re=g.useCallback(Be=>{L(He=>y6(He,Be))},[L]),Ce=g.useCallback((Be,He)=>{L($e=>$e.map(E=>E.id===Be?{...E,...He}:E))},[L]),De=g.useCallback((Be,He)=>{L($e=>$e.map(E=>E.id===Be?{...E,model:He}:E))},[L]),Je=g.useCallback((Be,He)=>{L($e=>$e.map(E=>E.id===Be?{...E,provider:He,model:uo(He,E.model,k)}:E))},[k,L]);P6({applyPayload:o,connection:l,locallyActiveSessionIds:f,panels:A,sessions:J,setError:F});const et=R6({approvals:a,codexHistoryEvents:i,contextCompaction:p,pendingChatUserMessages:y,rightChatHistoryEvents:R,rightChatPanels:A,runningSessionIds:x,selectedSessionId:P,sidebarSessions:J}),rt=g.useCallback(async(Be,He=[],$e=null,E=null,U={})=>{const G=A.find(nt=>nt.id===Be);if(!G)return!1;const ce=U.promptOverride??G.prompt,W=E?C6(E,ce):null;if(W?.kind==="open_training")return He.length>0?(fe("/train uses this chat; add other chats from Models.","error"),!1):(m({objective:W.objective,sessionId:G.sessionId}),U.preservePrompt||Pe(Be,""),!0);if(E&&W?.kind==="send_prompt"&&W.requiresInstructions&&!ce.trim())return fe(`Add instructions after ${E.command}.`,"info"),!1;if(E&&He.length>0)return fe(`${E.command} tasks do not accept attachments yet. Add file context in the task thread.`,"error"),!1;if(E?.id==="submit-issue"&&!_6(s))return fe("Connect the GitHub app before using /submit-issue.","error"),!1;const me=G.sessionId?J.find(nt=>nt.id===G.sessionId)??null:null,he=G.provider==="codex"?S:me?.openPondCommandAccessMode??S,Ze=W?.kind==="send_prompt"?W.prompt:ce,qe=Mt(G.sessionId)?(G.sessionId?R[G.sessionId]:void 0)??(G.sessionId===P?i:fb):D.getSessionEvents(G.sessionId),it=Mt(G.sessionId)&&G.sessionId?nt=>{const we=G.sessionId;H(Oe=>({...Oe,[we]:Da(Oe[we]??qe,[nt])}))}:void 0;return O(He,$e,Ze,{session:me,selectSession:!1,provider:G.provider,model:G.model,openPondCommandAccessMode:he,chatMessages:gc(qe),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:it,clearPrompt:U.preservePrompt?()=>{}:()=>Pe(Be,""),onSessionCreated:nt=>{L(we=>we.map(Oe=>Oe.id===Be?{...Oe,sessionId:nt.id,provider:nt.provider,model:nt.modelRef?.modelId??Oe.model}:Oe))}})},[i,s,R,A,z,D,P,m,S,O,L,ie,J,fe,Pe]);return{activateRightChatPanel:re,closeRightChatPanel:We,openRightChatPanel:ue,rightChatPanelViews:et,showRightChatPanel:ye,showRightPanelDiffTab:ee,submitRightChatPrompt:rt,updateRightChatModel:De,updateRightChatPrompt:Pe,updateRightChatProvider:Je,updateRightChatScrollState:Ce}}function E6(e){const{appPreferences:t,connection:n,selectedSessionId:a,setAppPreferences:o,setCodexHistorySessions:i,setError:s,setSelectedSessionId:l,setSessions:p}=e;async function m(z,D){if(!n)return;const x=t[z]??{},I={...x,...D,archived:D.pinned?!1:D.archived??x.archived};o(P=>({...P,[z]:I}));try{const P=await Z.patchSidebarAppPreference(n,z,D);o(O=>({...O,[z]:P}))}catch(P){s(P instanceof Error?P.message:String(P)),o(O=>({...O,[z]:x}))}}function f(z){m(z.id,{pinned:!z.pinned,archived:!1})}async function S(z,D){if(!n)return;const x=Mt(z.id)?i:p,I={...z,...D};x(P=>P.some(O=>O.id===z.id)?P.map(O=>O.id===z.id?I:O):[I,...P]);try{const P=await Z.patchSession(n,z.id,D);x(O=>O.some(T=>T.id===P.id)?O.map(T=>T.id===P.id?P:T):[P,...O])}catch(P){s(P instanceof Error?P.message:String(P)),x(O=>O.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 $(z,D){const x=D.trim();!x||x===z.title||S(z,{title:x})}return{archiveSession:R,renameSession:$,restoreSession:A,toggleProjectPinned:f,toggleSessionPinned:k,toggleSessionSavedForLater:y}}function M6(e){return e.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,72)||"new-branch"}function j6({connection:e,activeWorkspaceAppId:t,appDefaults:n,bootstrap:a,branchDialogName:o,commitIncludeUnstaged:i,commitMessage:s,commitNextStep:l,draftModel:p,draftProvider:m,cloudProjects:f,selectedApp:S,selectedProject:y,selectedProjectLinkedOpenPondApp:k,selectedSession:R,sessions:A,title:$,visibleWorkspaceDiff:z,visibleWorkspaceState:D,workspaceBusy:x,workspaceName:I,appDispatch:P,applyBootstrapPayload:O,expandProject:T,refreshWorkspace:F,refreshWorkspaceDiff:H,rememberWorkspaceState:L,setBranchDialogOpen:V,setCommitDialogOpen:Y,setError:ie,setSessions:_e,setSettingsSection:fe,setSyncingWorkspaceAppId:J,setView:Me,setWorkspaceBusy:Se,showToast:ae}){function xe(){return`${RS(n.defaultBranchPrefix)}${M6(I??$??"new-branch")}`}function ee(){return I?`Update ${I}`:(z?.filesChanged??D?.changedFilesCount??0)===1?"Update workspace file":"Update workspace files"}function ue($e="commit"){P({type:"openCommitDialog",nextStep:$e})}function ye(){P({type:"openBranchDialog",branchName:xe()})}function We(){x||V(!1),fe("defaults"),Me("settings")}async function Pe($e){if(!(!e||!t)){Se(!0),ie(null);try{const E=await Z.checkoutWorkspaceBranch(e,t,{branch:$e});L(E),E.initialized&&H(t)}catch(E){ie(E instanceof Error?E.message:String(E))}finally{Se(!1)}}}async function re(){if(!e||!t)return;const $e=o.trim();if($e){Se(!0),ie(null);try{const E=await Z.createWorkspaceBranch(e,t,{branch:$e});L(E),E.initialized&&H(t),V(!1),ae(`Checked out ${$e}`,"success")}catch(E){ie(E instanceof Error?E.message:String(E))}finally{Se(!1)}}}async function Ce($e){J($e);const E=a?.apps.find(U=>U.id===$e)?.name??a?.localProjects.find(U=>U.id===$e)?.name??"Workspace";try{const U=await F($e,!0);U?.initialized&&$e===t&&H($e),U?.initialized&&!U.error?ae(`${E} synced locally`,"success"):U?.error&&ae("Workspace sync failed","error")}finally{J(U=>U===$e?null:U)}}async function De(){t&&await Ce(t)}async function Je($e,E,U={}){if(!e)return null;const G=R&&!Mt(R.id)?R:null;if(D6(E,G,U)||G&&O6(G,y,S))return G;const ce=G?await et(G):null;if(ce)return ce;const W=N6(A,y,S);if(W){const qe=W.workspaceKind==="local_project"&&W.workspaceId?gt("local",W.workspaceId):null;return P({type:"selectSession",sessionId:W.id,appId:W.appId,projectId:qe}),W.workspaceKind==="local_project"&&W.workspaceId&&T(gt("local",W.workspaceId)),W}const me=aa(y,f),he=await Z.createSession(e,{provider:m,modelRef:la(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:me?.id??null,cloudTeamId:me?.teamId??null,cwd:y?y.workspacePath:null,title:$e});_e(qe=>[he,...qe]);const Ze=he.workspaceKind==="local_project"&&he.workspaceId?gt("local",he.workspaceId):null;return P({type:"selectSession",sessionId:he.id,appId:he.appId,projectId:Ze}),he.workspaceKind==="local_project"&&he.workspaceId&&T(gt("local",he.workspaceId)),he}async function et($e){if(!e||!y||!k?.appId||Mt($e.id)||$e.workspaceKind==="local_project"||$e.appId!==k.appId)return null;const E=aa(y,f),U=await Z.patchSession(e,$e.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 _e(G=>G.map(ce=>ce.id===U.id?U:ce)),P({type:"selectSession",sessionId:U.id,appId:U.appId,projectId:gt("local",y.id)}),T(gt("local",y.id)),U}async function rt($e,E={}){if(!e)return null;const U=await Je(I?`${I} workspace`:"Workspace action",$e,E);if(!U)return null;const G=await Z.workspaceTool(e,U.id,{action:$e,args:E,source:"ui_button"});ae(G.output,G.ok?"success":"error"),O(await Z.bootstrap(e));const ce=G.appId??$6(U);return ce&&(await F(ce,!1))?.initialized&&await H(ce),G}async function Be($e,E={}){if($e==="git_commit"&&typeof E.message!="string")return ue("commit"),null;Se(!0),ie(null);try{return await rt($e,E)}catch(U){return ie(U instanceof Error?U.message:String(U)),null}finally{Se(!1)}}async function He(){const $e=s.trim()||ee(),E=l==="commit_publish",U=E&&!!D?.remoteUrl;if(!(U&&!window.confirm("Replace the current origin remote with the new OpenPond repo after committing?"))){Se(!0),ie(null);try{if(!(await rt("git_commit",{message:$e,includeUnstaged:i}))?.ok||l==="commit_push"&&!(await rt("git_push",{runChecks:!1}))?.ok||E&&!(await rt("publish_openpond_repo",{replaceOrigin:U}))?.ok)return;Y(!1)}catch(G){ie(G instanceof Error?G.message:String(G))}finally{Se(!1)}}}return{changeWorkspaceBranch:Pe,openCommitDialog:ue,openCreateWorkspaceBranchDialog:ye,openDefaultsSettingsFromBranchDialog:We,runWorkspaceTool:Be,submitCommitDialog:He,submitCreateWorkspaceBranch:re,syncWorkspaceLocally:De,syncWorkspaceLocallyForApp:Ce}}function O6(e,t,n){return!t&&!n?!0:kk(e,t,n)}function N6(e,t,n){if(!t&&!n)return null;let a=null,o=Number.NEGATIVE_INFINITY;for(const i of e){if(i.archived||!kk(i,t,n))continue;const s=Date.parse(i.updatedAt),l=Number.isFinite(s)?s:0;(!a||l>o)&&(a=i,o=l)}return a}function kk(e,t,n){return t?e.workspaceKind==="local_project"&&e.workspaceId===t.id:n?e.appId===n.id||e.workspaceId===n.id:!1}function $6(e){return e.workspaceKind==="sandbox"?e.localProjectId??null:e.workspaceId??e.appId??null}function D6(e,t,n={}){return(L6(e)||U6(e,n))&&z6(t)}function L6(e){return e.startsWith("sandbox_")?e!=="sandbox_create"&&e!=="sandbox_templates"&&e!=="sandbox_template_launch":!1}function z6(e){return e?.workspaceKind==="sandbox"||e?.workspaceKind==="sandbox_template"}function U6(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 H6(e,t){return e.kind==="general"?"# general":e.title?e.title:e.participants.find(a=>a.userId!==t)?.name??"Direct message"}const q6=[];function B6(e){const{composerDraftStore:t,appDispatch:n,mentionedAppId:a,setMentionedAppId:o,cloudSetupDialog:i,setCloudSetupDialog:s,setRightPanelTabRequest:l,workspaceDiffPanelViewState:p,setWorkspaceDiffPanelViewState:m,rightChatHistoryEvents:f,setRightChatHistoryEvents:S,locallyActiveCodexHistorySessionIds:y,setCodexHistoryTurnLocallyActive:k,draftSubagentDelegationMode:R,setDraftSubagentDelegationMode:A,confirmProjectAction:$,view:z,selectedAppId:D,selectedProjectId:x,selectedSessionId:I,draftProvider:P,draftModel:O,activeExperience:T,codexPermissionMode:F,codexReasoningEffort:H,openPondCommandAccessMode:L,busy:V,diffPanelOpen:Y,diffPanelExpanded:ie,rightPanelMode:_e,rightChatPanels:fe,newProjectMode:J,newProjectName:Me,newProjectPath:Se,newProjectBusy:ae,commitMessage:xe,commitIncludeUnstaged:ee,commitNextStep:ue,branchDialogName:ye,setSectionMenuOpen:We,setView:Pe,setSelectedAppId:re,setSelectedProjectId:Ce,setSelectedSessionId:De,setPrompt:Je,setDraftProvider:et,setDraftModel:rt,setDiffPanelOpen:Be,setRightPanelMode:He,setRightChatPanels:$e,setSyncingWorkspaceAppId:E,setSettingsSection:U,setNewProjectDialogOpen:G,setNewProjectMode:ce,setNewProjectName:W,setNewProjectPath:me,setNewProjectBusy:he,setCommitDialogOpen:Ze,setBranchDialogOpen:qe,setError:it,showToast:nt,appPreferences:we,applyBootstrapPayload:Oe,approvals:d,bootstrap:M,connection:q,events:le,runtimeEventStore:N,sessions:K,startup:w,setAppPreferences:j,setCodexHistorySessions:oe,setEvents:X,setSessions:Q,cloudProjectById:pe,localProjectById:de,selectedApp:ze,selectedCloudProject:Te,selectedProject:Ne,selectedProjectLinkedOpenPondApp:Ye,selectedSession:Le,sidebarSessions:ut,runtimeIndexes:Vt,connectedAppMentions:dn,codexHistoryEvents:un,setCodexHistoryEvents:Xt,account:xt,accountPending:Wt,accountSignedOut:Pt,activeModel:Rt,activeProvider:qn,activeWorkspaceAppId:jt,activeWorkspaceKind:mn,activeWorkspaceLocation:Qt,appDefaults:ln,selectedSessionProjectId:Sn,workspaceName:Ia,accountScopeKey:qt,teamChat:xn,communities:lt,selectedProjectConfirmedCloudProject:Bt,activeOpenPondCommandAccessMode:te,viewWorkspaceAppId:Ke,viewWorkspaceId:Ge,viewWorkspaceKind:St,openPondActionCatalog:an,selectedActionCatalog:Ca,expandProject:kn,setExpandedProjectIds:Dt,advanceTrainingModelChatAfterTurn:kt,bindTrainingModelChatSession:Lt,prepareTrainingModelChatTurn:vt,chatMessages:_t,pendingChatUserMessages:Tt,recordPendingChatUserMessage:cn,runningSessionIds:En,workspaceBusy:Xe,visibleWorkspaceState:pn,visibleWorkspaceDiff:mt,rememberWorkspaceState:Kt,refreshWorkspace:wn,setWorkspaceBusy:Bn,refreshWorkspaceDiffWhenNeeded:po,setPendingWorkspaceTarget:Fn,pendingSidebarWorkspaceTarget:Jn,setPendingSidebarWorkspaceTarget:pt,projectTarget:ca,workspaceTarget:fo}=e,da=z==="apps"?"Apps":z==="get-started"?"Walkthroughs":z==="labs"?"Models":z==="scheduled"?"Workflows":z==="outputs"?"Outputs":z==="projects"?"Projects":z==="team"?xn.detail?H6(xn.detail.thread,xn.currentUserId):"Team Chat":z==="community"?lt.preview?.displayName??"Communities":Le?.title??yS(T),{browserConversationId:ia,handleWorkspaceDiffPanelViewStateChange:Zo}=m6({appDispatch:n,diffPanelExpanded:ie,diffPanelOpen:Y,rightChatPanels:fe,rightPanelMode:_e,selectedAppId:D,selectedCloudProject:Te,selectedProjectId:x,selectedSession:Le,selectedSessionId:I,setWorkspaceDiffPanelViewState:m,view:z,viewWorkspaceAppId:Ke,viewWorkspaceId:Ge,viewWorkspaceKind:St,workspaceDiffPanelViewState:p}),ua=g.useCallback(yt=>{De(yt),re(null),Ce(null),Pe("chat")},[re,Ce,De,Pe]),ho=g.useCallback(()=>{ce("existing-local"),W(""),me(""),G(!0)},[G,ce,W,me]),Jo=g.useCallback(()=>{ce("local"),W(""),me(""),G(!0)},[G,ce,W,me]),{addProjectFolder:go,addProjectFolderPath:Yo,createCloudProjectFromScratch:ni,createProjectFromScratch:ai,removeProject:ma}=g6({connection:q,defaultTeamId:ln.defaultTeamId,sessions:K,selectedProjectId:x,confirmProjectAction:$,openExistingProjectDialog:ho,applyBootstrapPayload:Oe,expandProject:kn,setExpandedProjectIds:Dt,setSelectedAppId:re,setSelectedProjectId:Ce,setSelectedSessionId:De,setError:it,setView:Pe,showToast:nt}),{changeWorkspaceBranch:oi,openCommitDialog:Xo,openCreateWorkspaceBranchDialog:Qo,openDefaultsSettingsFromBranchDialog:er,runWorkspaceTool:ri,submitCommitDialog:Yn,submitCreateWorkspaceBranch:ii,syncWorkspaceLocally:si}=j6({connection:q,activeWorkspaceAppId:jt,appDefaults:ln,bootstrap:M,branchDialogName:ye,commitIncludeUnstaged:ee,commitMessage:xe,commitNextStep:ue,draftModel:O,draftProvider:P,cloudProjects:M?.cloudProjects??[],selectedApp:ze,selectedProject:Ne,selectedProjectLinkedOpenPondApp:Ye,selectedSession:Le,sessions:K,title:da,visibleWorkspaceDiff:mt,visibleWorkspaceState:pn,workspaceBusy:Xe,workspaceName:Ia,appDispatch:n,applyBootstrapPayload:Oe,expandProject:kn,refreshWorkspace:wn,refreshWorkspaceDiff:po,rememberWorkspaceState:Kt,setBranchDialogOpen:qe,setCommitDialogOpen:Ze,setError:it,setSessions:Q,setSettingsSection:U,setSyncingWorkspaceAppId:E,setView:Pe,setWorkspaceBusy:Bn,showToast:nt}),li=r6({applyBootstrapPayload:Oe,cloudProjects:M?.cloudProjects??[],connection:q,localProjectById:de,selectedCloudProject:Te,selectedProject:Ne,setWorkspaceBusy:Bn,showToast:nt,visibleWorkspaceState:pn}),ci=M?.preferences.subagents.delegationMode??"manual",di=Le?.subagentDelegationMode??R,tr=!!(T==="development"&&M?.preferences.subagents.enabled&&qn!=="codex"&&!Mt(I)&&!Le?.subagentRunId),nr=g.useCallback(yt=>{if(!Le){A(yt);return}if(!q||Mt(Le.id)||Le.subagentRunId)return;const Ot=Le.id,On=Le.subagentDelegationMode??null;Q(Jt=>Jt.map(Wn=>Wn.id===Ot?{...Wn,subagentDelegationMode:yt}:Wn)),Z.patchSession(q,Ot,{subagentDelegationMode:yt}).then(Jt=>{Q(Wn=>Wn.map(Kn=>Kn.id===Jt.id?Jt:Kn))}).catch(Jt=>{Q(Wn=>Wn.map(Kn=>Kn.id===Ot?{...Kn,subagentDelegationMode:On}:Kn)),it(Jt instanceof Error?Jt.message:String(Jt))})},[q,Le,it,Q]),Ra=g.useCallback(yt=>{S(Ot=>Ot[yt.session.id]===yt.events?Ot:{...Ot,[yt.session.id]:yt.events}),oe(Ot=>fc(Ot,yt.session))},[oe]),{answerCreateImproveQuestion:ui,applyCreateImproveCandidate:bo,approveCreateImproveRun:Aa,cancelCreateImproveRun:Mn,changeDraftProvider:mi,openCreateImprovePullRequest:ar,reconcileCreateImprovePullRequest:Zt,rejectCreateImproveCandidate:vo,pauseCreateImproveRun:jn,resumeCreateImproveRun:Pa,reviseCreateImproveRun:yo,sendPrompt:pa,stopTurn:So}=e6({applyBootstrapPayload:Oe,bootstrap:M,chatMessages:_t,connection:q,codexPermissionMode:F,codexReasoningEffort:H,openPondCommandAccessMode:te,draftModel:O,draftProvider:P,experience:T,expandProject:kn,getPrompt:t.getSnapshot,apps:M?.apps??[],connectedAppMentions:dn,mentionedAppId:a,ensureCloudSessionReady:li,refreshWorkspace:wn,refreshWorkspaceDiff:po,selectedApp:ze,selectedActionCatalog:Ca,openPondActionCatalog:an,cloudProjects:M?.cloudProjects??[],accountScopeKey:qt,selectedCloudProject:Te,selectedProject:Ne,selectedProjectLinkedOpenPondApp:Ye,selectedSession:Le,sessions:K,workspaceTarget:fo.value,subagentDelegationMode:Le?.subagentDelegationMode??R,setDraftModel:rt,setDraftProvider:et,setError:it,setPrompt:Je,setMentionedAppId:o,setCodexHistoryEvents:Xt,setCodexHistorySessions:oe,onCodexHistoryTurnActivityChange:k,onCodexHistoryTurnPayload:Ra,onPendingUserMessage:cn,setEvents:X,setSelectedAppId:re,setSelectedProjectId:Ce,setSelectedSessionId:De,setSessions:Q,setView:Pe,setWorkspaceBusy:Bn}),{archiveSession:pi,restoreSession:fi,renameSession:xo,toggleProjectPinned:or,toggleSessionPinned:ko,toggleSessionSavedForLater:rr}=E6({appPreferences:we,connection:q,selectedSessionId:I,setAppPreferences:j,setCodexHistorySessions:oe,setError:it,setSelectedSessionId:De,setSessions:Q}),{changeWorkspaceTarget:wo,moveProjectToCloud:ir,startCloudSetupUpload:Xn}=p6({account:xt,accountPending:Wt,accountSignedOut:Pt,activeWorkspaceKind:mn,activeWorkspaceLocation:Qt,appDispatch:n,applyBootstrapPayload:Oe,busy:V,cloudSetupDialog:i,cloudProjects:M?.cloudProjects??[],connection:q,defaultTeamId:ln.defaultTeamId,expandProject:kn,localProjectById:de,selectedCloudProject:Te,selectedProject:Ne,selectedSession:Le,selectedSessionProjectId:Sn,setCloudSetupDialog:s,setDiffPanelOpen:Be,setError:it,setSessions:Q,setWorkspaceBusy:Bn,showToast:nt,visibleWorkspaceState:pn,workspaceBusy:Xe}),Ka=g.useCallback(async yt=>{if(T==="work"&&!Le){if(yt==="local"){Fn("local"),nt(Ne?`Next task will use the local ${Ne.name} checkout.`:"Next task will use an app-managed local workspace.","info");return}if(yt==="cloud"&&!Ne&&!Te){if(Wt){nt("Checking OpenPond account. Try again in a moment.","info");return}if(Pt){nt("Add an OpenPond account before using Hosted.","error");return}Fn("cloud"),nt("Next task will use Hosted without a Project.","info");return}}if(yt==="hybrid"){const Ot=Te?.id??Bt?.id??Le?.cloudProjectId??null,On=Te?.teamId??Bt?.teamId??Le?.cloudTeamId??null;if(Wt){nt("Checking OpenPond account. Try again in a moment.","info");return}if(Pt){nt("Add an OpenPond account before using Hybrid.","error");return}if(!Ot||!On){Fn(null),nt("Upload/sync this Project to Cloud before using Hybrid.","error");return}if(Le&&!Mt(Le.id)){if(_a(Le))return;if(!q){nt("OpenPond App server is not connected.","error");return}const Jt=await Z.patchSession(q,Le.id,{provider:P,modelRef:la(P,O,M?.providers??null),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:null,workspaceName:Te?.name??Bt?.name??Ne?.name??Le.workspaceName??"Hybrid workspace",localProjectId:Ne?.id??Le.localProjectId??null,cloudProjectId:Ot,cloudTeamId:On,metadata:px(Le.metadata),cwd:Ne?.workspacePath??Le.cwd??null});Q(Wn=>Wn.map(Kn=>Kn.id===Jt.id?Jt:Kn)),Fn(null),nt("Hybrid will use your selected model with hosted sandbox edits.","info");return}Fn("hybrid"),nt("Next message will use Hybrid with a hosted sandbox.","info");return}Fn(null),await wo(yt)},[Wt,Pt,T,M?.providers,wo,q,O,P,Te?.id,Te?.name,Te?.teamId,Ne?.id,Bt?.id,Bt?.name,Bt?.teamId,Ne?.name,Ne?.workspacePath,Le,Fn,Q,nt]),_o=g.useCallback((yt,Ot)=>{re(null),Ce(yt),De(null),Pe("chat"),kn(yt),pt({projectId:yt,target:Ot})},[kn,re,Ce,De,Pe]);g.useEffect(()=>{if(!Jn||z!=="chat"||x!==Jn.projectId||I!==null)return;const yt=Jn.target;pt(null),Ka(yt)},[Ka,Jn,x,I,z]);const Ta=f6({advanceTrainingTurn:kt,bindTrainingSession:Lt,composerDraftStore:t,onSessionCreated:()=>A(null),onSubmitted:async()=>{const yt=Le;if(!(!q||!yt||!cs(yt)))try{const Ot=await Z.patchSession(q,yt.id,{metadata:zD(yt.metadata)});Q(On=>On.map(Jt=>Jt.id===Ot.id?Ot:Jt))}catch(Ot){nt(Ot instanceof Error?`Task started, but its Draft label could not be cleared: ${Ot.message}`:"Task started, but its Draft label could not be cleared.","error")}},prepareTrainingTurn:vt,sendPrompt:pa,setMentionedAppId:o,showToast:nt}),sr=h6({appDispatch:n,connection:q,sessions:K,setDiffPanelOpen:Be,setRightPanelMode:He,setSessions:Q,setView:Pe}),{createCloudEnvironmentFromSidebar:fa,openCloudProjectDialog:lr,openUrlInBrowserPanel:hi,showBrowserPanel:Io,showChangesPanel:cr,showGoalSidebarTab:dr}=k4({account:xt,browserConversationId:ia,cloudProjectById:pe,cloudProjects:M?.cloudProjects??[],diffPanelOpen:Y,rightPanelMode:_e,selectedProjectId:x,setDiffPanelOpen:Be,setNewProjectDialogOpen:G,setNewProjectMode:ce,setNewProjectName:W,setRightPanelMode:He}),{changeProjectTarget:ur,submitNewProjectDialog:gi}=b6({addProjectFolder:go,addProjectFolderPath:Yo,appDispatch:n,busy:V,cloudProjectById:pe,createCloudProjectFromScratch:ni,createProjectFromScratch:ai,expandProject:kn,localProjectById:de,newProjectBusy:ae,newProjectMode:J,newProjectName:Me,newProjectPath:Se,onCreateCloudEnvironment:fa,onNewCloudProject:lr,onNewLocalProject:Jo,onUseExistingFolderPath:ho,projectTargetValue:ca.value,setDiffPanelOpen:Be,setDraftModel:rt,setDraftProvider:et,setError:it,setNewProjectBusy:he,setNewProjectDialogOpen:G,setNewProjectName:W,setNewProjectPath:me,showToast:nt,workspaceBusy:Xe}),mr=g.useMemo(()=>K.map(yt=>yt.id),[K]);_4({browserConversationId:ia,sessionIds:mr,onOpenSession:ua,onShowBrowserPanel:Io});const[pr,Ga]=g.useState(null),ha=g.useCallback(yt=>{Ga({id:Date.now(),objective:yt.objective,initialSessionIds:yt.sessionId?[yt.sessionId]:[]}),Pe("labs")},[Pe]),{activateRightChatPanel:bi,closeRightChatPanel:vi,openRightChatPanel:fr,rightChatPanelViews:yi,showRightChatPanel:Qn,showRightPanelDiffTab:hr,submitRightChatPrompt:Ea,updateRightChatModel:Co,updateRightChatPrompt:Si,updateRightChatProvider:Vn,updateRightChatScrollState:xi}=T6({activeModel:Rt,activeProvider:qn,approvals:d,applyRightCodexHistoryPayload:Ra,codexHistoryEvents:un,connectedAppMentions:dn,connection:q,contextCompaction:ln.contextCompaction,openLabTraining:ha,locallyActiveCodexHistorySessionIds:y,openPondCommandAccessMode:L,pendingChatUserMessages:Tt,providerSettings:M?.providers??null,rightChatHistoryEvents:f,rightChatPanels:fe,rightPanelMode:_e,runtimeIndexes:Vt,runtimeEventStore:N,runningSessionIds:En,selectedSession:Le,selectedSessionId:I,sendPrompt:pa,setDiffPanelOpen:Be,setError:it,setRightChatHistoryEvents:S,setRightChatPanels:$e,setRightPanelMode:He,setRightPanelTabRequest:l,setView:Pe,showChangesPanel:cr,showToast:nt,sidebarSessions:ut,startupReady:w.ready}),ki=g.useCallback(()=>{We(null),U("profile"),Pe("settings")},[We,U,Pe]),wi=g.useMemo(()=>Na(M?.diagnostics??q6,le.filter(yt=>yt.name==="diagnostic")),[M?.diagnostics,le]),gr=g.useCallback(()=>{if(Y){Be(!1);return}if(z==="labs"){He("changes"),l({id:Date.now(),tab:"summary"}),Be(!0);return}He("home"),Be(!0)},[Y,Be,He,l,z]);return{title:da,browserConversationId:ia,handleWorkspaceDiffPanelViewStateChange:Zo,openSessionInChat:ua,openExistingProjectPathDialog:ho,addProjectFolder:go,removeProject:ma,changeProjectTarget:ur,submitNewProjectDialog:gi,changeWorkspaceBranch:oi,openCommitDialog:Xo,openCreateWorkspaceBranchDialog:Qo,openDefaultsSettingsFromBranchDialog:er,runWorkspaceTool:ri,submitCommitDialog:Yn,submitCreateWorkspaceBranch:ii,syncWorkspaceLocally:si,subagentDelegationDefaultMode:ci,subagentDelegationMode:di,subagentDelegationAvailable:tr,changeSubagentDelegationMode:nr,answerCreateImproveQuestion:ui,applyCreateImproveCandidate:bo,approveCreateImproveRun:Aa,cancelCreateImproveRun:Mn,changeDraftProvider:mi,openCreateImprovePullRequest:ar,reconcileCreateImprovePullRequest:Zt,rejectCreateImproveCandidate:vo,pauseCreateImproveRun:jn,resumeCreateImproveRun:Pa,reviseCreateImproveRun:yo,sendPrompt:pa,stopTurn:So,archiveSession:pi,restoreSession:fi,renameSession:xo,toggleProjectPinned:or,toggleSessionPinned:ko,toggleSessionSavedForLater:rr,moveProjectToCloud:ir,startCloudSetupUpload:Xn,changeWorkspaceTarget:Ka,switchProjectWorkspaceTarget:_o,sendPromptFromMainComposer:Ta,openSandboxWorkspace:sr,createCloudEnvironmentFromSidebar:fa,openCloudProjectDialog:lr,openUrlInBrowserPanel:hi,showBrowserPanel:Io,showChangesPanel:cr,showGoalSidebarTab:dr,rightChatTrainingLaunchRequest:pr,setRightChatTrainingLaunchRequest:Ga,closeRightChatPanel:vi,openRightChatPanel:fr,rightChatPanelViews:yi,showRightChatPanel:Qn,showRightPanelDiffTab:hr,submitRightChatPrompt:Ea,activateRightChatPanel:bi,updateRightChatModel:Co,updateRightChatPrompt:Si,updateRightChatProvider:Vn,updateRightChatScrollState:xi,openProfileSettings:ki,diagnosticEvents:wi,toggleRightSidebar:gr}}function F6(){const e=h4(),t=B6(e);return b.jsx(zU,{primary:e,secondary:t})}const EV=Object.freeze(Object.defineProperty({__proto__:null,App:F6},Symbol.toStringTag,{value:"Module"}));export{Da as $,y$ as A,Dh as B,ro as C,aV as D,CV as E,F$ as F,K$ as G,uo as H,_V as I,om as J,M3 as K,tV as L,nH as M,TV as N,ZL as O,F4 as P,pV as Q,eV as R,vS as S,nV as T,dV as U,Oz as V,la as W,ti as X,nU as Y,Rr as Z,Mt as _,qo as a,AV as a$,Mx as a0,F3 as a1,RU as a2,i5 as a3,B3 as a4,mV as a5,r5 as a6,Zn as a7,wa as a8,Sk as a9,P3 as aA,T3 as aB,wC as aC,CU as aD,IU as aE,hS as aF,gS as aG,eD as aH,Tm as aI,E3 as aJ,j3 as aK,fS as aL,Qu as aM,l3 as aN,Um as aO,Iz as aP,I3 as aQ,uc as aR,Np as aS,em as aT,yD as aU,s3 as aV,jm as aW,Om as aX,_$ as aY,tu as aZ,i3 as a_,_6 as aa,I6 as ab,y4 as ac,V3 as ad,dD as ae,Op as af,TD as ag,Ep as ah,mS as ai,dc as aj,iV as ak,$p as al,Qh as am,jp as an,Pz as ao,dm as ap,KU as aq,RV as ar,UU as as,cg as at,pc as au,Tz as av,Jp as aw,RS as ax,j$ as ay,L$ as az,wB as b,cV as b$,Sc as b0,nD as b1,u3 as b2,Wl as b3,Mp as b4,pS as b5,Tp as b6,K3 as b7,X3 as b8,Q3 as b9,b3 as bA,g3 as bB,h3 as bC,f3 as bD,D0 as bE,ME as bF,ws as bG,v3 as bH,x3 as bI,S3 as bJ,y3 as bK,Lh as bL,zh as bM,ou as bN,ru as bO,ID as bP,_D as bQ,C$ as bR,X$ as bS,ib as bT,v4 as bU,cm as bV,cx as bW,WS as bX,lx as bY,PV as bZ,Kg as b_,ug as ba,Z3 as bb,pu as bc,Y3 as bd,J3 as be,Ox as bf,G3 as bg,dg as bh,W3 as bi,Ct as bj,oA as bk,d3 as bl,gx as bm,m3 as bn,_3 as bo,Zd as bp,c3 as bq,Dn as br,L3 as bs,z3 as bt,U3 as bu,H3 as bv,$3 as bw,D3 as bx,uV as by,p3 as bz,bt as c,sb as c0,km as c1,rV as c2,Nx as c3,sV as c4,lV as c5,SV as c6,$$ as c7,gV as c8,fV as c9,hV as ca,E5 as cb,H6 as cc,bV as cd,vV as ce,yV as cf,bD as cg,J$ as ch,PS as ci,O3 as cj,ds as ck,k3 as cl,w3 as cm,N3 as cn,EV as co,Mo as d,cc as e,R3 as f,oV as g,q3 as h,Pp as i,j4 as j,kV as k,IV as l,bk as m,wV as n,Z as o,ND as p,C3 as q,A3 as r,ls as s,Ml as t,mb as u,Oo as v,af as w,bn as x,xV as y,vx as z};