openpond 0.1.1 → 0.2.1

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 (225) hide show
  1. package/README.md +4 -4
  2. package/dist/cache.d.ts +7 -10
  3. package/dist/chunks/actions-command-QP3NMDK4.js +2 -0
  4. package/dist/chunks/app-layer-N7VFRVJ2.js +3 -0
  5. package/dist/chunks/app-server-runtime-OCLPUI7F.js +2 -0
  6. package/dist/chunks/apps-AMG75TI4.js +2 -0
  7. package/dist/chunks/chunk-22UARBPW.js +3 -0
  8. package/dist/chunks/chunk-3A7HZJNE.js +1 -0
  9. package/dist/chunks/chunk-3M53YXEI.js +2 -0
  10. package/dist/chunks/chunk-3NDRIQTI.js +2 -0
  11. package/dist/chunks/chunk-5BBVEWG3.js +2 -0
  12. package/dist/chunks/chunk-5O7ZVCMV.js +6 -0
  13. package/dist/chunks/chunk-6FA3GG5B.js +33 -0
  14. package/dist/chunks/chunk-6MI4KKWF.js +2 -0
  15. package/dist/chunks/chunk-BBG546O6.js +6 -0
  16. package/dist/chunks/chunk-BX4J2VDU.js +2 -0
  17. package/dist/chunks/chunk-BZMVB3GS.js +2 -0
  18. package/dist/chunks/chunk-C5LOZSVS.js +2 -0
  19. package/dist/chunks/chunk-CWQWV2T3.js +2 -0
  20. package/dist/chunks/chunk-DUA3QP6Y.js +19 -0
  21. package/dist/chunks/chunk-EAPFMACH.js +10 -0
  22. package/dist/chunks/chunk-ES2ISFJC.js +66 -0
  23. package/dist/chunks/chunk-F65NIZLM.js +2199 -0
  24. package/dist/chunks/chunk-FGJ5LFPL.js +5 -0
  25. package/dist/chunks/chunk-FTQLQJQV.js +2 -0
  26. package/dist/chunks/chunk-FY7OQ5RK.js +24 -0
  27. package/dist/chunks/chunk-FYCJSUFV.js +53 -0
  28. package/dist/chunks/chunk-GLUWATL5.js +2 -0
  29. package/dist/chunks/chunk-H7IWJN7L.js +17 -0
  30. package/dist/chunks/chunk-HZP5U2AA.js +3 -0
  31. package/dist/chunks/chunk-I5K74TOH.js +3 -0
  32. package/dist/chunks/chunk-IR3YJWPW.js +7 -0
  33. package/dist/chunks/chunk-KU7QOHFT.js +2872 -0
  34. package/dist/chunks/chunk-KV553EWX.js +16 -0
  35. package/dist/chunks/chunk-MGN6GLNZ.js +2 -0
  36. package/dist/chunks/chunk-OG5Q6NXK.js +28 -0
  37. package/dist/chunks/chunk-OGPHXXCD.js +1 -0
  38. package/dist/chunks/chunk-PI36UHRA.js +18 -0
  39. package/dist/chunks/chunk-RWSAGQTP.js +2 -0
  40. package/dist/chunks/chunk-SAE4OIPC.js +2 -0
  41. package/dist/chunks/chunk-SDO4FC4Q.js +2 -0
  42. package/dist/chunks/chunk-UKUVMXOW.js +12 -0
  43. package/dist/chunks/chunk-VCLCFK3O.js +36 -0
  44. package/dist/chunks/chunk-VYUMTRB3.js +5 -0
  45. package/dist/chunks/chunk-X37KMV27.js +1 -0
  46. package/dist/chunks/chunk-XDHAGACI.js +3 -0
  47. package/dist/chunks/chunk-XEOEKFG6.js +71 -0
  48. package/dist/chunks/chunk-ZF7TEGY5.js +5 -0
  49. package/dist/chunks/chunk-ZVOO7FKM.js +2 -0
  50. package/dist/chunks/cli-M2FG7SSI.js +2 -0
  51. package/dist/chunks/configuration-command-XBKBIZBO.js +2 -0
  52. package/dist/chunks/continual-D75WA7E7.js +7 -0
  53. package/dist/chunks/core-commands-LUZVWXQR.js +2 -0
  54. package/dist/chunks/database-X2CUV732.js +2 -0
  55. package/dist/chunks/desktop-test-KGC4JVJ7.js +3 -0
  56. package/dist/chunks/dist-NKLXFA37.js +2 -0
  57. package/dist/chunks/extension-NQ7N5LEY.js +5 -0
  58. package/dist/chunks/help-MWK66XZK.js +8 -0
  59. package/dist/chunks/module-ES6BEMUI-ZVL3F6NW.js +2 -0
  60. package/dist/chunks/module-asyncify-2EFITU5U-R7TVXNAE.js +2 -0
  61. package/dist/chunks/opchat-XJZA3QKZ.js +3 -0
  62. package/dist/chunks/organizations-UECDFEYE.js +2 -0
  63. package/dist/chunks/profile-KUMIZURM.js +3 -0
  64. package/dist/chunks/project-agent-NILMJHLV.js +2 -0
  65. package/dist/chunks/sandbox-command-QHH65OSE.js +2 -0
  66. package/dist/chunks/sandbox-template-N7I63PNU.js +10 -0
  67. package/dist/chunks/src-724HF43W.js +82 -0
  68. package/dist/chunks/src-VTKTTKQO.js +319 -0
  69. package/dist/chunks/taskset-PISBOILQ.js +2 -0
  70. package/dist/chunks/teams-bot-UV4RU53M.js +3 -0
  71. package/dist/chunks/training-2NDOWH5S.js +2 -0
  72. package/dist/chunks/workspaces-XXT4KUD3.js +2 -0
  73. package/dist/cli.js +3 -101
  74. package/dist/client.d.ts +1 -1
  75. package/dist/config.d.ts +1 -0
  76. package/dist/index.js +1 -26305
  77. package/dist/private-json-file.d.ts +1 -2
  78. package/dist/sandbox-template/manifest.js +1 -18380
  79. package/dist/web/assets/App-DxecRQUL.js +176 -0
  80. package/dist/web/assets/AppDialog-B65Eo3gp.js +1 -0
  81. package/dist/web/assets/AppTerminalPanel-B2EKQM7W.js +2 -0
  82. package/dist/web/assets/{AppsView-Ck_OzQWf.js → AppsView-BBoVe7s2.js} +1 -1
  83. package/dist/web/assets/{BrowserSidebar-CqciX8aL.js → BrowserSidebar-CSM1atSJ.js} +1 -1
  84. package/dist/web/assets/{CartesianChart-Y0lsL4vC.js → CartesianChart-CJKfXiEG.js} +1 -1
  85. package/dist/web/assets/{CollaborationTabs-BOb9PjvS.js → CollaborationTabs-BMZamWFC.js} +1 -1
  86. package/dist/web/assets/{CommandMenu-Co6JnmTu.js → CommandMenu-B3U1z2eo.js} +1 -1
  87. package/dist/web/assets/{CommunityView-BbTSeL7h.js → CommunityView-CTyRUcfy.js} +1 -1
  88. package/dist/web/assets/{ComposerCreateImproveStrip-BGzCWVFp.js → ComposerCreateImproveStrip-D7usvRtK.js} +1 -1
  89. package/dist/web/assets/GetStartedView-Ibu7oKWJ.js +1 -0
  90. package/dist/web/assets/HostedModelLearningReview-qnzIkT70.js +1 -0
  91. package/dist/web/assets/HostedModelLearningSettings--PKjpYsy.js +1 -0
  92. package/dist/web/assets/LabModelVersionDetailPage-s9uUN6fV.js +1 -0
  93. package/dist/web/assets/{LabSkillSidebar-C5oS6UmH.js → LabSkillSidebar-BKYseMiJ.js} +1 -1
  94. package/dist/web/assets/LabsRoute-C1FWCoYb.css +1 -0
  95. package/dist/web/assets/LabsRoute-DoRs0K6v.js +32 -0
  96. package/dist/web/assets/MainChatThread-DvuyMcMB.js +2 -0
  97. package/dist/web/assets/MainPane-BWwcxgHD.js +8 -0
  98. package/dist/web/assets/{MarkdownText-DqJarmTh.js → MarkdownText-D8XC5UT_.js} +1 -1
  99. package/dist/web/assets/{Messages-BaT7HOzB.js → Messages-e4A8JUjD.js} +6 -6
  100. package/dist/web/assets/{NativeSkillSidebar-DXp8snN5.js → NativeSkillSidebar-D2Joh8XB.js} +1 -1
  101. package/dist/web/assets/{NewExperienceSwitcher-CLHuGUN5.js → NewExperienceSwitcher-CzGebt2E.js} +1 -1
  102. package/dist/web/assets/{NewProjectDialog-CzpHCAaC.js → NewProjectDialog-CdMTSxUE.js} +1 -1
  103. package/dist/web/assets/{OutputsPage-DIzx-Ge6.js → OutputsPage-m7cSb8dW.js} +1 -1
  104. package/dist/web/assets/{ProjectsPage-DojwrhOy.js → ProjectsPage-C9mz8W1g.js} +1 -1
  105. package/dist/web/assets/RightChatPanelStack-B4LEqKEj.js +1 -0
  106. package/dist/web/assets/{RightSidebarHomePanel-DTzfuEX3.js → RightSidebarHomePanel-DOeUsH7h.js} +1 -1
  107. package/dist/web/assets/ScheduledWorkPage-UXZSSWgA.js +1 -0
  108. package/dist/web/assets/SettingsView-CAH0vreE.css +1 -0
  109. package/dist/web/assets/SettingsView-CQm1ai73.js +9 -0
  110. package/dist/web/assets/TeamChatView-C4haojB7.js +3 -0
  111. package/dist/web/assets/{TerminalOverlay-DnNVrCtu.js → TerminalOverlay-p2GZsuyQ.js} +3 -3
  112. package/dist/web/assets/{TrainingCreationPanel-CDwwyucO.js → TrainingCreationPanel-BYJSlO8X.js} +1 -1
  113. package/dist/web/assets/{TrainingDraftPanel-BijDnV_0.js → TrainingDraftPanel-DR5KlayH.js} +1 -1
  114. package/dist/web/assets/{UsageSettingsSection-Y5BFAu1p.js → UsageSettingsSection-BQToNXE4.js} +5 -5
  115. package/dist/web/assets/{WorkSidebarPanel-CkJlvZKm.js → WorkSidebarPanel--EeytWeg.js} +1 -1
  116. package/dist/web/assets/WorkspaceDiffPanel-BrovSYhn.js +14 -0
  117. package/dist/web/assets/{WorkspaceEnvironmentMenu-D8knAy1q.js → WorkspaceEnvironmentMenu-l-keRgvj.js} +3 -3
  118. package/dist/web/assets/{WorkspaceGitDialogs-_LHTrvh6.js → WorkspaceGitDialogs-aicWzaZu.js} +1 -1
  119. package/dist/web/assets/{WorkspaceMonacoEditor-B2B7OM_L.js → WorkspaceMonacoEditor-CO_E74jM.js} +36 -36
  120. package/dist/web/assets/{arrow-up-right-4nAzMtjW.js → arrow-up-right-rwPXNfVn.js} +1 -1
  121. package/dist/web/assets/chat-file-links-B3jDstSC.js +1 -0
  122. package/dist/web/assets/chevron-up-D089nvYQ.js +1 -0
  123. package/dist/web/assets/{clipboard-BzjUoZFo.js → clipboard-DwEExyU4.js} +1 -1
  124. package/dist/web/assets/{cloud-upload-CsrrwS-b.js → cloud-upload-D2he0-vQ.js} +1 -1
  125. package/dist/web/assets/{cssMode-CIbSSHKJ.js → cssMode-DS4k0NcI.js} +1 -1
  126. package/dist/web/assets/{folder-open-vRTuLzpS.js → folder-open-CAOLduKD.js} +1 -1
  127. package/dist/web/assets/{folder-plus-hyqwgUnx.js → folder-plus-D56MrxVT.js} +1 -1
  128. package/dist/web/assets/{git-commit-horizontal-CaxKfeYa.js → git-commit-horizontal-CeNM0oKJ.js} +1 -1
  129. package/dist/web/assets/{htmlMode-C3MGQGam.js → htmlMode-Xkni5erh.js} +1 -1
  130. package/dist/web/assets/{index-ByQIHpc9.css → index-BGMzUaup.css} +1 -1
  131. package/dist/web/assets/{index-Dvq7bpBG.js → index-KwyAyscP.js} +1 -1
  132. package/dist/web/assets/{info-aYWeE1Iw.js → info-CcrBaEE_.js} +1 -1
  133. package/dist/web/assets/{jsonMode-CpD6UkT7.js → jsonMode-C4YPbQB7.js} +1 -1
  134. package/dist/web/assets/{lspLanguageFeatures-DpcK8ZI6.js → lspLanguageFeatures-CF5oMTz6.js} +1 -1
  135. package/dist/web/assets/{minimize-2-DeYg7XqB.js → minimize-2-DzHQnInk.js} +1 -1
  136. package/dist/web/assets/{monaco.contribution-CrrdDQgP.js → monaco.contribution-0EN4mGCC.js} +2 -2
  137. package/dist/web/assets/{monaco.contribution-JWFq0HzV.js → monaco.contribution-B4qcTP0w.js} +2 -2
  138. package/dist/web/assets/{monaco.contribution-BDTM0ZJq.js → monaco.contribution-CJK_NrBm.js} +2 -2
  139. package/dist/web/assets/{monaco.contribution-C-_ekTxy.js → monaco.contribution-CkPGKNd-.js} +2 -2
  140. package/dist/web/assets/{play-BqgRTddV.js → play-p3-AMTPL.js} +1 -1
  141. package/dist/web/assets/{python-B67wope9.js → python-B0kpTxAZ.js} +1 -1
  142. package/dist/web/assets/{refresh-cw-DwMA_2On.js → refresh-cw-_jbTIzzr.js} +1 -1
  143. package/dist/web/assets/{save-B0BKh5oQ.js → save-Cy6hEotx.js} +1 -1
  144. package/dist/web/assets/{square-LY3oz82L.js → square-DKQkcrOH.js} +1 -1
  145. package/dist/web/assets/{toggleHighContrast-B2jka5B1.js → toggleHighContrast-Bnk1VVVq.js} +1 -1
  146. package/dist/web/assets/{tsMode-1MUwluYD.js → tsMode-BDrSVy7V.js} +1 -1
  147. package/dist/web/assets/{upload-bSKSkFVa.js → upload-COn0my_O.js} +1 -1
  148. package/dist/web/assets/{useLocalAgentSchedules--jnnM4Fz.js → useLocalAgentSchedules-iZNB4Oee.js} +1 -1
  149. package/dist/web/assets/{wifi-off-DA34iPmr.js → wifi-off-Cqt-ZLXY.js} +1 -1
  150. package/dist/web/assets/{workers-CczIcRcl.js → workers-hu0Ym93h.js} +1 -1
  151. package/dist/web/assets/{yaml-DwEGoHA9.js → yaml-D-JLDGL6.js} +1 -1
  152. package/dist/web/index.html +2 -2
  153. package/docs/command-reference.md +28 -2
  154. package/package.json +10 -7
  155. package/dist/chunks/actions-command-6N5XWMR6.js +0 -185
  156. package/dist/chunks/app-layer-XEYHFJHI.js +0 -214
  157. package/dist/chunks/app-server-runtime-FJM2EQPH.js +0 -21
  158. package/dist/chunks/apps-GSXUDK6V.js +0 -427
  159. package/dist/chunks/chunk-2JABRRNR.js +0 -183
  160. package/dist/chunks/chunk-47EIAYI7.js +0 -2162
  161. package/dist/chunks/chunk-4L3ZJS2T.js +0 -1207
  162. package/dist/chunks/chunk-5TKZBMQM.js +0 -731
  163. package/dist/chunks/chunk-6G6MDZLM.js +0 -14509
  164. package/dist/chunks/chunk-BVY5JYM6.js +0 -512
  165. package/dist/chunks/chunk-C5TKGE5Y.js +0 -1275
  166. package/dist/chunks/chunk-CNTM26OW.js +0 -602
  167. package/dist/chunks/chunk-D7BO5Y5J.js +0 -1531
  168. package/dist/chunks/chunk-DJL4TJYG.js +0 -70
  169. package/dist/chunks/chunk-DLQQIWN2.js +0 -648
  170. package/dist/chunks/chunk-DNXBJZAU.js +0 -630
  171. package/dist/chunks/chunk-EFET7LB7.js +0 -1331
  172. package/dist/chunks/chunk-FQS2QL5F.js +0 -14522
  173. package/dist/chunks/chunk-HFPUR4CQ.js +0 -669
  174. package/dist/chunks/chunk-J3YDKJFD.js +0 -88
  175. package/dist/chunks/chunk-J7PYGDRY.js +0 -634
  176. package/dist/chunks/chunk-JTHL5XJ2.js +0 -1838
  177. package/dist/chunks/chunk-KSRWKXRB.js +0 -12
  178. package/dist/chunks/chunk-KWDOAJJI.js +0 -238
  179. package/dist/chunks/chunk-MUMPWI4O.js +0 -92
  180. package/dist/chunks/chunk-N3TGCM7J.js +0 -1135
  181. package/dist/chunks/chunk-NTK22KJD.js +0 -10707
  182. package/dist/chunks/chunk-O6B6YCMI.js +0 -57688
  183. package/dist/chunks/chunk-R3C3MNSI.js +0 -140
  184. package/dist/chunks/chunk-SMNFI2FU.js +0 -113
  185. package/dist/chunks/chunk-UACZUFIA.js +0 -47
  186. package/dist/chunks/chunk-W5GKHH77.js +0 -168
  187. package/dist/chunks/chunk-WBAZFKC7.js +0 -1643
  188. package/dist/chunks/chunk-X7ZG4TSW.js +0 -3063
  189. package/dist/chunks/chunk-YVCYVDNP.js +0 -746
  190. package/dist/chunks/cli-6PFRZ2WV.js +0 -21
  191. package/dist/chunks/continual-FYDKLCO7.js +0 -803
  192. package/dist/chunks/core-commands-MAN3CSJQ.js +0 -48
  193. package/dist/chunks/desktop-test-OE5SST2W.js +0 -146
  194. package/dist/chunks/extension-J3CIEDP4.js +0 -10041
  195. package/dist/chunks/help-JNGJJFU5.js +0 -67
  196. package/dist/chunks/opchat-6HEQJFLL.js +0 -167
  197. package/dist/chunks/organizations-MWAPNOCK.js +0 -804
  198. package/dist/chunks/profile-P7HMONTZ.js +0 -1134
  199. package/dist/chunks/project-agent-2RAK7GAZ.js +0 -514
  200. package/dist/chunks/sandbox-command-G22CPFNK.js +0 -1659
  201. package/dist/chunks/sandbox-template-S4WRUWJ6.js +0 -1653
  202. package/dist/chunks/src-BKBZ7WLO.js +0 -3624
  203. package/dist/chunks/src-RTGN2O4H.js +0 -65745
  204. package/dist/chunks/taskset-BMI7KOWP.js +0 -66
  205. package/dist/chunks/teams-bot-5VBYEN7M.js +0 -144
  206. package/dist/chunks/training-UPVSGDTB.js +0 -17
  207. package/dist/chunks/workspaces-IJQPWX3H.js +0 -99
  208. package/dist/web/assets/App-BOkhmdHu.js +0 -173
  209. package/dist/web/assets/AppDialog-BCjKFUBn.js +0 -1
  210. package/dist/web/assets/AppTerminalPanel-DRU8GIfy.js +0 -2
  211. package/dist/web/assets/GetStartedView-jEogFjxP.js +0 -1
  212. package/dist/web/assets/LabModelVersionDetailPage-CrudId_1.js +0 -1
  213. package/dist/web/assets/LabsRoute-9v8qwEBc.js +0 -2
  214. package/dist/web/assets/LabsRoute-CGFgymTX.css +0 -1
  215. package/dist/web/assets/MainChatThread-VtMpAxlP.js +0 -2
  216. package/dist/web/assets/MainPane-BbknUzp3.js +0 -8
  217. package/dist/web/assets/RightChatPanelStack-CIE5bgmO.js +0 -1
  218. package/dist/web/assets/ScheduledWorkPage-DdbcQGSv.js +0 -1
  219. package/dist/web/assets/SettingsView-CC5GXaE1.css +0 -1
  220. package/dist/web/assets/SettingsView-QT_OLmDh.js +0 -6
  221. package/dist/web/assets/TeamChatView-C4-nG1tC.js +0 -3
  222. package/dist/web/assets/WorkspaceDiffPanel-CBgzmBk8.js +0 -14
  223. package/dist/web/assets/chat-file-links-Bned0MT7.js +0 -1
  224. package/dist/web/assets/chevron-up-DK7ejCfk.js +0 -1
  225. package/dist/web/assets/index-66-ohHD5.js +0 -1
@@ -1,173 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CommandMenu-Co6JnmTu.js","./index-Dvq7bpBG.js","./index-ByQIHpc9.css","./CommandMenu-hNQCm8mw.css","./SettingsView-QT_OLmDh.js","./chat-file-links-Bned0MT7.js","./refresh-cw-DwMA_2On.js","./save-B0BKh5oQ.js","./folder-open-vRTuLzpS.js","./chevron-up-DK7ejCfk.js","./play-BqgRTddV.js","./wifi-off-DA34iPmr.js","./useLocalAgentSchedules--jnnM4Fz.js","./cloud-upload-CsrrwS-b.js","./git-commit-horizontal-CaxKfeYa.js","./index-66-ohHD5.js","./folder-plus-hyqwgUnx.js","./AppDialog-BCjKFUBn.js","./WorkspaceDiffPanel-CBgzmBk8.js","./MarkdownText-DqJarmTh.js","./desktop-files-BQj1J-ob.js","./training-model-data-CKOkpBBL.js","./info-aYWeE1Iw.js","./minimize-2-DeYg7XqB.js","./clipboard-BzjUoZFo.js","./SettingsView-CC5GXaE1.css","./git-dialogs-BZDqS1eT.css","./NewProjectDialog-CzpHCAaC.js","./WorkspaceGitDialogs-_LHTrvh6.js","./upload-bSKSkFVa.js","./WorkspaceEnvironmentMenu-D8knAy1q.js","./square-LY3oz82L.js","./WorkspaceEnvironmentMenu-DGIFdG3o.css","./MainPane-BbknUzp3.js","./arrow-up-right-4nAzMtjW.js"])))=>i.map(i=>d[i]);
2
- import{r as g,j as v,_ as ri}from"./index-Dvq7bpBG.js";var Bf;function ge(e,t,n){function a(d,p){if(d._zod||Object.defineProperty(d,"_zod",{value:{def:p,constr:s,traits:new Set},enumerable:!1}),d._zod.traits.has(e))return;d._zod.traits.add(e),t(d,p);const m=s.prototype,h=Object.keys(m);for(let S=0;S<h.length;S++){const y=h[S];y in d||(d[y]=m[y].bind(d))}}const i=n?.Parent??Object;class r extends i{}Object.defineProperty(r,"name",{value:e});function s(d){var p;const m=n?.Parent?new r:this;a(m,d),(p=m._zod).deferred??(p.deferred=[]);for(const h of m._zod.deferred)h();return m}return Object.defineProperty(s,"init",{value:a}),Object.defineProperty(s,Symbol.hasInstance,{value:d=>n?.Parent&&d instanceof n.Parent?!0:d?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}class nr extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class iv extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(Bf=globalThis).__zod_globalConfig??(Bf.__zod_globalConfig={});const up=globalThis.__zod_globalConfig;function ho(e){return up}function rv(e){const t=Object.values(e).filter(a=>typeof a=="number");return Object.entries(e).filter(([a,i])=>t.indexOf(+a)===-1).map(([a,i])=>i)}function fm(e,t){return typeof t=="bigint"?t.toString():t}function hc(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function mp(e){return e==null}function pp(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function $_(e,t){const n=e/t,a=Math.round(n),i=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-a)<i?0:n-a}const Ff=Symbol("evaluating");function Tt(e,t,n){let a;Object.defineProperty(e,t,{get(){if(a!==Ff)return a===void 0&&(a=Ff,a=n()),a},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function si(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function jo(...e){const t={};for(const n of e){const a=Object.getOwnPropertyDescriptors(n);Object.assign(t,a)}return Object.defineProperties({},t)}function Vf(e){return JSON.stringify(e)}function D_(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const sv="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Is(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const L_=hc(()=>{if(up.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function or(e){if(Is(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Is(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function lv(e){return or(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const z_=new Set(["string","number","symbol"]);function ir(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Oo(e,t,n){const a=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(a._zod.parent=e),a}function ot(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 U_(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const H_={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 q_(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 r=jo(e._zod.def,{get shape(){const s={};for(const d in t){if(!(d in n.shape))throw new Error(`Unrecognized key: "${d}"`);t[d]&&(s[d]=n.shape[d])}return si(this,"shape",s),s},checks:[]});return Oo(e,r)}function B_(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 r=jo(e._zod.def,{get shape(){const s={...e._zod.def.shape};for(const d in t){if(!(d in n.shape))throw new Error(`Unrecognized key: "${d}"`);t[d]&&delete s[d]}return si(this,"shape",s),s},checks:[]});return Oo(e,r)}function F_(e,t){if(!or(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const r=e._zod.def.shape;for(const s in t)if(Object.getOwnPropertyDescriptor(r,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const i=jo(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return si(this,"shape",r),r}});return Oo(e,i)}function V_(e,t){if(!or(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=jo(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t};return si(this,"shape",a),a}});return Oo(e,n)}function W_(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=jo(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t._zod.def.shape};return si(this,"shape",a),a},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Oo(e,n)}function K_(e,t,n){const i=t._zod.def.checks;if(i&&i.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const s=jo(t._zod.def,{get shape(){const d=t._zod.def.shape,p={...d};if(n)for(const m in n){if(!(m in d))throw new Error(`Unrecognized key: "${m}"`);n[m]&&(p[m]=e?new e({type:"optional",innerType:d[m]}):d[m])}else for(const m in d)p[m]=e?new e({type:"optional",innerType:d[m]}):d[m];return si(this,"shape",p),p},checks:[]});return Oo(t,s)}function G_(e,t,n){const a=jo(t._zod.def,{get shape(){const i=t._zod.def.shape,r={...i};if(n)for(const s in n){if(!(s in r))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(r[s]=new e({type:"nonoptional",innerType:i[s]}))}else for(const s in i)r[s]=new e({type:"nonoptional",innerType:i[s]});return si(this,"shape",r),r}});return Oo(t,a)}function Ki(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 Z_(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 Gi(e,t){return t.map(n=>{var a;return(a=n).path??(a.path=[]),n.path.unshift(e),n})}function kl(e){return typeof e=="string"?e:e?.message}function go(e,t,n){const a=e.message?e.message:kl(e.inst?._zod.def?.error?.(e))??kl(t?.error?.(e))??kl(n.customError?.(e))??kl(n.localeError?.(e))??"Invalid input",{inst:i,continue:r,input:s,...d}=e;return d.path??(d.path=[]),d.message=a,t?.reportInput&&(d.input=s),d}function fp(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Cs(...e){const[t,n,a]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:a}:{...t}}const cv=(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,fm,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},dv=ge("$ZodError",cv),uv=ge("$ZodError",cv,{Parent:Error});function J_(e,t=n=>n.message){const n={},a=[];for(const i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):a.push(t(i));return{formErrors:a,fieldErrors:n}}function Y_(e,t=n=>n.message){const n={_errors:[]},a=(i,r=[])=>{for(const s of i.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(d=>a({issues:d},[...r,...s.path]));else if(s.code==="invalid_key")a({issues:s.issues},[...r,...s.path]);else if(s.code==="invalid_element")a({issues:s.issues},[...r,...s.path]);else{const d=[...r,...s.path];if(d.length===0)n._errors.push(t(s));else{let p=n,m=0;for(;m<d.length;){const h=d[m];m===d.length-1?(p[h]=p[h]||{_errors:[]},p[h]._errors.push(t(s))):p[h]=p[h]||{_errors:[]},p=p[h],m++}}}};return a(e),n}const hp=e=>(t,n,a,i)=>{const r=a?{...a,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},r);if(s instanceof Promise)throw new nr;if(s.issues.length){const d=new(i?.Err??e)(s.issues.map(p=>go(p,r,ho())));throw sv(d,i?.callee),d}return s.value},gp=e=>async(t,n,a,i)=>{const r=a?{...a,async:!0}:{async:!0};let s=t._zod.run({value:n,issues:[]},r);if(s instanceof Promise&&(s=await s),s.issues.length){const d=new(i?.Err??e)(s.issues.map(p=>go(p,r,ho())));throw sv(d,i?.callee),d}return s.value},gc=e=>(t,n,a)=>{const i=a?{...a,async:!1}:{async:!1},r=t._zod.run({value:n,issues:[]},i);if(r instanceof Promise)throw new nr;return r.issues.length?{success:!1,error:new(e??dv)(r.issues.map(s=>go(s,i,ho())))}:{success:!0,data:r.value}},X_=gc(uv),bc=e=>async(t,n,a)=>{const i=a?{...a,async:!0}:{async:!0};let r=t._zod.run({value:n,issues:[]},i);return r instanceof Promise&&(r=await r),r.issues.length?{success:!1,error:new e(r.issues.map(s=>go(s,i,ho())))}:{success:!0,data:r.value}},Q_=bc(uv),ew=e=>(t,n,a)=>{const i=a?{...a,direction:"backward"}:{direction:"backward"};return hp(e)(t,n,i)},tw=e=>(t,n,a)=>hp(e)(t,n,a),nw=e=>async(t,n,a)=>{const i=a?{...a,direction:"backward"}:{direction:"backward"};return gp(e)(t,n,i)},aw=e=>async(t,n,a)=>gp(e)(t,n,a),ow=e=>(t,n,a)=>{const i=a?{...a,direction:"backward"}:{direction:"backward"};return gc(e)(t,n,i)},iw=e=>(t,n,a)=>gc(e)(t,n,a),rw=e=>async(t,n,a)=>{const i=a?{...a,direction:"backward"}:{direction:"backward"};return bc(e)(t,n,i)},sw=e=>async(t,n,a)=>bc(e)(t,n,a),lw=/^[cC][0-9a-z]{6,}$/,cw=/^[0-9a-z]+$/,dw=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,uw=/^[0-9a-vA-V]{20}$/,mw=/^[A-Za-z0-9]{27}$/,pw=/^[a-zA-Z0-9_-]{21}$/,fw=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,hw=/^([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})$/,Wf=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)$/,gw=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,bw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function vw(){return new RegExp(bw,"u")}const yw=/^(?:(?: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])$/,Sw=/^(([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}|:))$/,xw=/^((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])$/,kw=/^(([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])$/,_w=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,mv=/^[A-Za-z0-9_-]*$/,ww=/^https?$/,Iw=/^\+[1-9]\d{6,14}$/,pv="(?:(?:\\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])))",Cw=new RegExp(`^${pv}$`);function fv(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 Rw(e){return new RegExp(`^${fv(e)}$`)}function Aw(e){const t=fv({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(`^${pv}T(?:${a})$`)}const Pw=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Tw=/^-?\d+$/,hv=/^-?\d+(?:\.\d+)?$/,Ew=/^(?:true|false)$/i,Mw=/^null$/i,jw=/^[^A-Z]*$/,Ow=/^[^a-z]*$/,Jn=ge("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),gv={number:"number",bigint:"bigint",object:"date"},bv=ge("$ZodCheckLessThan",(e,t)=>{Jn.init(e,t);const n=gv[typeof t.value];e._zod.onattach.push(a=>{const i=a._zod.bag,r=(t.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<r&&(t.inclusive?i.maximum=t.value:i.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})}}),vv=ge("$ZodCheckGreaterThan",(e,t)=>{Jn.init(e,t);const n=gv[typeof t.value];e._zod.onattach.push(a=>{const i=a._zod.bag,r=(t.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>r&&(t.inclusive?i.minimum=t.value:i.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})}}),Nw=ge("$ZodCheckMultipleOf",(e,t)=>{Jn.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):$_(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)=>{Jn.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),a=n?"int":"number",[i,r]=H_[t.format];e._zod.onattach.push(s=>{const d=s._zod.bag;d.format=t.format,d.minimum=i,d.maximum=r,n&&(d.pattern=Tw)}),e._zod.check=s=>{const d=s.value;if(n){if(!Number.isInteger(d)){s.issues.push({expected:a,format:t.format,code:"invalid_type",continue:!1,input:d,inst:e});return}if(!Number.isSafeInteger(d)){d>0?s.issues.push({input:d,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:d,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}}d<i&&s.issues.push({origin:"number",input:d,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),d>r&&s.issues.push({origin:"number",input:d,code:"too_big",maximum:r,inclusive:!0,inst:e,continue:!t.abort})}}),Dw=ge("$ZodCheckMaxLength",(e,t)=>{var n;Jn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const i=a.value;return!mp(i)&&i.length!==void 0}),e._zod.onattach.push(a=>{const i=a._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<i&&(a._zod.bag.maximum=t.maximum)}),e._zod.check=a=>{const i=a.value;if(i.length<=t.maximum)return;const s=fp(i);a.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Lw=ge("$ZodCheckMinLength",(e,t)=>{var n;Jn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const i=a.value;return!mp(i)&&i.length!==void 0}),e._zod.onattach.push(a=>{const i=a._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(a._zod.bag.minimum=t.minimum)}),e._zod.check=a=>{const i=a.value;if(i.length>=t.minimum)return;const s=fp(i);a.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),zw=ge("$ZodCheckLengthEquals",(e,t)=>{var n;Jn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const i=a.value;return!mp(i)&&i.length!==void 0}),e._zod.onattach.push(a=>{const i=a._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=a=>{const i=a.value,r=i.length;if(r===t.length)return;const s=fp(i),d=r>t.length;a.issues.push({origin:s,...d?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:a.value,inst:e,continue:!t.abort})}}),vc=ge("$ZodCheckStringFormat",(e,t)=>{var n,a;Jn.init(e,t),e._zod.onattach.push(i=>{const r=i._zod.bag;r.format=t.format,t.pattern&&(r.patterns??(r.patterns=new Set),r.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(a=e._zod).check??(a.check=()=>{})}),Uw=ge("$ZodCheckRegex",(e,t)=>{vc.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})}}),Hw=ge("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=jw),vc.init(e,t)}),qw=ge("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Ow),vc.init(e,t)}),Bw=ge("$ZodCheckIncludes",(e,t)=>{Jn.init(e,t);const n=ir(t.includes),a=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=a,e._zod.onattach.push(i=>{const r=i._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(a)}),e._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),Fw=ge("$ZodCheckStartsWith",(e,t)=>{Jn.init(e,t);const n=new RegExp(`^${ir(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(a=>{const i=a._zod.bag;i.patterns??(i.patterns=new Set),i.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})}}),Vw=ge("$ZodCheckEndsWith",(e,t)=>{Jn.init(e,t);const n=new RegExp(`.*${ir(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(a=>{const i=a._zod.bag;i.patterns??(i.patterns=new Set),i.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})}}),Ww=ge("$ZodCheckOverwrite",(e,t)=>{Jn.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class Kw{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),i=Math.min(...a.map(s=>s.length-s.trimStart().length)),r=a.map(s=>s.slice(i)).map(s=>" ".repeat(this.indent*2)+s);for(const s of r)this.content.push(s)}compile(){const t=Function,n=this?.args,i=[...(this?.content??[""]).map(r=>` ${r}`)];return new t(...n,i.join(`
4
- `))}}const Gw={major:4,minor:4,patch:3},Ft=ge("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Gw;const a=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&a.unshift(e);for(const i of a)for(const r of i._zod.onattach)r(e);if(a.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const i=(s,d,p)=>{let m=Ki(s),h;for(const S of d){if(S._zod.def.when){if(Z_(s)||!S._zod.def.when(s))continue}else if(m)continue;const y=s.issues.length,w=S._zod.check(s);if(w instanceof Promise&&p?.async===!1)throw new nr;if(h||w instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await w,s.issues.length!==y&&(m||(m=Ki(s,y)))});else{if(s.issues.length===y)continue;m||(m=Ki(s,y))}}return h?h.then(()=>s):s},r=(s,d,p)=>{if(Ki(s))return s.aborted=!0,s;const m=i(d,a,p);if(m instanceof Promise){if(p.async===!1)throw new nr;return m.then(h=>e._zod.parse(h,p))}return e._zod.parse(m,p)};e._zod.run=(s,d)=>{if(d.skipChecks)return e._zod.parse(s,d);if(d.direction==="backward"){const m=e._zod.parse({value:s.value,issues:[]},{...d,skipChecks:!0});return m instanceof Promise?m.then(h=>r(h,s,d)):r(m,s,d)}const p=e._zod.parse(s,d);if(p instanceof Promise){if(d.async===!1)throw new nr;return p.then(m=>i(m,a,d))}return i(p,a,d)}}Tt(e,"~standard",()=>({validate:i=>{try{const r=X_(e,i);return r.success?{value:r.data}:{issues:r.error?.issues}}catch{return Q_(e,i).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),bp=ge("$ZodString",(e,t)=>{Ft.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Pw(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}}),Vt=ge("$ZodStringFormat",(e,t)=>{vc.init(e,t),bp.init(e,t)}),Zw=ge("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=hw),Vt.init(e,t)}),Jw=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=Wf(a))}else t.pattern??(t.pattern=Wf());Vt.init(e,t)}),Yw=ge("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=gw),Vt.init(e,t)}),Xw=ge("$ZodURL",(e,t)=>{Vt.init(e,t),e._zod.check=n=>{try{const a=n.value.trim();if(!t.normalize&&t.protocol?.source===ww.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 i=new URL(a);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.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(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.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=i.href:n.value=a;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Qw=ge("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=vw()),Vt.init(e,t)}),eI=ge("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=pw),Vt.init(e,t)}),tI=ge("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=lw),Vt.init(e,t)}),nI=ge("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=cw),Vt.init(e,t)}),aI=ge("$ZodULID",(e,t)=>{t.pattern??(t.pattern=dw),Vt.init(e,t)}),oI=ge("$ZodXID",(e,t)=>{t.pattern??(t.pattern=uw),Vt.init(e,t)}),iI=ge("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=mw),Vt.init(e,t)}),rI=ge("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Aw(t)),Vt.init(e,t)}),sI=ge("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Cw),Vt.init(e,t)}),lI=ge("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Rw(t)),Vt.init(e,t)}),cI=ge("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=fw),Vt.init(e,t)}),dI=ge("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=yw),Vt.init(e,t),e._zod.bag.format="ipv4"}),uI=ge("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Sw),Vt.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})}}}),mI=ge("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=xw),Vt.init(e,t)}),pI=ge("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=kw),Vt.init(e,t),e._zod.check=n=>{const a=n.value.split("/");try{if(a.length!==2)throw new Error;const[i,r]=a;if(!r)throw new Error;const s=Number(r);if(`${s}`!==r)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${i}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function yv(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const fI=ge("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=_w),Vt.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{yv(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function hI(e){if(!mv.test(e))return!1;const t=e.replace(/[-_]/g,a=>a==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return yv(n)}const gI=ge("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=mv),Vt.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{hI(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),bI=ge("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Iw),Vt.init(e,t)});function vI(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[a]=n;if(!a)return!1;const i=JSON.parse(atob(a));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}}const yI=ge("$ZodJWT",(e,t)=>{Vt.init(e,t),e._zod.check=n=>{vI(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Sv=ge("$ZodNumber",(e,t)=>{Ft.init(e,t),e._zod.pattern=e._zod.bag.pattern??hv,e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const i=n.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return n;const r=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...r?{received:r}:{}}),n}}),SI=ge("$ZodNumberFormat",(e,t)=>{$w.init(e,t),Sv.init(e,t)}),xI=ge("$ZodBoolean",(e,t)=>{Ft.init(e,t),e._zod.pattern=Ew,e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=!!n.value}catch{}const i=n.value;return typeof i=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}}),kI=ge("$ZodNull",(e,t)=>{Ft.init(e,t),e._zod.pattern=Mw,e._zod.values=new Set([null]),e._zod.parse=(n,a)=>{const i=n.value;return i===null||n.issues.push({expected:"null",code:"invalid_type",input:i,inst:e}),n}}),_I=ge("$ZodUnknown",(e,t)=>{Ft.init(e,t),e._zod.parse=n=>n}),wI=ge("$ZodNever",(e,t)=>{Ft.init(e,t),e._zod.parse=(n,a)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Kf(e,t,n){e.issues.length&&t.issues.push(...Gi(n,e.issues)),t.value[n]=e.value}const II=ge("$ZodArray",(e,t)=>{Ft.init(e,t),e._zod.parse=(n,a)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);const r=[];for(let s=0;s<i.length;s++){const d=i[s],p=t.element._zod.run({value:d,issues:[]},a);p instanceof Promise?r.push(p.then(m=>Kf(m,n,s))):Kf(p,n,s)}return r.length?Promise.all(r).then(()=>n):n}});function Yl(e,t,n,a,i,r){const s=n in a;if(e.issues.length){if(i&&r&&!s)return;t.issues.push(...Gi(n,e.issues))}if(!s&&!i){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 xv(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=U_(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function kv(e,t,n,a,i,r){const s=[],d=i.keySet,p=i.catchall._zod,m=p.def.type,h=p.optin==="optional",S=p.optout==="optional";for(const y in t){if(y==="__proto__"||d.has(y))continue;if(m==="never"){s.push(y);continue}const w=p.run({value:t[y],issues:[]},a);w instanceof Promise?e.push(w.then(R=>Yl(R,n,y,t,h,S))):Yl(w,n,y,t,h,S)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:r}),e.length?Promise.all(e).then(()=>n):n}const CI=ge("$ZodObject",(e,t)=>{if(Ft.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const d=t.shape;Object.defineProperty(t,"shape",{get:()=>{const p={...d};return Object.defineProperty(t,"shape",{value:p}),p}})}const a=hc(()=>xv(t));Tt(e._zod,"propValues",()=>{const d=t.shape,p={};for(const m in d){const h=d[m]._zod;if(h.values){p[m]??(p[m]=new Set);for(const S of h.values)p[m].add(S)}}return p});const i=Is,r=t.catchall;let s;e._zod.parse=(d,p)=>{s??(s=a.value);const m=d.value;if(!i(m))return d.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),d;d.value={};const h=[],S=s.shape;for(const y of s.keys){const w=S[y],R=w._zod.optin==="optional",A=w._zod.optout==="optional",N=w._zod.run({value:m[y],issues:[]},p);N instanceof Promise?h.push(N.then(O=>Yl(O,d,y,m,R,A))):Yl(N,d,y,m,R,A)}return r?kv(h,m,d,p,a.value,e):h.length?Promise.all(h).then(()=>d):d}}),RI=ge("$ZodObjectJIT",(e,t)=>{CI.init(e,t);const n=e._zod.parse,a=hc(()=>xv(t)),i=y=>{const w=new Kw(["shape","payload","ctx"]),R=a.value,A=x=>{const I=Vf(x);return`shape[${I}]._zod.run({ value: input[${I}], issues: [] }, ctx)`};w.write("const input = payload.value;");const N=Object.create(null);let O=0;for(const x of R.keys)N[x]=`key_${O++}`;w.write("const newResult = {};");for(const x of R.keys){const I=N[x],P=Vf(x),E=y[x],T=E?._zod?.optin==="optional",z=E?._zod?.optout==="optional";w.write(`const ${I} = ${A(x)};`),T&&z?w.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?w.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
- `):w.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
- `)}w.write("payload.value = newResult;"),w.write("return payload;");const D=w.compile();return(x,I)=>D(y,x,I)};let r;const s=Is,d=!up.jitless,m=d&&L_.value,h=t.catchall;let S;e._zod.parse=(y,w)=>{S??(S=a.value);const R=y.value;return s(R)?d&&m&&w?.async===!1&&w.jitless!==!0?(r||(r=i(t.shape)),y=r(y,w),h?kv([],R,y,w,S,e):y):n(y,w):(y.issues.push({expected:"object",code:"invalid_type",input:R,inst:e}),y)}});function Gf(e,t,n,a){for(const r of e)if(r.issues.length===0)return t.value=r.value,t;const i=e.filter(r=>!Ki(r));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(r=>r.issues.map(s=>go(s,a,ho())))}),t)}const _v=ge("$ZodUnion",(e,t)=>{Ft.init(e,t),Tt(e._zod,"optin",()=>t.options.some(a=>a._zod.optin==="optional")?"optional":void 0),Tt(e._zod,"optout",()=>t.options.some(a=>a._zod.optout==="optional")?"optional":void 0),Tt(e._zod,"values",()=>{if(t.options.every(a=>a._zod.values))return new Set(t.options.flatMap(a=>Array.from(a._zod.values)))}),Tt(e._zod,"pattern",()=>{if(t.options.every(a=>a._zod.pattern)){const a=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${a.map(i=>pp(i.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(a,i)=>{if(n)return n(a,i);let r=!1;const s=[];for(const d of t.options){const p=d._zod.run({value:a.value,issues:[]},i);if(p instanceof Promise)s.push(p),r=!0;else{if(p.issues.length===0)return p;s.push(p)}}return r?Promise.all(s).then(d=>Gf(d,a,e,i)):Gf(s,a,e,i)}}),AI=ge("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,_v.init(e,t);const n=e._zod.parse;Tt(e._zod,"propValues",()=>{const i={};for(const r of t.options){const s=r._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(const[d,p]of Object.entries(s)){i[d]||(i[d]=new Set);for(const m of p)i[d].add(m)}}return i});const a=hc(()=>{const i=t.options,r=new Map;for(const s of i){const d=s._zod.propValues?.[t.discriminator];if(!d||d.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const p of d){if(r.has(p))throw new Error(`Duplicate discriminator value "${String(p)}"`);r.set(p,s)}}return r});e._zod.parse=(i,r)=>{const s=i.value;if(!Is(s))return i.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),i;const d=a.value.get(s?.[t.discriminator]);return d?d._zod.run(i,r):t.unionFallback||r.direction==="backward"?n(i,r):(i.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}),i)}}),PI=ge("$ZodIntersection",(e,t)=>{Ft.init(e,t),e._zod.parse=(n,a)=>{const i=n.value,r=t.left._zod.run({value:i,issues:[]},a),s=t.right._zod.run({value:i,issues:[]},a);return r instanceof Promise||s instanceof Promise?Promise.all([r,s]).then(([p,m])=>Zf(n,p,m)):Zf(n,r,s)}});function hm(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(or(e)&&or(t)){const n=Object.keys(t),a=Object.keys(e).filter(r=>n.indexOf(r)!==-1),i={...e,...t};for(const r of a){const s=hm(e[r],t[r]);if(!s.valid)return{valid:!1,mergeErrorPath:[r,...s.mergeErrorPath]};i[r]=s.data}return{valid:!0,data:i}}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 i=e[a],r=t[a],s=hm(i,r);if(!s.valid)return{valid:!1,mergeErrorPath:[a,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Zf(e,t,n){const a=new Map;let i;for(const d of t.issues)if(d.code==="unrecognized_keys"){i??(i=d);for(const p of d.keys)a.has(p)||a.set(p,{}),a.get(p).l=!0}else e.issues.push(d);for(const d of n.issues)if(d.code==="unrecognized_keys")for(const p of d.keys)a.has(p)||a.set(p,{}),a.get(p).r=!0;else e.issues.push(d);const r=[...a].filter(([,d])=>d.l&&d.r).map(([d])=>d);if(r.length&&i&&e.issues.push({...i,keys:r}),Ki(e))return e;const s=hm(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 TI=ge("$ZodRecord",(e,t)=>{Ft.init(e,t),e._zod.parse=(n,a)=>{const i=n.value;if(!or(i))return n.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),n;const r=[],s=t.keyType._zod.values;if(s){n.value={};const d=new Set;for(const m of s)if(typeof m=="string"||typeof m=="number"||typeof m=="symbol"){d.add(typeof m=="number"?m.toString():m);const h=t.keyType._zod.run({value:m,issues:[]},a);if(h instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(h.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:h.issues.map(w=>go(w,a,ho())),input:m,path:[m],inst:e});continue}const S=h.value,y=t.valueType._zod.run({value:i[m],issues:[]},a);y instanceof Promise?r.push(y.then(w=>{w.issues.length&&n.issues.push(...Gi(m,w.issues)),n.value[S]=w.value})):(y.issues.length&&n.issues.push(...Gi(m,y.issues)),n.value[S]=y.value)}let p;for(const m in i)d.has(m)||(p=p??[],p.push(m));p&&p.length>0&&n.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:p})}else{n.value={};for(const d of Reflect.ownKeys(i)){if(d==="__proto__"||!Object.prototype.propertyIsEnumerable.call(i,d))continue;let p=t.keyType._zod.run({value:d,issues:[]},a);if(p instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof d=="string"&&hv.test(d)&&p.issues.length){const S=t.keyType._zod.run({value:Number(d),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[d]=i[d]:n.issues.push({code:"invalid_key",origin:"record",issues:p.issues.map(S=>go(S,a,ho())),input:d,path:[d],inst:e});continue}const h=t.valueType._zod.run({value:i[d],issues:[]},a);h instanceof Promise?r.push(h.then(S=>{S.issues.length&&n.issues.push(...Gi(d,S.issues)),n.value[p.value]=S.value})):(h.issues.length&&n.issues.push(...Gi(d,h.issues)),n.value[p.value]=h.value)}}return r.length?Promise.all(r).then(()=>n):n}}),EI=ge("$ZodEnum",(e,t)=>{Ft.init(e,t);const n=rv(t.entries),a=new Set(n);e._zod.values=a,e._zod.pattern=new RegExp(`^(${n.filter(i=>z_.has(typeof i)).map(i=>typeof i=="string"?ir(i):i.toString()).join("|")})$`),e._zod.parse=(i,r)=>{const s=i.value;return a.has(s)||i.issues.push({code:"invalid_value",values:n,input:s,inst:e}),i}}),MI=ge("$ZodLiteral",(e,t)=>{if(Ft.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"?ir(a):a?ir(a.toString()):String(a)).join("|")})$`),e._zod.parse=(a,i)=>{const r=a.value;return n.has(r)||a.issues.push({code:"invalid_value",values:t.values,input:r,inst:e}),a}}),jI=ge("$ZodTransform",(e,t)=>{Ft.init(e,t),e._zod.optin="optional",e._zod.parse=(n,a)=>{if(a.direction==="backward")throw new iv(e.constructor.name);const i=t.transform(n.value,n);if(a.async)return(i instanceof Promise?i:Promise.resolve(i)).then(s=>(n.value=s,n.fallback=!0,n));if(i instanceof Promise)throw new nr;return n.value=i,n.fallback=!0,n}});function Jf(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const wv=ge("$ZodOptional",(e,t)=>{Ft.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Tt(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Tt(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${pp(n.source)})?$`):void 0}),e._zod.parse=(n,a)=>{if(t.innerType._zod.optin==="optional"){const i=n.value,r=t.innerType._zod.run(n,a);return r instanceof Promise?r.then(s=>Jf(s,i)):Jf(r,i)}return n.value===void 0?n:t.innerType._zod.run(n,a)}}),OI=ge("$ZodExactOptional",(e,t)=>{wv.init(e,t),Tt(e._zod,"values",()=>t.innerType._zod.values),Tt(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,a)=>t.innerType._zod.run(n,a)}),NI=ge("$ZodNullable",(e,t)=>{Ft.init(e,t),Tt(e._zod,"optin",()=>t.innerType._zod.optin),Tt(e._zod,"optout",()=>t.innerType._zod.optout),Tt(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${pp(n.source)}|null)$`):void 0}),Tt(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)}),$I=ge("$ZodDefault",(e,t)=>{Ft.init(e,t),e._zod.optin="optional",Tt(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 i=t.innerType._zod.run(n,a);return i instanceof Promise?i.then(r=>Yf(r,t)):Yf(i,t)}});function Yf(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const DI=ge("$ZodPrefault",(e,t)=>{Ft.init(e,t),e._zod.optin="optional",Tt(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))}),LI=ge("$ZodNonOptional",(e,t)=>{Ft.init(e,t),Tt(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 i=t.innerType._zod.run(n,a);return i instanceof Promise?i.then(r=>Xf(r,e)):Xf(i,e)}});function Xf(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 zI=ge("$ZodCatch",(e,t)=>{Ft.init(e,t),e._zod.optin="optional",Tt(e._zod,"optout",()=>t.innerType._zod.optout),Tt(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,a)=>{if(a.direction==="backward")return t.innerType._zod.run(n,a);const i=t.innerType._zod.run(n,a);return i instanceof Promise?i.then(r=>(n.value=r.value,r.issues.length&&(n.value=t.catchValue({...n,error:{issues:r.issues.map(s=>go(s,a,ho()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(r=>go(r,a,ho()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),Iv=ge("$ZodPipe",(e,t)=>{Ft.init(e,t),Tt(e._zod,"values",()=>t.in._zod.values),Tt(e._zod,"optin",()=>t.in._zod.optin),Tt(e._zod,"optout",()=>t.out._zod.optout),Tt(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,a)=>{if(a.direction==="backward"){const r=t.out._zod.run(n,a);return r instanceof Promise?r.then(s=>_l(s,t.in,a)):_l(r,t.in,a)}const i=t.in._zod.run(n,a);return i instanceof Promise?i.then(r=>_l(r,t.out,a)):_l(i,t.out,a)}});function _l(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 UI=ge("$ZodPreprocess",(e,t)=>{Iv.init(e,t)}),HI=ge("$ZodReadonly",(e,t)=>{Ft.init(e,t),Tt(e._zod,"propValues",()=>t.innerType._zod.propValues),Tt(e._zod,"values",()=>t.innerType._zod.values),Tt(e._zod,"optin",()=>t.innerType?._zod?.optin),Tt(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,a)=>{if(a.direction==="backward")return t.innerType._zod.run(n,a);const i=t.innerType._zod.run(n,a);return i instanceof Promise?i.then(Qf):Qf(i)}});function Qf(e){return e.value=Object.freeze(e.value),e}const qI=ge("$ZodCustom",(e,t)=>{Jn.init(e,t),Ft.init(e,t),e._zod.parse=(n,a)=>n,e._zod.check=n=>{const a=n.value,i=t.fn(a);if(i instanceof Promise)return i.then(r=>eh(r,n,a,e));eh(i,n,a,e)}});function eh(e,t,n,a){if(!e){const i={code:"custom",input:n,inst:a,path:[...a._zod.def.path??[]],continue:!a._zod.def.abort};a._zod.def.params&&(i.params=a._zod.def.params),t.issues.push(Cs(i))}}var th;class BI{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 i={...a,...this._map.get(t)};return Object.keys(i).length?i:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function FI(){return new BI}(th=globalThis).__zod_globalRegistry??(th.__zod_globalRegistry=FI());const vs=globalThis.__zod_globalRegistry;function VI(e,t){return new e({type:"string",...ot(t)})}function WI(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...ot(t)})}function nh(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...ot(t)})}function KI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...ot(t)})}function GI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ot(t)})}function ZI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ot(t)})}function JI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ot(t)})}function YI(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...ot(t)})}function XI(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...ot(t)})}function QI(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...ot(t)})}function e1(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...ot(t)})}function t1(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...ot(t)})}function n1(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...ot(t)})}function a1(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...ot(t)})}function o1(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...ot(t)})}function i1(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...ot(t)})}function r1(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...ot(t)})}function s1(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ot(t)})}function l1(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ot(t)})}function c1(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...ot(t)})}function d1(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...ot(t)})}function u1(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...ot(t)})}function m1(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...ot(t)})}function p1(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ot(t)})}function f1(e,t){return new e({type:"string",format:"date",check:"string_format",...ot(t)})}function h1(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...ot(t)})}function g1(e,t){return new e({type:"string",format:"duration",check:"string_format",...ot(t)})}function b1(e,t){return new e({type:"number",checks:[],...ot(t)})}function v1(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...ot(t)})}function y1(e,t){return new e({type:"boolean",...ot(t)})}function S1(e,t){return new e({type:"null",...ot(t)})}function x1(e){return new e({type:"unknown"})}function k1(e,t){return new e({type:"never",...ot(t)})}function ah(e,t){return new bv({check:"less_than",...ot(t),value:e,inclusive:!1})}function au(e,t){return new bv({check:"less_than",...ot(t),value:e,inclusive:!0})}function oh(e,t){return new vv({check:"greater_than",...ot(t),value:e,inclusive:!1})}function ou(e,t){return new vv({check:"greater_than",...ot(t),value:e,inclusive:!0})}function ih(e,t){return new Nw({check:"multiple_of",...ot(t),value:e})}function Cv(e,t){return new Dw({check:"max_length",...ot(t),maximum:e})}function Xl(e,t){return new Lw({check:"min_length",...ot(t),minimum:e})}function Rv(e,t){return new zw({check:"length_equals",...ot(t),length:e})}function _1(e,t){return new Uw({check:"string_format",format:"regex",...ot(t),pattern:e})}function w1(e){return new Hw({check:"string_format",format:"lowercase",...ot(e)})}function I1(e){return new qw({check:"string_format",format:"uppercase",...ot(e)})}function C1(e,t){return new Bw({check:"string_format",format:"includes",...ot(t),includes:e})}function R1(e,t){return new Fw({check:"string_format",format:"starts_with",...ot(t),prefix:e})}function A1(e,t){return new Vw({check:"string_format",format:"ends_with",...ot(t),suffix:e})}function br(e){return new Ww({check:"overwrite",tx:e})}function P1(e){return br(t=>t.normalize(e))}function T1(){return br(e=>e.trim())}function E1(){return br(e=>e.toLowerCase())}function M1(){return br(e=>e.toUpperCase())}function j1(){return br(e=>D_(e))}function O1(e,t,n){return new e({type:"array",element:t,...ot(n)})}function N1(e,t,n){const a=ot(n);return a.abort??(a.abort=!0),new e({type:"custom",check:"custom",fn:t,...a})}function $1(e,t,n){return new e({type:"custom",check:"custom",fn:t,...ot(n)})}function D1(e,t){const n=L1(a=>(a.addIssue=i=>{if(typeof i=="string")a.issues.push(Cs(i,a.value,n._zod.def));else{const r=i;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=a.value),r.inst??(r.inst=n),r.continue??(r.continue=!n._zod.def.abort),a.issues.push(Cs(r))}},e(a.value,a)),t);return n}function L1(e,t){const n=new Jn({check:"custom",...ot(t)});return n._zod.check=e,n}function Av(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??vs,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 dn(e,t,n={path:[],schemaPath:[]}){var a;const i=e._zod.def,r=t.seen.get(e);if(r)return r.count++,n.schemaPath.includes(e)&&(r.cycle=n.path),r.schema;const s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s);const d=e._zod.toJSONSchema?.();if(d)s.schema=d;else{const h={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,h);else{const y=s.schema,w=t.processors[i.type];if(!w)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);w(e,t,y,h)}const S=e._zod.parent;S&&(s.ref||(s.ref=S),dn(S,t,h),t.seen.get(S).isParent=!0)}const p=t.metadataRegistry.get(e);return p&&Object.assign(s.schema,p),t.io==="input"&&On(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 Pv(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 d=e.metadataRegistry.get(s[0])?.id;if(d){const p=a.get(d);if(p&&p!==s[0])throw new Error(`Duplicate schema id "${d}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);a.set(d,s[0])}}const i=s=>{const d=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 w=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=w,{defId:w,ref:`${y("__shared")}#/${d}/${w}`}}if(s[1]===n)return{ref:"#"};const m=`#/${d}/`,h=s[1].schema.id??`__schema${e.counter++}`;return{defId:h,ref:m+h}},r=s=>{if(s[1].schema.$ref)return;const d=s[1],{ref:p,defId:m}=i(s);d.def={...d.schema},m&&(d.defId=m);const h=d.schema;for(const S in h)delete h[S];h.$ref=p};if(e.cycles==="throw")for(const s of e.seen.entries()){const d=s[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.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 d=s[1];if(t===s[0]){r(s);continue}if(e.external){const m=e.external.registry.get(s[0])?.id;if(t!==s[0]&&m){r(s);continue}}if(e.metadataRegistry.get(s[0])?.id){r(s);continue}if(d.cycle){r(s);continue}if(d.count>1&&e.reused==="ref"){r(s);continue}}}function Tv(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const a=d=>{const p=e.seen.get(d);if(p.ref===null)return;const m=p.def??p.schema,h={...m},S=p.ref;if(p.ref=null,S){a(S);const w=e.seen.get(S),R=w.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,h),d._zod.parent===S)for(const N in m)N==="$ref"||N==="allOf"||N in h||delete m[N];if(R.$ref&&w.def)for(const N in m)N==="$ref"||N==="allOf"||N in w.def&&JSON.stringify(m[N])===JSON.stringify(w.def[N])&&delete m[N]}const y=d._zod.parent;if(y&&y!==S){a(y);const w=e.seen.get(y);if(w?.schema.$ref&&(m.$ref=w.schema.$ref,w.def))for(const R in m)R==="$ref"||R==="allOf"||R in w.def&&JSON.stringify(m[R])===JSON.stringify(w.def[R])&&delete m[R]}e.override({zodSchema:d,jsonSchema:m,path:p.path??[]})};for(const d of[...e.seen.entries()].reverse())a(d[0]);const i={};if(e.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const d=e.external.registry.get(t)?.id;if(!d)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(d)}Object.assign(i,n.def??n.schema);const r=e.metadataRegistry.get(t)?.id;r!==void 0&&i.id===r&&delete i.id;const s=e.external?.defs??{};for(const d of e.seen.entries()){const p=d[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"?i.$defs=s:i.definitions=s);try{const d=JSON.parse(JSON.stringify(i));return Object.defineProperty(d,"~standard",{value:{...t["~standard"],jsonSchema:{input:Ql(t,"input",e.processors),output:Ql(t,"output",e.processors)}},enumerable:!1,writable:!1}),d}catch{throw new Error("Error converting schema to JSON.")}}function On(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 On(a.element,n);if(a.type==="set")return On(a.valueType,n);if(a.type==="lazy")return On(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 On(a.innerType,n);if(a.type==="intersection")return On(a.left,n)||On(a.right,n);if(a.type==="record"||a.type==="map")return On(a.keyType,n)||On(a.valueType,n);if(a.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:On(a.in,n)||On(a.out,n);if(a.type==="object"){for(const i in a.shape)if(On(a.shape[i],n))return!0;return!1}if(a.type==="union"){for(const i of a.options)if(On(i,n))return!0;return!1}if(a.type==="tuple"){for(const i of a.items)if(On(i,n))return!0;return!!(a.rest&&On(a.rest,n))}return!1}const z1=(e,t={})=>n=>{const a=Av({...n,processors:t});return dn(e,a),Pv(a,e),Tv(a,e)},Ql=(e,t,n={})=>a=>{const{libraryOptions:i,target:r}=a??{},s=Av({...i??{},target:r,io:t,processors:n});return dn(e,s),Pv(s,e),Tv(s,e)},U1={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},H1=(e,t,n,a)=>{const i=n;i.type="string";const{minimum:r,maximum:s,format:d,patterns:p,contentEncoding:m}=e._zod.bag;if(typeof r=="number"&&(i.minLength=r),typeof s=="number"&&(i.maxLength=s),d&&(i.format=U1[d]??d,i.format===""&&delete i.format,d==="time"&&delete i.format),m&&(i.contentEncoding=m),p&&p.size>0){const h=[...p];h.length===1?i.pattern=h[0].source:h.length>1&&(i.allOf=[...h.map(S=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:S.source}))])}},q1=(e,t,n,a)=>{const i=n,{minimum:r,maximum:s,format:d,multipleOf:p,exclusiveMaximum:m,exclusiveMinimum:h}=e._zod.bag;typeof d=="string"&&d.includes("int")?i.type="integer":i.type="number";const S=typeof h=="number"&&h>=(r??Number.NEGATIVE_INFINITY),y=typeof m=="number"&&m<=(s??Number.POSITIVE_INFINITY),w=t.target==="draft-04"||t.target==="openapi-3.0";S?w?(i.minimum=h,i.exclusiveMinimum=!0):i.exclusiveMinimum=h:typeof r=="number"&&(i.minimum=r),y?w?(i.maximum=m,i.exclusiveMaximum=!0):i.exclusiveMaximum=m:typeof s=="number"&&(i.maximum=s),typeof p=="number"&&(i.multipleOf=p)},B1=(e,t,n,a)=>{n.type="boolean"},F1=(e,t,n,a)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},V1=(e,t,n,a)=>{n.not={}},W1=(e,t,n,a)=>{},K1=(e,t,n,a)=>{const i=e._zod.def,r=rv(i.entries);r.every(s=>typeof s=="number")&&(n.type="number"),r.every(s=>typeof s=="string")&&(n.type="string"),n.enum=r},G1=(e,t,n,a)=>{const i=e._zod.def,r=[];for(const s of i.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");r.push(Number(s))}else r.push(s);if(r.length!==0)if(r.length===1){const s=r[0];n.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[s]:n.const=s}else r.every(s=>typeof s=="number")&&(n.type="number"),r.every(s=>typeof s=="string")&&(n.type="string"),r.every(s=>typeof s=="boolean")&&(n.type="boolean"),r.every(s=>s===null)&&(n.type="null"),n.enum=r},Z1=(e,t,n,a)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},J1=(e,t,n,a)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},Y1=(e,t,n,a)=>{const i=n,r=e._zod.def,{minimum:s,maximum:d}=e._zod.bag;typeof s=="number"&&(i.minItems=s),typeof d=="number"&&(i.maxItems=d),i.type="array",i.items=dn(r.element,t,{...a,path:[...a.path,"items"]})},X1=(e,t,n,a)=>{const i=n,r=e._zod.def;i.type="object",i.properties={};const s=r.shape;for(const m in s)i.properties[m]=dn(s[m],t,{...a,path:[...a.path,"properties",m]});const d=new Set(Object.keys(s)),p=new Set([...d].filter(m=>{const h=r.shape[m]._zod;return t.io==="input"?h.optin===void 0:h.optout===void 0}));p.size>0&&(i.required=Array.from(p)),r.catchall?._zod.def.type==="never"?i.additionalProperties=!1:r.catchall?r.catchall&&(i.additionalProperties=dn(r.catchall,t,{...a,path:[...a.path,"additionalProperties"]})):t.io==="output"&&(i.additionalProperties=!1)},Q1=(e,t,n,a)=>{const i=e._zod.def,r=i.inclusive===!1,s=i.options.map((d,p)=>dn(d,t,{...a,path:[...a.path,r?"oneOf":"anyOf",p]}));r?n.oneOf=s:n.anyOf=s},eC=(e,t,n,a)=>{const i=e._zod.def,r=dn(i.left,t,{...a,path:[...a.path,"allOf",0]}),s=dn(i.right,t,{...a,path:[...a.path,"allOf",1]}),d=m=>"allOf"in m&&Object.keys(m).length===1,p=[...d(r)?r.allOf:[r],...d(s)?s.allOf:[s]];n.allOf=p},tC=(e,t,n,a)=>{const i=n,r=e._zod.def;i.type="object";const s=r.keyType,p=s._zod.bag?.patterns;if(r.mode==="loose"&&p&&p.size>0){const h=dn(r.valueType,t,{...a,path:[...a.path,"patternProperties","*"]});i.patternProperties={};for(const S of p)i.patternProperties[S.source]=h}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(i.propertyNames=dn(r.keyType,t,{...a,path:[...a.path,"propertyNames"]})),i.additionalProperties=dn(r.valueType,t,{...a,path:[...a.path,"additionalProperties"]});const m=s._zod.values;if(m){const h=[...m].filter(S=>typeof S=="string"||typeof S=="number");h.length>0&&(i.required=h)}},nC=(e,t,n,a)=>{const i=e._zod.def,r=dn(i.innerType,t,a),s=t.seen.get(e);t.target==="openapi-3.0"?(s.ref=i.innerType,n.nullable=!0):n.anyOf=[r,{type:"null"}]},aC=(e,t,n,a)=>{const i=e._zod.def;dn(i.innerType,t,a);const r=t.seen.get(e);r.ref=i.innerType},oC=(e,t,n,a)=>{const i=e._zod.def;dn(i.innerType,t,a);const r=t.seen.get(e);r.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},iC=(e,t,n,a)=>{const i=e._zod.def;dn(i.innerType,t,a);const r=t.seen.get(e);r.ref=i.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},rC=(e,t,n,a)=>{const i=e._zod.def;dn(i.innerType,t,a);const r=t.seen.get(e);r.ref=i.innerType;let s;try{s=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=s},sC=(e,t,n,a)=>{const i=e._zod.def,r=i.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?r?i.out:i.in:i.out;dn(s,t,a);const d=t.seen.get(e);d.ref=s},lC=(e,t,n,a)=>{const i=e._zod.def;dn(i.innerType,t,a);const r=t.seen.get(e);r.ref=i.innerType,n.readOnly=!0},Ev=(e,t,n,a)=>{const i=e._zod.def;dn(i.innerType,t,a);const r=t.seen.get(e);r.ref=i.innerType},cC=ge("ZodISODateTime",(e,t)=>{rI.init(e,t),Yt.init(e,t)});function dC(e){return p1(cC,e)}const uC=ge("ZodISODate",(e,t)=>{sI.init(e,t),Yt.init(e,t)});function mC(e){return f1(uC,e)}const pC=ge("ZodISOTime",(e,t)=>{lI.init(e,t),Yt.init(e,t)});function fC(e){return h1(pC,e)}const hC=ge("ZodISODuration",(e,t)=>{cI.init(e,t),Yt.init(e,t)});function gC(e){return g1(hC,e)}const bC=(e,t)=>{dv.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>Y_(e,n)},flatten:{value:n=>J_(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,fm,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,fm,2)}},isEmpty:{get(){return e.issues.length===0}}})},pa=ge("ZodError",bC,{Parent:Error}),vC=hp(pa),yC=gp(pa),SC=gc(pa),xC=bc(pa),kC=ew(pa),_C=tw(pa),wC=nw(pa),IC=aw(pa),CC=ow(pa),RC=iw(pa),AC=rw(pa),PC=sw(pa),rh=new WeakMap;function zs(e,t,n){const a=Object.getPrototypeOf(e);let i=rh.get(a);if(i||(i=new Set,rh.set(a,i)),!i.has(t)){i.add(t);for(const r in n){const s=n[r];Object.defineProperty(a,r,{configurable:!0,enumerable:!1,get(){const d=s.bind(this);return Object.defineProperty(this,r,{configurable:!0,writable:!0,enumerable:!0,value:d}),d},set(d){Object.defineProperty(this,r,{configurable:!0,writable:!0,enumerable:!0,value:d})}})}}}const Wt=ge("ZodType",(e,t)=>(Ft.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Ql(e,"input"),output:Ql(e,"output")}}),e.toJSONSchema=z1(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,a)=>vC(e,n,a,{callee:e.parse}),e.safeParse=(n,a)=>SC(e,n,a),e.parseAsync=async(n,a)=>yC(e,n,a,{callee:e.parseAsync}),e.safeParseAsync=async(n,a)=>xC(e,n,a),e.spa=e.safeParseAsync,e.encode=(n,a)=>kC(e,n,a),e.decode=(n,a)=>_C(e,n,a),e.encodeAsync=async(n,a)=>wC(e,n,a),e.decodeAsync=async(n,a)=>IC(e,n,a),e.safeEncode=(n,a)=>CC(e,n,a),e.safeDecode=(n,a)=>RC(e,n,a),e.safeEncodeAsync=async(n,a)=>AC(e,n,a),e.safeDecodeAsync=async(n,a)=>PC(e,n,a),zs(e,"ZodType",{check(...n){const a=this.def;return this.clone(jo(a,{checks:[...a.checks??[],...n.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,a){return Oo(this,n,a)},brand(){return this},register(n,a){return n.add(this,a),this},refine(n,a){return this.check(SR(n,a))},superRefine(n,a){return this.check(xR(n,a))},overwrite(n){return this.check(br(n))},optional(){return dh(this)},exactOptional(){return lR(this)},nullable(){return uh(this)},nullish(){return dh(uh(this))},nonoptional(n){return fR(this,n)},array(){return f(this)},or(n){return mn([this,n])},and(n){return oR(this,n)},transform(n){return mh(this,$v(n))},default(n){return uR(this,n)},prefault(n){return pR(this,n)},catch(n){return gR(this,n)},pipe(n){return mh(this,n)},readonly(){return yR(this)},describe(n){const a=this.clone();return vs.add(a,{description:n}),a},meta(...n){if(n.length===0)return vs.get(this);const a=this.clone();return vs.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 vs.get(e)?.description},configurable:!0}),e)),Mv=ge("_ZodString",(e,t)=>{bp.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(a,i,r)=>H1(e,a,i);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,zs(e,"_ZodString",{regex(...a){return this.check(_1(...a))},includes(...a){return this.check(C1(...a))},startsWith(...a){return this.check(R1(...a))},endsWith(...a){return this.check(A1(...a))},min(...a){return this.check(Xl(...a))},max(...a){return this.check(Cv(...a))},length(...a){return this.check(Rv(...a))},nonempty(...a){return this.check(Xl(1,...a))},lowercase(a){return this.check(w1(a))},uppercase(a){return this.check(I1(a))},trim(){return this.check(T1())},normalize(...a){return this.check(P1(...a))},toLowerCase(){return this.check(E1())},toUpperCase(){return this.check(M1())},slugify(){return this.check(j1())}})}),TC=ge("ZodString",(e,t)=>{bp.init(e,t),Mv.init(e,t),e.email=n=>e.check(WI(EC,n)),e.url=n=>e.check(YI(MC,n)),e.jwt=n=>e.check(m1(KC,n)),e.emoji=n=>e.check(XI(jC,n)),e.guid=n=>e.check(nh(sh,n)),e.uuid=n=>e.check(KI(wl,n)),e.uuidv4=n=>e.check(GI(wl,n)),e.uuidv6=n=>e.check(ZI(wl,n)),e.uuidv7=n=>e.check(JI(wl,n)),e.nanoid=n=>e.check(QI(OC,n)),e.guid=n=>e.check(nh(sh,n)),e.cuid=n=>e.check(e1(NC,n)),e.cuid2=n=>e.check(t1($C,n)),e.ulid=n=>e.check(n1(DC,n)),e.base64=n=>e.check(c1(FC,n)),e.base64url=n=>e.check(d1(VC,n)),e.xid=n=>e.check(a1(LC,n)),e.ksuid=n=>e.check(o1(zC,n)),e.ipv4=n=>e.check(i1(UC,n)),e.ipv6=n=>e.check(r1(HC,n)),e.cidrv4=n=>e.check(s1(qC,n)),e.cidrv6=n=>e.check(l1(BC,n)),e.e164=n=>e.check(u1(WC,n)),e.datetime=n=>e.check(dC(n)),e.date=n=>e.check(mC(n)),e.time=n=>e.check(fC(n)),e.duration=n=>e.check(gC(n))});function o(e){return VI(TC,e)}const Yt=ge("ZodStringFormat",(e,t)=>{Vt.init(e,t),Mv.init(e,t)}),EC=ge("ZodEmail",(e,t)=>{Yw.init(e,t),Yt.init(e,t)}),sh=ge("ZodGUID",(e,t)=>{Zw.init(e,t),Yt.init(e,t)}),wl=ge("ZodUUID",(e,t)=>{Jw.init(e,t),Yt.init(e,t)}),MC=ge("ZodURL",(e,t)=>{Xw.init(e,t),Yt.init(e,t)}),jC=ge("ZodEmoji",(e,t)=>{Qw.init(e,t),Yt.init(e,t)}),OC=ge("ZodNanoID",(e,t)=>{eI.init(e,t),Yt.init(e,t)}),NC=ge("ZodCUID",(e,t)=>{tI.init(e,t),Yt.init(e,t)}),$C=ge("ZodCUID2",(e,t)=>{nI.init(e,t),Yt.init(e,t)}),DC=ge("ZodULID",(e,t)=>{aI.init(e,t),Yt.init(e,t)}),LC=ge("ZodXID",(e,t)=>{oI.init(e,t),Yt.init(e,t)}),zC=ge("ZodKSUID",(e,t)=>{iI.init(e,t),Yt.init(e,t)}),UC=ge("ZodIPv4",(e,t)=>{dI.init(e,t),Yt.init(e,t)}),HC=ge("ZodIPv6",(e,t)=>{uI.init(e,t),Yt.init(e,t)}),qC=ge("ZodCIDRv4",(e,t)=>{mI.init(e,t),Yt.init(e,t)}),BC=ge("ZodCIDRv6",(e,t)=>{pI.init(e,t),Yt.init(e,t)}),FC=ge("ZodBase64",(e,t)=>{fI.init(e,t),Yt.init(e,t)}),VC=ge("ZodBase64URL",(e,t)=>{gI.init(e,t),Yt.init(e,t)}),WC=ge("ZodE164",(e,t)=>{bI.init(e,t),Yt.init(e,t)}),KC=ge("ZodJWT",(e,t)=>{yI.init(e,t),Yt.init(e,t)}),jv=ge("ZodNumber",(e,t)=>{Sv.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(a,i,r)=>q1(e,a,i),zs(e,"ZodNumber",{gt(a,i){return this.check(oh(a,i))},gte(a,i){return this.check(ou(a,i))},min(a,i){return this.check(ou(a,i))},lt(a,i){return this.check(ah(a,i))},lte(a,i){return this.check(au(a,i))},max(a,i){return this.check(au(a,i))},int(a){return this.check(lh(a))},safe(a){return this.check(lh(a))},positive(a){return this.check(oh(0,a))},nonnegative(a){return this.check(ou(0,a))},negative(a){return this.check(ah(0,a))},nonpositive(a){return this.check(au(0,a))},multipleOf(a,i){return this.check(ih(a,i))},step(a,i){return this.check(ih(a,i))},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 c(e){return b1(jv,e)}const GC=ge("ZodNumberFormat",(e,t)=>{SI.init(e,t),jv.init(e,t)});function lh(e){return v1(GC,e)}const ZC=ge("ZodBoolean",(e,t)=>{xI.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>B1(e,n,a)});function C(e){return y1(ZC,e)}const JC=ge("ZodNull",(e,t)=>{kI.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>F1(e,n,a)});function Ov(e){return S1(JC,e)}const YC=ge("ZodUnknown",(e,t)=>{_I.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>W1()});function ye(){return x1(YC)}const XC=ge("ZodNever",(e,t)=>{wI.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>V1(e,n,a)});function QC(e){return k1(XC,e)}const eR=ge("ZodArray",(e,t)=>{II.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Y1(e,n,a,i),e.element=t.element,zs(e,"ZodArray",{min(n,a){return this.check(Xl(n,a))},nonempty(n){return this.check(Xl(1,n))},max(n,a){return this.check(Cv(n,a))},length(n,a){return this.check(Rv(n,a))},unwrap(){return this.element}})});function f(e,t){return O1(eR,e,t)}const tR=ge("ZodObject",(e,t)=>{RI.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>X1(e,n,a,i),Tt(e,"shape",()=>t.shape),zs(e,"ZodObject",{keyof(){return b(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:ye()})},loose(){return this.clone({...this._zod.def,catchall:ye()})},strict(){return this.clone({...this._zod.def,catchall:QC()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return F_(this,n)},safeExtend(n){return V_(this,n)},merge(n){return W_(this,n)},pick(n){return q_(this,n)},omit(n){return B_(this,n)},partial(...n){return K_(Dv,this,n[0])},required(...n){return G_(Lv,this,n[0])}})});function l(e,t){const n={type:"object",shape:e??{},...ot(t)};return new tR(n)}const Nv=ge("ZodUnion",(e,t)=>{_v.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Q1(e,n,a,i),e.options=t.options});function mn(e,t){return new Nv({type:"union",options:e,...ot(t)})}const nR=ge("ZodDiscriminatedUnion",(e,t)=>{Nv.init(e,t),AI.init(e,t)});function Kt(e,t,n){return new nR({type:"union",options:t,discriminator:e,...ot(n)})}const aR=ge("ZodIntersection",(e,t)=>{PI.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>eC(e,n,a,i)});function oR(e,t){return new aR({type:"intersection",left:e,right:t})}const ch=ge("ZodRecord",(e,t)=>{TI.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>tC(e,n,a,i),e.keyType=t.keyType,e.valueType=t.valueType});function fe(e,t,n){return!t||!t._zod?new ch({type:"record",keyType:o(),valueType:e,...ot(t)}):new ch({type:"record",keyType:e,valueType:t,...ot(n)})}const gm=ge("ZodEnum",(e,t)=>{EI.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(a,i,r)=>K1(e,a,i),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(a,i)=>{const r={};for(const s of a)if(n.has(s))r[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new gm({...t,checks:[],...ot(i),entries:r})},e.exclude=(a,i)=>{const r={...t.entries};for(const s of a)if(n.has(s))delete r[s];else throw new Error(`Key ${s} not found in enum`);return new gm({...t,checks:[],...ot(i),entries:r})}});function b(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(a=>[a,a])):e;return new gm({type:"enum",entries:n,...ot(t)})}const iR=ge("ZodLiteral",(e,t)=>{MI.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>G1(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 k(e,t){return new iR({type:"literal",values:Array.isArray(e)?e:[e],...ot(t)})}const rR=ge("ZodTransform",(e,t)=>{jI.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>J1(e,n),e._zod.parse=(n,a)=>{if(a.direction==="backward")throw new iv(e.constructor.name);n.addIssue=r=>{if(typeof r=="string")n.issues.push(Cs(r,n.value,t));else{const s=r;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=e),n.issues.push(Cs(s))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(r=>(n.value=r,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function $v(e){return new rR({type:"transform",transform:e})}const Dv=ge("ZodOptional",(e,t)=>{wv.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Ev(e,n,a,i),e.unwrap=()=>e._zod.def.innerType});function dh(e){return new Dv({type:"optional",innerType:e})}const sR=ge("ZodExactOptional",(e,t)=>{OI.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Ev(e,n,a,i),e.unwrap=()=>e._zod.def.innerType});function lR(e){return new sR({type:"optional",innerType:e})}const cR=ge("ZodNullable",(e,t)=>{NI.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>nC(e,n,a,i),e.unwrap=()=>e._zod.def.innerType});function uh(e){return new cR({type:"nullable",innerType:e})}const dR=ge("ZodDefault",(e,t)=>{$I.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>oC(e,n,a,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function uR(e,t){return new dR({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():lv(t)}})}const mR=ge("ZodPrefault",(e,t)=>{DI.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>iC(e,n,a,i),e.unwrap=()=>e._zod.def.innerType});function pR(e,t){return new mR({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():lv(t)}})}const Lv=ge("ZodNonOptional",(e,t)=>{LI.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>aC(e,n,a,i),e.unwrap=()=>e._zod.def.innerType});function fR(e,t){return new Lv({type:"nonoptional",innerType:e,...ot(t)})}const hR=ge("ZodCatch",(e,t)=>{zI.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>rC(e,n,a,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function gR(e,t){return new hR({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const zv=ge("ZodPipe",(e,t)=>{Iv.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>sC(e,n,a,i),e.in=t.in,e.out=t.out});function mh(e,t){return new zv({type:"pipe",in:e,out:t})}const bR=ge("ZodPreprocess",(e,t)=>{zv.init(e,t),UI.init(e,t)}),vR=ge("ZodReadonly",(e,t)=>{HI.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>lC(e,n,a,i),e.unwrap=()=>e._zod.def.innerType});function yR(e){return new vR({type:"readonly",innerType:e})}const Uv=ge("ZodCustom",(e,t)=>{qI.init(e,t),Wt.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Z1(e,n)});function iu(e,t){return N1(Uv,(()=>!0),t)}function SR(e,t={}){return $1(Uv,e,t)}function xR(e,t){return D1(e,t)}function kR(e,t){return new bR({type:"pipe",in:$v(e),out:t})}const $n={custom:"custom"},vp=["openpond","codex","anthropic","openai","xai","google","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],li=b(vp),yc=b(["active","preview","planned","deprecated"]),Hv=b(["openpond-account","openpond-managed","codex-login","chatgpt-subscription","local-byok","hosted-byok","custom"]),_R=b(["none","local_secret","env","openpond_account","codex_login","chatgpt_subscription","hosted"]),ph=l({connected:C().default(!1),source:_R.default("none"),redacted:o().nullable().default(null),lastValidatedAt:o().nullable().default(null),lastError:o().nullable().default(null)}),bm=l({hostedOpChat:C().default(!1),localRuntime:C().default(!0),localByok:C().default(!1),hostedByok:C().default(!1)}),wR=b(["hosted","provider","manual","none"]),vm=l({chatCompletions:C().default(!0),streaming:C().default(!0),modelDiscovery:wR.default("none"),toolCalling:C().default(!1),reasoning:C().default(!1),imageInput:C().default(!1),structuredOutput:C().default(!1)}),IR=b(["hosted","provider","curated","manual","cache"]),ym=l({streaming:C().default(!0),toolCalling:C().default(!1),reasoning:C().default(!1),vision:C().default(!1),structuredOutput:C().default(!1)}),CR=l({id:o().trim().min(1).max(300),providerId:li,displayName:o().trim().min(1).max(300),contextWindow:c().int().positive().nullable().default(null),outputLimit:c().int().positive().nullable().default(null),lifecycleStatus:yc.default("active"),source:IR,capabilities:ym.default(()=>ym.parse({})),raw:fe(o(),ye()).optional()}),RR=l({providerId:li,models:f(CR).default([]),fetchedAt:o().nullable().default(null),lastError:o().nullable().default(null),source:b(["none","hosted","provider","curated","manual"]).default("none")}),AR=l({enabled:C().default(!1),baseUrl:o().trim().min(1).max(2048).nullable().default(null),defaultModel:o().trim().min(1).max(300).nullable().default(null),modelOverrides:f(o().trim().min(1).max(300)).max(500).default([]),updatedAt:o().nullable().default(null)}),PR=l({enabled:C().optional(),baseUrl:o().trim().min(1).max(2048).nullable().optional(),defaultModel:o().trim().min(1).max(300).nullable().optional(),modelOverrides:f(o().trim().min(1).max(300)).max(500).optional()}),TR=l({id:o().trim().min(1).max(300),displayName:o().trim().min(1).max(300),contextWindow:c().int().positive().nullable().optional(),outputLimit:c().int().positive().nullable().optional(),lifecycleStatus:yc.optional(),capabilities:ym.partial().optional()}),ER=l({id:li,displayName:o().trim().min(1).max(160),lifecycleStatus:yc.default("active"),credentialModes:f(Hv).default([]),routing:bm,capabilities:vm,defaultEnabled:C().optional(),defaultBaseUrl:o().trim().min(1).max(2048).nullable().optional(),defaultModel:o().trim().min(1).max(300).nullable().optional(),modelCacheSource:b(["none","hosted","provider","curated","manual"]),models:f(TR).default([])});l({version:k(1).default(1),generatedAt:o().datetime(),providers:f(ER)});const MR=l({id:li,displayName:o().trim().min(1).max(160),lifecycleStatus:yc.default("active"),credentialModes:f(Hv).default([]),routing:bm.default(()=>bm.parse({})),capabilities:vm.default(()=>vm.parse({})),credential:ph.default(()=>ph.parse({})),enabled:C().default(!1),available:C().default(!1),defaultModel:o().trim().min(1).max(300).nullable().default(null),modelIds:f(o().trim().min(1).max(300)).max(1e3).default([]),lastError:o().nullable().default(null)}),fh=l({version:k(1).default(1),providers:fe(o(),AR).default({}),statuses:fe(o(),MR).default({}),modelCaches:fe(o(),RR).default({}),updatedAt:o().nullable().default(null)}),Jt=l({providerId:li,modelId:o().trim().min(1).max(300)});l({providers:fe(o(),PR).optional()});l({source:b(["local_secret","env"]).default("local_secret"),value:o().min(1).max(2e4).optional(),envVar:o().trim().min(1).max(160).optional()}).superRefine((e,t)=>{e.source==="env"&&!e.envVar&&t.addIssue({code:"custom",path:["envVar"],message:"envVar is required when provider credential source is env."}),e.source==="local_secret"&&!e.value&&t.addIssue({code:"custom",path:["value"],message:"value is required when provider credential source is local_secret."})});l({source:b(["local_secret","env","chatgpt_subscription"]).optional()});l({modelId:o().trim().min(1).max(300).optional(),baseUrl:o().trim().min(1).max(2048).optional()});l({query:o().trim().max(200).optional(),refresh:C().default(!1),limit:c().int().positive().max(500).default(100)});l({query:o().trim().max(200).optional(),force:C().default(!1)});const jR=["coding","research","review","test","docs","planner","summarizer"];b(jR);const vr=o().trim().min(1).max(80).regex(/^[a-z][a-z0-9_-]*$/),qv=b(["none","worktree","copy_on_write"]),Bv=b(["read_only","workspace_write","full_tools"]),Fv=b(["disabled","parent_scoped"]),Sc=b(["manual","balanced","proactive"]),OR=b(["queued","running","completed","failed","cancelled","needs_resume"]),Vv=["subagent.started","subagent.reported","subagent.completed","subagent.progress","subagent.failed","subagent.cancelled","subagent.cleanup","subagent.workspace_retained","subagent.workspace_retention_expiring","subagent.archived","subagent.message"];b(Vv);const NR=[{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"}],yp=l({id:vr,enabled:C().default(!0),modelRef:Jt.nullable().default(null),isolationMode:qv.default("none"),maxConcurrentRuns:c().int().min(1).max(16).default(1),toolPolicy:Bv.default("read_only"),background:C().default(!0),peerMessages:Fv.default("parent_scoped")}),Rs=l({enabled:C().default(!0),workspaceDefaultsVersion:k(1).default(1),toolDefaultsVersion:k(1).default(1),delegationMode:Sc.default("manual"),defaultModelRef:Jt.nullable().default(null),roles:f(yp).max(64).default(()=>Gv()),maxConcurrentRuns:c().int().min(1).max(32).default(4),maxConcurrentRunsPerProvider:c().int().min(1).max(32).nullable().default(2),maxConcurrentRunsPerWorkspaceTarget:c().int().min(1).max(32).nullable().default(1)}).transform(e=>({...e,roles:WR(e.roles)})),xs=l({kind:b(["session","turn","file","diff","artifact"]),id:o().trim().min(1).max(500),label:o().trim().min(1).max(500)}),$R=l({kind:b(["retain_with_parent"]).default("retain_with_parent"),messageRetentionDays:c().int().min(1).max(3650).nullable().default(null),artifactRetentionDays:c().int().min(1).max(3650).nullable().default(null),cleanupAfterExpiry:C().default(!1)}).default(()=>({kind:"retain_with_parent",messageRetentionDays:null,artifactRetentionDays:null,cleanupAfterExpiry:!1})),DR=b(["orient","edit","validate","report"]),LR=l({command:o().trim().min(1).max(2e3),status:b(["passed","failed","unknown"]).default("unknown"),exitCode:c().int().nullable().default(null),outputSummary:o().trim().max(5e3).nullable().default(null),startedAt:o().nullable().default(null),completedAt:o().nullable().default(null)}),zR=l({phase:DR.default("orient"),inspectedFiles:f(o().trim().min(1).max(1e3)).max(500).default([]),inspectedResources:f(o().trim().min(1).max(1e3)).max(500).default([]),repeatedSearches:f(o().trim().min(1).max(1e3)).max(200).default([]),repeatedReads:f(o().trim().min(1).max(1e3)).max(200).default([]),repeatedCommands:f(o().trim().min(1).max(1e3)).max(200).default([]),changedFiles:f(o().trim().min(1).max(1e3)).max(500).default([]),patchRefs:f(xs).max(100).default([]),validationAttempts:f(LR).max(100).default([]),latestMeaningfulActivity:o().trim().max(5e3).nullable().default(null),currentBlocker:o().trim().max(5e3).nullable().default(null),updatedAt:o().nullable().default(null)}).default(()=>({phase:"orient",inspectedFiles:[],inspectedResources:[],repeatedSearches:[],repeatedReads:[],repeatedCommands:[],changedFiles:[],patchRefs:[],validationAttempts:[],latestMeaningfulActivity:null,currentBlocker:null,updatedAt:null})),UR=l({summary:o().trim().max(2e4).default(""),findings:f(o().trim().min(1).max(5e3)).max(200).default([]),artifacts:f(xs).max(200).default([]),patchRef:xs.nullable().default(null),diffRef:xs.nullable().default(null),testsRun:f(o().trim().min(1).max(2e3)).max(100).default([]),blockers:f(o().trim().min(1).max(5e3)).max(100).default([]),confidence:b(["low","medium","high"]).nullable().default(null),followUpNeeded:C().default(!1)}),Wv=l({id:o().trim().min(1).max(200),parentSessionId:o().trim().min(1).max(200),parentTurnId:o().trim().min(1).max(200).nullable().default(null),childSessionId:o().trim().min(1).max(200).nullable().default(null),roleId:vr,objective:o().trim().min(1).max(5e4),modelRef:Jt.nullable().default(null),isolationMode:qv.default("none"),toolPolicy:Bv.default("read_only"),background:C().default(!0),peerMessages:Fv.default("parent_scoped"),status:OR.default("queued"),progress:zR,evidenceRetention:$R,createdAt:o(),startedAt:o().nullable().default(null),completedAt:o().nullable().default(null),updatedAt:o().nullable().default(null),error:o().nullable().default(null),report:UR.nullable().default(null),metadata:fe(o(),ye()).optional().default({})}),Kv=b(["cleanup","archive","cleanup_and_archive"]);l({action:Kv,reason:o().trim().min(1).max(2e3).nullable().default(null)});l({action:Kv,run:Wv,workspaceCleanup:fe(o(),ye()).nullable().default(null),sessionArchive:fe(o(),ye()).nullable().default(null),nextStep:o()});const HR=b(["question","answer","handoff","artifact","status","blocker"]),qR=b(["normal","interrupt"]),BR=l({status:b(["pending","delivered","undelivered"]).default("pending"),deliveredRunIds:f(o().trim().min(1).max(200)).max(200).default([]),acknowledgedRunIds:f(o().trim().min(1).max(200)).max(200).default([]),deliveredParentSessionId:o().trim().min(1).max(200).nullable().default(null),acknowledgedParentSessionId:o().trim().min(1).max(200).nullable().default(null),wakeRequestedParentSessionId:o().trim().min(1).max(200).nullable().default(null),wakeQueuedParentSessionId:o().trim().min(1).max(200).nullable().default(null),wakeDeferredParentSessionId:o().trim().min(1).max(200).nullable().default(null),wakeParentReason:o().trim().min(1).max(1e3).nullable().default(null),wakeRequestedRunIds:f(o().trim().min(1).max(200)).max(200).default([]),wakeInterruptedRunIds:f(o().trim().min(1).max(200)).max(200).default([]),wakeDeferredRunIds:f(o().trim().min(1).max(200)).max(200).default([]),reason:o().trim().min(1).max(1e3).nullable().default(null)}),FR=l({id:o().trim().min(1).max(200),fromRunId:o().trim().min(1).max(200),toRunId:o().trim().min(1).max(200).nullable().default(null),toRole:vr.nullable().default(null),kind:HR,priority:qR.optional(),body:o().trim().min(1).max(5e4),refs:f(xs).max(100).default([]),delivery:BR.optional(),createdAt:o()});function Gv(){return NR.map(e=>yp.parse({id:e.id,toolPolicy:e.defaultToolPolicy}))}function VR(){return Rs.parse({})}function WR(e){const t=Gv(),n=new Map(t.map(i=>[i.id,i])),a=[];for(const i of e??[]){const r=yp.parse(i);n.has(r.id)?n.set(r.id,r):a.push(r)}return[...t.map(i=>n.get(i.id)??i),...a]}const KR=b(["session.started","session.title.updated","turn.started","assistant.delta","assistant.reasoning.delta","tool.started","tool.completed","skill.selected","skill.loaded","skill.load_failed","user_question.asked","user_question.answered","user_question.dismissed","approval.requested","approval.resolved","command.output","workspace_action","workspace_action_result","workspace.diff","create_improve.updated","session.context.updated","session.compaction.started","session.compaction.completed","session.compaction.failed","goal.continuation.started","goal.continuation.skipped","goal.continuation.failed","harness.refiner.queued","harness.refiner.started","harness.refiner.completed","harness.refiner.failed","turn.completed","turn.failed","turn.interrupted","session.closed",...Vv,"diagnostic"]),hh=l({id:o(),sequence:c().int().positive().optional(),sessionId:o().optional(),turnId:o().optional(),name:KR,timestamp:o(),source:b(["ui_button","chat_action","terminal_command","hook","provider","server"]).optional(),action:o().optional(),appId:o().nullable().optional(),args:fe(o(),ye()).optional(),status:b(["started","completed","failed","pending"]).optional(),output:o().optional(),error:o().optional(),relatedDeploymentId:o().optional(),data:ye().optional()}),GR=l({id:o().trim().min(1).max(80),label:o().trim().min(1).max(160),description:o().trim().max(500).nullable().optional().default(null)}),ZR=l({id:o().trim().min(1),sessionId:o().trim().min(1),turnId:o().trim().min(1),toolCallId:o().trim().min(1),question:o().trim().min(1).max(2e3),reason:o().trim().max(1e3).nullable().optional().default(null),options:f(GR).max(5).default([]),allowFreeform:C().default(!0),status:b(["pending","answered","dismissed"]),answer:l({optionId:o().trim().min(1).nullable(),text:o().max(4e3)}).nullable(),createdAt:o(),answeredAt:o().nullable()}),JR=l({questionId:o().trim().min(1),action:b(["answer","dismiss"]),optionId:o().trim().min(1).nullable().optional().default(null),text:o().trim().max(4e3).optional().default("")});l({kind:b(["session","project","draft"]),id:o().trim().min(1).max(300)});b(["unknown","idle","running","success","failed"]);b(["none","idle","running","success","failed","unknown"]);function YR(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Cn={},Il={},xo={},gh;function Us(){if(gh)return xo;gh=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,d){if(d){const p=Object.keys(d);for(let m=0,h=p.length;m<h;m+=1){const S=p[m];s[S]=d[S]}}return s}function i(s,d){let p="";for(let m=0;m<d;m+=1)p+=s;return p}function r(s){return s===0&&Number.NEGATIVE_INFINITY===1/s}return xo.isNothing=e,xo.isObject=t,xo.toArray=n,xo.repeat=i,xo.isNegativeZero=r,xo.extend=a,xo}var ru,bh;function Hs(){if(bh)return ru;bh=1;function e(n,a){let i="";const r=n.reason||"(unknown reason)";return n.mark?(n.mark.name&&(i+='in "'+n.mark.name+'" '),i+="("+(n.mark.line+1)+":"+(n.mark.column+1)+")",!a&&n.mark.snippet&&(i+=`
66
-
67
- `+n.mark.snippet),r+" "+i):r}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)},ru=t,ru}var su,vh;function XR(){if(vh)return su;vh=1;const e=Us();function t(i,r,s,d,p){let m="",h="";const S=Math.floor(p/2)-1;return d-r>S&&(m=" ... ",r=d-S+m.length),s-d>S&&(h=" ...",s=d+S-h.length),{str:m+i.slice(r,s).replace(/\t/g,"→")+h,pos:d-r+m.length}}function n(i,r){return e.repeat(" ",r-i.length)+i}function a(i,r){if(r=Object.create(r||null),!i.buffer)return null;r.maxLength||(r.maxLength=79),typeof r.indent!="number"&&(r.indent=1),typeof r.linesBefore!="number"&&(r.linesBefore=3),typeof r.linesAfter!="number"&&(r.linesAfter=2);const s=/\r?\n|\r|\0/g,d=[0],p=[];let m,h=-1;for(;m=s.exec(i.buffer);)p.push(m.index),d.push(m.index+m[0].length),i.position<=m.index&&h<0&&(h=d.length-2);h<0&&(h=d.length-1);let S="";const y=Math.min(i.line+r.linesAfter,p.length).toString().length,w=r.maxLength-(r.indent+y+3);for(let A=1;A<=r.linesBefore&&!(h-A<0);A++){const N=t(i.buffer,d[h-A],p[h-A],i.position-(d[h]-d[h-A]),w);S=e.repeat(" ",r.indent)+n((i.line-A+1).toString(),y)+" | "+N.str+`
68
- `+S}const R=t(i.buffer,d[h],p[h],i.position,w);S+=e.repeat(" ",r.indent)+n((i.line+1).toString(),y)+" | "+R.str+`
69
- `,S+=e.repeat("-",r.indent+y+3+R.pos)+`^
70
- `;for(let A=1;A<=r.linesAfter&&!(h+A>=p.length);A++){const N=t(i.buffer,d[h+A],p[h+A],i.position-(d[h]-d[h+A]),w);S+=e.repeat(" ",r.indent)+n((i.line+A+1).toString(),y)+" | "+N.str+`
71
- `}return S.replace(/\n$/,"")}return su=a,su}var lu,yh;function Ln(){if(yh)return lu;yh=1;const e=Hs(),t=["kind","multi","resolve","construct","instanceOf","predicate","represent","representName","defaultStyle","styleAliases"],n=["scalar","sequence","mapping"];function a(r){const s={};return r!==null&&Object.keys(r).forEach(function(d){r[d].forEach(function(p){s[String(p)]=d})}),s}function i(r,s){if(s=s||{},Object.keys(s).forEach(function(d){if(t.indexOf(d)===-1)throw new e('Unknown option "'+d+'" is met in definition of "'+r+'" YAML type.')}),this.options=s,this.tag=r,this.kind=s.kind||null,this.resolve=s.resolve||function(){return!0},this.construct=s.construct||function(d){return d},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 "'+r+'" YAML type.')}return lu=i,lu}var cu,Sh;function Zv(){if(Sh)return cu;Sh=1;const e=Hs(),t=Ln();function n(r,s){const d=[];return r[s].forEach(function(p){let m=d.length;d.forEach(function(h,S){h.tag===p.tag&&h.kind===p.kind&&h.multi===p.multi&&(m=S)}),d[m]=p}),d}function a(){const r={scalar:{},sequence:{},mapping:{},fallback:{},multi:{scalar:[],sequence:[],mapping:[],fallback:[]}};function s(d){d.multi?(r.multi[d.kind].push(d),r.multi.fallback.push(d)):r[d.kind][d.tag]=r.fallback[d.tag]=d}for(let d=0,p=arguments.length;d<p;d+=1)arguments[d].forEach(s);return r}function i(r){return this.extend(r)}return i.prototype.extend=function(s){let d=[],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&&(d=d.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: [...] })");d.forEach(function(h){if(!(h instanceof t))throw new e("Specified list of YAML types (or a single Type object) contains a non-Type object.");if(h.loadKind&&h.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(h.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(h){if(!(h instanceof t))throw new e("Specified list of YAML types (or a single Type object) contains a non-Type object.")});const m=Object.create(i.prototype);return m.implicit=(this.implicit||[]).concat(d),m.explicit=(this.explicit||[]).concat(p),m.compiledImplicit=n(m,"implicit"),m.compiledExplicit=n(m,"explicit"),m.compiledTypeMap=a(m.compiledImplicit,m.compiledExplicit),m},cu=i,cu}var du,xh;function Jv(){if(xh)return du;xh=1;const e=Ln();return du=new e("tag:yaml.org,2002:str",{kind:"scalar",construct:function(t){return t!==null?t:""}}),du}var uu,kh;function Yv(){if(kh)return uu;kh=1;const e=Ln();return uu=new e("tag:yaml.org,2002:seq",{kind:"sequence",construct:function(t){return t!==null?t:[]}}),uu}var mu,_h;function Xv(){if(_h)return mu;_h=1;const e=Ln();return mu=new e("tag:yaml.org,2002:map",{kind:"mapping",construct:function(t){return t!==null?t:{}}}),mu}var pu,wh;function Qv(){if(wh)return pu;wh=1;const e=Zv();return pu=new e({explicit:[Jv(),Yv(),Xv()]}),pu}var fu,Ih;function e0(){if(Ih)return fu;Ih=1;const e=Ln();function t(i){if(i===null)return!0;const r=i.length;return r===1&&i==="~"||r===4&&(i==="null"||i==="Null"||i==="NULL")}function n(){return null}function a(i){return i===null}return fu=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"}),fu}var hu,Ch;function t0(){if(Ch)return hu;Ch=1;const e=Ln();function t(i){if(i===null)return!1;const r=i.length;return r===4&&(i==="true"||i==="True"||i==="TRUE")||r===5&&(i==="false"||i==="False"||i==="FALSE")}function n(i){return i==="true"||i==="True"||i==="TRUE"}function a(i){return Object.prototype.toString.call(i)==="[object Boolean]"}return hu=new e("tag:yaml.org,2002:bool",{kind:"scalar",resolve:t,construct:n,predicate:a,represent:{lowercase:function(i){return i?"true":"false"},uppercase:function(i){return i?"TRUE":"FALSE"},camelcase:function(i){return i?"True":"False"}},defaultStyle:"lowercase"}),hu}var gu,Rh;function n0(){if(Rh)return gu;Rh=1;const e=Us(),t=Ln();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 i(m){return m>=48&&m<=57}function r(m){if(m===null)return!1;const h=m.length;let S=0,y=!1;if(!h)return!1;let w=m[S];if((w==="-"||w==="+")&&(w=m[++S]),w==="0"){if(S+1===h)return!0;if(w=m[++S],w==="b"){for(S++;S<h;S++){if(w=m[S],w!=="0"&&w!=="1")return!1;y=!0}return y&&isFinite(s(m))}if(w==="x"){for(S++;S<h;S++){if(!n(m.charCodeAt(S)))return!1;y=!0}return y&&isFinite(s(m))}if(w==="o"){for(S++;S<h;S++){if(!a(m.charCodeAt(S)))return!1;y=!0}return y&&isFinite(s(m))}}for(;S<h;S++){if(!i(m.charCodeAt(S)))return!1;y=!0}return y?isFinite(s(m)):!1}function s(m){let h=m,S=1,y=h[0];if((y==="-"||y==="+")&&(y==="-"&&(S=-1),h=h.slice(1),y=h[0]),h==="0")return 0;if(y==="0"){if(h[1]==="b")return S*parseInt(h.slice(2),2);if(h[1]==="x")return S*parseInt(h.slice(2),16);if(h[1]==="o")return S*parseInt(h.slice(2),8)}return S*parseInt(h,10)}function d(m){return s(m)}function p(m){return Object.prototype.toString.call(m)==="[object Number]"&&m%1===0&&!e.isNegativeZero(m)}return gu=new t("tag:yaml.org,2002:int",{kind:"scalar",resolve:r,construct:d,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"]}}),gu}var bu,Ah;function a0(){if(Ah)return bu;Ah=1;const e=Us(),t=Ln(),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 i(m){return m===null||!n.test(m)?!1:isFinite(parseFloat(m,10))?!0:a.test(m)}function r(m){let h=m.toLowerCase();const S=h[0]==="-"?-1:1;return"+-".indexOf(h[0])>=0&&(h=h.slice(1)),h===".inf"?S===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:h===".nan"?NaN:S*parseFloat(h,10)}const s=/^[-+]?[0-9]+e/;function d(m,h){if(isNaN(m))switch(h){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===m)switch(h){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===m)switch(h){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 bu=new t("tag:yaml.org,2002:float",{kind:"scalar",resolve:i,construct:r,predicate:p,represent:d,defaultStyle:"lowercase"}),bu}var vu,Ph;function o0(){return Ph||(Ph=1,vu=Qv().extend({implicit:[e0(),t0(),n0(),a0()]})),vu}var yu,Th;function i0(){return Th||(Th=1,yu=o0()),yu}var Su,Eh;function r0(){if(Eh)return Su;Eh=1;const e=Ln(),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 i(s){let d=0,p=null,m=t.exec(s);if(m===null&&(m=n.exec(s)),m===null)throw new Error("Date resolve error");const h=+m[1],S=+m[2]-1,y=+m[3];if(!m[4])return new Date(Date.UTC(h,S,y));const w=+m[4],R=+m[5],A=+m[6];if(m[7]){for(d=m[7].slice(0,3);d.length<3;)d+="0";d=+d}if(m[9]){const O=+m[10],D=+(m[11]||0);p=(O*60+D)*6e4,m[9]==="-"&&(p=-p)}const N=new Date(Date.UTC(h,S,y,w,R,A,d));return p&&N.setTime(N.getTime()-p),N}function r(s){return s.toISOString()}return Su=new e("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:a,construct:i,instanceOf:Date,represent:r}),Su}var xu,Mh;function s0(){if(Mh)return xu;Mh=1;const e=Ln();function t(n){return n==="<<"||n===null}return xu=new e("tag:yaml.org,2002:merge",{kind:"scalar",resolve:t}),xu}var ku,jh;function l0(){if(jh)return ku;jh=1;const e=Ln(),t=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
72
- \r`;function n(s){if(s===null)return!1;let d=0;const p=s.length,m=t;for(let h=0;h<p;h++){const S=m.indexOf(s.charAt(h));if(!(S>64)){if(S<0)return!1;d+=6}}return d%8===0}function a(s){const d=s.replace(/[\r\n=]/g,""),p=d.length,m=t;let h=0;const S=[];for(let w=0;w<p;w++)w%4===0&&w&&(S.push(h>>16&255),S.push(h>>8&255),S.push(h&255)),h=h<<6|m.indexOf(d.charAt(w));const y=p%4*6;return y===0?(S.push(h>>16&255),S.push(h>>8&255),S.push(h&255)):y===18?(S.push(h>>10&255),S.push(h>>2&255)):y===12&&S.push(h>>4&255),new Uint8Array(S)}function i(s){let d="",p=0;const m=s.length,h=t;for(let y=0;y<m;y++)y%3===0&&y&&(d+=h[p>>18&63],d+=h[p>>12&63],d+=h[p>>6&63],d+=h[p&63]),p=(p<<8)+s[y];const S=m%3;return S===0?(d+=h[p>>18&63],d+=h[p>>12&63],d+=h[p>>6&63],d+=h[p&63]):S===2?(d+=h[p>>10&63],d+=h[p>>4&63],d+=h[p<<2&63],d+=h[64]):S===1&&(d+=h[p>>2&63],d+=h[p<<4&63],d+=h[64],d+=h[64]),d}function r(s){return Object.prototype.toString.call(s)==="[object Uint8Array]"}return ku=new e("tag:yaml.org,2002:binary",{kind:"scalar",resolve:n,construct:a,predicate:r,represent:i}),ku}var _u,Oh;function c0(){if(Oh)return _u;Oh=1;const e=Ln(),t=Object.prototype.hasOwnProperty,n=Object.prototype.toString;function a(r){if(r===null)return!0;const s=[],d=r;for(let p=0,m=d.length;p<m;p+=1){const h=d[p];let S=!1;if(n.call(h)!=="[object Object]")return!1;let y;for(y in h)if(t.call(h,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 i(r){return r!==null?r:[]}return _u=new e("tag:yaml.org,2002:omap",{kind:"sequence",resolve:a,construct:i}),_u}var wu,Nh;function d0(){if(Nh)return wu;Nh=1;const e=Ln(),t=Object.prototype.toString;function n(i){if(i===null)return!0;const r=i,s=new Array(r.length);for(let d=0,p=r.length;d<p;d+=1){const m=r[d];if(t.call(m)!=="[object Object]")return!1;const h=Object.keys(m);if(h.length!==1)return!1;s[d]=[h[0],m[h[0]]]}return!0}function a(i){if(i===null)return[];const r=i,s=new Array(r.length);for(let d=0,p=r.length;d<p;d+=1){const m=r[d],h=Object.keys(m);s[d]=[h[0],m[h[0]]]}return s}return wu=new e("tag:yaml.org,2002:pairs",{kind:"sequence",resolve:n,construct:a}),wu}var Iu,$h;function u0(){if($h)return Iu;$h=1;const e=Ln(),t=Object.prototype.hasOwnProperty;function n(i){if(i===null)return!0;const r=i;for(const s in r)if(t.call(r,s)&&r[s]!==null)return!1;return!0}function a(i){return i!==null?i:{}}return Iu=new e("tag:yaml.org,2002:set",{kind:"mapping",resolve:n,construct:a}),Iu}var Cu,Dh;function Sp(){return Dh||(Dh=1,Cu=i0().extend({implicit:[r0(),s0()],explicit:[l0(),c0(),d0(),u0()]})),Cu}var Lh;function QR(){if(Lh)return Il;Lh=1;const e=Us(),t=Hs(),n=XR(),a=Sp(),i=Object.prototype.hasOwnProperty,r=1,s=2,d=3,p=4,m=1,h=2,S=3,y=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,w=/[\x85\u2028\u2029]/,R=/[,\[\]{}]/,A=/^(?:!|!!|![0-9A-Za-z-]+!)$/,N=/^(?:!|[^,\[\]{}])(?:%[0-9a-f]{2}|[0-9a-z\-#;/?:@&=+$,_.!~*'()\[\]])*$/i;function O(u){return Object.prototype.toString.call(u)}function D(u){return u===10||u===13}function x(u){return u===9||u===32}function I(u){return u===9||u===32||u===10||u===13}function P(u){return u===44||u===91||u===93||u===123||u===125}function E(u){if(u>=48&&u<=57)return u-48;const j=u|32;return j>=97&&j<=102?j-97+10:-1}function T(u){return u===120?2:u===117?4:u===85?8:0}function z(u){return u>=48&&u<=57?u-48:-1}function U(u){switch(u){case 48:return"\0";case 97:return"\x07";case 98:return"\b";case 116:return" ";case 9:return" ";case 110:return`
73
- `;case 118:return"\v";case 102:return"\f";case 114:return"\r";case 101:return"\x1B";case 32:return" ";case 34:return'"';case 47:return"/";case 92:return"\\";case 78:return"…";case 95:return" ";case 76:return"\u2028";case 80:return"\u2029";default:return""}}function $(u){return u<=65535?String.fromCharCode(u):String.fromCharCode((u-65536>>10)+55296,(u-65536&1023)+56320)}function V(u,j,q){j==="__proto__"?Object.defineProperty(u,j,{configurable:!0,enumerable:!0,writable:!0,value:q}):u[j]=q}const re=new Array(256),Q=new Array(256);for(let u=0;u<256;u++)re[u]=U(u)?1:0,Q[u]=U(u);function Ie(u,j){this.input=u,this.filename=j.filename||null,this.schema=j.schema||a,this.onWarning=j.onWarning||null,this.legacy=j.legacy||!1,this.json=j.json||!1,this.listener=j.listener||null,this.maxDepth=typeof j.maxDepth=="number"?j.maxDepth:100,this.maxTotalMergeKeys=typeof j.maxTotalMergeKeys=="number"?j.maxTotalMergeKeys:1e4,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=u.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.depth=0,this.totalMergeKeys=0,this.firstTabInLine=-1,this.documents=[],this.anchorMapTransactions=[]}function Se(u,j){const q={name:u.filename,buffer:u.input.slice(0,-1),position:u.position,line:u.line,column:u.position-u.lineStart};return q.snippet=n(q),new t(j,q)}function G(u,j){throw Se(u,j)}function Ee(u,j){u.onWarning&&u.onWarning.call(null,Se(u,j))}function xe(u,j,q){const oe=u.anchorMapTransactions;if(oe.length!==0){const ne=oe[oe.length-1];i.call(ne,j)||(ne[j]={existed:i.call(u.anchorMap,j),value:u.anchorMap[j]})}u.anchorMap[j]=q}function le(u){u.anchorMapTransactions.push(Object.create(null))}function ke(u){const j=u.anchorMapTransactions.pop(),q=u.anchorMapTransactions;if(q.length===0)return;const oe=q[q.length-1],ne=Object.keys(j);for(let F=0,_=ne.length;F<_;F+=1){const W=ne[F];i.call(oe,W)||(oe[W]=j[W])}}function ae(u){const j=u.anchorMapTransactions.pop(),q=Object.keys(j);for(let oe=q.length-1;oe>=0;oe-=1){const ne=j[q[oe]];ne.existed?u.anchorMap[q[oe]]=ne.value:delete u.anchorMap[q[oe]]}}function he(u){return{position:u.position,line:u.line,lineStart:u.lineStart,lineIndent:u.lineIndent,firstTabInLine:u.firstTabInLine,tag:u.tag,anchor:u.anchor,kind:u.kind,result:u.result}}function ve(u,j){u.position=j.position,u.line=j.line,u.lineStart=j.lineStart,u.lineIndent=j.lineIndent,u.firstTabInLine=j.firstTabInLine,u.tag=j.tag,u.anchor=j.anchor,u.kind=j.kind,u.result=j.result}const Ze={YAML:function(j,q,oe){j.version!==null&&G(j,"duplication of %YAML directive"),oe.length!==1&&G(j,"YAML directive accepts exactly one argument");const ne=/^([0-9]+)\.([0-9]+)$/.exec(oe[0]);ne===null&&G(j,"ill-formed argument of the YAML directive");const F=parseInt(ne[1],10),_=parseInt(ne[2],10);F!==1&&G(j,"unacceptable YAML version of the document"),j.version=oe[0],j.checkLineBreaks=_<2,_!==1&&_!==2&&Ee(j,"unsupported YAML version of the document")},TAG:function(j,q,oe){let ne;oe.length!==2&&G(j,"TAG directive accepts exactly two arguments");const F=oe[0];ne=oe[1],A.test(F)||G(j,"ill-formed tag handle (first argument) of the TAG directive"),i.call(j.tagMap,F)&&G(j,'there is a previously declared suffix for "'+F+'" tag handle'),N.test(ne)||G(j,"ill-formed tag prefix (second argument) of the TAG directive");try{ne=decodeURIComponent(ne)}catch{G(j,"tag prefix is malformed: "+ne)}j.tagMap[F]=ne}};function Re(u,j,q,oe){if(j<q){const ne=u.input.slice(j,q);if(oe)for(let F=0,_=ne.length;F<_;F+=1){const W=ne.charCodeAt(F);W===9||W>=32&&W<=1114111||G(u,"expected valid JSON character")}else y.test(ne)&&G(u,"the stream contains non-printable characters");u.result+=ne}}function se(u,j,q,oe){e.isObject(q)||G(u,"cannot merge mappings; the provided source object is unacceptable");const ne=Object.keys(q);for(let F=0,_=ne.length;F<_;F+=1){const W=ne[F];u.maxTotalMergeKeys!==-1&&++u.totalMergeKeys>u.maxTotalMergeKeys&&G(u,"merge keys exceeded maxTotalMergeKeys ("+u.maxTotalMergeKeys+")"),i.call(j,W)||(V(j,W,q[W]),oe[W]=!0)}}function Ce(u,j,q,oe,ne,F,_,W,Y){if(Array.isArray(ne)){ne=Array.prototype.slice.call(ne);for(let ee=0,K=ne.length;ee<K;ee+=1)Array.isArray(ne[ee])&&G(u,"nested arrays are not supported inside keys"),typeof ne=="object"&&O(ne[ee])==="[object Object]"&&(ne[ee]="[object Object]")}if(typeof ne=="object"&&O(ne)==="[object Object]"&&(ne="[object Object]"),ne=String(ne),j===null&&(j={}),oe==="tag:yaml.org,2002:merge")if(Array.isArray(F))for(let ee=0,K=F.length;ee<K;ee+=1)se(u,j,F[ee],q);else se(u,j,F,q);else!u.json&&!i.call(q,ne)&&i.call(j,ne)&&(u.line=_||u.line,u.lineStart=W||u.lineStart,u.position=Y||u.position,G(u,"duplicated mapping key")),V(j,ne,F),delete q[ne];return j}function Le(u){const j=u.input.charCodeAt(u.position);j===10?u.position++:j===13?(u.position++,u.input.charCodeAt(u.position)===10&&u.position++):G(u,"a line break is expected"),u.line+=1,u.lineStart=u.position,u.firstTabInLine=-1}function Qe(u,j,q){let oe=0,ne=u.input.charCodeAt(u.position);for(;ne!==0;){for(;x(ne);)ne===9&&u.firstTabInLine===-1&&(u.firstTabInLine=u.position),ne=u.input.charCodeAt(++u.position);if(j&&ne===35)do ne=u.input.charCodeAt(++u.position);while(ne!==10&&ne!==13&&ne!==0);if(D(ne))for(Le(u),ne=u.input.charCodeAt(u.position),oe++,u.lineIndent=0;ne===32;)u.lineIndent++,ne=u.input.charCodeAt(++u.position);else break}return q!==-1&&oe!==0&&u.lineIndent<q&&Ee(u,"deficient indentation"),oe}function it(u){let j=u.position,q=u.input.charCodeAt(j);return!!((q===45||q===46)&&q===u.input.charCodeAt(j+1)&&q===u.input.charCodeAt(j+2)&&(j+=3,q=u.input.charCodeAt(j),q===0||I(q)))}function ut(u,j){j===1?u.result+=" ":j>1&&(u.result+=e.repeat(`
74
- `,j-1))}function Fe(u,j,q){let oe,ne,F,_,W,Y;const ee=u.kind,K=u.result;let ce=u.input.charCodeAt(u.position);if(I(ce)||P(ce)||ce===35||ce===38||ce===42||ce===33||ce===124||ce===62||ce===39||ce===34||ce===37||ce===64||ce===96)return!1;if(ce===63||ce===45){const ue=u.input.charCodeAt(u.position+1);if(I(ue)||q&&P(ue))return!1}for(u.kind="scalar",u.result="",oe=ne=u.position,F=!1;ce!==0;){if(ce===58){const ue=u.input.charCodeAt(u.position+1);if(I(ue)||q&&P(ue))break}else if(ce===35){const ue=u.input.charCodeAt(u.position-1);if(I(ue))break}else{if(u.position===u.lineStart&&it(u)||q&&P(ce))break;if(D(ce))if(_=u.line,W=u.lineStart,Y=u.lineIndent,Qe(u,!1,-1),u.lineIndent>=j){F=!0,ce=u.input.charCodeAt(u.position);continue}else{u.position=ne,u.line=_,u.lineStart=W,u.lineIndent=Y;break}}F&&(Re(u,oe,ne,!1),ut(u,u.line-_),oe=ne=u.position,F=!1),x(ce)||(ne=u.position+1),ce=u.input.charCodeAt(++u.position)}return Re(u,oe,ne,!1),u.result?!0:(u.kind=ee,u.result=K,!1)}function Ue(u,j){let q,oe,ne=u.input.charCodeAt(u.position);if(ne!==39)return!1;for(u.kind="scalar",u.result="",u.position++,q=oe=u.position;(ne=u.input.charCodeAt(u.position))!==0;)if(ne===39)if(Re(u,q,u.position,!0),ne=u.input.charCodeAt(++u.position),ne===39)q=u.position,u.position++,oe=u.position;else return!0;else D(ne)?(Re(u,q,oe,!0),ut(u,Qe(u,!1,j)),q=oe=u.position):u.position===u.lineStart&&it(u)?G(u,"unexpected end of the document within a single quoted scalar"):(u.position++,x(ne)||(oe=u.position));G(u,"unexpected end of the stream within a single quoted scalar")}function ze(u,j){let q,oe,ne,F=u.input.charCodeAt(u.position);if(F!==34)return!1;for(u.kind="scalar",u.result="",u.position++,q=oe=u.position;(F=u.input.charCodeAt(u.position))!==0;){if(F===34)return Re(u,q,u.position,!0),u.position++,!0;if(F===92){if(Re(u,q,u.position,!0),F=u.input.charCodeAt(++u.position),D(F))Qe(u,!1,j);else if(F<256&&re[F])u.result+=Q[F],u.position++;else if((ne=T(F))>0){let _=ne,W=0;for(;_>0;_--)F=u.input.charCodeAt(++u.position),(ne=E(F))>=0?W=(W<<4)+ne:G(u,"expected hexadecimal character");u.result+=$(W),u.position++}else G(u,"unknown escape sequence");q=oe=u.position}else D(F)?(Re(u,q,oe,!0),ut(u,Qe(u,!1,j)),q=oe=u.position):u.position===u.lineStart&&it(u)?G(u,"unexpected end of the document within a double quoted scalar"):(u.position++,x(F)||(oe=u.position))}G(u,"unexpected end of the stream within a double quoted scalar")}function M(u,j){let q=!0,oe,ne,F;const _=u.tag;let W;const Y=u.anchor;let ee,K,ce,ue;const Ne=Object.create(null);let je,$e,Ge,We=u.input.charCodeAt(u.position);if(We===91)ee=93,ue=!1,W=[];else if(We===123)ee=125,ue=!0,W={};else return!1;for(u.anchor!==null&&xe(u,u.anchor,W),We=u.input.charCodeAt(++u.position);We!==0;){if(Qe(u,!0,j),We=u.input.charCodeAt(u.position),We===ee)return u.position++,u.tag=_,u.anchor=Y,u.kind=ue?"mapping":"sequence",u.result=W,!0;if(q?We===44&&G(u,"expected the node content, but found ','"):G(u,"missed comma between flow collection entries"),$e=je=Ge=null,K=ce=!1,We===63){const mt=u.input.charCodeAt(u.position+1);I(mt)&&(K=ce=!0,u.position++,Qe(u,!0,j))}oe=u.line,ne=u.lineStart,F=u.position,qe(u,j,r,!1,!0),$e=u.tag,je=u.result,Qe(u,!0,j),We=u.input.charCodeAt(u.position),(ce||u.line===oe)&&We===58&&(K=!0,We=u.input.charCodeAt(++u.position),Qe(u,!0,j),qe(u,j,r,!1,!0),Ge=u.result),ue?Ce(u,W,Ne,$e,je,Ge,oe,ne,F):K?W.push(Ce(u,null,Ne,$e,je,Ge,oe,ne,F)):W.push(je),Qe(u,!0,j),We=u.input.charCodeAt(u.position),We===44?(q=!0,We=u.input.charCodeAt(++u.position)):q=!1}G(u,"unexpected end of the stream within a flow collection")}function H(u,j){let q,oe=m,ne=!1,F=!1,_=j,W=0,Y=!1,ee,K=u.input.charCodeAt(u.position);if(K===124)q=!1;else if(K===62)q=!0;else return!1;for(u.kind="scalar",u.result="";K!==0;)if(K=u.input.charCodeAt(++u.position),K===43||K===45)m===oe?oe=K===43?S:h:G(u,"repeat of a chomping mode identifier");else if((ee=z(K))>=0)ee===0?G(u,"bad explicit indentation width of a block scalar; it cannot be less than one"):F?G(u,"repeat of an indentation width identifier"):(_=j+ee-1,F=!0);else break;if(x(K)){do K=u.input.charCodeAt(++u.position);while(x(K));if(K===35)do K=u.input.charCodeAt(++u.position);while(!D(K)&&K!==0)}for(;K!==0;){for(Le(u),u.lineIndent=0,K=u.input.charCodeAt(u.position);(!F||u.lineIndent<_)&&K===32;)u.lineIndent++,K=u.input.charCodeAt(++u.position);if(!F&&u.lineIndent>_&&(_=u.lineIndent),D(K)){W++;continue}if(!F&&_===0&&G(u,"missing indentation for block scalar"),u.lineIndent<_){oe===S?u.result+=e.repeat(`
75
- `,ne?1+W:W):oe===m&&ne&&(u.result+=`
76
- `);break}q?x(K)?(Y=!0,u.result+=e.repeat(`
77
- `,ne?1+W:W)):Y?(Y=!1,u.result+=e.repeat(`
78
- `,W+1)):W===0?ne&&(u.result+=" "):u.result+=e.repeat(`
79
- `,W):u.result+=e.repeat(`
80
- `,ne?1+W:W),ne=!0,F=!0,W=0;const ce=u.position;for(;!D(K)&&K!==0;)K=u.input.charCodeAt(++u.position);Re(u,ce,u.position,!1)}return!0}function X(u,j){const q=u.tag,oe=u.anchor,ne=[];let F=!1;if(u.firstTabInLine!==-1)return!1;u.anchor!==null&&xe(u,u.anchor,ne);let _=u.input.charCodeAt(u.position);for(;_!==0&&(u.firstTabInLine!==-1&&(u.position=u.firstTabInLine,G(u,"tab characters must not be used in indentation")),_===45);){const W=u.input.charCodeAt(u.position+1);if(!I(W))break;if(F=!0,u.position++,Qe(u,!0,-1)&&u.lineIndent<=j){ne.push(null),_=u.input.charCodeAt(u.position);continue}const Y=u.line;if(qe(u,j,d,!1,!0),ne.push(u.result),Qe(u,!0,-1),_=u.input.charCodeAt(u.position),(u.line===Y||u.lineIndent>j)&&_!==0)G(u,"bad indentation of a sequence entry");else if(u.lineIndent<j)break}return F?(u.tag=q,u.anchor=oe,u.kind="sequence",u.result=ne,!0):!1}function pe(u,j,q){let oe,ne,F,_;const W=u.tag,Y=u.anchor,ee={},K=Object.create(null);let ce=null,ue=null,Ne=null,je=!1,$e=!1;if(u.firstTabInLine!==-1)return!1;u.anchor!==null&&xe(u,u.anchor,ee);let Ge=u.input.charCodeAt(u.position);for(;Ge!==0;){!je&&u.firstTabInLine!==-1&&(u.position=u.firstTabInLine,G(u,"tab characters must not be used in indentation"));const We=u.input.charCodeAt(u.position+1),mt=u.line;if((Ge===63||Ge===58)&&I(We))Ge===63?(je&&(Ce(u,ee,K,ce,ue,null,ne,F,_),ce=ue=Ne=null),$e=!0,je=!0,oe=!0):je?(je=!1,oe=!0):G(u,"incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line"),u.position+=1,Ge=We;else{if(ne=u.line,F=u.lineStart,_=u.position,!qe(u,q,s,!1,!0))break;if(u.line===mt){for(Ge=u.input.charCodeAt(u.position);x(Ge);)Ge=u.input.charCodeAt(++u.position);if(Ge===58)Ge=u.input.charCodeAt(++u.position),I(Ge)||G(u,"a whitespace character is expected after the key-value separator within a block mapping"),je&&(Ce(u,ee,K,ce,ue,null,ne,F,_),ce=ue=Ne=null),$e=!0,je=!1,oe=!1,ce=u.tag,ue=u.result;else if($e)G(u,"can not read an implicit mapping pair; a colon is missed");else return u.tag=W,u.anchor=Y,!0}else if($e)G(u,"can not read a block mapping entry; a multiline key may not be an implicit key");else return u.tag=W,u.anchor=Y,!0}if((u.line===mt||u.lineIndent>j)&&(je&&(ne=u.line,F=u.lineStart,_=u.position),qe(u,j,p,!0,oe)&&(je?ue=u.result:Ne=u.result),je||(Ce(u,ee,K,ce,ue,Ne,ne,F,_),ce=ue=Ne=null),Qe(u,!0,-1),Ge=u.input.charCodeAt(u.position)),(u.line===mt||u.lineIndent>j)&&Ge!==0)G(u,"bad indentation of a mapping entry");else if(u.lineIndent<j)break}return je&&Ce(u,ee,K,ce,ue,null,ne,F,_),$e&&(u.tag=W,u.anchor=Y,u.kind="mapping",u.result=ee),$e}function Z(u){let j=!1,q=!1,oe,ne,F=u.input.charCodeAt(u.position);if(F!==33)return!1;u.tag!==null&&G(u,"duplication of a tag property"),F=u.input.charCodeAt(++u.position),F===60?(j=!0,F=u.input.charCodeAt(++u.position)):F===33?(q=!0,oe="!!",F=u.input.charCodeAt(++u.position)):oe="!";let _=u.position;if(j){do F=u.input.charCodeAt(++u.position);while(F!==0&&F!==62);u.position<u.length?(ne=u.input.slice(_,u.position),F=u.input.charCodeAt(++u.position)):G(u,"unexpected end of the stream within a verbatim tag")}else{for(;F!==0&&!I(F);)F===33&&(q?G(u,"tag suffix cannot contain exclamation marks"):(oe=u.input.slice(_-1,u.position+1),A.test(oe)||G(u,"named tag handle cannot contain such characters"),q=!0,_=u.position+1)),F=u.input.charCodeAt(++u.position);ne=u.input.slice(_,u.position),R.test(ne)&&G(u,"tag suffix cannot contain flow indicator characters")}ne&&!N.test(ne)&&G(u,"tag name cannot contain such characters: "+ne);try{ne=decodeURIComponent(ne)}catch{G(u,"tag name is malformed: "+ne)}return j?u.tag=ne:i.call(u.tagMap,oe)?u.tag=u.tagMap[oe]+ne:oe==="!"?u.tag="!"+ne:oe==="!!"?u.tag="tag:yaml.org,2002:"+ne:G(u,'undeclared tag handle "'+oe+'"'),!0}function me(u){let j=u.input.charCodeAt(u.position);if(j!==38)return!1;u.anchor!==null&&G(u,"duplication of an anchor property"),j=u.input.charCodeAt(++u.position);const q=u.position;for(;j!==0&&!I(j)&&!P(j);)j=u.input.charCodeAt(++u.position);return u.position===q&&G(u,"name of an anchor node must contain at least one character"),u.anchor=u.input.slice(q,u.position),!0}function _e(u){let j=u.input.charCodeAt(u.position);if(j!==42)return!1;j=u.input.charCodeAt(++u.position);const q=u.position;for(;j!==0&&!I(j)&&!P(j);)j=u.input.charCodeAt(++u.position);u.position===q&&G(u,"name of an alias node must contain at least one character");const oe=u.input.slice(q,u.position);return i.call(u.anchorMap,oe)||G(u,'unidentified alias "'+oe+'"'),u.result=u.anchorMap[oe],Qe(u,!0,-1),!0}function He(u,j,q,oe){const ne=he(u);return le(u),ve(u,j),u.tag=null,u.anchor=null,u.kind=null,u.result=null,pe(u,q,oe)&&u.kind==="mapping"?(ke(u),!0):(ae(u),ve(u,ne),!1)}function qe(u,j,q,oe,ne){let F,_,W=1,Y=!1,ee=!1,K=null,ce,ue,Ne;u.depth>=u.maxDepth&&G(u,"nesting exceeded maxDepth ("+u.maxDepth+")"),u.depth+=1,u.listener!==null&&u.listener("open",u),u.tag=null,u.anchor=null,u.kind=null,u.result=null;const je=F=_=p===q||d===q;if(oe&&Qe(u,!0,-1)&&(Y=!0,u.lineIndent>j?W=1:u.lineIndent===j?W=0:u.lineIndent<j&&(W=-1)),W===1)for(;;){const $e=u.input.charCodeAt(u.position),Ge=he(u);if(Y&&($e===33&&u.tag!==null||$e===38&&u.anchor!==null)||!Z(u)&&!me(u))break;K===null&&(K=Ge),Qe(u,!0,-1)?(Y=!0,_=je,u.lineIndent>j?W=1:u.lineIndent===j?W=0:u.lineIndent<j&&(W=-1)):_=!1}if(_&&(_=Y||ne),W===1||p===q)if(r===q||s===q?ue=j:ue=j+1,Ne=u.position-u.lineStart,W===1)if(_&&(X(u,Ne)||pe(u,Ne,ue))||M(u,ue))ee=!0;else{const $e=u.input.charCodeAt(u.position);K!==null&&je&&!_&&$e!==124&&$e!==62&&He(u,K,K.position-K.lineStart,ue)||F&&H(u,ue)||Ue(u,ue)||ze(u,ue)?ee=!0:_e(u)?(ee=!0,(u.tag!==null||u.anchor!==null)&&G(u,"alias node should not have any properties")):Fe(u,ue,r===q)&&(ee=!0,u.tag===null&&(u.tag="?")),u.anchor!==null&&xe(u,u.anchor,u.result)}else W===0&&(ee=_&&X(u,Ne));if(u.tag===null)u.anchor!==null&&xe(u,u.anchor,u.result);else if(u.tag==="?"){u.result!==null&&u.kind!=="scalar"&&G(u,'unacceptable node kind for !<?> tag; it should be "scalar", not "'+u.kind+'"');for(let $e=0,Ge=u.implicitTypes.length;$e<Ge;$e+=1)if(ce=u.implicitTypes[$e],ce.resolve(u.result)){u.result=ce.construct(u.result),u.tag=ce.tag,u.anchor!==null&&xe(u,u.anchor,u.result);break}}else if(u.tag!=="!"){if(i.call(u.typeMap[u.kind||"fallback"],u.tag))ce=u.typeMap[u.kind||"fallback"][u.tag];else{ce=null;const $e=u.typeMap.multi[u.kind||"fallback"];for(let Ge=0,We=$e.length;Ge<We;Ge+=1)if(u.tag.slice(0,$e[Ge].tag.length)===$e[Ge].tag){ce=$e[Ge];break}}ce||G(u,"unknown tag !<"+u.tag+">"),u.result!==null&&ce.kind!==u.kind&&G(u,"unacceptable node kind for !<"+u.tag+'> tag; it should be "'+ce.kind+'", not "'+u.kind+'"'),ce.resolve(u.result,u.tag)?(u.result=ce.construct(u.result,u.tag),u.anchor!==null&&xe(u,u.anchor,u.result)):G(u,"cannot resolve a node with !<"+u.tag+"> explicit tag")}return u.listener!==null&&u.listener("close",u),u.depth-=1,u.tag!==null||u.anchor!==null||ee}function Xe(u){const j=u.position;let q=!1,oe;for(u.version=null,u.checkLineBreaks=u.legacy,u.tagMap=Object.create(null),u.anchorMap=Object.create(null);(oe=u.input.charCodeAt(u.position))!==0&&(Qe(u,!0,-1),oe=u.input.charCodeAt(u.position),!(u.lineIndent>0||oe!==37));){q=!0,oe=u.input.charCodeAt(++u.position);let ne=u.position;for(;oe!==0&&!I(oe);)oe=u.input.charCodeAt(++u.position);const F=u.input.slice(ne,u.position),_=[];for(F.length<1&&G(u,"directive name must not be less than one character in length");oe!==0;){for(;x(oe);)oe=u.input.charCodeAt(++u.position);if(oe===35){do oe=u.input.charCodeAt(++u.position);while(oe!==0&&!D(oe));break}if(D(oe))break;for(ne=u.position;oe!==0&&!I(oe);)oe=u.input.charCodeAt(++u.position);_.push(u.input.slice(ne,u.position))}oe!==0&&Le(u),i.call(Ze,F)?Ze[F](u,F,_):Ee(u,'unknown document directive "'+F+'"')}if(Qe(u,!0,-1),u.lineIndent===0&&u.input.charCodeAt(u.position)===45&&u.input.charCodeAt(u.position+1)===45&&u.input.charCodeAt(u.position+2)===45?(u.position+=3,Qe(u,!0,-1)):q&&G(u,"directives end mark is expected"),qe(u,u.lineIndent-1,p,!1,!0),Qe(u,!0,-1),u.checkLineBreaks&&w.test(u.input.slice(j,u.position))&&Ee(u,"non-ASCII line breaks are interpreted as content"),u.documents.push(u.result),u.position===u.lineStart&&it(u)){u.input.charCodeAt(u.position)===46&&(u.position+=3,Qe(u,!0,-1));return}u.position<u.length-1&&G(u,"end of the stream or a document separator is expected")}function at(u,j){u=String(u),j=j||{},u.length!==0&&(u.charCodeAt(u.length-1)!==10&&u.charCodeAt(u.length-1)!==13&&(u+=`
81
- `),u.charCodeAt(0)===65279&&(u=u.slice(1)));const q=new Ie(u,j),oe=u.indexOf("\0");for(oe!==-1&&(q.position=oe,G(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;)Xe(q);return q.documents}function Pe(u,j,q){j!==null&&typeof j=="object"&&typeof q>"u"&&(q=j,j=null);const oe=at(u,q);if(typeof j!="function")return oe;for(let ne=0,F=oe.length;ne<F;ne+=1)j(oe[ne])}function Ve(u,j){const q=at(u,j);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 Il.loadAll=Pe,Il.load=Ve,Il}var Ru={},zh;function eA(){if(zh)return Ru;zh=1;const e=Us(),t=Hs(),n=Sp(),a=Object.prototype.toString,i=Object.prototype.hasOwnProperty,r=65279,s=9,d=10,p=13,m=32,h=33,S=34,y=35,w=37,R=38,A=39,N=42,O=44,D=45,x=58,I=61,P=62,E=63,T=64,z=91,U=93,$=96,V=123,re=124,Q=125,Ie={};Ie[0]="\\0",Ie[7]="\\a",Ie[8]="\\b",Ie[9]="\\t",Ie[10]="\\n",Ie[11]="\\v",Ie[12]="\\f",Ie[13]="\\r",Ie[27]="\\e",Ie[34]='\\"',Ie[92]="\\\\",Ie[133]="\\N",Ie[160]="\\_",Ie[8232]="\\L",Ie[8233]="\\P";const Se=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"],G=/^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;function Ee(_,W){if(W===null)return{};const Y={},ee=Object.keys(W);for(let K=0,ce=ee.length;K<ce;K+=1){let ue=ee[K],Ne=String(W[ue]);ue.slice(0,2)==="!!"&&(ue="tag:yaml.org,2002:"+ue.slice(2));const je=_.compiledTypeMap.fallback[ue];je&&i.call(je.styleAliases,Ne)&&(Ne=je.styleAliases[Ne]),Y[ue]=Ne}return Y}function xe(_){let W,Y;const ee=_.toString(16).toUpperCase();if(_<=255)W="x",Y=2;else if(_<=65535)W="u",Y=4;else if(_<=4294967295)W="U",Y=8;else throw new t("code point within a string may not be greater than 0xFFFFFFFF");return"\\"+W+e.repeat("0",Y-ee.length)+ee}const le=1,ke=2;function ae(_){this.schema=_.schema||n,this.indent=Math.max(1,_.indent||2),this.noArrayIndent=_.noArrayIndent||!1,this.skipInvalid=_.skipInvalid||!1,this.flowLevel=e.isNothing(_.flowLevel)?-1:_.flowLevel,this.styleMap=Ee(this.schema,_.styles||null),this.sortKeys=_.sortKeys||!1,this.lineWidth=_.lineWidth||80,this.noRefs=_.noRefs||!1,this.noCompatMode=_.noCompatMode||!1,this.condenseFlow=_.condenseFlow||!1,this.quotingType=_.quotingType==='"'?ke:le,this.forceQuotes=_.forceQuotes||!1,this.replacer=typeof _.replacer=="function"?_.replacer:null,this.implicitTypes=this.schema.compiledImplicit,this.explicitTypes=this.schema.compiledExplicit,this.tag=null,this.result="",this.duplicates=[],this.usedDuplicates=null}function he(_,W){const Y=e.repeat(" ",W);let ee=0,K="";const ce=_.length;for(;ee<ce;){let ue;const Ne=_.indexOf(`
82
- `,ee);Ne===-1?(ue=_.slice(ee),ee=ce):(ue=_.slice(ee,Ne+1),ee=Ne+1),ue.length&&ue!==`
83
- `&&(K+=Y),K+=ue}return K}function ve(_,W){return`
84
- `+e.repeat(" ",_.indent*W)}function Ze(_,W){for(let Y=0,ee=_.implicitTypes.length;Y<ee;Y+=1)if(_.implicitTypes[Y].resolve(W))return!0;return!1}function Re(_){return _===m||_===s}function se(_){return _>=32&&_<=126||_>=161&&_<=55295&&_!==8232&&_!==8233||_>=57344&&_<=65533&&_!==r||_>=65536&&_<=1114111}function Ce(_){return se(_)&&_!==r&&_!==p&&_!==d}function Le(_,W,Y){const ee=Ce(_),K=ee&&!Re(_);return(Y?ee:ee&&_!==O&&_!==z&&_!==U&&_!==V&&_!==Q)&&_!==y&&!(W===x&&!K)||Ce(W)&&!Re(W)&&_===y||W===x&&K}function Qe(_){return se(_)&&_!==r&&!Re(_)&&_!==D&&_!==E&&_!==x&&_!==O&&_!==z&&_!==U&&_!==V&&_!==Q&&_!==y&&_!==R&&_!==N&&_!==h&&_!==re&&_!==I&&_!==P&&_!==A&&_!==S&&_!==w&&_!==T&&_!==$}function it(_){return!Re(_)&&_!==x}function ut(_,W){const Y=_.charCodeAt(W);let ee;return Y>=55296&&Y<=56319&&W+1<_.length&&(ee=_.charCodeAt(W+1),ee>=56320&&ee<=57343)?(Y-55296)*1024+ee-56320+65536:Y}function Fe(_){return/^\n* /.test(_)}const Ue=1,ze=2,M=3,H=4,X=5;function pe(_,W,Y,ee,K,ce,ue,Ne){let je,$e=0,Ge=null,We=!1,mt=!1;const qt=ee!==-1;let jt=-1,_n=Qe(ut(_,0))&&it(ut(_,_.length-1));if(W||ue)for(je=0;je<_.length;$e>=65536?je+=2:je++){if($e=ut(_,je),!se($e))return X;_n=_n&&Le($e,Ge,Ne),Ge=$e}else{for(je=0;je<_.length;$e>=65536?je+=2:je++){if($e=ut(_,je),$e===d)We=!0,qt&&(mt=mt||je-jt-1>ee&&_[jt+1]!==" ",jt=je);else if(!se($e))return X;_n=_n&&Le($e,Ge,Ne),Ge=$e}mt=mt||qt&&je-jt-1>ee&&_[jt+1]!==" "}return!We&&!mt?_n&&!ue&&!K(_)?Ue:ce===ke?X:ze:Y>9&&Fe(_)?X:ue?ce===ke?X:ze:mt?H:M}function Z(_,W,Y,ee,K){_.dump=(function(){if(W.length===0)return _.quotingType===ke?'""':"''";if(!_.noCompatMode&&(Se.indexOf(W)!==-1||G.test(W)))return _.quotingType===ke?'"'+W+'"':"'"+W+"'";const ce=_.indent*Math.max(1,Y),ue=_.lineWidth===-1?-1:Math.max(Math.min(_.lineWidth,40),_.lineWidth-ce),Ne=ee||_.flowLevel>-1&&Y>=_.flowLevel;function je($e){return Ze(_,$e)}switch(pe(W,Ne,_.indent,ue,je,_.quotingType,_.forceQuotes&&!ee,K)){case Ue:return W;case ze:return"'"+W.replace(/'/g,"''")+"'";case M:return"|"+me(W,_.indent)+_e(he(W,ce));case H:return">"+me(W,_.indent)+_e(he(He(W,ue),ce));case X:return'"'+Xe(W)+'"';default:throw new t("impossible error: invalid scalar style")}})()}function me(_,W){const Y=Fe(_)?String(W):"",ee=_[_.length-1]===`
85
- `,ce=ee&&(_[_.length-2]===`
86
- `||_===`
87
- `)?"+":ee?"":"-";return Y+ce+`
88
- `}function _e(_){return _[_.length-1]===`
89
- `?_.slice(0,-1):_}function He(_,W){const Y=/(\n+)([^\n]*)/g;let ee=(function(){let Ne=_.indexOf(`
90
- `);return Ne=Ne!==-1?Ne:_.length,Y.lastIndex=Ne,qe(_.slice(0,Ne),W)})(),K=_[0]===`
91
- `||_[0]===" ",ce,ue;for(;ue=Y.exec(_);){const Ne=ue[1],je=ue[2];ce=je[0]===" ",ee+=Ne+(!K&&!ce&&je!==""?`
92
- `:"")+qe(je,W),K=ce}return ee}function qe(_,W){if(_===""||_[0]===" ")return _;const Y=/ [^ ]/g;let ee,K=0,ce,ue=0,Ne=0,je="";for(;ee=Y.exec(_);)Ne=ee.index,Ne-K>W&&(ce=ue>K?ue:Ne,je+=`
93
- `+_.slice(K,ce),K=ce+1),ue=Ne;return je+=`
94
- `,_.length-K>W&&ue>K?je+=_.slice(K,ue)+`
95
- `+_.slice(ue+1):je+=_.slice(K),je.slice(1)}function Xe(_){let W="",Y=0;for(let ee=0;ee<_.length;Y>=65536?ee+=2:ee++){Y=ut(_,ee);const K=Ie[Y];!K&&se(Y)?(W+=_[ee],Y>=65536&&(W+=_[ee+1])):W+=K||xe(Y)}return W}function at(_,W,Y){let ee="";const K=_.tag;for(let ce=0,ue=Y.length;ce<ue;ce+=1){let Ne=Y[ce];_.replacer&&(Ne=_.replacer.call(Y,String(ce),Ne)),(q(_,W,Ne,!1,!1)||typeof Ne>"u"&&q(_,W,null,!1,!1))&&(ee!==""&&(ee+=","+(_.condenseFlow?"":" ")),ee+=_.dump)}_.tag=K,_.dump="["+ee+"]"}function Pe(_,W,Y,ee){let K="";const ce=_.tag;for(let ue=0,Ne=Y.length;ue<Ne;ue+=1){let je=Y[ue];_.replacer&&(je=_.replacer.call(Y,String(ue),je)),(q(_,W+1,je,!0,!0,!1,!0)||typeof je>"u"&&q(_,W+1,null,!0,!0,!1,!0))&&((!ee||K!=="")&&(K+=ve(_,W)),_.dump&&d===_.dump.charCodeAt(0)?K+="-":K+="- ",K+=_.dump)}_.tag=ce,_.dump=K||"[]"}function Ve(_,W,Y){let ee="";const K=_.tag,ce=Object.keys(Y);for(let ue=0,Ne=ce.length;ue<Ne;ue+=1){let je="";ee!==""&&(je+=", "),_.condenseFlow&&(je+='"');const $e=ce[ue];let Ge=Y[$e];_.replacer&&(Ge=_.replacer.call(Y,$e,Ge)),q(_,W,$e,!1,!1)&&(_.dump.length>1024&&(je+="? "),je+=_.dump+(_.condenseFlow?'"':"")+":"+(_.condenseFlow?"":" "),q(_,W,Ge,!1,!1)&&(je+=_.dump,ee+=je))}_.tag=K,_.dump="{"+ee+"}"}function u(_,W,Y,ee){let K="";const ce=_.tag,ue=Object.keys(Y);if(_.sortKeys===!0)ue.sort();else if(typeof _.sortKeys=="function")ue.sort(_.sortKeys);else if(_.sortKeys)throw new t("sortKeys must be a boolean or a function");for(let Ne=0,je=ue.length;Ne<je;Ne+=1){let $e="";(!ee||K!=="")&&($e+=ve(_,W));const Ge=ue[Ne];let We=Y[Ge];if(_.replacer&&(We=_.replacer.call(Y,Ge,We)),!q(_,W+1,Ge,!0,!0,!0))continue;const mt=_.tag!==null&&_.tag!=="?"||_.dump&&_.dump.length>1024;mt&&(_.dump&&d===_.dump.charCodeAt(0)?$e+="?":$e+="? "),$e+=_.dump,mt&&($e+=ve(_,W)),q(_,W+1,We,!0,mt)&&(_.dump&&d===_.dump.charCodeAt(0)?$e+=":":$e+=": ",$e+=_.dump,K+=$e)}_.tag=ce,_.dump=K||"{}"}function j(_,W,Y){const ee=Y?_.explicitTypes:_.implicitTypes;for(let K=0,ce=ee.length;K<ce;K+=1){const ue=ee[K];if((ue.instanceOf||ue.predicate)&&(!ue.instanceOf||typeof W=="object"&&W instanceof ue.instanceOf)&&(!ue.predicate||ue.predicate(W))){if(Y?ue.multi&&ue.representName?_.tag=ue.representName(W):_.tag=ue.tag:_.tag="?",ue.represent){const Ne=_.styleMap[ue.tag]||ue.defaultStyle;let je;if(a.call(ue.represent)==="[object Function]")je=ue.represent(W,Ne);else if(i.call(ue.represent,Ne))je=ue.represent[Ne](W,Ne);else throw new t("!<"+ue.tag+'> tag resolver accepts not "'+Ne+'" style');_.dump=je}return!0}}return!1}function q(_,W,Y,ee,K,ce,ue){_.tag=null,_.dump=Y,j(_,Y,!1)||j(_,Y,!0);const Ne=a.call(_.dump),je=ee;ee&&(ee=_.flowLevel<0||_.flowLevel>W);const $e=Ne==="[object Object]"||Ne==="[object Array]";let Ge,We;if($e&&(Ge=_.duplicates.indexOf(Y),We=Ge!==-1),(_.tag!==null&&_.tag!=="?"||We||_.indent!==2&&W>0)&&(K=!1),We&&_.usedDuplicates[Ge])_.dump="*ref_"+Ge;else{if($e&&We&&!_.usedDuplicates[Ge]&&(_.usedDuplicates[Ge]=!0),Ne==="[object Object]")ee&&Object.keys(_.dump).length!==0?(u(_,W,_.dump,K),We&&(_.dump="&ref_"+Ge+_.dump)):(Ve(_,W,_.dump),We&&(_.dump="&ref_"+Ge+" "+_.dump));else if(Ne==="[object Array]")ee&&_.dump.length!==0?(_.noArrayIndent&&!ue&&W>0?Pe(_,W-1,_.dump,K):Pe(_,W,_.dump,K),We&&(_.dump="&ref_"+Ge+_.dump)):(at(_,W,_.dump),We&&(_.dump="&ref_"+Ge+" "+_.dump));else if(Ne==="[object String]")_.tag!=="?"&&Z(_,_.dump,W,ce,je);else{if(Ne==="[object Undefined]")return!1;if(_.skipInvalid)return!1;throw new t("unacceptable kind of an object to dump "+Ne)}if(_.tag!==null&&_.tag!=="?"){let mt=encodeURI(_.tag[0]==="!"?_.tag.slice(1):_.tag).replace(/!/g,"%21");_.tag[0]==="!"?mt="!"+mt:mt.slice(0,18)==="tag:yaml.org,2002:"?mt="!!"+mt.slice(18):mt="!<"+mt+">",_.dump=mt+" "+_.dump}}return!0}function oe(_,W){const Y=[],ee=[];ne(_,Y,ee);const K=ee.length;for(let ce=0;ce<K;ce+=1)W.duplicates.push(Y[ee[ce]]);W.usedDuplicates=new Array(K)}function ne(_,W,Y){if(_!==null&&typeof _=="object"){const ee=W.indexOf(_);if(ee!==-1)Y.indexOf(ee)===-1&&Y.push(ee);else if(W.push(_),Array.isArray(_))for(let K=0,ce=_.length;K<ce;K+=1)ne(_[K],W,Y);else{const K=Object.keys(_);for(let ce=0,ue=K.length;ce<ue;ce+=1)ne(_[K[ce]],W,Y)}}}function F(_,W){W=W||{};const Y=new ae(W);Y.noRefs||oe(_,Y);let ee=_;return Y.replacer&&(ee=Y.replacer.call({"":ee},"",ee)),q(Y,0,ee,!0,!0)?Y.dump+`
96
- `:""}return Ru.dump=F,Ru}var Uh;function tA(){if(Uh)return Cn;Uh=1;const e=QR(),t=eA();function n(a,i){return function(){throw new Error("Function yaml."+a+" is removed in js-yaml 4. Use yaml."+i+" instead, which is now safe by default.")}}return Cn.Type=Ln(),Cn.Schema=Zv(),Cn.FAILSAFE_SCHEMA=Qv(),Cn.JSON_SCHEMA=o0(),Cn.CORE_SCHEMA=i0(),Cn.DEFAULT_SCHEMA=Sp(),Cn.load=e.load,Cn.loadAll=e.loadAll,Cn.dump=t.dump,Cn.YAMLException=Hs(),Cn.types={binary:l0(),float:a0(),map:Xv(),null:e0(),pairs:d0(),set:u0(),timestamp:r0(),bool:t0(),int:n0(),merge:s0(),omap:c0(),seq:Yv(),str:Jv()},Cn.safeLoad=n("safeLoad","load"),Cn.safeLoadAll=n("safeLoadAll","loadAll"),Cn.safeDump=n("safeDump","dump"),Cn}var nA=tA();const aA=YR(nA),{Type:N9,Schema:$9,FAILSAFE_SCHEMA:D9,JSON_SCHEMA:L9,CORE_SCHEMA:z9,DEFAULT_SCHEMA:U9,load:H9,loadAll:q9,dump:B9,YAMLException:F9,types:V9,safeLoad:W9,safeLoadAll:K9,safeDump:G9}=aA,xp=3e3,kp=9999,Z9="openpond.yaml",oA=["google","github","x"],_p=new Set([22,2222,2375,2376,3108,5900,5901,6080,7818]),Hh=f(o().trim().min(1).max(1e3)).max(50),As=o().trim().min(1).max(4096).refine(h0,{message:"path must be a relative workspace path"}),iA=o().trim().min(1).max(500).refine(e=>!e.includes("\0")&&!/\s/.test(e),"image ref must be a single OCI reference"),rA=o().trim().regex(/^sha256:[0-9a-f]{64}$/i),m0=o().trim().min(1).max(500).refine(e=>e.startsWith("/")&&!e.includes("\0"),"workspaceRoot must be an absolute guest path"),sA=l({ref:iA,digest:rA.optional(),registrySecretRef:o().trim().min(1).max(500).optional(),platform:k("linux/amd64").optional(),workspaceRoot:m0.optional()}).strict(),lA=l({context:As.default("."),path:As.default("Dockerfile"),target:o().trim().min(1).max(191).optional(),buildArgs:fe(o().max(191),o().max(500)).optional(),registrySecretRefs:f(o().trim().min(1).max(500)).max(10).optional(),platform:k("linux/amd64").optional(),workspaceRoot:m0.optional()}).strict(),cA=l({base:o().trim().min(1).max(120).optional(),snapshot:o().trim().min(1).max(191).optional(),image:sA.optional(),dockerfile:lA.optional()}).strict().superRefine((e,t)=>{[e.base,e.snapshot,e.image,e.dockerfile].filter(Boolean).length!==1&&t.addIssue({code:$n.custom,message:"runtime must declare exactly one of base, snapshot, image, or dockerfile"})}),p0=l({cpu:c().positive().max(8).optional(),memoryGb:c().positive().max(32).optional(),diskGb:c().positive().max(100).optional()}).strict(),dA=l({provider:b(oA),scopes:f(o().trim().min(1).max(200)).max(100).default([]),capabilities:f(o().trim().min(1).max(200)).max(100).default([])}).strict(),uA=l({models:f(o().trim().min(1).max(200)).max(100).default([]),scopes:f(o().trim().min(1).max(200)).max(100).default([])}).strict(),mA=l({opchat:uA.optional()}).catchall(fe(o(),ye())).default({}),pA=l({name:o().trim().regex(/^[A-Za-z_][A-Za-z0-9_-]*$/).max(63).optional(),mountPath:o().trim().min(1).max(256).optional(),storageGb:c().int().positive().max(100).optional(),deleteOnSandboxDelete:C().optional()}).strict(),fA=l({port:c().int().min(xp).max(kp).refine(e=>!_p.has(e),{message:"preview port is reserved"}),protocol:k("http").default("http"),label:o().trim().min(1).max(80).optional(),access:b(["private","public"]).default("private"),path:o().trim().min(1).max(512).refine(e=>e.startsWith("/"),{message:"preview path must start with /"}).default("/")}).strict(),f0=l({command:o().trim().min(1).max(1e3),cwd:As.optional(),timeoutSeconds:c().int().positive().max(86400).optional(),requiresStart:C().default(!1),ports:f(fA).max(20).default([]),artifactPaths:f(As).max(100).default([])}).strict(),qh=f0.extend({name:o().trim().min(1).max(80)}).strict(),hA=l({name:o().trim().min(1).max(80).optional(),service:o().trim().min(1).max(80).optional(),port:c().int().min(xp).max(kp).refine(e=>!_p.has(e),{message:"app MCP port is reserved"}),path:o().trim().min(1).max(512).refine(e=>e.startsWith("/"),{message:"app MCP path must start with /"}).default("/mcp")}).strict(),gA=l({name:o().trim().min(1).max(80).optional(),port:c().int().min(xp).max(kp).refine(e=>!_p.has(e),{message:"validation probe port is reserved"}),path:o().trim().min(1).max(512).refine(e=>e.startsWith("/"),{message:"validation probe path must start with /"}).default("/"),expectedStatus:c().int().min(100).max(599).default(200)}).strict(),bA=fe(o(),ye()).refine(e=>e.type==="object","input schema must be a JSON schema object"),vA=l({name:o().trim().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).max(191),required:C().default(!1),secret:C().default(!0),description:o().trim().max(500).optional()}).strict(),Au=o().trim().min(1).max(120),yA=l({name:o().trim().min(1).max(120),description:o().trim().max(500).optional(),cron:o().trim().min(1).max(500).optional(),rate:o().trim().min(1).max(500).optional(),once:Au.optional(),scheduleType:b(["rate","cron","once"]).optional(),scheduleExpression:o().trim().min(1).max(500).optional(),timezone:o().trim().min(1).max(100).optional(),enabled:C().default(!0),startAt:Au.optional(),endAt:Au.optional(),maxRuns:c().int().positive().nullable().optional(),runtimePolicy:b(["run_and_stop","run_and_archive","run_and_delete","use_existing_running"]).default("run_and_stop"),action:o().trim().min(1).max(120).optional(),actionName:o().trim().min(1).max(120).optional(),command:o().trim().min(1).max(2e3).optional(),target:l({kind:b(["start","action","service","command"]).optional(),name:o().trim().min(1).max(120).optional(),actionName:o().trim().min(1).max(120).optional(),command:o().trim().min(1).max(2e3).optional(),requiresStart:C().optional()}).strict().optional(),requiresStart:C().optional(),budget:l({maxUsd:o().trim().min(1).max(40).optional()}).strict().optional(),resources:p0.optional(),quotas:fe(o(),ye()).optional(),lifecycle:fe(o(),ye()).optional(),retentionPolicy:fe(o(),ye()).optional(),env:f(l({name:o().trim().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).max(191),value:o().optional(),secretRef:o().optional()}).strict()).max(100).optional(),integrationLeases:f(fe(o(),ye())).max(20).optional(),metadata:fe(o(),ye()).optional()}).strict().superRefine((e,t)=>{[e.cron,e.rate,e.once,e.scheduleExpression].filter(d=>typeof d=="string"&&d.trim()).length!==1&&t.addIssue({code:$n.custom,path:["scheduleExpression"],message:"schedule must declare exactly one of cron, rate, once, or scheduleExpression"}),e.scheduleExpression&&!e.scheduleType&&t.addIssue({code:$n.custom,path:["scheduleType"],message:"scheduleType is required with scheduleExpression"});const a=e.command??e.target?.command??null,i=e.target?.name??null,r=e.actionName??e.action??e.target?.actionName??(e.target?.kind==="action"?i:null),s=e.target?.kind??(a?"command":"action");s==="action"&&!r&&t.addIssue({code:$n.custom,path:["action"],message:"schedule action target is required"}),s==="service"&&!i&&t.addIssue({code:$n.custom,path:["target","name"],message:"schedule service target name is required"}),s==="command"&&!a&&t.addIssue({code:$n.custom,path:["command"],message:"schedule command target is required"})}),SA=l({schemaVersion:k(1),name:o().trim().min(1).max(80).regex(/^[a-z0-9][a-z0-9-]*[a-z0-9]$/),version:o().trim().min(1).max(40),useCase:o().trim().min(1).max(80),description:o().trim().min(1).max(500),runtime:cA,resources:p0.optional(),setup:l({commands:Hh.default([])}).strict().default({commands:[]}),validation:l({commands:Hh.min(1),probes:f(gA).max(20).default([])}).strict(),start:f0,actions:f(qh).max(20).default([]),services:f(qh).max(20).default([]),schedules:f(yA).max(20).default([]),mcp:l({endpoints:f(hA).max(10).default([])}).strict().default({endpoints:[]}),volumes:f(pA).max(5).default([]),integrations:l({requiredLeases:f(dA).max(20).default([])}).strict().default({requiredLeases:[]}),permissions:mA,inputs:l({schema:bA.default({type:"object"}),env:f(vA).max(100).default([])}).strict().default({schema:{type:"object"},env:[]}),artifacts:l({paths:f(As).max(100).default([])}).strict().default({paths:[]}),network:l({egress:b(["restricted","allow","block"]).default("restricted")}).strict().default({egress:"restricted"})}).strict().superRefine((e,t)=>{kA(e,t),wp(t,e.volumes.flatMap(n=>n.name?[n.name]:[]),"volume names must be unique","volumes"),_A(e,t),wA(e,t),IA(e,t),CA(e,t)}),xA=l({path:o(),message:o(),code:o()});function J9(e){return[{kind:"start",name:"start",...e.start,artifactPaths:Tu(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:Tu(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:Tu(t,e)}))]}function h0(e){return!e.includes("\0")&&!e.startsWith("/")&&!e.split(/[\\/]+/).some(t=>t===".."||t==="")}function wp(e,t,n,a){const i=new Set;for(const r of t){if(i.has(r)){e.addIssue({code:$n.custom,path:[a],message:n});return}i.add(r)}}function kA(e,t){const n=["start",...e.actions.map(a=>a.name),...e.services.map(a=>a.name)];wp(t,n,"start, action, and service names must be unique","actions")}function _A(e,t){const n=Pu(e.inputs.schema.properties),a=new Set(e.volumes.map(i=>i.name).filter(i=>!!i));for(const[i,r]of Object.entries(n)){const s=Pu(r),d=Pu(s["x-openpond-upload"]??s.xOpenPondUpload),p=typeof d.targetPath=="string"&&d.targetPath.trim()?d.targetPath.trim():typeof d.path=="string"&&d.path.trim()?d.path.trim():"";if(!p)continue;const m=p.replace(/^workspace\//,"").replace(/^\/+/,"").replace(/\/+$/,"");if(!h0(m)){t.addIssue({code:$n.custom,path:["inputs","schema","properties",i,"x-openpond-upload","targetPath"],message:"upload target must be a relative workspace path"});continue}const h=m.split("/");h[0]==="volumes"&&(!h[1]||!a.has(h[1]))&&t.addIssue({code:$n.custom,path:["inputs","schema","properties",i,"x-openpond-upload","targetPath"],message:"upload target references an undeclared volume"})}}function wA(e,t){wp(t,e.inputs.env.map(n=>n.name),"env input names must be unique","inputs")}function IA(e,t){const n=new Map(e.services.map(i=>[i.name,new Set(i.ports.map(r=>r.port))])),a=new Set([...e.start.ports.map(i=>i.port),...e.services.flatMap(i=>i.ports.map(r=>r.port))]);for(const[i,r]of e.mcp.endpoints.entries()){if(r.service){const s=n.get(r.service);if(!s){t.addIssue({code:$n.custom,path:["mcp","endpoints",i,"service"],message:`app MCP service does not exist: ${r.service}`});continue}s.has(r.port)||t.addIssue({code:$n.custom,path:["mcp","endpoints",i,"port"],message:`app MCP port ${r.port} is not declared on service ${r.service}`});continue}a.has(r.port)||t.addIssue({code:$n.custom,path:["mcp","endpoints",i,"port"],message:`app MCP port ${r.port} is not declared on start or services`})}}function CA(e,t){const n=new Set(e.actions.map(i=>i.name)),a=new Set(e.services.map(i=>i.name));for(const[i,r]of e.schedules.entries()){const s=r.command??r.target?.command??null;if(r.target?.kind==="command"||s)continue;const d=r.actionName??r.action??r.target?.actionName??(r.target?.kind==="action"?r.target?.name:null);if(d&&!n.has(d)&&t.addIssue({code:$n.custom,path:["schedules",i,"action"],message:`schedule action target does not exist: ${d}`}),r.target?.kind==="service"){const p=r.target.name??"";p&&!a.has(p)&&t.addIssue({code:$n.custom,path:["schedules",i,"target","name"],message:`schedule service target does not exist: ${p}`})}}}function Pu(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Tu(e,t){return e.artifactPaths.length>0?e.artifactPaths:t.artifacts.paths}const RA=l({id:o(),name:o(),description:o().nullable(),scheduleType:o(),scheduleExpression:o(),enabled:C(),rawEnabled:C().optional(),syncStatus:o().nullable(),syncError:o().nullable().optional(),startAt:o().nullable(),endAt:o().nullable(),maxRuns:c().nullable(),executionCount:c().nullable(),lifecycleStatus:o().nullable(),lifecycleReason:o().nullable(),lastExecutionAt:o().nullable().optional(),lastExecutionStatus:o().nullable().optional(),lastRunNowAt:o().nullable().optional(),lastRunNowStatus:o().nullable().optional(),updatedAt:o(),deploymentId:o(),isProduction:C().optional(),payload:ye().optional()}).passthrough(),AA=l({total:c().int().nonnegative(),active:c().int().nonnegative(),paused:c().int().nonnegative(),enabled:c().int().nonnegative().optional(),disabled:c().int().nonnegative().optional(),nextRunAt:o().nullable().optional(),lastRunAt:o().nullable().optional(),schedules:f(RA).optional().default([]),truncated:C().optional()}).passthrough(),Eu=l({name:o(),kind:b(["start","action","service"]),command:o(),cwd:o().nullable(),timeoutSeconds:c().nullable(),requiresStart:C(),ports:f(l({port:c(),protocol:o(),label:o().nullable(),access:o(),path:o()}).passthrough()).default([]),artifactPaths:f(o()).default([])}).passthrough(),PA=l({schemaVersion:k(1),source:k("openpond.yaml"),manifestName:o(),manifestVersion:o(),manifestUseCase:o(),manifestDescription:o(),manifestPath:o(),manifestHash:o(),inputSchema:fe(o(),ye()).default({}),env:f(l({name:o(),required:C(),secret:C(),description:o().nullable()}).passthrough()).default([]),start:Eu,actions:f(Eu).default([]),services:f(Eu).default([]),defaultActionName:o().nullable(),updatedAt:o()}).passthrough(),TA=l({id:o(),name:o(),description:o().nullable(),visibility:o().nullable().optional(),gitOwner:o().nullable().optional(),gitRepo:o().nullable().optional(),gitHost:o().nullable().optional(),defaultBranch:o().nullable().optional(),sandbox:C().optional().default(!1),sandboxActionRegistry:PA.nullable().optional(),sandboxManifestHash:o().nullable().optional(),sandboxManifestPath:o().nullable().optional(),sandboxManifestSyncedAt:o().nullable().optional(),sandboxManifestError:o().nullable().optional(),updatedAt:o().nullable().optional(),latestDeployment:l({id:o().optional(),status:o().optional(),deploymentDomain:o().nullable().optional(),createdAt:o().optional(),isProduction:C().nullable().optional(),gitBranch:o().nullable().optional()}).nullable().optional(),scheduleSummary:AA.nullable().optional()}),EA=l({detected:C(),rootPath:o(),manifestPath:o(),manifestHash:o().nullable().optional().default(null),manifest:fe(o(),ye()).nullable().optional().default(null),normalizedManifest:SA.nullable().optional().default(null),valid:C().optional().default(!1),diagnostics:f(xA).optional().default([])}),MA=l({appId:o(),appName:o(),gitOwner:o().nullable(),gitRepo:o().nullable(),gitHost:o().nullable(),defaultBranch:o().nullable(),linkedAt:o()}),g0=l({teamId:o(),projectId:o(),projectSlug:o().nullable().optional().default(null),projectName:o().nullable().optional().default(null),sourceRepoUrl:o().nullable().optional().default(null),defaultBranch:o().nullable().optional().default(null),lastUploadedCommit:o().nullable().optional().default(null),lastUploadTransport:b(["git_head","snapshot","api_source_upload"]).nullable().optional().default(null),manifestPath:o().nullable().optional().default(null),manifestHash:o().nullable().optional().default(null),syncedAt:o().nullable().optional().default(null),linkedAt:o()}),jA=b(["github_repo","internal_repo","template","manual"]),OA=l({id:o(),teamId:o(),name:o(),slug:o().nullable().optional().default(null),sourceType:jA.optional().default("manual"),sourceLabel:o().nullable().optional().default(null),defaultBranch:o().nullable().optional().default(null),internalRepoPath:o().nullable().optional().default(null),manifestPath:o().nullable().optional().default(null),manifestHash:o().nullable().optional().default(null),syncedAt:o().nullable().optional().default(null),organizationName:o().nullable().optional().default(null),organizationSlug:o().nullable().optional().default(null),createdAt:o().nullable().optional().default(null),updatedAt:o().nullable().optional().default(null)}),NA=l({id:o(),name:o(),path:o(),workspacePath:o(),repoPath:o().nullable(),source:b(["folder","git"]),hiddenFromDefaultSidebar:C().optional(),sandboxTemplate:EA.nullable().optional().default(null),linkedOpenPondApp:MA.nullable().optional().default(null),linkedSandboxProject:g0.nullable().optional().default(null),preferredSandboxAgentId:o().nullable().optional().default(null),createdAt:o(),updatedAt:o()});l({path:o().trim().min(1).optional(),name:o().trim().min(1).max(120).optional(),createNew:C().optional(),baseDirectory:o().trim().min(1).max(4096).optional()}).superRefine((e,t)=>{if(e.createNew){e.name?.trim()||t.addIssue({code:"custom",path:["name"],message:"Project name is required when creating a new project."});return}e.path?.trim()||t.addIssue({code:"custom",path:["path"],message:"Project path is required."})});l({linkedSandboxProject:g0.nullable().optional(),preferredSandboxAgentId:o().nullable().optional(),hiddenFromDefaultSidebar:C().optional()});const $A=["connected_app_search","connected_app_read","connected_app_write"],Mu="https://openpond.ai",Ip=["slack","google","github","turnkey","x","microsoft_teams","mcp"],Cp={slack:[Ut("slack.channel.bind","Bind channels","Bind Slack channels or threads to OpenPond profiles.","setup",!1),Ut("slack.message.ingest","Ingest messages","Ingest Slack channel or thread activity into OpenPond context.","setup",!1)],microsoft_teams:[Ut("microsoft_teams.channel.bind","Bind channels","Bind Teams channels or chats to OpenPond profiles.","setup",!1),Ut("microsoft_teams.message.ingest","Ingest messages","Ingest Teams channel or chat activity into OpenPond context.","setup",!1)],google:[Ut("google.drive.file.read","Read Drive files","Find and read Google Drive files.","read",!0),Ut("google.drive.file.write","Write Drive files","Create or update approved Google Drive files.","write",!0),Ut("google.docs.read","Read Docs","Read Google Docs content and structure.","read",!0),Ut("google.docs.write","Edit Docs","Apply approved Google Docs edits.","write",!0),Ut("google.comments.read","Read comments","Read Google file comments.","read",!0),Ut("google.comments.write","Write comments","Create or resolve approved Google comments.","write",!0)],github:[Ut("github.repo.read","Read repositories","Read repository metadata and file context.","read",!0),Ut("github.issue.read","Read issues","Read GitHub issues and comments.","read",!0),Ut("github.issue.write","Update issues","Create or update approved GitHub issue content.","write",!0),Ut("github.pull_request.read","Read pull requests","Read pull request metadata, diffs, checks, and reviews.","read",!0),Ut("github.pull_request.write","Update pull requests","Create approved comments or pull request updates.","write",!0)],turnkey:[Ut("turnkey.wallets.read","Read Agent Wallet","Read the connected OpenPond Agent Wallet address and metadata.","read",!0),Ut("turnkey.balances.read","Read wallet balances","Read balances for the connected OpenPond Agent Wallet.","read",!0),Ut("turnkey.activities.read","Read wallet activity","Read recent Turnkey activity for the connected OpenPond Agent Wallet.","read",!0)],x:[Ut("x.profile.read","Read profile","Read the connected X profile.","read",!0),Ut("x.search.read","Search X","Search public X posts when granted.","read",!0),Ut("x.mentions.read","Read mentions","Read mentions for the connected X account.","read",!0),Ut("x.post.write","Post","Create approved X posts.","write",!0),Ut("x.reply.write","Reply","Create approved X replies.","write",!0)],mcp:[Ut("mcp.tool.discover","Discover tools","Discover team-scoped MCP tools.","tooling",!1),Ut("mcp.tool.call","Call tools","Call approved MCP tools through the team endpoint.","tooling",!1)]},Rp={slack:[],microsoft_teams:[],google:[Mt("google.drive.search","search","Search Drive","Search Google Drive files by grounded query.",["google.drive.file.read"]),Mt("google.drive.read_file","read","Read Drive file","Read Drive file metadata or exported content by stable ref.",["google.drive.file.read"],{requiredKeys:["ref"]}),Mt("google.docs.read","read","Read Google Doc","Read Google Docs content and structure by stable ref.",["google.docs.read"],{requiredKeys:["ref"]}),Mt("google.comments.read","read","Read comments","Read comments for a grounded Google file ref.",["google.comments.read"],{requiredKeys:["ref"]}),Mt("google.docs.update","write","Update Google Doc","Apply an explicitly approved Google Docs edit and return readback verification.",["google.docs.write"],{requiredKeys:["ref","patch"]}),Mt("google.comments.create","write","Create comment","Create an explicitly approved Google file comment and return readback verification.",["google.comments.write"],{requiredKeys:["ref","body"]}),Mt("google.comments.resolve","write","Resolve comment","Resolve an explicitly approved Google comment and return readback verification.",["google.comments.write"],{requiredKeys:["ref","commentId"]})],github:[Mt("github.repo.search","search","Search repositories","Search accessible repositories by owner, name, or topic.",["github.repo.read"]),Mt("github.issue.search","search","Search issues","Search accessible GitHub issues.",["github.issue.read"]),Mt("github.pull_request.search","search","Search pull requests","Search accessible GitHub pull requests.",["github.pull_request.read"]),Mt("github.repo.read","read","Read repository","Read grounded repository metadata or file context.",["github.repo.read"],{requiredKeys:["ref"]}),Mt("github.issue.read","read","Read issue","Read a grounded GitHub issue and comments.",["github.issue.read"],{requiredKeys:["ref"]}),Mt("github.pull_request.read","read","Read pull request","Read a grounded pull request, checks, reviews, or diff summary.",["github.pull_request.read"],{requiredKeys:["ref"]}),Mt("github.issue.create","write","Create issue","Create an explicitly approved GitHub issue and return readback verification.",["github.issue.write"],{requiredKeys:["repo","title","body"]}),Mt("github.issue.comment","write","Comment on issue","Create an explicitly approved GitHub issue comment and return readback verification.",["github.issue.write"],{requiredKeys:["ref","body"]}),Mt("github.issue.update","write","Update issue","Apply an explicitly approved issue metadata/content update and return readback verification.",["github.issue.write"],{requiredKeys:["ref"]}),Mt("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"]}),Mt("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:[Mt("turnkey.wallets.read","read","Read Agent Wallet","Read the address and metadata for the connected OpenPond Agent Wallet.",["turnkey.wallets.read"]),Mt("turnkey.balances.read","read","Read wallet balances","Read supported-network balances for the connected OpenPond Agent Wallet.",["turnkey.balances.read"]),Mt("turnkey.activities.read","read","Read wallet activity","Read recent Turnkey activity for the connected OpenPond Agent Wallet.",["turnkey.activities.read"])],x:[Mt("x.profile.read","read","Read profile","Read the connected X account profile.",["x.profile.read"]),Mt("x.post.read","read","Read post","Read a public X post by stable ref, status URL, or post id.",["x.search.read"],{requiredKeys:["ref"]}),Mt("x.search.posts","search","Search recent posts","Search public X posts from the X recent-search window by grounded query.",["x.search.read"]),Mt("x.mentions.search","search","Search mentions","Search mentions for the connected X account.",["x.mentions.read"]),Mt("x.mention.read","read","Read mention","Read a grounded mention or post ref.",["x.mentions.read"],{requiredKeys:["ref"]}),Mt("x.post.create","write","Create post","Create an explicitly approved X post and return readback verification.",["x.post.write"],{requiredKeys:["text"]}),Mt("x.reply.create","write","Create reply","Create an explicitly approved X reply and return readback verification.",["x.reply.write"],{requiredKeys:["inReplyToRef","text"]})],mcp:[]},DA={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
- `)},Y9=Ip.map(e=>{const t=v0(e),n=DA[e];return{...t,provider:e,body:n,sourceHash:`connected-app-skill:${e}:${aP(n)}`,charCount:n.length}});function LA(e){const t=Ap(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=XA(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",i=new Set(t.capabilities.filter(d=>d.access===a&&d.leaseable).map(d=>d.id)),r=e.capabilityIds.filter(d=>!i.has(d));if(r.length>0)return{ok:!1,error:`Connected app capability ${r[0]} is not allowed for ${e.provider} ${e.operation}.`};const s=UA(e);return s.ok?{ok:!0,request:e}:s}function zA(e){const t=kc(e);return t?Rp[t]:[]}function UA(e){const t=FA(e.args),n=zA(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 i=e.capabilityIds.filter(s=>!a.capabilityIds.includes(s));if(i.length>0)return{ok:!1,error:`Connected app operation ${a.id} does not allow capability ${i[0]}.`};const r=WA(e.args,e.operation);for(const s of a.input?.requiredKeys??[]){const d=r[s];if(d==null||typeof d=="string"&&!d.trim())return{ok:!1,error:`Connected app operation ${a.id} requires input.${s}.`}}return{ok:!0,request:e}}const HA=[{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"}],xc=HA,qA=Ip.map(e=>{const t=xc.filter(a=>a.providerFamily===e),n=t[0];return{id:e,label:ks(e),shortLabel:n.shortLabel,category:n.category,icon:n.icon,description:n.description,setupSurfaces:t,capabilities:Cp[e],skills:JA(e),tools:YA(e),operations:Rp[e],leasePolicy:QA(e)}});function b0(e){const t=BA(e);return t?xc.find(n=>n.id===t)??null:null}function Ap(e){const t=kc(e);return t?qA.find(n=>n.id===t)??null:null}function X9(e){const t=b0(e.appId),n=GA(e.baseUrl),a=t?.kind==="mcp"?"/sandboxes/mcp":"/sandboxes/apps",i=new URL(a,n);t?.kind!=="mcp"&&i.searchParams.set("app",t?.deepLinkAppId??e.appId);const r=e.teamId?.trim();return r&&i.searchParams.set("teamId",r),i.toString()}function BA(e){const t=e?.trim().toLowerCase().replace(/[-\s]+/g,"_");return t?t==="teams"||t==="microsoft"?"microsoft_teams":xc.some(n=>n.id===t)?t:null:null}function kc(e){const t=e?.trim().toLowerCase().replace(/[-\s]+/g,"_");return t?t==="teams"||t==="microsoft"?"microsoft_teams":Ip.includes(t)?t:b0(t)?.providerFamily??null:null}function ju(e={}){const t=eP(e.connections??[]);return xc.map(n=>{const a=Ap(n.providerFamily),i=n.statusSource==="integration_connection"?t.filter(d=>d.provider===n.providerFamily):[],r=i.some(d=>d.status==="active"),s=tP(n,r);return{...n,providerLabel:a.label,setupSurfaceLabel:ZA(n.setupSurface),status:s,statusLabel:nP(n,s,i),connections:i,connected:r,capabilities:Bh(n,a.capabilities),capabilityLabels:Bh(n,a.capabilities).map(d=>d.label),leasePolicy:a.leasePolicy}})}function Ut(e,t,n,a,i){return{id:e,label:t,description:n,access:a,leaseable:i}}function Mt(e,t,n,a,i,r){return{id:e,operation:t,label:n,description:a,capabilityIds:i,...r?{input:r}:{},requiresReadback:t==="write",requiresRuntimeLease:!1}}function FA(e){return VA(e.operation)}function VA(e){return typeof e=="string"&&e.trim()?e.trim():null}function WA(e,t){return t==="write"?KA(e.input)?e.input:{}:e}function KA(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function GA(e){const t=e?.trim();if(!t)return Mu;try{const n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?Mu:(n.pathname="/",n.search="",n.hash="",n.toString())}catch{return Mu}}function ks(e){return e==="microsoft_teams"?"Microsoft Teams":e==="mcp"?"OpenPond MCP":e==="x"?"X":e[0].toUpperCase()+e.slice(1)}function ZA(e){return e==="native_bot"?"Native app":e==="oauth_connector"?"OAuth connector":e==="wallet_connector"?"Wallet connector":"MCP endpoint"}function JA(e){return[v0(e)]}function v0(e){return{name:`${e}-connected-app`,description:`Use ${ks(e)} safely through connected app tools.`,path:`integration_skills/${e}.md`}}function YA(e){if(e==="mcp")return[];const t=Cp[e],n=Rp[e],a=t.filter(s=>s.access==="read").map(s=>s.id),i=t.filter(s=>s.access==="write").map(s=>s.id),r=[];return n.some(s=>s.operation==="search")&&r.push({name:"connected_app_search",description:`Search ${ks(e)} through a server-owned connected app connector.`,capabilityIds:a,write:!1}),n.some(s=>s.operation==="read")&&r.push({name:"connected_app_read",description:`Read a grounded ${ks(e)} object through a server-owned connected app connector.`,capabilityIds:a,write:!1}),i.length>0&&n.some(s=>s.operation==="write")&&r.push({name:"connected_app_write",description:`Perform an explicitly approved ${ks(e)} write through a server-owned connected app connector.`,capabilityIds:i,write:!0}),r}function XA(e){return e==="search"?"connected_app_search":e==="read"?"connected_app_read":"connected_app_write"}function QA(e){const t=Cp[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 Bh(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 eP(e){return e.flatMap(t=>{const n=kc(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 tP(e,t){return e.statusSource==="integration_connection"?t?"connected":"disconnected":"setup_available"}function nP(e,t,n){if(t==="connected"){const a=n.filter(i=>i.status==="active").length;return a>1?`${a} connected`:"Connected"}return t==="disconnected"?"Not connected":e.statusSource==="native_binding"?"Bot setup":"Configure"}function aP(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 oP=b(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),iP=b(["search","read","write"]),rP=b($A);l({provider:oP,operation:iP,toolName:rP,sessionId:o().trim().min(1).max(200),turnId:o().trim().min(1).max(200),toolCallId:o().trim().min(1).max(300),userPrompt:o().max(2e5),connectionIds:f(o().trim().min(1).max(300)).min(1).max(8),capabilityIds:f(o().trim().min(1).max(200)).min(1).max(64),args:fe(o(),ye()).default({})}).strict().superRefine((e,t)=>{const n=LA(e);n.ok||t.addIssue({code:$n.custom,message:n.error})});l({ok:C(),output:o().nullable().optional(),data:ye().optional()}).strict();const sP="local_path:";function y0(e){return`${sP}${e.trim()}`}l({appId:o(),source:b(["openpond","github","local_git","local_folder","unknown"]),workspacePath:o(),repoPath:o(),initialized:C(),remoteUrl:o().nullable(),expectedRemoteUrl:o().nullable(),currentBranch:o().nullable(),headCommit:o().nullable().optional().default(null),upstreamBranch:o().nullable().optional().default(null),ahead:c().int().nonnegative().optional().default(0),behind:c().int().nonnegative().optional().default(0),diverged:C().optional().default(!1),linkedSourceHeadCommit:o().nullable().optional().default(null),aheadOfLinkedSource:c().int().nonnegative().optional().default(0),behindLinkedSource:c().int().nonnegative().optional().default(0),divergedFromLinkedSource:C().optional().default(!1),linkedSourceComparisonError:o().nullable().optional().default(null),lastFetchAt:o().nullable().optional().default(null),defaultBranch:o().nullable(),branches:f(o()),dirty:C(),changedFilesCount:c(),untrackedFilesCount:c(),error:o().nullable(),updatedAt:o()});const lP=l({path:o(),status:o(),additions:c(),deletions:c(),patch:o(),content:o().nullable().optional().default(null)}),cP=l({appId:o(),repoPath:o(),initialized:C(),dirty:C(),filesChanged:c(),additions:c(),deletions:c(),repoFiles:f(o()).optional().default([]),files:f(lP),error:o().nullable(),updatedAt:o()});l({branch:o().trim().min(1).max(160)});l({path:o().trim().min(1),content:o()});const Fh=l({line:c().int().nonnegative(),character:c().int().nonnegative()}),dP=l({start:Fh,end:Fh}),uP=l({path:o(),range:dP,severity:b(["error","warning","info","hint"]),message:o(),source:o().nullable().optional().default(null),code:o().nullable().optional().default(null)}),S0=l({id:o(),root:o(),status:b(["connected","unavailable","error"]),message:o().nullable().optional().default(null)});l({path:o().trim().min(1),content:o().optional(),waitForDiagnostics:C().optional().default(!0)});l({appId:o(),path:o(),diagnostics:f(uP),servers:f(S0),updatedAt:o()});const mP=l({operation:b(["hover","definition","references","documentSymbol"]),path:o().trim().min(1),content:o().optional(),line:c().int().nonnegative().optional(),character:c().int().nonnegative().optional()});l({appId:o(),operation:mP.shape.operation,path:o(),results:ye(),servers:f(S0),updatedAt:o()});const pP=l({pinned:C().optional(),archived:C().optional(),order:c().optional()}),fP=fe(o(),pP),x0=b(["local","sandbox"]),hP=b(["pinned","saved_for_later"]),k0=l({id:o().min(1),workspaceKind:x0,workspaceId:o().min(1),workspaceName:o().min(1),path:o().min(1),status:hP,order:c().int().nonnegative().nullable().default(null),sourceSessionId:o().min(1).nullable().default(null),available:C().default(!0),createdAt:o().min(1),updatedAt:o().min(1)});l({items:f(k0)});l({workspaceKind:x0,workspaceId:o().trim().min(1),workspaceName:o().trim().min(1),path:o().trim().min(1),status:b(["pinned","saved_for_later","none"]),order:c().int().nonnegative().nullable().optional(),sourceSessionId:o().trim().min(1).nullable().optional()});b(["pin","save_for_later","remove","list"]);function gP(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 Q9(e){return["sidebar-file",e.workspaceKind,encodeURIComponent(e.workspaceId),encodeURIComponent(gP(e.path))].join(":")}const bP=l({id:o(),name:o(),type:o(),status:o(),isActive:C().nullable(),price:o().nullable(),currency:o().nullable(),credits:o().nullable()}).passthrough(),vP=l({reachable:C(),authenticated:C().nullable(),apiBase:o(),latencyMs:c(),status:c().nullable(),service:o().nullable(),checkedAt:o(),error:o().nullable()}),yP=l({id:o().nullable(),email:o().nullable(),name:o().nullable(),handle:o().nullable(),image:o().nullable(),timezone:o().nullable(),isAdmin:C().nullable(),isVerified:C().nullable(),dailyAgentAppId:o().nullable(),dailyAgentDeploymentId:o().nullable(),credits:o().nullable()}),SP=l({handle:o(),baseUrl:o().nullable().optional()}),xP=l({state:b(["signed_out","signed_in","loading","switching","auth_error"]),activeProfile:SP.nullable(),label:o(),email:o().nullable(),avatarUrl:o().nullable(),environment:o().nullable(),baseUrl:o().nullable(),apiBaseUrl:o().nullable(),chatApiBaseUrl:o().nullable().optional().default(null),creditsLabel:o().nullable(),profile:yP.nullable(),products:f(bP),apiHealth:vP.nullable(),accounts:f(l({handle:o(),baseUrl:o().nullable(),apiBaseUrl:o().nullable().optional().default(null),chatApiBaseUrl:o().nullable().optional(),environment:o().nullable(),isActive:C(),authHealth:b(["signed_out","signed_in","auth_error","unknown"]),displayLabel:o().nullable(),email:o().nullable().optional().default(null),avatarUrl:o().nullable()})),error:o().nullable()}),Vh=l({asOf:o().nullable(),refreshing:C(),lastRefreshError:o().nullable(),source:b(["fresh","cache","empty"])}),kP=l({available:C(),binaryPath:o().nullable(),version:o().nullable(),authHealth:b(["unknown","signed_in","signed_out","auth_error"]),account:l({type:o(),email:o().nullable(),planType:o().nullable(),label:o().nullable()}).nullable().default(null),appServer:l({status:b(["idle","starting","ready","error"]),lastError:o().nullable()})}),Pp="gpt-5.6-sol",rr="openpond-chat",oi="openpond",Ps=rr,_c="default",wc="high",qs="ask",yr=li,Tp=b(["default","auto-review","full-access"]),Bs=b(["ask","full-access","disabled"]),Ic=b(["low","medium","high","xhigh"]),Fs=b(["sandbox_app","local_project","sandbox","sandbox_template"]);b(["openpond"]);const _P=b(["provider_usage","provider_tokenizer","model_family","heuristic"]),wP=l({provider:yr,model:o().min(1),usedTokens:c().int().nonnegative(),maxContextTokens:c().int().positive(),usableContextTokens:c().int().positive(),percentFull:c().min(0).max(100),source:_P,updatedAtEventId:o().nullable()}),Sm=l({pinned:C().default(!1),projects:C().default(!1),cloudProjects:C().default(!1),chats:C().default(!1),savedForLater:C().default(!0)}),IP=b(["auto","off"]),CP=b(["typescript","python","rust"]),_0=b(["auto","disabled","custom"]),to=l({mode:_0.default("auto"),customCommand:o().trim().max(4096).default("")}),ec=l({languageServers:IP.default("auto"),diagnosticsWhileEditing:C().default(!0),checkOnSave:C().default(!0),languages:l({typescript:to.optional().default(()=>to.parse({})),python:to.optional().default(()=>to.parse({})),rust:to.optional().default(()=>to.parse({}))}).optional().default(()=>({typescript:to.parse({}),python:to.parse({}),rust:to.parse({})}))}),RP=l({language:CP,label:o(),mode:_0,status:b(["found","missing","disabled","error"]),command:o().nullable(),message:o().nullable()});l({settings:ec,languages:f(RP),updatedAt:o()});const AP=l({id:o(),root:o(),status:b(["starting","connected","unavailable","error"]),message:o().nullable().optional().default(null),openedDocuments:c().int().nonnegative(),pendingRequests:c().int().nonnegative(),lastUsedAt:o(),stderrTail:o()});l({clients:f(AP),maxClients:c().int().positive(),idleTimeoutMs:c().int().positive(),updatedAt:o()});const xm=l({autoEnabled:C().default(!0),triggerPercent:c().int().min(50).max(95).default(85),summaryModel:b(["same_model"]).default("same_model")}),km=l({defaultModelRef:Jt.nullable().default(null),creationMode:b(["defaults","customize"]).default("customize"),autoApproveEvidence:C().default(!1)}),Wh=l({defaultChatProvider:yr.default(oi),defaultChatModel:o().min(1).default(Ps),defaultChatModelRef:Jt.nullable().optional(),subagents:Rs.optional().default(()=>Rs.parse({})),codexPermissionMode:Tp.default(_c),codexReasoningEffort:Ic.default(wc),openPondCommandAccessMode:Bs.default(qs),defaultBranchPrefix:o().trim().max(48).default("feat/"),defaultNewProjectDirectory:o().trim().max(4096).default(""),defaultTeamId:o().trim().max(191).nullable().default(null),advancedWorkspaceControls:C().default(!1),steerActiveResponses:C().default(!0),contextCompaction:xm.optional().default(()=>xm.parse({})),training:km.optional().default(()=>km.parse({})),sidebarWidth:c().int().min(244).max(560).default(332),diffPanelWidth:c().int().min(320).max(2400).default(560),sidebarSectionsCollapsed:Sm.optional().default(()=>Sm.parse({})),editor:ec.optional().default(()=>ec.parse({}))}),PP="default",w0=[{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.`}],Ep=o().trim().min(1).max(120),TP=l({id:Ep,name:o(),source:b(["built_in","custom"]).default("custom"),description:o(),content:o()}),Kh=l({activeTemplateId:Ep.default(PP),customized:C().default(!1),soul:o(),soulPath:o().nullable(),updatedAt:o().nullable(),templates:f(TP).default(()=>[...w0])}),EP=l({id:o(),host:o(),port:c(),startedAt:o(),storePath:o(),version:o(),runtimeVersion:o()}),Mp=b(["chat","work","development"]);b(["chat","models","development"]);const MP="work",Je=o().trim().min(1).nullable(),fa=fe(o(),ye()).default({}),jP=b(["direct_prompt_create","context_backed_create","create_as_agent","workflow_suggestion","local_extend","hosted_create","local_import","direct_prompt_improve","context_backed_improve","hosted_improve","lab_create","lab_improve","training"]),I0=b(["/create","/edit","openpond extend","create_as_agent","suggest_workflow","local_import","lab_create","lab_improve","training"]),OP=b(["create","improve","import","promote"]),NP=b(["planning","awaiting_questions","awaiting_plan_approval","paused","applying_source","running_checks","evaluating","awaiting_promotion","opening_pull_request","pull_request_open","reconciling_release","released","rejected","ready","ready_local","pushing_hosted","running_hosted_checks","published_hosted","blocked","failed","cancelled"]),Cl=b(["always_require_plan_approval","approval_already_granted"]);b(["local_profile","hosted_profile","promote_local_to_hosted","managed_artifact"]);const $P=Kt("kind",[l({kind:k("local"),sourceAuthority:k("local_profile"),activeProfile:o().trim().min(1).nullable(),repoPath:Je,sourcePath:Je,localHead:Je,confirmationPolicy:Cl.default("always_require_plan_approval")}),l({kind:k("hosted"),sourceAuthority:k("hosted_profile"),teamId:Je,projectId:Je,activeProfile:o().trim().min(1).nullable(),sourceRef:Je,baseSha:Je,confirmationPolicy:Cl.default("always_require_plan_approval")}),l({kind:k("promote_local_to_hosted"),sourceAuthority:k("promote_local_to_hosted"),teamId:Je,projectId:Je,activeProfile:o().trim().min(1).nullable(),repoPath:Je,sourcePath:Je,localHead:Je,hostedHead:Je,sourceRef:Je,confirmationPolicy:Cl.default("always_require_plan_approval")}),l({kind:k("managed_artifact"),sourceAuthority:k("managed_artifact"),activeProfile:o().trim().min(1).nullable(),confirmationPolicy:Cl.default("always_require_plan_approval")})]),DP=l({id:Je,kind:b(["user","system","automation"]).default("user"),label:Je}),LP=l({profileId:o().trim().min(1),conversationId:Je,originTurnId:Je,projectId:Je,targetProject:l({id:Je,name:Je,workspacePath:Je,sourceRef:Je,baseSha:Je}).nullable()}),ys=l({messageIds:f(o().trim().min(1)).default([]),conversationExcerpts:f(l({messageId:Je,role:o().trim().min(1).nullable(),excerpt:o().trim().min(1),reason:o().trim().min(1).nullable()})).default([]),attachments:f(l({id:Je,name:o().trim().min(1),mediaType:Je,ref:Je})).default([]),apps:f(l({id:o().trim().min(1),name:o().trim().min(1),connectionId:Je,required:C().default(!1)})).default([]),tools:f(l({name:o().trim().min(1),inputSummary:Je,outputSummary:Je,artifactRefs:f(o().trim().min(1)).default([]),sideEffects:f(o().trim().min(1)).default([])})).default([]),signalRefs:f(o().trim().min(1)).default([]),evalRefs:f(o().trim().min(1)).default([]),targetRepoAssumptions:f(o().trim().min(1)).default([])}),Li={id:Je,displayName:Je},jp=Kt("kind",[l({kind:k("unselected"),...Li}),l({kind:k("agent"),...Li,defaultActionKey:Je}),l({kind:k("skill"),...Li,skillName:Je}),l({kind:k("extension"),...Li,slot:Je}),l({kind:k("model"),...Li,trainingPlanId:Je,trainingJobId:Je,artifactId:Je}),l({kind:k("configuration"),...Li,key:Je})]),_m=b(["agent","skill","extension","model","configuration"]),zP=l({schemaVersion:k("openpond.createImprove.evidenceSnapshot.v1"),id:o().trim().min(1),contentHash:o().trim().min(8),consent:l({status:b(["granted","denied","revoked"]),scope:b(["metadata_only","selected_turns","full_session","direct_intent"]),reviewedBy:Je,reviewedAt:o().trim().min(1)}),sources:f(l({kind:b(["signal","conversation","direct_correction","manual_intent","artifact"]),id:o().trim().min(1),sourceHash:o().trim().min(8),excerptRef:Je})).min(1),reviewerIntent:o().trim().min(1),createdAt:o().trim().min(1),metadata:fa}),C0=l({schemaVersion:k("openpond.createImprove.tasksetRef.v1"),id:o().trim().min(1),revision:c().int().positive(),contentHash:o().trim().min(8),evidenceSnapshotIds:f(o().trim().min(1)).min(1),policyBoundary:l({policyVisibleFields:f(o().trim().min(1)).default([]),privilegedFields:f(o().trim().min(1)).default([]),hiddenGraderRefs:f(o().trim().min(1)).default([]),connectedAppScopes:f(o().trim().min(1)).default([])}),targetRecommendation:l({kind:_m,rationale:f(o().trim().min(1)).min(1),confidence:c().min(0).max(1)}),authoringSplitRefs:f(o().trim().min(1)).default([]),privateSplitRefs:f(o().trim().min(1)).default([]),approvedBy:Je,approvedAt:o().trim().min(1),metadata:fa}),UP=l({kind:b(["npm_package","runtime_tool","setup_command","secret","integration","volume","target_project","external_service"]),name:o().trim().min(1),status:b(["declared","required","blocked","satisfied"]).default("declared"),detail:Je,metadata:fa}),HP=l({mode:b(["chat","direct_action","chat_and_direct_actions"]),label:o().trim().min(1),detail:o().trim().min(1),defaultActionKey:Je,directActionHint:Je,artifactPolicy:o().trim().min(1)}),qP=l({schemaVersion:k("openpond.createImprove.plan.v1"),id:o().trim().min(1),runId:o().trim().min(1),status:b(["draft","pending_approval","approved","rejected","cancelled","superseded"]).default("pending_approval"),objective:o().trim().min(1),summary:o().trim().min(1),capturedContextSummary:o().trim().min(1),defaultChatAction:l({key:Je,label:Je,required:C().default(!0)}),sourcePlan:f(l({path:o().trim().min(1),operation:b(["create","update","delete","inspect"]),reason:o().trim().min(1)})).default([]),requirements:f(UP).default([]),checks:f(l({name:o().trim().min(1),command:o().trim().min(1),required:C().default(!0)})).default([]),approvalId:Je,approvedAt:Je,editedFromPlanId:Je,metadata:fa,createdAt:o().trim().min(1),updatedAt:o().trim().min(1)}),BP=l({id:o().trim().min(1),label:o().trim().min(1),value:o().trim().min(1),description:Je,metadata:fa}),FP=l({value:o().trim().min(1),label:Je,detail:Je,answeredAt:o().trim().min(1),metadata:fa}),VP=l({id:o().trim().min(1),kind:b(["single_choice","free_text"]).default("single_choice"),title:o().trim().min(1),prompt:o().trim().min(1),required:C().default(!0),status:b(["pending","answered","skipped"]).default("pending"),options:f(BP).default([]),answer:FP.nullable().default(null),metadata:fa}),WP=l({schemaVersion:k("openpond.createImprove.workflowCapture.v1"),id:o().trim().min(1),runId:o().trim().min(1),command:I0,objective:o().trim().min(1),conversationExcerpts:ys.shape.conversationExcerpts,attachments:ys.shape.attachments,apps:ys.shape.apps,tools:ys.shape.tools,sideEffects:f(o().trim().min(1)).default([]),profileActions:f(o().trim().min(1)).default([]),externalProviders:f(o().trim().min(1)).default([]),environmentVariables:f(o().trim().min(1)).default([]),files:f(o().trim().min(1)).default([]),schedules:f(o().trim().min(1)).default([]),webhooks:f(o().trim().min(1)).default([]),channelTargets:f(o().trim().min(1)).default([]),outputArtifacts:f(o().trim().min(1)).default([]),targetRepoAssumptions:f(o().trim().min(1)).default([]),traceRefs:f(o().trim().min(1)).default([]),metadata:fa,createdAt:o().trim().min(1)}),R0=l({provider:k("github"),number:c().int().positive(),url:o().url(),state:b(["open","merged","closed"]),baseBranch:o().trim().min(1),headBranch:o().trim().min(1),mergeCommit:Je,openedAt:o().trim().min(1),updatedAt:o().trim().min(1)}),KP=l({baseBranch:o().trim().min(1),baseCommit:o().trim().min(1),branch:o().trim().min(1),headCommit:Je,remoteName:o().trim().min(1).default("origin"),remoteUrl:Je,worktreePath:Je,changedPaths:f(o().trim().min(1)).default([]),diffStat:Je,pullRequest:R0.nullable().default(null)}),GP=l({id:o().trim().min(1),target:jp,status:b(["draft","authored","checking","evaluated","accepted","rejected","failed"]),git:KP.nullable().default(null),parentCandidateId:Je.default(null),tasksetRef:C0.nullable().default(null),authoringModelRef:Je.default(null),allowedPaths:f(o().trim().min(1)).default([]),sourceRefs:f(o().trim().min(1)).default([]),artifactRefs:f(o().trim().min(1)).default([]),checkRefs:f(o().trim().min(1)).default([]),evaluationReceiptRefs:f(o().trim().min(1)).default([]),createdAt:o().trim().min(1),updatedAt:o().trim().min(1),metadata:fa}),ZP=l({id:o().trim().min(1),candidateId:Je,target:jp,evaluatorKind:b(["agent_sdk","taskset","extension","skill","configuration","checks"]).default("checks"),subject:b(["active","candidate","post_release","standalone"]).default("standalone"),sourceCommit:Je.default(null),sourceBranch:Je.default(null),tasksetId:Je.default(null),tasksetHash:Je.default(null),taskAttemptRefs:f(o().trim().min(1)).default([]),status:b(["pending","passed","failed","blocked"]),publishGate:b(["passed","failed","not_applicable"]).default("not_applicable"),summaryCounts:l({total:c().int().nonnegative(),passed:c().int().nonnegative(),failed:c().int().nonnegative()}).nullable().default(null),evalRefs:f(o().trim().min(1)).default([]),artifactRefs:f(o().trim().min(1)).default([]),summary:Je,createdAt:o().trim().min(1),metadata:fa}),JP=l({mode:b(["foreground","background"]).default("background"),pauseAllowed:C().default(!0),cancellationAllowed:C().default(!0)}),YP=l({mode:b(["single","bounded","until_evals_pass"]).default("single"),maximumAttempts:c().int().min(1).max(20).default(1),currentAttempt:c().int().min(0).max(20).default(0)}),XP=l({kind:b(["candidate_authoring","local_apply","hosted_turn","training_job","evaluation","pull_request","release"]),id:o().trim().min(1),status:Je,metadata:fa}),QP=l({status:b(["not_requested","pending","released","rejected","rolled_back"]),profileCommit:Je,profileTag:Je,releaseReceiptRef:Je,pullRequest:R0.nullable().default(null),updatedAt:Je}),Vs=l({schemaVersion:k("openpond.createImprove.run.v1"),id:o().trim().min(1),revision:c().int().nonnegative(),operation:OP,surface:jP,command:I0,objective:o().trim().min(1),state:NP,adapter:$P,actor:DP,scope:LP,context:ys,target:jp,evidenceSnapshots:f(zP).default([]),tasksetRef:C0.nullable().default(null),targetSelection:l({status:b(["open","recommended","confirmed"]),preselectedKind:_m.nullable(),confirmedKind:_m.nullable()}).nullable().default(null),plan:qP.nullable(),workflowCapture:WP.nullable(),executionPolicy:JP.default({mode:"background",pauseAllowed:!0,cancellationAllowed:!0}),iterationPolicy:YP.default({mode:"single",maximumAttempts:1,currentAttempt:0}),approvalIds:f(o().trim().min(1)).default([]),questionIds:f(o().trim().min(1)).default([]),questions:f(VP).default([]),candidates:f(GP).default([]),evaluationReceipts:f(ZP).default([]),checkRefs:f(o().trim().min(1)).default([]),sourceRefs:f(o().trim().min(1)).default([]),externalExecutionRefs:f(XP).default([]),localProfileCommit:Je,hostedSourceCommit:Je,hostedSourceRef:Je,releaseOutcome:QP.default({status:"not_requested",profileCommit:null,profileTag:null,releaseReceiptRef:null,pullRequest:null,updatedAt:null}),blockedReason:Je,appliedActionIds:f(o().trim().min(1)).max(200).default([]),metadata:fa,createdAt:o().trim().min(1),updatedAt:o().trim().min(1)}),Ua={runId:o().trim().min(1),expectedRevision:c().int().nonnegative(),actionId:o().trim().min(1)};Kt("type",[l({...Ua,type:k("answer_question"),questionId:o().trim().min(1),value:o().trim().min(1)}),l({...Ua,type:k("approve_plan")}),l({...Ua,type:k("revise_plan"),revision:o().trim().min(1)}),l({...Ua,type:k("cancel"),reason:Je.optional().default(null)}),l({...Ua,type:k("pause")}),l({...Ua,type:k("resume")}),l({...Ua,type:k("open_pull_request"),candidateId:o().trim().min(1)}),l({...Ua,type:k("apply_candidate"),candidateId:o().trim().min(1)}),l({...Ua,type:k("reject_candidate"),candidateId:o().trim().min(1),reason:Je.optional().default(null)}),l({...Ua,type:k("reconcile_pull_request"),candidateId:o().trim().min(1)})]);l({schemaVersion:k("openpond.createImprove.runList.v1"),runs:f(Vs),generatedAt:o().trim().min(1)});function eW(e){const t=HP.safeParse(e?.actionShape);return t.success?t.data:null}const ci=l({source:b(["local","github","openpond_git"]),repositoryId:o().trim().min(1),profileId:o().trim().min(1)}),eT=l({ref:ci,revision:o().nullable(),sourceHash:o()}),tT=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),nT=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 aT(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 i=t.byteLength*8,r=new DataView(a.buffer);r.setUint32(n-8,Math.floor(i/4294967296),!1),r.setUint32(n-4,i>>>0,!1);const s=new Uint32Array(tT),d=new Uint32Array(64);for(let p=0;p<n;p+=64){for(let O=0;O<16;O+=1)d[O]=r.getUint32(p+O*4,!1);for(let O=16;O<64;O+=1){const D=d[O-15],x=d[O-2],I=Ha(D,7)^Ha(D,18)^D>>>3,P=Ha(x,17)^Ha(x,19)^x>>>10;d[O]=d[O-16]+I+d[O-7]+P>>>0}let m=s[0],h=s[1],S=s[2],y=s[3],w=s[4],R=s[5],A=s[6],N=s[7];for(let O=0;O<64;O+=1){const D=w&R^~w&A,x=m&h^m&S^h&S,I=Ha(m,2)^Ha(m,13)^Ha(m,22),P=Ha(w,6)^Ha(w,11)^Ha(w,25),E=N+P+D+nT[O]+d[O]>>>0,T=I+x>>>0;N=A,A=R,R=w,w=y+E>>>0,y=S,S=h,h=m,m=E+T>>>0}s[0]=s[0]+m>>>0,s[1]=s[1]+h>>>0,s[2]=s[2]+S>>>0,s[3]=s[3]+y>>>0,s[4]=s[4]+w>>>0,s[5]=s[5]+R>>>0,s[6]=s[6]+A>>>0,s[7]=s[7]+N>>>0}return Array.from(s,p=>p.toString(16).padStart(8,"0")).join("")}function Ha(e,t){return e>>>t|e<<32-t}const oT=2e3,A0=25e7,ie=o().trim().min(1).max(240),we=o().regex(/^[a-f0-9]{64}$/),nt=o().datetime({offset:!0}),Ct=fe(o(),ye()).default({}),de=l({id:ie,contentHash:we}).strict(),Gn=l({id:ie,path:o().trim().min(1).max(oT).refine(rT),contentHash:we,sizeBytes:c().int().nonnegative().max(A0),mediaType:o().trim().min(1).max(200),visibility:b(["policy","verifier","host_private"])}).strict(),Zn=l({id:ie,contentHash:we,mediaType:o().trim().min(1).max(200).nullable().default(null),sizeBytes:c().int().nonnegative().max(A0).nullable().default(null)}).strict(),Cc=b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]);function P0(e){return`${JSON.stringify(wm(e),null,2)}
124
- `}function iT(e){return aT(e)}function _t(e){return iT(P0(e))}function rT(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function wm(e){return Array.isArray(e)?e.map(wm):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,wm(n)]))}const Sr=fe(o(),ye()).default({}),ca=c().int().nonnegative(),Rc=o().trim().min(1).max(1e5),T0=l({kind:b(["personal","team"]),id:ie}).strict(),sT=l({name:ie,release:de.nullable(),revision:ca}).strict();l({schemaVersion:k("openpond.harnessWorkspace.v1"),id:ie,ownerScope:T0,name:o().trim().min(1).max(240),location:b(["local","hosted"]),sourceRevision:o().trim().min(1).max(500),revision:ca,dirty:C(),currentChannel:sT,createdAt:nt,updatedAt:nt,metadata:Sr}).strict();const sr=b(["runtime","memory","prompt","skill","agent","product","taskset","training"]),E0=b(["text_instruction","memory","dependency_selection","executable_code","business_logic","financial_logic","permission","connected_app","publication","deployment","training","model_binding","team_or_global"]),M0=l({id:ie,route:sr,operation:b(["create","update","delete"]),target:o().trim().min(1).max(2e3),summary:o().trim().min(1).max(2e3),content:o().max(1e6).nullable(),contentHash:we.nullable(),effects:f(E0).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=_t(e.content);e.contentHash!==n&&t.addIssue({code:"custom",message:`edit contentHash is ${e.contentHash}; expected ${n}`,path:["contentHash"]})}),j0=l({workspaceId:ie,revision:ca,sourceRevision:o().trim().min(1).max(500),channelRevision:ca}).strict(),co=l({id:ie,revision:ca,contentHash:we}).strict(),lT=l({schemaVersion:k("openpond.harnessTurnSnapshot.v1"),workspaceId:ie,workspaceRevision:ca,sourceRevision:o().trim().min(1).max(500),channelName:ie,channelRevision:ca,harnessRelease:de,toolCatalogHash:we.nullable().optional(),overlay:co.nullable().optional().default(null)}).strict(),cT=l({schemaVersion:k("openpond.harnessRunOverlay.v1"),id:ie,runId:ie,baseHarnessRelease:de,workspace:j0,revision:ca,status:b(["active","frozen","abandoned"]),edits:f(M0).max(1e3),createdAt:nt,updatedAt:nt,metadata:Sr}).strict();cT.extend({contentHash:we}).strict();const O0=l({kind:b(["tool_event","recovery","validation","user_turn","work_output","work_receipt"]),id:ie,contentHash:we.nullable()}).strict(),N0=l({id:ie,kind:b(["dependency","schema","package","file_render","skill","prompt","business_formula","targeted_evaluation","observed_recovery","memory","component_activation"]),description:Rc,required:C()}).strict(),dT=l({schemaVersion:k("openpond.harnessImprovementProposal.v1"),id:ie,overlay:co,baseHarnessRelease:de,expectedWorkspace:j0,requestedScope:b(["personal","team","global"]),route:sr,risk:b(["low","review","restricted"]),effects:f(E0).min(1).max(20),evidence:f(O0).min(1).max(1e3),edits:f(M0).min(1).max(1e3),validationPlan:f(N0).min(1).max(100),expectedOutcome:Rc,createdAt:nt,metadata:Sr}).strict().superRefine((e,t)=>{const n=new Set(e.effects);for(const[a,i]of e.edits.entries()){i.route!==e.route&&t.addIssue({code:"custom",message:"every edit route must match the proposal route",path:["edits",a,"route"]});for(const r of i.effects)n.has(r)||t.addIssue({code:"custom",message:`edit effect ${r} 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"]})});dT.extend({contentHash:we}).strict();const uT=l({schemaVersion:k("openpond.harnessTargetedValidationReceipt.v1"),id:ie,proposal:de,validationId:ie,kind:N0.shape.kind,status:b(["passed","failed","blocked","skipped"]),summary:Rc,evidenceRefs:f(O0).max(1e3),createdAt:nt,metadata:Sr}).strict();uT.extend({contentHash:we}).strict();const mT=b(["advanced","retained","conflict","rolled_back"]),pT=l({schemaVersion:k("openpond.harnessAdvanceReceipt.v1"),id:ie,workspaceId:ie,ownerScope:T0,proposal:de.nullable(),expectedWorkspaceRevision:ca,observedWorkspaceRevision:ca,previousChannelRevision:ca,nextChannelRevision:ca,previousRelease:de.nullable(),nextRelease:de.nullable(),validationReceipts:f(de).max(100),decision:mT,reason:Rc,rollbackOf:de.nullable(),createdAt:nt,metadata:Sr}).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"]})});pT.extend({contentHash:we}).strict();const fT=l({schemaVersion:k("openpond.harnessOverlayMergeReceipt.v1"),id:ie,workspaceId:ie,baseHarnessRelease:de,leftOverlay:co,rightOverlay:co,decision:b(["merged","conflict"]),mergedOverlay:co.nullable(),conflictTargets:f(o().trim().min(1).max(2e3)).max(1e3),requiresRevalidation:k(!0),createdAt:nt,metadata:Sr}).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"]})});fT.extend({contentHash:we}).strict();const $0=b(["openpond.lab"]),Im=l({id:o(),experience:Mp.default(MP),provider:yr,modelRef:Jt.nullable().optional(),openPondCommandAccessMode:Bs.default(qs),systemKind:$0.nullable().optional(),hiddenFromDefaultSidebar:C().optional(),parentSessionId:o().nullable().optional(),parentTurnId:o().nullable().optional(),subagentRunId:o().nullable().optional(),subagentRoleId:vr.nullable().optional(),subagentDelegationMode:Sc.nullable().optional(),title:o(),appId:o().nullable(),appName:o().nullable(),workspaceKind:Fs.optional(),workspaceId:o().nullable().optional(),workspaceName:o().nullable().optional(),localProjectId:o().nullable().optional(),cloudProjectId:o().nullable().optional(),cloudTeamId:o().nullable().optional(),currentProfile:ci.nullable().optional(),metadata:fe(o(),ye()).optional(),cwd:o().nullable(),codexThreadId:o().nullable(),createdAt:o(),updatedAt:o(),status:b(["idle","active","failed","closed"]),runtimeSeconds:c().int().nonnegative().optional(),runtimeRunningSince:o().nullable().optional(),pinned:C(),savedForLater:C().optional(),archived:C(),order:c()});l({id:o(),sessionId:o(),providerTurnId:o().nullable(),modelRef:Jt.nullable().optional(),prompt:o(),startedAt:o(),completedAt:o().nullable(),status:b(["in_progress","completed","failed","interrupted"]),error:o().nullable(),metadata:fe(o(),ye()).optional().default({}),createImproveRun:Vs.nullable().optional().default(null),profileSnapshot:eT.nullable().optional(),harnessSnapshot:lT.nullable().optional()});const hT=l({id:o(),sessionId:o(),turnId:o().nullable(),providerRequestId:mn([o(),c()]),kind:b(["command","file_change","permissions","user_input","create_plan","subagent_patch_apply","legacy_exec","legacy_patch"]),title:o(),detail:o(),status:b(["pending","accepted","accepted_for_session","declined","cancelled"]),createdAt:o()}),gT=l({key:b(["files","diffs","checks","deploys","sources","schedules","tool_runs","logs","app_config"]),label:o(),status:b(["placeholder","available","error"]),summary:o()}),D0=l({id:o().trim().min(1).max(191),agentId:o().trim().min(1).max(191).optional().nullable(),sourcePath:o().trim().min(1).max(2e3).optional().nullable(),sourceActionId:o().trim().min(1).max(191).optional().nullable(),name:o().trim().min(1).max(191).optional().nullable(),label:o().trim().min(1).max(160).optional().nullable(),description:o().trim().max(1e3).optional().nullable(),visibility:o().trim().max(80).optional().nullable(),inputSchema:mn([o().trim().max(191),fe(o(),ye())]).optional().nullable(),outputSchema:mn([o().trim().max(191),fe(o(),ye())]).optional().nullable(),approvalPolicy:fe(o(),ye()).optional().nullable(),artifactPolicy:fe(o(),ye()).optional().nullable(),setupRequirements:f(fe(o(),ye())).optional(),mcp:fe(o(),ye()).optional().nullable(),schedulePolicy:fe(o(),ye()).optional().nullable(),trace:fe(o(),ye()).optional().nullable(),implementation:fe(o(),ye()).optional().nullable(),invokesModel:C().optional()}),bT=l({command:b(["inspect","build","validate","eval","traces","run"]),status:b(["passed","failed"]),checkedAt:o(),exitCode:c().nullable().optional(),sourceHead:o().nullable().optional()}),vT=l({id:o(),name:o(),path:o(),enabled:C()}),yT=l({name:o(),description:o(),path:o(),scope:k("profile"),enabled:C(),sourcePath:o(),charCount:c(),sourceHash:o(),validationStatus:b(["valid","warning","error"]),validationMessages:f(o()),resourceFiles:f(o()).optional().default([])}),ST=l({id:o(),name:o(),path:o(),agentId:o().nullable(),sourcePath:o()}),L0=l({path:o(),originalPath:o().nullable().optional(),indexStatus:o().nullable(),worktreeStatus:o().nullable(),status:o(),category:b(["added","modified","deleted","renamed","untracked","changed"])}),xT=l({isRepo:C(),branch:o().nullable(),head:o().nullable(),shortHead:o().nullable(),dirty:C(),upstream:o().nullable(),ahead:c().nullable(),behind:c().nullable(),remoteUrl:o().nullable(),files:f(L0),fileCount:c().int().nonnegative().optional(),error:o().nullable()}),kT=l({actionCount:c(),generatedAt:o().nullable(),manifestPath:o().nullable(),registryPath:o().nullable(),stale:C(),error:o().nullable()}),_T=l({skillCount:c(),generatedAt:o().nullable(),stale:C(),error:o().nullable()}),Gh=l({ref:o(),source:b(["action_catalog","source_upload_metadata"]),actionId:o().nullable(),kind:o().nullable(),label:o(),status:o(),required:C(),blocking:C()}),wT=l({status:b(["ready","setup_required","blocked"]),requirementCount:c(),blockingCount:c(),optionalMissingCount:c(),readyCount:c(),requirements:f(Gh),blockingRequirements:f(Gh)}),IT=l({changedAgents:f(o()),newAgents:f(o()),deletedAgents:f(o()),changedSkills:f(o()).optional().default([]),changedActions:f(o()),changedExtensions:f(o()),setupChanges:f(o()),envRequirementChanges:f(o()),files:f(L0),fileCount:c().int().nonnegative().optional()}),CT=l({status:o(),agentId:o().nullable().optional(),deployPlanStatus:o().nullable().optional(),canRun:C().nullable().optional(),canDeploy:C().nullable().optional(),sourceRef:o().nullable().optional(),sourceCommitSha:o().nullable().optional(),manifestHash:o().nullable().optional(),manifestPath:o().nullable().optional(),setupCommands:f(o()).optional(),validationCommands:f(o()).optional(),requiredChecks:f(o()).optional(),evalNames:f(o()).optional(),blockedReasons:f(o()).optional(),staleReasons:f(o()).optional(),runtimeId:o().nullable().optional(),sandboxId:o().nullable().optional(),traceArtifactRefs:f(o()).optional(),evalResultArtifactRefs:f(o()).optional(),validatorArtifactRefs:f(o()).optional(),checkedAt:o().nullable().optional(),error:o().nullable().optional()}),RT=l({status:o(),agentId:o().nullable().optional(),runtimeAgentId:o().nullable().optional(),projectId:o().nullable().optional(),sourceRoot:o().nullable().optional(),sourceRef:o().nullable().optional(),sourceCommitSha:o().nullable().optional(),manifestHash:o().nullable().optional(),manifestPath:o().nullable().optional(),manifestSyncedAt:o().nullable().optional(),fileCount:c().nullable().optional(),totalBytes:c().nullable().optional(),generatedManifestPath:o().nullable().optional(),synthesizedOpenPondYaml:C().nullable().optional(),uploadMetadataPath:o().nullable().optional(),setupCommands:f(o()).optional(),validationCommands:f(o()).optional(),materializedAt:o().nullable().optional(),error:o().nullable().optional()}),AT=l({status:o(),agentId:o().nullable().optional(),snapshotId:o().nullable().optional(),sourceRef:o().nullable().optional(),sourceCommitSha:o().nullable().optional(),manifestHash:o().nullable().optional(),manifestPath:o().nullable().optional(),buildStatus:o().nullable().optional(),validationStatus:o().nullable().optional(),evalStatus:o().nullable().optional(),publishedAt:o().nullable().optional(),error:o().nullable().optional()}),PT=l({status:o(),agentId:o().nullable().optional(),runId:o().nullable().optional(),runtimeId:o().nullable().optional(),sandboxId:o().nullable().optional(),sourceRef:o().nullable().optional(),sourceCommitSha:o().nullable().optional(),manifestHash:o().nullable().optional(),setupGateStatus:o().nullable().optional(),setupRequirementRefs:f(o()).optional(),artifactRefs:f(o()).optional(),traceArtifactRefs:f(o()).optional(),evalArtifactRefs:f(o()).optional(),startedAt:o().nullable().optional(),completedAt:o().nullable().optional(),error:o().nullable().optional()}),TT=l({teamId:o().nullable(),projectId:o().nullable(),sourceRef:o().nullable(),sourceCommitSha:o().nullable(),lastPushedAt:o().nullable(),lastPushedLocalHead:o().nullable(),lastPushedHostedHead:o().nullable(),promotionStatus:o().nullable().optional().default(null),hostedRunStatus:o().nullable().optional().default(null),hostedRunAgentId:o().nullable().optional().default(null),hostedRunId:o().nullable().optional().default(null),hostedRunAt:o().nullable().optional().default(null),hostedSourceMaterialization:RT.nullable().optional().default(null),hostedSourceCheck:CT.nullable().optional().default(null),hostedPublish:AT.nullable().optional().default(null),hostedRun:PT.nullable().optional().default(null)}),ET=l({state:b(["none","ready","dirty","pending_commit","error"]),message:o(),agentCount:c(),actionCount:c(),defaultAction:o().nullable(),checkFresh:C(),checkStaleReason:o().nullable(),localHead:o().nullable(),hostedHead:o().nullable()}),z0=l({mode:b(["none","local"]),repoPath:o().nullable(),activeProfile:o().nullable(),sourcePath:o().nullable(),manifestPath:o().nullable(),agents:f(vT),skills:f(yT).optional().default([]),evals:f(ST).optional().default([]),git:xT.nullable(),catalog:kT,skillCatalog:_T.optional().default({skillCount:0,generatedAt:null,stale:!0,error:null}),actionCatalog:f(D0),sourceSetupRequirements:f(fe(o(),ye())),setupGate:wT,diff:IT,hosted:TT.nullable(),summary:ET,lastCheck:bT.nullable(),error:o().nullable()}),MT=l({ref:ci,name:o(),repoPath:o(),sourcePath:o().nullable(),state:z0}),jT=l({lastUsed:ci.nullable(),profiles:f(MT)});function OT(){return{lastUsed:null,profiles:[]}}function NT(){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 $T=l({name:o(),description:o(),path:o(),sourcePath:o(),enabled:C(),charCount:c().int().nonnegative(),sourceHash:o(),validationStatus:b(["valid","error"]),validationMessages:f(o()),resourceFiles:f(o()),updatedAt:o().nullable()}),DT=b(["codex","profile","extension"]);l({skillName:o(),scope:DT,path:o(),byteSize:c().int().nonnegative(),isBinary:C(),content:o().nullable()});const LT=[{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"]}],zT=l({name:o(),description:o(),relativePath:o(),sourcePath:o(),charCount:c().int().nonnegative(),sourceHash:o(),resourceFiles:f(o()),validationStatus:b(["valid","error"]),validationMessages:f(o())}),U0=l({id:o(),source:k("github"),owner:o(),repo:o(),repositoryUrl:o().url(),requestedRef:o(),resolvedCommit:o(),sourcePath:o(),readmePath:o().nullable(),installedAt:o(),updatedAt:o(),packageHash:o(),skills:f(zT),validationStatus:b(["valid","error"]),validationMessages:f(o())});U0.omit({installedAt:!0,updatedAt:!0,sourcePath:!0}).extend({sourcePath:Ov()});const UT=l({rootPath:o(),registryPath:o(),extensions:f(U0),error:o().nullable()});l({source:o().trim().min(1),ref:o().trim().min(1).optional()});const HT=l({latestSequence:c().int().nonnegative(),oldestSequence:c().int().nonnegative(),totalEvents:c().int().nonnegative(),limit:c().int().nonnegative(),hasMoreBefore:C()});l({server:EP,account:xP,codex:kP,preferences:Wh.optional().default(()=>Wh.parse({})),providers:fh.optional().default(()=>fh.parse({})),personalization:Kh.optional().default(()=>Kh.parse({soul:w0[0].content,soulPath:null,updatedAt:null})),apps:f(TA),localProjects:f(NA).optional().default([]),cloudProjects:f(OA).optional().default([]),profile:z0.optional().default(NT),profileLibrary:jT.optional().default(OT),codexPersonalSkills:f($T).optional().default([]),extensionCatalog:UT.optional().default({rootPath:"",registryPath:"",extensions:[],error:null}),codexHistorySessions:f(Im).optional().default([]),sidebarAppPreferences:fP,sidebarFileBookmarks:f(k0).optional().default([]),appsError:o().nullable(),appsMeta:Vh,accountMeta:Vh,sessions:f(Im),events:f(hh),eventWindow:HT.optional(),approvals:f(hT),placeholders:f(gT),diagnostics:f(hh)});const Op=b(["openpond_hosted","local_byok","codex_app_server","unknown"]),H0=b(["provider_usage","codex_context_usage","missing"]),qT=b(["provider_usage_body","provider_response_headers"]),BT=b(["chat_turn","tool_loop","slash_command","create_improve_planner","harness_refiner","context_compaction","subagent","codex_context","other"]),FT=b(["foreground","tool_loop","compaction","subagent","refiner","other"]),q0=b(["user_facing","background","system"]),B0=b(["started","completed","failed","interrupted"]),Np=b(["composer_selection","prompt_parse","server_parser","model_tool","api"]),F0=b(["chat","settings","goal","create_improve","compaction","system"]),V0=b(["direct_chat","tool_loop","slash_command","planner","summary","scan","subagent","other"]),VT=l({surface:F0,workflowKind:V0,sessionId:o().trim().min(1).nullable().default(null),turnId:o().trim().min(1).nullable().default(null),goalId:o().trim().min(1).nullable().default(null),subagentRunId:o().trim().min(1).nullable().default(null),subagentRoleId:o().trim().min(1).nullable().default(null),createImproveRunId:o().trim().min(1).nullable().default(null),commandName:o().trim().min(1).max(160).nullable().default(null),commandSource:Np.nullable().default(null),appId:o().trim().min(1).nullable().default(null),workspaceKind:Fs.nullable().default(null),workspaceId:o().trim().min(1).nullable().default(null),localProjectId:o().trim().min(1).nullable().default(null),cloudProjectId:o().trim().min(1).nullable().default(null),sourceEventSequence:c().int().nonnegative().nullable().default(null)}),WT=l({surface:F0.optional(),workflowKind:V0.optional(),goalId:o().trim().min(1).nullable().optional(),subagentRunId:o().trim().min(1).nullable().optional(),subagentRoleId:o().trim().min(1).nullable().optional(),createImproveRunId:o().trim().min(1).nullable().optional(),commandName:o().trim().min(1).max(160).nullable().optional(),commandSource:Np.nullable().optional()}).strict(),di=o().trim().min(1).max(160),KT=l({id:o().trim().min(1),requestId:o().trim().min(1),requestOrdinal:c().int().nonnegative(),sessionId:o().trim().min(1).nullable(),turnId:o().trim().min(1).nullable(),provider:di,model:o().trim().min(1),route:Op,source:H0,requestKind:BT,visibility:q0,status:B0,startedAt:o().trim().min(1),completedAt:o().trim().min(1).nullable(),durationMs:c().int().nonnegative().nullable(),firstTokenMs:c().int().nonnegative().nullable(),promptTokens:c().int().nonnegative().nullable(),cachedPromptTokens:c().int().nonnegative().nullable(),uncachedPromptTokens:c().int().nonnegative().nullable(),cacheWritePromptTokens:c().int().nonnegative().nullable(),cacheTelemetrySource:qT.nullable(),completionTokens:c().int().nonnegative().nullable(),totalTokens:c().int().nonnegative().nullable(),errorType:o().trim().min(1).max(160).nullable(),errorMessage:o().trim().min(1).max(2e3).nullable(),attribution:VT}),W0=l({from:o().trim().min(1),to:o().trim().min(1),bucket:b(["day","all_time"])}),$p=mn([k("all"),q0]),Dp=b(["all","started","completed","failed","interrupted","missing"]),GT=l({range:b(["7d","30d","90d","all"]).default("30d"),visibility:$p.default("all"),status:Dp.default("all"),provider:di.optional(),model:o().trim().min(1).optional()});GT.extend({sessionId:o().trim().min(1).optional(),turnId:o().trim().min(1).optional(),limit:c().int().positive().max(500).default(100)});l({sessionId:o().trim().min(1)});const ui=l({requests:c().int().nonnegative(),promptTokens:c().int().nonnegative().nullable(),cacheTelemetryRequests:c().int().nonnegative(),cacheHitRequests:c().int().nonnegative(),cachedPromptTokens:c().int().nonnegative().nullable(),uncachedPromptTokens:c().int().nonnegative().nullable(),cacheWritePromptTokens:c().int().nonnegative().nullable(),cacheHitRate:c().min(0).max(1).nullable(),cacheRequestHitRate:c().min(0).max(1).nullable(),cacheTelemetryCoverage:c().min(0).max(1),completionTokens:c().int().nonnegative().nullable(),totalTokens:c().int().nonnegative().nullable(),averageLatencyMs:c().nonnegative().nullable(),p95LatencyMs:c().nonnegative().nullable(),averageFirstTokenMs:c().nonnegative().nullable(),p95FirstTokenMs:c().nonnegative().nullable(),failures:c().int().nonnegative(),failureRate:c().nonnegative(),firstSeenAt:o().trim().min(1),lastSeenAt:o().trim().min(1)}),ZT=ui.extend({provider:di,model:o().trim().min(1),route:Op}),JT=ui.extend({sessionId:o().trim().min(1),title:o().trim().min(1).nullable(),workspaceKind:Fs.nullable(),workspaceId:o().trim().min(1).nullable()}),YT=ui.extend({commandName:o().trim().min(1),commandSource:Np.nullable()}),XT=ui.extend({route:Op}),QT=ui.extend({status:B0}),eE=ui.extend({source:H0}),tE=ui.extend({cohort:FT}),nE=l({date:o().trim().min(1),totalTokens:c().int().nonnegative(),requests:c().int().nonnegative(),models:f(l({provider:di,model:o().trim().min(1),totalTokens:c().int().nonnegative(),requests:c().int().nonnegative()}))}),aE=l({requests:c().int().nonnegative(),completedRequests:c().int().nonnegative(),failedRequests:c().int().nonnegative(),missingUsageRequests:c().int().nonnegative(),promptTokens:c().int().nonnegative().nullable(),cacheTelemetryRequests:c().int().nonnegative(),cacheHitRequests:c().int().nonnegative(),cachedPromptTokens:c().int().nonnegative().nullable(),uncachedPromptTokens:c().int().nonnegative().nullable(),cacheWritePromptTokens:c().int().nonnegative().nullable(),cacheHitRate:c().min(0).max(1).nullable(),cacheRequestHitRate:c().min(0).max(1).nullable(),cacheTelemetryCoverage:c().min(0).max(1),completionTokens:c().int().nonnegative().nullable(),totalTokens:c().int().nonnegative().nullable(),averageLatencyMs:c().nonnegative().nullable(),p95LatencyMs:c().nonnegative().nullable(),averageFirstTokenMs:c().nonnegative().nullable(),p95FirstTokenMs:c().nonnegative().nullable(),failureRate:c().nonnegative(),activeModelCount:c().int().nonnegative(),peakDailyTokens:c().int().nonnegative(),longestRequestMs:c().int().nonnegative().nullable(),activeDays:c().int().nonnegative(),currentStreakDays:c().int().nonnegative(),longestStreakDays:c().int().nonnegative()});l({generatedAt:o().trim().min(1),range:W0,filters:l({visibility:$p,status:Dp,provider:di.nullable(),model:o().trim().min(1).nullable()}),totals:aE,daily:f(nE),models:f(ZT),threads:f(JT),commands:f(YT),routes:f(XT),statuses:f(QT),sources:f(eE),cohorts:f(tE)});l({generatedAt:o().trim().min(1),range:W0,filters:l({visibility:$p,status:Dp,provider:di.nullable(),model:o().trim().min(1).nullable(),sessionId:o().trim().min(1).nullable(),turnId:o().trim().min(1).nullable()}),limit:c().int().positive(),hasMore:C(),records:f(KT)});const oE=l({turnId:o().trim().min(1),requests:c().int().nonnegative(),cacheTelemetryRequests:c().int().nonnegative(),cachedPromptTokens:c().int().nonnegative().nullable(),uncachedPromptTokens:c().int().nonnegative().nullable(),cacheWritePromptTokens:c().int().nonnegative().nullable(),cacheHitRate:c().min(0).max(1).nullable(),cacheTelemetryCoverage:c().min(0).max(1),providers:f(di)});l({generatedAt:o().trim().min(1),sessionId:o().trim().min(1),turns:f(oE)});const iE=b(["usage_spike","model_usage_spike","latency_regression","failure_cluster","missing_usage_frames"]);l({type:iE,title:o().trim().min(1),summary:o().trim().min(1),severity:b(["nit","concern","blocker"]),payload:fe(o(),ye()).default({})});const rE=b(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),sE=b(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),lE=b(["native_bot","oauth_connector","wallet_connector","mcp_endpoint"]),cE=l({kind:k("integration"),provider:rE,appIds:f(sE).min(1).max(4),setupSurfaces:f(lE).min(1).max(4),connectionIds:f(o().trim().min(1)).max(8).optional(),capabilities:f(o().trim().min(1)).max(64).optional()}).strict(),Xo={maxAttachments:10,maxAttachmentBytes:12*1024*1024,maxAttachmentBase64Chars:Math.ceil(12*1024*1024*4/3)+16,maxTextChars:2e5},dE=b(["image","text","file"]),uE=l({sessionId:o().trim().min(1).max(200),turnId:o().trim().min(1).max(200),attachmentId:o().trim().min(1).max(200),storageName:o().trim().min(1).max(240),contentType:o().trim().min(1).max(160)}),mE=l({sessionId:o().trim().min(1).max(200),turnId:o().trim().min(1).max(200),attachmentId:o().trim().min(1).max(200),storageName:o().trim().min(1).max(1024),contentType:o().trim().min(1).max(160)}),K0=l({id:o().trim().min(1),name:o().trim().min(1).max(240),mediaType:o().trim().min(1).max(160),sizeBytes:c().int().nonnegative().max(Xo.maxAttachmentBytes),kind:dE,lineCount:c().int().nonnegative().max(Xo.maxAttachmentBytes+1).optional(),relativePath:o().trim().min(1).max(1024).optional(),text:o().max(Xo.maxTextChars).optional(),contentsBase64:o().max(Xo.maxAttachmentBase64Chars).optional()}),pE=K0.omit({text:!0,contentsBase64:!0}).extend({imagePreview:uE.optional(),filePreview:mE.optional()});l({experience:Mp.optional(),provider:yr.default(oi),modelRef:Jt.optional(),openPondCommandAccessMode:Bs.optional(),systemKind:$0.nullable().optional(),hiddenFromDefaultSidebar:C().optional(),parentSessionId:o().trim().min(1).max(200).nullable().optional(),parentTurnId:o().trim().min(1).max(200).nullable().optional(),subagentRunId:o().trim().min(1).max(200).nullable().optional(),subagentRoleId:vr.nullable().optional(),subagentDelegationMode:Sc.nullable().optional(),appId:o().nullable().optional(),appName:o().nullable().optional(),workspaceKind:Fs.optional(),workspaceId:o().nullable().optional(),workspaceName:o().nullable().optional(),localProjectId:o().nullable().optional(),cloudProjectId:o().nullable().optional(),cloudTeamId:o().nullable().optional(),currentProfile:ci.nullable().optional(),metadata:fe(o(),ye()).optional(),cwd:o().nullable().optional(),title:o().optional(),autoTitlePrompt:o().trim().min(1).max(2e4).optional()});l({teamId:o().trim().min(1),projectName:o().trim().min(1).max(120).optional(),branch:o().trim().min(1).max(120).optional(),chatSessionId:o().trim().min(1).max(200).optional(),displayPrompt:o().trim().min(1).max(2e3).optional()});l({branch:o().trim().min(1).max(120).optional()});l({prompt:o().min(1),metadata:fe(o(),ye()).optional(),usageAttribution:WT.optional().nullable(),cwd:o().nullable().optional(),model:o().nullable().optional(),modelRef:Jt.optional(),mentionedAppIds:f(o().trim().min(1)).max(8).optional(),mentionedConnectedApps:f(cE).max(8).optional(),openPondActionCatalog:f(D0).max(100).optional(),attachments:f(K0).max(Xo.maxAttachments).optional(),createImproveRun:Vs.optional().nullable(),approvalPolicy:b(["untrusted","on-failure","on-request","never"]).default("on-request"),sandbox:b(["read-only","workspace-write","danger-full-access"]).default("workspace-write"),codexPermissionMode:Tp.default("default"),codexReasoningEffort:Ic.optional()});l({prompt:o().min(1),error:o().min(1),target:b(["cloud_workspace","hybrid_sandbox"])});l({reason:b(["manual"]).default("manual"),model:o().nullable().optional(),modelRef:Jt.optional()});l({experience:Mp.optional(),provider:yr.optional(),modelRef:Jt.nullable().optional(),openPondCommandAccessMode:Bs.optional(),pinned:C().optional(),savedForLater:C().optional(),archived:C().optional(),order:c().optional(),title:o().optional(),parentSessionId:o().trim().min(1).max(200).nullable().optional(),parentTurnId:o().trim().min(1).max(200).nullable().optional(),subagentRunId:o().trim().min(1).max(200).nullable().optional(),subagentRoleId:vr.nullable().optional(),subagentDelegationMode:Sc.nullable().optional(),appId:o().nullable().optional(),appName:o().nullable().optional(),workspaceKind:Fs.optional(),workspaceId:o().nullable().optional(),workspaceName:o().nullable().optional(),localProjectId:o().nullable().optional(),cloudProjectId:o().nullable().optional(),cloudTeamId:o().nullable().optional(),currentProfile:ci.nullable().optional(),metadata:fe(o(),ye()).optional(),cwd:o().nullable().optional()});l({command:o().trim().min(1),cwd:o().trim().min(1).max(4096).nullable().optional(),timeoutSeconds:c().int().min(1).max(3600).optional()});l({appIds:f(o()).min(1)});l({defaultChatProvider:yr.optional(),defaultChatModel:o().min(1).optional(),defaultChatModelRef:Jt.nullable().optional(),subagents:Rs.optional(),codexPermissionMode:Tp.optional(),codexReasoningEffort:Ic.optional(),openPondCommandAccessMode:Bs.optional(),defaultBranchPrefix:o().trim().max(48).optional(),defaultNewProjectDirectory:o().trim().max(4096).optional(),defaultTeamId:o().trim().max(191).nullable().optional(),advancedWorkspaceControls:C().optional(),steerActiveResponses:C().optional(),contextCompaction:xm.optional(),training:km.optional(),sidebarWidth:c().int().min(244).max(560).optional(),diffPanelWidth:c().int().min(320).max(2400).optional(),sidebarSectionsCollapsed:Sm.optional(),editor:ec.optional()});l({message:o().trim().min(1).max(4e3),surface:o().trim().min(1).max(120).default("app"),stack:o().max(12e3).nullable().optional(),context:fe(o(),ye()).optional()}).strict();l({activeTemplateId:Ep,templateName:o().trim().min(1).max(80),soul:o().trim().min(1).max(8e3),saveAsNew:C().optional().default(!1)});l({decision:b(["accept","acceptForSession","decline","cancel"])});l({branch:o().trim().min(1).max(240).nullable().optional(),surface:b(["desktop","terminal"])});l({handle:o().min(1),baseUrl:o().nullable().optional()});l({handle:o().min(1),baseUrl:o().nullable().optional()});l({handle:o().min(1).optional(),apiKey:o().min(1),baseUrl:o().nullable().optional(),apiBaseUrl:o().nullable().optional(),chatApiBaseUrl:o().nullable().optional(),environment:o().nullable().optional(),setActive:C().optional()});l({handle:o().min(1),currentBaseUrl:o().nullable().optional(),baseUrl:o().nullable().optional(),apiBaseUrl:o().nullable().optional(),chatApiBaseUrl:o().nullable().optional(),environment:o().nullable().optional(),setActive:C().optional()});l({appId:o(),exists:C(),configPath:o().nullable().optional(),envVar:o().nullable(),toolName:o().nullable(),version:mn([o(),c()]).nullable(),source:b(["hosted_env","local_file","defaults","missing"]),currentConfig:fe(o(),ye()).nullable(),defaults:fe(o(),ye()).nullable(),schema:fe(o(),ye()).nullable(),error:o().nullable().optional(),updatedAt:o()}).passthrough();const tc=b(["create_sandbox_template_scaffold","resource_read","resource_search","list_files","read_files","search_files","preview_write_files","preview_write_file","preview_edit_file","preview_delete_file","write_files","write_file","edit_file","delete_file","workspace_status","validate_sandbox_template","build_sandbox_template","run_sandbox_template","git_init","git_status","git_diff","git_fetch","git_commit","git_push","publish_openpond_repo","sandbox_create","sandbox_templates","sandbox_template_launch","sandbox_status","sandbox_start","sandbox_list_files","sandbox_read_file","sandbox_search_files","sandbox_upload_file","sandbox_write_file","sandbox_edit_file","sandbox_delete_file","sandbox_mkdir","sandbox_move_file","sandbox_exec","sandbox_git_status","sandbox_git_diff","sandbox_git_export_patch","sandbox_git_apply_patch_local","sandbox_git_branch","sandbox_git_commit","sandbox_git_pull","sandbox_git_push","sandbox_preserve_source","sandbox_promote_source","sandbox_run_action","sandbox_open_port","sandbox_snapshot_catalog","sandbox_snapshot_create","sandbox_snapshot_update","sandbox_snapshot_validate","sandbox_snapshot_publish","sandbox_replays","sandbox_replay_start","sandbox_replay_get","sandbox_replay_logs","sandbox_replay_artifacts","sandbox_replay_cancel","sandbox_logs","sandbox_receipts","sandbox_prepare_agent","sandbox_save_agent_package","sandbox_save_output","work_agent_package_install","work_output_delete","work_output_read","sandbox_schedule_create","sandbox_stop"]);l({action:tc,args:fe(o(),ye()).optional().default({}),source:b(["ui_button","chat_action","terminal_command","hook"]).default("chat_action")});l({ok:C(),action:tc,appId:o().nullable().optional(),output:o(),data:ye().optional()});const Ws=l({id:o().trim().min(1).max(200),title:o().trim().min(1).max(240),sourceTaskId:o().trim().min(1).max(200),sourceTurnId:o().trim().min(1).max(200),revision:c().int().positive().default(1),createdAt:o().datetime()}),Ks=l({kind:b(["structural","visual","test","user_review"]),status:b(["passed","failed","not_run"]),label:o().trim().min(1).max(240),detail:o().trim().max(4e3).nullable().optional(),ref:o().trim().max(4096).nullable().optional()}),G0=l({kind:k("local"),path:o().trim().min(1).max(4096),deviceId:o().trim().min(1).max(200)}),Z0=l({kind:k("managed"),fileId:o().trim().min(1).max(200),downloadPath:o().trim().min(1).max(4096)}),fE=l({kind:k("external"),provider:o().trim().min(1).max(120),resourceId:o().trim().min(1).max(500),url:o().url().nullable()}),J0=Ws.extend({kind:k("file"),contentType:o().trim().min(1).max(200),sizeBytes:c().int().nonnegative(),sha256:o().regex(/^[a-f0-9]{64}$/),location:Kt("kind",[G0,Z0,fE]),validation:f(Ks).max(32).default([])}),hE=Ws.extend({kind:k("source_change"),projectId:o().trim().min(1).max(200),ref:o().trim().min(1).max(500),url:o().url().nullable(),validation:f(Ks).max(32).default([])}),gE=Ws.extend({kind:k("deployment"),deploymentId:o().trim().min(1).max(200),url:o().url(),validation:f(Ks).max(32).default([])}),bE=Ws.extend({kind:k("external_resource"),provider:o().trim().min(1).max(120),resourceId:o().trim().min(1).max(500),url:o().url(),contentType:o().trim().min(1).max(200).nullable(),validation:f(Ks).max(32).default([])}),Y0=l({id:o().trim().min(1).max(191),label:o().trim().min(1).max(160).nullable(),description:o().trim().max(1e3).nullable(),inputSchema:fe(o(),ye()).nullable(),outputSchema:fe(o(),ye()).nullable(),schedulePolicy:fe(o(),ye()).nullable()}),X0=l({base:o().trim().min(1).max(200),resources:fe(o(),ye()),modelPolicy:fe(o(),ye()).nullable(),setup:fe(o(),ye()).nullable()}),vE=l({id:o().trim().min(1).max(200),kind:b(["sdk_validation","sdk_eval"]),status:b(["passed","failed"]),summary:o().trim().min(1).max(2e3),artifactPath:o().trim().min(1).max(4096),artifactSha256:o().regex(/^[a-f0-9]{64}$/)}),yE=l({path:o().trim().min(1).max(4096),sizeBytes:c().int().nonnegative(),sha256:o().regex(/^[a-f0-9]{64}$/),contentsBase64:o()});l({schema:k("openpond.agent-package.v1"),agentId:o().trim().min(1).max(191),versionId:o().trim().min(1).max(200),digest:o().regex(/^[a-f0-9]{64}$/),title:o().trim().min(1).max(240),source:l({files:f(yE).min(1).max(1e3),totalSizeBytes:c().int().nonnegative()}),manifest:fe(o(),ye()),actions:f(Y0).min(1).max(256),runtimeRequirements:X0,receipts:f(vE).min(2).max(64)});const SE=Ws.extend({kind:k("agent_package"),agentId:o().trim().min(1).max(191),versionId:o().trim().min(1).max(200),digest:o().regex(/^[a-f0-9]{64}$/),packageFileId:o().trim().min(1).max(200),manifestFileId:o().trim().min(1).max(200),actions:f(Y0).min(1).max(256),runtimeRequirements:X0,validationReceiptIds:f(o().trim().min(1).max(200)).min(1).max(32),evalReceiptIds:f(o().trim().min(1).max(200)).min(1).max(32),sourceFileCount:c().int().positive(),sourceSizeBytes:c().int().nonnegative(),location:Kt("kind",[G0,Z0]),validation:f(Ks).max(32).default([])}),tW=Kt("kind",[J0,hE,gE,bE,SE]);l({outputs:f(J0)});const xE=b(["sandbox_template","sandbox","generic_git","plain_folder"]),kE=b(["sandbox_template"]).nullable();l({productKind:xE,actions:l({files:C(),git:C(),sandboxRuntime:C(),sandboxTemplate:C()}),checks:l({validate:tc.nullable(),build:tc.nullable(),postEdit:kE}),ui:l({showSandboxTemplateActions:C(),showSandboxRuntimeActions:C()})});const _E=l({id:o(),name:o(),dnsName:o().nullable(),os:o().nullable(),online:C(),active:C(),isSelf:C(),tailscaleIps:f(o()),lastSeen:o().nullable()}),wE=l({installed:C(),running:C(),version:o().nullable(),backendState:o().nullable(),tailnetName:o().nullable(),magicDnsSuffix:o().nullable(),machineName:o().nullable(),dnsName:o().nullable(),authUrl:o().nullable(),tailscaleIps:f(o()),health:f(o()),error:o().nullable(),peers:f(_E)}),IE=l({enabled:C(),reachable:C(),targetUrl:o().nullable(),httpsUrl:o().nullable(),httpsHost:o().nullable(),httpsPort:c().nullable(),setupUrl:o().nullable(),configText:o().nullable(),error:o().nullable()}),CE=l({localUrl:o(),localWebUrl:o(),remoteUrl:o().nullable(),remoteWebUrl:o().nullable(),tokenHash:o(),tailscaleUpCommand:o(),serveCommand:o(),disableCommand:o(),operatorCommand:o(),webUiAvailable:C(),updatedAt:o(),tailscale:wE,serve:IE});l({message:o(),status:CE});const Q0=b(["github","openpond_git"]),ey=b(["private","public"]),RE=b(["actions","prompts","goals","evals","examples","tasksets","extensions"]),AE=l({agentIds:f(o().trim().min(1)).max(100),skillNames:f(o().trim().min(1)).max(200),optionalContent:f(RE).max(20).default([])}),ty=l({provider:Q0,owner:o().trim().min(1).max(191).nullable().optional(),repository:o().trim().min(1).max(191),visibility:ey.default("private")}),PE=l({ref:ci,selection:AE,target:ty}),TE=l({path:o(),sizeBytes:c().int().nonnegative(),category:o()});l({sourceHash:o(),sourceRevision:o().nullable(),clean:C(),blockedReasons:f(o()),warnings:f(o()),files:f(TE),excludedFiles:f(o()),target:ty,replacesExisting:C()});PE.extend({expectedSourceHash:o().trim().min(1),confirmed:k(!0)});l({provider:Q0,owner:o(),repository:o(),visibility:ey,remoteUrl:o(),webUrl:o(),revision:o()});const EE=b(["cron","rate"]),ny=b(["queued","running","succeeded","failed","skipped"]),ay=l({id:o(),localProjectId:o(),localProjectName:o(),agentRootPath:o(),agentName:o(),scheduleName:o(),scheduleType:EE,scheduleExpression:o(),timezone:o().nullable(),targetAction:o(),input:fe(o(),ye()).optional().default({}),enabledByDefault:C(),enabled:C(),sourceHash:o(),manifestHash:o().nullable(),agentVersionId:o().nullable().optional(),agentPackageDigest:o().nullable().optional(),nextRunAt:o().nullable(),lastRunAt:o().nullable(),lastRunStatus:ny.nullable(),lastRunId:o().nullable(),lastError:o().nullable(),createdAt:o(),updatedAt:o()}),oy=l({id:o(),scheduleId:o(),localProjectId:o(),scheduleName:o(),scheduledFor:o(),trigger:b(["schedule","manual"]),status:ny,targetAction:o(),agentVersionId:o().nullable().optional(),agentPackageDigest:o().nullable().optional(),startedAt:o().nullable(),completedAt:o().nullable(),exitCode:c().int().nullable(),stdout:o().nullable(),stderr:o().nullable(),result:fe(o(),ye()).nullable(),traceArtifactRef:o().nullable(),error:o().nullable(),createdAt:o(),updatedAt:o()});l({schedules:f(ay),scheduler:l({running:C(),nextTickAt:o().nullable(),lastSyncAt:o().nullable(),scanRunning:C()})});l({runs:f(oy)});l({enabled:C().optional()});l({input:fe(o(),ye()).optional()});l({schedule:ay,run:oy});const ME=b(["sunday","monday","tuesday","wednesday","thursday","friday","saturday"]),xr=l({version:k(1),kind:b(["once","daily","weekdays","weekly","monthly"]),timeZone:o().trim().min(1).max(100),startDate:o().regex(/^\d{4}-\d{2}-\d{2}$/),localTime:o().regex(/^([01]\d|2[0-3]):([0-5]\d)$/),weekdays:f(ME).min(1).max(7).optional(),dayOfMonth:c().int().min(1).max(31).optional(),end:Kt("kind",[l({kind:k("never")}),l({kind:k("on_date"),date:o().regex(/^\d{4}-\d{2}-\d{2}$/)}),l({kind:k("after_occurrences"),occurrences:c().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"]})}),jE=l({id:o(),expression:o().nullable(),timeZone:o(),recurrence:xr.nullable(),configurationVersion:c().int(),enabled:C(),nextRunAt:o().nullable(),lastTriggeredAt:o().nullable(),delivery:fe(o(),ye()).default({})}),OE=l({id:o(),definitionKey:o(),version:c().int(),name:o(),prompt:o(),modelId:o(),schedules:f(jE)}),NE=l({id:o(),definitionId:o(),scheduleId:o().nullable(),definitionName:o(),definitionVersion:c().int(),conversationId:o(),triggerKind:b(["manual","schedule","webhook","retry"]),status:o(),notificationStatus:o(),deliveryStatus:o(),deliveryError:o().nullable(),createdAt:o()});l({definitions:f(OE),runs:f(NE),asOf:o(),webBaseUrl:o().url().optional()});l({clientRequestId:o().trim().min(1).max(191),sourceTurnId:o().trim().min(1).max(191).nullable().optional(),targetSessionId:o().trim().min(1).max(191).nullable().optional(),name:o().trim().min(1).max(180),prompt:o().trim().min(1).max(2e4),recurrence:xr,modelId:o().trim().min(1).max(191).default("openpond-chat")});mn([l({enabled:C()}),l({name:o().trim().min(1).max(180),prompt:o().trim().min(1).max(2e4),recurrence:xr})]);const iy=b(["queued","running","succeeded","failed"]),$E=l({id:o(),sessionId:o(),sessionTitle:o(),sourceTurnId:o().nullable(),name:o(),prompt:o(),recurrence:xr,enabled:C(),nextRunAt:o().nullable(),lastRunAt:o().nullable(),lastRunStatus:iy.nullable(),lastRunId:o().nullable(),lastError:o().nullable(),scheduledRunCount:c().int().nonnegative(),createdAt:o(),updatedAt:o()}),DE=l({id:o(),workflowId:o(),sessionId:o(),scheduledFor:o(),trigger:b(["schedule","manual"]),status:iy,turnId:o().nullable(),error:o().nullable(),createdAt:o(),startedAt:o().nullable(),completedAt:o().nullable(),updatedAt:o()});l({sessionId:o().trim().min(1).max(191),sourceTurnId:o().trim().min(1).max(191).nullable().optional(),name:o().trim().min(1).max(180),prompt:o().trim().min(1).max(2e4),recurrence:xr});mn([l({enabled:C()}),l({name:o().trim().min(1).max(180),prompt:o().trim().min(1).max(2e4),recurrence:xr})]);l({workflows:f($E),runs:f(DE),asOf:o()});const Lp=fe(o(),ye());l({userId:o(),role:b(["owner","admin","member"]),name:o(),handle:o().nullable(),image:o().nullable()});const LE=l({userId:o(),role:b(["owner","admin","member"]),name:o(),handle:o().nullable(),image:o().nullable(),lastReadSequence:c().int().nonnegative()}),zE=l({id:o(),messageId:o(),refType:b(["hosted_ai_thread","goal","openpond_session","project","agent_run","message_reply"]),refId:o(),preview:Lp,createdAt:o()}),ry=l({id:o(),messageId:o().nullable(),clientAttachmentId:o(),kind:k("image"),name:o(),mediaType:b(["image/png","image/jpeg","image/webp","image/gif"]),sizeBytes:c().int().positive(),status:b(["pending","ready","failed"]),createdAt:o(),readyAt:o().nullable()});l({attachment:ry,uploadUrl:o().url().nullable(),uploadHeaders:fe(o(),o()),expiresAt:o().nullable()});l({url:o().url(),expiresAt:o()});const zp=l({id:o(),threadId:o(),teamId:o(),clientRequestId:o().nullable(),authorType:b(["user","agent","system"]),authorUserId:o().nullable(),authorAgentId:o().nullable(),sequence:c().int().nonnegative(),kind:b(["text","system","command_result"]),body:o(),metadata:Lp,editedAt:o().nullable(),deletedAt:o().nullable(),createdAt:o(),refs:f(zE),attachments:f(ry)}),UE=l({id:o(),teamId:o(),kind:b(["general","dm","group","channel"]),title:o().nullable(),createdByUserId:o(),lastMessageId:o().nullable(),lastMessageSequence:c().int().nonnegative(),lastMessageAt:o(),createdAt:o(),updatedAt:o(),unreadCount:c().int().nonnegative(),pinnedAt:o().nullable(),mutedAt:o().nullable(),archivedAt:o().nullable(),participants:f(LE),lastMessage:zp.nullable()});l({thread:UE,messages:f(zp),hasMoreBefore:C()});l({threadId:o(),mutedAt:o().nullable()});const HE=b(["pending","running","completed","failed","interrupted","cancelled"]),Zh=l({id:o(),conversationId:o(),threadId:o(),teamId:o(),requestedByUserId:o(),executorUserId:o().nullable(),providerId:o(),modelId:o(),clientRequestId:o(),baseMessageSequence:c().int().nonnegative(),status:HE,partialBody:o().nullable(),userMessageId:o(),assistantMessageId:o().nullable(),errorCode:o().nullable(),cancelledByUserId:o().nullable(),leaseExpiresAt:o().nullable(),heartbeatAt:o().nullable(),createdAt:o(),updatedAt:o()}),qE=l({id:o(),conversationId:o(),sequence:c().int().nonnegative(),role:b(["user","assistant","system","action"]),body:o(),createdByUserId:o().nullable(),createdAt:o()});l({conversationId:o(),parentThreadId:o(),parentMessageId:o(),teamId:o(),title:o().nullable(),providerId:o().nullable(),modelId:o(),createdByUserId:o(),messages:f(qE),turns:f(Zh),activeTurn:Zh.nullable(),createdAt:o(),updatedAt:o()});const sy=l({id:c().int().nonnegative(),teamId:o(),threadId:o(),conversationId:o().nullable(),type:b(["thread.created","message.created","message.updated","message.deleted","read.updated","ai_thread.created","ai_turn.updated"]),payload:Lp,createdAt:o()});l({events:f(sy),cursor:c().int().nonnegative(),hasMore:C()});l({httpUrl:o().min(1),realtimeUrl:o().min(1),region:o().min(1),token:o().min(1),expiresAt:o().min(1),teamId:o().min(1),userId:o().min(1)});const Up=fe(o(),ye()),da=o().nullable(),BE=b(["draft","published","archived"]),Hp=b(["owner","admin","member"]),ly=b(["active","left"]),cy=b(["mentions","all","none"]),dy=b(["public_preview","members"]),FE=b(["members","admins"]),VE=l({canPreview:C(),canJoin:C(),canLeave:C(),canRead:C(),canPost:C(),canUpload:C(),canMention:C(),canManage:C(),requiresRulesAcceptance:C(),currentRulesVersionId:o().nullable()}),uy=l({id:o(),communityId:o(),version:c().int().positive(),title:o(),requiresReacceptance:C(),publishedAt:o()}),WE=uy.extend({bodyMarkdown:o(),contentHash:o()}),KE=l({role:Hp,status:ly,notificationMode:cy}),GE=l({id:o(),communityId:o(),userId:o(),role:Hp,status:ly,notificationMode:cy,joinedAt:o(),leftAt:da,createdAt:o(),updatedAt:o()}),my=l({id:o(),slug:o(),displayName:o(),description:o(),imageUrl:o().nullable(),status:BE,visibility:b(["public","private"]),joinPolicy:b(["open","closed"]),historyVisibility:dy,featuredAt:da,publishedAt:da,archivedAt:da,memberCount:c().int().nonnegative(),membership:KE.nullable(),capabilities:VE,currentRules:uy.nullable()});l({items:f(my),nextCursor:o().nullable()});const py=l({lastReadSequence:c().int().nonnegative(),lastReadAt:da.optional(),mutedAt:da,pinnedAt:da}),qp=l({id:o(),communityId:o(),chatThreadId:o().nullable(),slug:o(),displayName:o(),topic:o(),position:c().int().nonnegative(),visibility:dy,postingPolicy:FE,isDefault:C(),archivedAt:da,lastMessageSequence:c().int().nonnegative(),unreadCount:c().int().nonnegative(),readState:py.nullable()});my.omit({currentRules:!0}).extend({currentRules:WE.nullable(),channels:f(qp),previewMessageLimit:c().int().positive()});const ZE=l({id:o(),messageId:o(),refType:b(["hosted_ai_thread","goal","openpond_session","project","agent_run","message_reply"]),refId:o(),preview:Up,createdAt:o()}),fy=l({id:o(),messageId:o().nullable(),clientAttachmentId:o(),kind:k("image"),name:o(),mediaType:b(["image/png","image/jpeg","image/webp","image/gif"]),sizeBytes:c().int().positive(),status:b(["pending","ready","failed"]),createdAt:o(),readyAt:da});l({attachment:fy,uploadUrl:o().url().nullable(),uploadHeaders:fe(o(),o()),expiresAt:da});l({url:o().url(),expiresAt:o()});const hy=l({id:o(),threadId:o(),teamId:Ov(),clientRequestId:o().nullable(),authorType:b(["user","agent","system"]),authorUserId:o().nullable(),authorAgentId:o().nullable(),sequence:c().int().nonnegative(),kind:b(["text","system","command_result"]),body:o(),metadata:Up,editedAt:da,deletedAt:da,createdAt:o(),refs:f(ZE),attachments:f(fy)});l({messages:f(hy),hasMoreBefore:C(),channelId:o(),readState:py.omit({lastReadAt:!0}).nullable(),preview:C()});const JE=l({userId:o(),handle:o().nullable(),name:o().nullable(),role:Hp});l({items:f(JE),nextCursor:o().nullable()});const gy=l({id:c().int().nonnegative(),communityId:o(),channelId:o(),threadId:o(),type:b(["thread.created","message.created","message.updated","message.deleted","read.updated"]),payload:Up,createdAt:o()});l({events:f(gy),cursor:c().int().nonnegative(),hasMore:C()});l({httpUrl:o().min(1),realtimeUrl:o().min(1),region:o().min(1),token:o().min(1),expiresAt:o().min(1),communityId:o().min(1),userId:o().min(1),channel:o().min(1)});l({membership:GE,channels:f(qp)});l({channels:f(qp)});const Kn=o().trim().min(1).max(240),Co=o().trim().min(1),by=fe(o(),ye()).default({}),vy=b(["nominated","needs_review","approved_for_creation","creating","needs_task_review","baselining","ready_for_export","rejected","dismissed","retired","blocked"]),yy=b(["no_training","prompting","retrieval","sft","preference","grpo_rft","sdft_opsd","sdpo","agentic_rl"]),YE=l({id:Kn,kind:b(["repeated_success","accepted_correction","agent_action_recurrence","outcome_linked_change","frontier_cost","expert_label","runtime_feedback"]),sourceRefIds:f(Kn).min(1).max(1e4),occurredAt:Co,signature:o().trim().min(1).max(2e3),summary:o().trim().min(1).max(5e3),confidence:c().min(0).max(1),consented:C(),metadata:by}),XE=l({frequency:c().min(0).max(1),businessValue:c().min(0).max(1),frontierCost:c().min(0).max(1),signalQuality:c().min(0).max(1),verifiability:c().min(0).max(1),repeatability:c().min(0).max(1),privacyRisk:c().min(0).max(1),overall:c().min(0).max(1)}),QE=l({tactic:yy,eligible:C(),reasons:f(o().trim().min(1).max(5e3)).min(1).max(100),blockers:f(o().trim().min(1).max(5e3)).max(100).default([]),requiredSignals:f(o().trim().min(1).max(500)).max(100).default([]),generatedBy:b(["decision_table","baseline_reassessment"])}),Sy=l({schemaVersion:k("openpond.taskCandidate.v1"),id:Kn,profileId:Kn,status:vy,fingerprint:o().trim().min(1).max(512),title:o().trim().min(1).max(500),summary:o().trim().min(1).max(1e4),workflowSignature:o().trim().min(1).max(2e3),evidence:f(YE).min(1).max(1e5),scorecard:XE,recommendation:QE,mergedIntoId:Kn.nullable(),createdAt:Co,updatedAt:Co,metadata:by}),Ac=l({schemaVersion:k("openpond.taskMinerConfig.v1"),enabled:C().default(!1),localOnly:C().default(!0),observationWindowDays:c().int().min(1).max(365).default(30),minimumRecurrence:c().int().min(2).max(100).default(3),clustering:k("hybrid_deterministic_first").default("hybrid_deterministic_first"),consentRequired:C().default(!0)});l({items:f(Sy),generatedAt:Co,config:Ac});l({status:vy.optional(),mergeIntoId:Kn.nullable().optional()});l({profileId:Kn,sourceIds:f(Kn).max(1e5).default([]),sessionIds:f(Kn).max(1e5).default([]),config:Ac.optional()});const eM=l({schemaVersion:k("openpond.taskMinerRun.v1"),id:Kn,profileId:Kn,status:b(["queued","running","cancelling","cancelled","succeeded","failed"]),config:Ac,sourceIds:f(Kn).max(1e5),sessionIds:f(Kn).max(1e5).default([]),progress:l({stage:b(["queued","ingesting","preparing","clustering","persisting","complete"]),processedSources:c().int().nonnegative(),totalSources:c().int().nonnegative(),candidatesFound:c().int().nonnegative(),skippedSources:c().int().nonnegative().default(0)}),candidateIds:f(Kn).max(1e5),cancelRequested:C(),error:o().trim().min(1).max(2e4).nullable(),createdAt:Co,startedAt:Co.nullable(),completedAt:Co.nullable(),updatedAt:Co}),ua=o().trim().min(1).max(240),uo=o().trim().min(1),Eo=o().trim().min(8).max(256),xy=o().trim().min(1).max(1e3).refine(e=>!e.startsWith("/")&&!e.startsWith("\\")&&!e.split(/[\\/]/).includes(".."),"Artifact paths must be relative and stay inside the Dataset."),No=b(["train","validation","test","frozen_eval"]),tM=l({name:o().trim().min(1).max(500),semanticRole:b(["row_id","cluster_id","prompt","messages","demonstration","chosen","rejected","expected_output","privileged_context","reward","feedback","tag","metadata"]),logicalType:b(["string","integer","float","boolean","json","messages"]),nullable:C(),policy:b(["visible","privileged","metadata"])}),nM=l({schemaVersion:k("openpond.datasetSemanticSchema.v1"),fields:f(tM).min(1).max(1e4),schemaHash:Eo}),aM=l({id:ua,split:No,path:xy,contentHash:Eo,schemaHash:Eo,sizeBytes:c().int().nonnegative(),rowCount:c().int().positive(),rowGroupCount:c().int().positive()}),Bp=l({schemaVersion:k("openpond.datasetArtifact.v1"),id:ua,tasksetId:ua,tasksetRevision:c().int().positive(),contentHash:Eo,format:k("parquet"),schema:nM,shards:f(aM).min(1).max(1e5),rowCount:c().int().positive(),splitCounts:fe(No,c().int().nonnegative()),sourceReceiptRefs:f(ua).min(1).max(1e5),mappingHash:Eo,qualityReportHash:Eo,createdAt:uo}),oM=l({schemaVersion:k("openpond.datasetArtifactSummary.v1"),artifactId:ua,tasksetId:ua,tasksetRevision:c().int().positive(),format:k("parquet"),rowCount:c().int().positive(),splitCounts:fe(No,c().int().nonnegative()),sizeBytes:c().int().nonnegative(),contentHash:Eo,available:C(),unavailableReason:o().trim().min(1).max(2e3).nullable(),createdAt:uo}),iM=l({schemaVersion:k("openpond.datasetCatalogItem.v1"),tasksetId:ua,tasksetRevision:c().int().positive(),artifactId:ua.nullable(),name:o().trim().min(1).max(500),status:b(["draft","awaiting_disclosure_approval","awaiting_materialization_approval","materializing","validating","needs_review","baselining","ready","blocked","failed","archived"]),storageKind:b(["inline","parquet"]),rowCount:c().int().nonnegative(),splitCounts:fe(No,c().int().nonnegative()),sizeBytes:c().int().nonnegative().nullable(),available:C(),unavailableReason:o().trim().min(1).max(2e3).nullable(),createdAt:uo,updatedAt:uo});l({schemaVersion:k("openpond.datasetCatalog.v1"),profileId:ua,datasets:f(iM),generatedAt:uo});l({schemaVersion:k("openpond.datasetArtifactRegistry.v1"),manifest:Bp,profileId:ua,storageRoot:o().trim().min(1).max(4e3),relativeManifestPath:xy,available:C(),unavailableReason:o().trim().min(1).max(2e3).nullable(),verifiedAt:uo.nullable(),createdAt:uo,updatedAt:uo});l({split:No.nullable().default(null),cursor:o().trim().min(1).max(2e3).nullable().default(null),limit:c().int().min(1).max(100).default(25),columns:f(o().trim().min(1).max(500)).max(100).default([])});l({schemaVersion:k("openpond.datasetRowPage.v1"),tasksetId:ua,tasksetRevision:c().int().positive(),artifactHash:Eo,split:No.nullable(),rows:f(fe(o(),ye())).max(100),nextCursor:o().max(2e3).nullable(),totalRows:c().int().nonnegative(),returnedRows:c().int().nonnegative()});const rM=l({schemaVersion:k("openpond.datasetStorageSettings.v1"),datasetStorePath:o().trim().min(1).max(4e3),updatedAt:uo}),sM=l({id:ua,label:o().trim().min(1).max(500),path:o().trim().min(1).max(4e3),datasetStorePath:o().trim().min(1).max(4e3),kind:b(["local","network","removable","cache"]),configured:C(),mounted:C(),writable:C(),totalBytes:c().int().nonnegative().nullable(),freeBytes:c().int().nonnegative().nullable()});l({schemaVersion:k("openpond.datasetStorageState.v1"),settings:rM,storageRoots:f(sM)});l({datasetStorePath:o().trim().min(1).max(4e3)});const Cm=o().trim().min(1).max(240),lM=o().trim().min(1),Pc=o().trim().min(8).max(256),cM=fe(o(),ye()).default({}),dM=o().trim().min(7).max(256),uM=b(["pending","approved","review","blocked"]),Fp=l({id:Cm,profileId:Cm,title:o().trim().min(1).max(500),sourceHash:Pc,occurredAt:lM,licensingStatus:uM,secretScanStatus:b(["pending","passed","blocked"]),piiScanStatus:b(["pending","passed","review","blocked"]),metadata:cM}),mM=Fp.extend({schemaVersion:k("openpond.huggingFaceDatasetSource.v1"),kind:k("huggingface"),repositoryId:o().trim().regex(/^[^/\s]+\/[^/\s]+$/).max(500),repositoryUrl:o().url().max(2e3),revision:dM,configuration:o().trim().min(1).max(500),upstreamSplits:f(o().trim().min(1).max(500)).min(1).max(1e3),gated:C(),private:C(),declaredLicense:o().trim().min(1).max(500).nullable(),sourceFileHashes:f(Pc).min(1).max(1e5)}),pM=Fp.extend({schemaVersion:k("openpond.uploadedFileDatasetSource.v1"),kind:k("uploaded_file"),originalFileNames:f(o().trim().min(1).max(500)).min(1).max(1e3),mediaTypes:f(o().trim().min(1).max(200)).min(1).max(1e3),sourceFileHashes:f(Pc).min(1).max(1e3),totalBytes:c().int().nonnegative(),parserVersion:o().trim().min(1).max(200)}),fM=Fp.extend({schemaVersion:k("openpond.generatedDatasetSource.v1"),kind:k("generated"),generatorId:Cm,generatorVersion:o().trim().min(1).max(200),seed:c().int(),generatorHash:Pc}),hM=Kt("kind",[mM,pM,fM]),L=o().trim().min(1).max(240),Me=o().regex(/^[a-f0-9]{64}$/),ct=o().datetime({offset:!0}),Ye=l({id:L,contentHash:Me}).strict(),Qt=Ye.extend({revision:c().int().positive()}).strict(),gM=l({id:L,purpose:o().trim().min(1).max(500),audience:b(["orchestrator","environment","privileged_scorer","trainer","infrastructure"]),required:C(),ttlSeconds:c().int().positive().max(86400),scopes:f(o().trim().min(1).max(500)).max(100).default([])}).strict(),bM=l({declarationId:L,leaseRef:o().trim().min(8).max(1e3),audience:gM.shape.audience,expiresAt:ct}).strict(),vM=l({schemaVersion:k("openpond.harnessActionBinding.v1"),actionId:L,modelToolName:o().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:o().trim().min(1).max(1e3),inputSchema:fe(o(),ye()),actionSchemaHash:Me,agentRelease:Ye,implementationHash:Me,runtimeBindingId:L,capabilityReceiptHash:Me,sideEffect:b(["read","write"]),studentVisible:C(),timeoutMs:c().int().positive().max(36e5),episodeArgumentBindings:f(l({argument:L,source:k("case_id")}).strict()).max(20).default([])}).strict(),Be=o().trim().min(1).max(240),en=o().trim().min(1),Ia=o().trim().min(8).max(256),Tc=o().trim().regex(/^[a-f0-9]{64}$/),ky=o().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),Pn=fe(o(),ye()).default({}),Dn=Be.nullable();function kr(e){const t=e.trim().replaceAll("\\","/");return!t||t.startsWith("/")||t==="."||t===".."?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function yM(e){const t=e.trim();return t.length>0&&t!=="."&&t!==".."&&!t.includes("/")&&!t.includes("\\")&&!t.includes("\0")}const lr=No,SM=b(["draft","awaiting_disclosure_approval","awaiting_materialization_approval","materializing","validating","needs_review","baselining","ready","blocked","failed","archived"]),_y=b(["general","benchmark"]),wy=l({schemaVersion:k("openpond.tasksetBenchmark.v1"),definitionId:Be,releaseId:Be,releaseHash:Tc,managedReleasePath:o().trim().min(1).max(1e3).refine(kr,"Benchmark release paths must remain relative."),adaptationSplit:lr,evaluationSplit:lr,primaryMetric:b(["foreground_tokens","success_rate","latency_ms","cost_usd"]),qualityGate:b(["none","non_regression","all_pass"]),source:b(["builtin","imported"]),metadata:Pn}),Iy=l({schemaVersion:k("openpond.tasksetPreferenceComparisonBinding.v1"),releaseId:Be,releaseHash:Tc,publishedAt:en,metadata:Pn}),xM=b(["slash_train","session_menu","bulk_selection","training_page","task_candidate"]),kM=b(["defaults","customize"]),_M=b(["automated","manual"]),Cy=b(["demonstrations","preferences","verifiable_reward","rubric","discovery"]),jn=o().trim().max(1e5),Ry=Kt("kind",[l({kind:k("demonstrations"),behavior:jn,examples:f(l({id:Be,prompt:jn,response:jn})).max(1e3).default([])}),l({kind:k("preferences"),preference:jn,pairs:f(l({id:Be,prompt:jn,chosen:jn,rejected:jn,rationale:jn})).max(1e3).default([])}),l({kind:k("verifiable_reward"),task:jn,rules:f(l({id:Be,points:c().finite(),condition:jn})).max(1e3).default([]),otherwisePoints:c().finite().default(0)}),l({kind:k("rubric"),task:jn,criteria:f(l({id:Be,label:o().trim().max(500),description:jn})).max(1e3).default([]),positiveExample:jn,negativeExample:jn,boundaryExample:jn})]),wM=l({status:b(["pending","granted","denied","revoked"]),scope:b(["metadata_only","selected_turns","full_session"]),grantedBy:Dn,grantedAt:en.nullable(),purpose:k("task_authoring_and_evaluation")}),Ay=l({schemaVersion:k("openpond.trainingSource.v1"),id:Be,profileId:Be,sessionId:Be,turnIds:f(Be).max(1e3).default([]),workspaceId:Dn,sourceHash:Ia,clusterKey:Be,title:o().trim().min(1).max(500),occurredAt:en,consent:wM,connectedAppIds:f(Be).max(100).default([]),secretScanStatus:b(["pending","passed","blocked"]),piiScanStatus:b(["pending","passed","review","blocked"]),licensingStatus:b(["pending","approved","review","blocked"]),metadata:Pn}),Py=mn([Ay,hM]);l({schemaVersion:k("openpond.trainingSourceEstimate.v1"),sessionId:Be,messageCount:c().int().nonnegative(),estimatedTokens:c().int().nonnegative(),textBytes:c().int().nonnegative()});l({query:o().max(500).default(""),offset:c().int().nonnegative().default(0),limit:c().int().min(1).max(100).default(20),candidates:f(l({sessionId:Be,title:o().trim().min(1).max(500),updatedAt:en})).max(500).default([])});const IM=l({sessionId:Be,title:o().trim().min(1).max(500),updatedAt:en,snippet:o().max(2e3).nullable()});l({schemaVersion:k("openpond.trainingChatSearchResult.v1"),query:o(),offset:c().int().nonnegative(),limit:c().int().positive(),total:c().int().nonnegative(),hasMore:C(),indexedChats:c().int().nonnegative(),totalChats:c().int().nonnegative(),indexing:C(),entries:f(IM)});const Vp=l({policyVisibleFields:f(Be).max(1e3).default([]),privilegedFields:f(Be).max(1e3).default([]),hiddenGraderRefs:f(Be).max(100).default([]),connectedAppScopes:f(Be).max(100).default([])}),CM=l({id:Be,sourceRefId:Be,artifactRef:o().trim().min(1).max(4e3).refine(kr,"Task asset references must be safe relative paths."),fileName:o().trim().min(1).max(500).refine(yM,"Task asset file names must not contain path separators."),mediaType:o().trim().min(1).max(200),sha256:Tc,sizeBytes:c().int().nonnegative().max(25e7),split:lr,metadata:Pn}),RM=l({path:o().trim().min(1).max(1e3).refine(kr,"Required output paths must stay inside the Work output directory."),mediaType:o().trim().min(1).max(200),schemaRef:Be.nullable().optional(),maxBytes:c().int().positive().max(1e7).optional(),metadata:Pn}),Ty=l({schemaVersion:k("openpond.taskData.v1"),id:Be,clusterKey:Be,split:lr,input:fe(o(),ye()),expectedOutput:fe(o(),ye()).nullable(),policyVisibleContext:fe(o(),ye()).default({}),privilegedContextRef:Dn,sourceRefs:f(Be).min(1).max(100),assets:f(CM).max(1e3).optional(),resourceRefs:f(Be).max(1e3).optional(),requiredOutputs:f(RM).max(100).optional(),tags:f(Be).max(100).default([]),metadata:Pn}),AM=l({id:Be,kind:b(["file","catalog","configuration","code_module"]),path:o().trim().min(1).max(1e3).refine(kr,"Environment resource paths must remain relative."),mediaType:o().trim().min(1).max(200).nullable().optional(),visibility:b(["policy_visible","policy_hidden","privileged"]),required:C(),metadata:Pn}),_r=l({id:Be,taskId:Dn,sourceRefs:f(Be).min(1).max(100),artifactRef:Be,approved:C(),confidence:c().min(0).max(1),metadata:Pn}),Ey=_r.extend({kind:k("demonstration"),prompt:o().max(1e5).nullable().default(null),response:o().max(2e5).nullable().default(null)}),My=_r.extend({kind:k("preference"),prompt:o().max(1e5),chosen:o().max(2e5),rejected:o().max(2e5),rationale:o().max(1e5).nullable().default(null)}),jy=_r.extend({kind:k("correction"),original:o().max(2e5),corrected:o().max(2e5),rationale:o().max(1e5).nullable().default(null)}),Oy=_r.extend({kind:k("feedback"),feedback:o().max(1e5),polarity:b(["positive","negative","mixed","neutral"])}),Ny=_r.extend({kind:k("reward"),task:o().max(1e5),rules:f(l({id:Be,points:c().finite(),condition:o().trim().min(1).max(1e5)})).min(1).max(1e3),otherwisePoints:c().finite(),executable:C()}),$y=_r.extend({kind:k("label"),labelKind:k("rubric"),task:o().max(1e5),criteria:f(l({id:Be,label:o().trim().min(1).max(500),description:o().trim().min(1).max(1e5)})).min(1).max(1e3),calibrationExamples:l({positive:o().trim().min(1).max(2e5),negative:o().trim().min(1).max(2e5),boundary:o().trim().min(1).max(2e5)})});Kt("kind",[Ey,My,jy,Oy,Ny,$y]);const Dy=l({demonstrations:f(Ey).max(1e5).default([]),preferences:f(My).max(1e5).default([]),corrections:f(jy).max(1e5).default([]),feedback:f(Oy).max(1e5).default([]),rewards:f(Ny).max(1e5).default([]),labels:f($y).max(1e5).default([])}),Ly=l({protocolVersion:k("openpond.taskEnvironment.v1"),kind:b(["chat","agent","program","stateful_harness","work"]),entrypoint:o().trim().min(1).max(1e3),stateful:C(),deterministicSeeds:C(),toolNames:f(Be).max(200).default([]),actionBindings:f(vM).max(200).optional(),lifecycle:f(b(["create","reset","step","grade","cleanup"])).min(1),defaultTimeoutMs:c().int().positive().max(36e5),networkPolicy:b(["none","declared_read_only","declared_scoped"]),resources:f(AM).max(1e4).optional(),metadata:Pn}),Wp=l({schemaVersion:k("openpond.tasksetCapabilities.v1"),taskKind:b(["chat","single_agent","multi_agent","custom_program"]),supportedSignals:f(b(["demonstration","preference","correction","feedback","reward","label"])),compatibleMethods:f(b(["none","retrieval","sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"])),rewardKinds:f(b(["none","exact","deterministic","model_judge","human"])),requiresTools:C(),requiresState:C(),requiresPrivilegedGrading:C(),environmentPlacements:f(b(["local","remote","colocated","provider_native"])),exportable:C(),portabilityBlockers:f(o().trim().min(1).max(2e3)).default([])}),zy=l({schemaVersion:k("openpond.tasksetMetricPolicy.v1"),primaryMetric:Be,aggregation:b(["mean_score","pass_rate","weighted_mean","custom"]),missingReward:b(["zero","exclude"]),customAggregator:l({module:o().trim().min(1).max(1e3).refine(kr,"Custom metric modules must use a safe relative path."),exportName:ky,contentHash:Tc,timeoutMs:c().int().positive().max(3e5),networkPolicy:k("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"]})}),Kp=b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]),Ec=l({id:Be,version:o().trim().min(1).max(100),label:o().trim().min(1).max(500),weight:c().min(0).max(1e3).default(1),hardGate:C().default(!1),rewardEligible:C().default(!1),privileged:C().default(!1),metadata:Pn}),PM=Ec.extend({kind:b(["content","schema","file","diff","test","runtime_event","state"]),config:fe(o(),ye())}),TM=Ec.extend({kind:k("model_judge"),rubric:o().trim().min(1).max(5e4),judge:Jt,calibrationFixtureRefs:f(Be).min(1).max(500),calibrationStatus:b(["pending","passed","failed"]),temperature:c().min(0).max(2).default(0)}),EM=Ec.extend({kind:k("human"),rubric:o().trim().min(1).max(5e4),reviewerRole:o().trim().min(1).max(500)}),MM=Ec.extend({kind:k("custom_verifier"),module:o().trim().min(1).max(1e3).refine(kr,"Custom verifier modules must use a safe relative path."),exportName:ky,timeoutMs:c().int().positive().max(3e5),networkPolicy:k("none")}),Mc=mn([PM,TM,EM,MM]),jM=l({graderId:Be.nullable(),path:o().trim().min(1).max(1e3),language:b(["javascript","typescript","python","json","text"]),content:o().max(2e6),sha256:Ia,declaredSha256:Ia.nullable(),integrity:b(["verified","unverified","mismatch"])}),OM=l({protocolVersion:o().trim().min(1).max(200),module:o().trim().min(1).max(1e3),moduleSha256:Ia,command:f(o().max(2e3)).max(100),cwd:o().trim().min(1).max(4e3),maxTurns:c().int().positive().max(100)});l({schemaVersion:k("openpond.tasksetGraderDetails.v1"),taskset:Qt,sourceTasksetId:Be,graders:f(Mc).max(1e3),runtime:OM.nullable(),sources:f(jM).max(1e3),unavailableReason:o().max(2e3).nullable()});const Gp=b(["positive","negative","boundary","adversarial","prompt_injection","infrastructure_failure"]),Uy=l({id:Be,taskId:Be,label:Gp,output:fe(o(),ye()),infrastructureError:o().trim().min(1).max(1e4).nullable(),expectedPassed:C(),expectedRewardEligible:C(),metadata:Pn}),NM=l({id:Be,taskIndex:c().int().nonnegative(),label:Gp,output:fe(o(),ye()),infrastructureError:o().trim().min(1).max(1e4).nullable(),expectedPassed:C(),expectedRewardEligible:C(),metadata:Pn}),$M=l({path:o().trim().min(1).max(1e3),role:b(["environment","verifier","fixture"]),content:o().max(25e4)}),DM=l({schemaVersion:k("openpond.taskAttempt.v1"),id:Be,tasksetId:Be,taskId:Be,split:lr,attempt:c().int().nonnegative(),seed:c().int(),modelRef:Jt.nullable(),startedAt:en,completedAt:en,output:fe(o(),ye()),runtimeEventRefs:f(Be).max(1e4).default([]),artifactRefs:f(Be).max(1e4).default([]),privilegedOutcomeRef:Dn,infrastructureError:o().trim().min(1).max(1e4).nullable(),costUsd:c().nonnegative().nullable(),latencyMs:c().int().nonnegative(),userInterventions:c().int().nonnegative().default(0),metadata:Pn}),LM=l({schemaVersion:k("openpond.taskAttemptArtifact.v1"),id:Be,tasksetId:Be,taskId:Be,attemptId:Be,kind:b(["raw_model_response","runtime_trace","environment_state","grader_evidence","output_artifact"]),path:o().trim().min(1).max(4e3),mediaType:o().trim().min(1).max(200).nullable().optional(),sha256:Ia,sizeBytes:c().int().nonnegative(),createdAt:en,metadata:Pn}),zM=l({graderId:Be,graderVersion:o().trim().min(1).max(100),score:c().min(0).max(1),passed:C(),hardGate:C(),rewardEligible:C(),feedback:o().trim().max(2e4).nullable(),evidenceRefs:f(Be).max(1e4).default([]),judge:Jt.nullable().optional().default(null),calibrationStatus:b(["not_applicable","pending","passed","failed"])}),UM=l({schemaVersion:k("openpond.gradeResult.v1"),id:Be,attemptId:Be,graderSetHash:Ia,score:c().min(0).max(1).nullable(),passed:C(),components:f(zM).min(1).max(1e3),failureClass:Kp.nullable(),feedback:f(o().trim().min(1).max(2e4)).max(1e3).default([]),rewardEligible:C(),createdAt:en});b(["stable_hash_top_n","rft_easy_curriculum_v1"]);const HM=l({schemaVersion:k("openpond.graderAuditReport.v1"),id:Be,tasksetId:Be,tasksetHash:Ia,fixtureRefs:f(Be).min(1).max(1e5),gradeRefs:f(Be).min(1).max(1e5),passed:C(),hackingChecksPassed:C(),leakageChecksPassed:C(),infrastructureSafetyPassed:C(),failures:f(l({fixtureId:Be,label:Gp,gradeId:Be,reason:o().trim().min(1).max(5e3)})).max(1e5),createdAt:en}),Hy=l({primaryMethod:b(["sft","dpo","grpo","ppo","sdft","opsd","sdpo"]),bootstrap:l({method:k("sft"),purpose:k("trajectory_bootstrap"),demonstrationRefs:f(Be).min(1).max(1e5),limitations:f(o().trim().min(1).max(5e3)).min(1).max(100)}).nullable()}),qy=b(["taskset_not_ready","demonstrations_missing","preference_pairs_missing","preference_pairs_invalid","executable_reward_missing","reward_not_calibrated","reward_model_missing","value_model_required","frozen_eval_missing"]),qM=l({method:b(["sft","dpo","grpo","ppo"]),status:b(["recommended","compatible","needs_dataset_work"]),reasonCodes:f(qy).default([]),reasons:f(o().trim().min(1).max(5e3)).default([])}),Jh=l({code:Be,message:o().trim().min(1).max(5e3),path:o().trim().max(2e3).nullable()}),By=l({schemaVersion:k("openpond.tasksetReadiness.v1"),tasksetId:Be,tasksetHash:Ia,ready:C(),recommendedMethod:b(["none","retrieval","sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),trainingPath:Hy.nullable().default(null),methodReadiness:f(qM).default([]),compatibleDestinationClasses:f(b(["export","custom","hosted_managed"])),blockers:f(Jh).default([]),advisories:f(Jh).default([]),warnings:f(o().trim().min(1).max(5e3)).default([]),generatedAt:en}),BM=l({schemaVersion:k("openpond.capabilityDiagnosis.v1"),summary:o().trim().min(1).max(1e4),stableBehavior:f(o().trim().min(1).max(5e3)).max(100).default([]),changingKnowledge:f(o().trim().min(1).max(5e3)).max(100).default([]),requiredContext:f(o().trim().min(1).max(5e3)).max(100).default([]),requiredTools:f(Be).max(100).default([]),intervention:yy,trainingEligible:C(),rationale:f(o().trim().min(1).max(5e3)).min(1).max(100),confidence:c().min(0).max(1)}),FM=l({id:Be,sourceId:Be,sourceTurnId:Dn,split:lr,origin:b(["extracted","corrected","synthetic","expert_authored"]),inputPrompt:o().trim().min(1).max(1e5),expectedOutputText:o().trim().min(1).max(2e5).nullable(),rationale:o().trim().min(1).max(5e3)}),Fy=l({attempt:c().int().positive(),summary:o().trim().min(1).max(5e3),createdAt:en}),VM=l({schemaVersion:k("openpond.taskAuthoringProvenance.v1"),model:Jt.nullable(),modelConfig:Pn,skillHash:Ia,promptTemplateVersion:o().trim().min(1).max(200),buildIntent:Cy.default("demonstrations"),buildSpecification:Ry.nullable().default(null),evidenceHashes:f(Ia).max(1e5),tasksetSdkVersion:o().trim().min(1).max(100),sourceCommit:o().trim().min(1).max(256).nullable(),repairHistory:f(Fy).max(1e3),createdAt:en}),Yh=l({schemaVersion:k("openpond.taskset.v1"),id:Be,revision:c().int().positive().default(1),profileId:Be,profileRelease:Qt.nullable().optional(),createImproveRunId:Dn.default(null),name:o().trim().min(1).max(500),objective:o().trim().min(1).max(2e4),purpose:_y.default("general"),benchmark:wy.nullable().default(null),preferenceComparison:Iy.nullable().default(null),status:SM,sourceRefs:f(Py).min(1).max(1e5),datasetArtifact:Bp.nullable().optional(),policy:Vp,environment:Ly,capabilities:Wp,metrics:zy.optional(),tasks:f(Ty).max(1e6),graders:f(Mc).min(1).max(1e3),graderFixtures:f(Uy).min(1).max(1e5),learningSignals:Dy,authoringProvenance:VM,readiness:By.nullable(),contentHash:Ia,createdAt:en,updatedAt:en,metadata:Pn}).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"]})}),WM=l({schemaVersion:k("openpond.taskDesignProposal.v1"),id:Be,name:o().trim().min(1).max(500),objective:o().trim().min(1).max(2e4),diagnosis:BM.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:Wp.shape.taskKind,sourceIds:f(Be).min(1).max(1e5),assumptions:f(o().trim().min(1).max(5e3)).max(1e3),successCriteria:f(o().trim().min(1).max(5e3)).min(1).max(1e3),proposedGraders:f(Mc).max(1e3).default([]),graderFixtures:f(NM).max(1e5).default([]),generatedFiles:f($M).max(1e3).default([]),proposedExamples:f(FM).max(1e5).default([]),proposedMethod:By.shape.recommendedMethod,trainingPath:Hy.nullable().default(null),policy:Vp,warnings:f(o().trim().min(1).max(5e3)).default([]),createdAt:en}),KM=5;function nW(e,t="New model"){const n=e?.trim().split(/\s+/).filter(Boolean)??[];return n.length===0?t:n.slice(0,KM).join(" ")}const Gs=l({schemaVersion:k("openpond.baseModelPreference.v1"),modelId:Be,revision:o().trim().min(1).max(256).nullable(),tokenizerRevision:o().trim().min(1).max(256).nullable(),chatTemplateHash:o().trim().min(8).max(256).nullable(),modelAssetId:Dn,source:b(["managed","local","builtin"])}),GM=l({schemaVersion:k("openpond.taskCreationRequest.v1"),id:Be,profileId:Be,surface:xM,mode:kM,entryMode:_M.default("manual"),resourceIntent:b(["workproduct","dataset"]).default("workproduct"),buildIntent:Cy.default("demonstrations"),buildSpecification:Ry.nullable().default(null),objective:o().trim().min(1).max(2e4).nullable(),methodHint:b(["sft","dpo","grpo","ppo"]).nullable().default(null),preferredBaseModelId:Be.nullable().default(null),preferredBaseModel:Gs.nullable().default(null),sourceIds:f(Be).max(1e5),candidateId:Dn,analysisModel:Jt.nullable(),analysisReasoningEffort:Ic.nullable().default(null),createImproveRunId:Dn.default(null),targetIntent:l({kind:b(["agent","skill","extension","model","configuration"]).nullable(),id:Dn,displayName:o().trim().min(1).max(500).nullable(),operation:b(["create","improve"])}).default({kind:"model",id:null,displayName:null,operation:"create"}),disclosure:l({status:b(["not_required","pending","approved","declined"]),content:k("raw_excerpts"),sourceIds:f(Be).max(1e5),providerModel:Jt.nullable(),approvalId:Dn,approvedAt:en.nullable()}).default({status:"not_required",content:"raw_excerpts",sourceIds:[],providerModel:null,approvalId:null,approvedAt:null}),createdAt:en}),Vy=l({schemaVersion:k("openpond.taskCreationSnapshot.v1"),id:Be,request:GM,state:b(["planning","awaiting_disclosure_approval","awaiting_questions","recommendation_ready","awaiting_materialization_approval","materializing","validating","ready","blocked","failed","cancelled"]),proposal:WM.nullable(),materializedTasksetId:Dn,disclosureApprovalId:Dn,materializationApprovalId:Dn,blockingQuestions:f(l({id:Be,kind:b(["objective","consent","success_signal","privacy_licensing","interpretation"]),prompt:o().trim().min(1).max(5e3),answer:o().trim().min(1).max(2e4).nullable()})).default([]),transcript:f(l({id:Be,role:b(["user","assistant","system","tool"]),text:o().max(1e5),createdAt:en})).max(1e4).default([]),repairHistory:f(Fy).max(1e3).default([]),blockedReason:o().trim().min(1).max(1e4).nullable(),createdAt:en,updatedAt:en});l({schemaVersion:k("openpond.taskCreationTranscript.v1"),creationId:Be,profileId:Be,messages:Vy.shape.transcript,updatedAt:en});function ZM(e){return e.schemaVersion==="openpond.trainingSource.v1"}const _s=o().trim().min(1).max(240),Xh=o().trim().min(1),JM=o().trim().min(8).max(256),YM=o().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),XM=fe(o(),ye()).default({});function Qh(e){const t=e.trim().replaceAll("\\","/");return!t||t.startsWith("/")||t==="."||t===".."?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}const QM=Ty.extend({sourceRefs:f(_s).max(100).default([])}),ej=b(["draft","validating","needs_review","published"]),tj=l({enabled:C(),candidateCount:c().int().min(2).max(4),minimumSamples:c().int().min(1).max(1e4).default(100),allowTies:C(),allowRejectAll:C(),rubric:o().trim().max(5e4),criteria:f(l({id:_s,label:o().trim().min(1).max(500),description:o().trim().max(1e4),weight:c().nonnegative().max(1e3)})).max(100)}),nj=l({mode:b(["text","structured_json","artifacts"]),jsonSchema:fe(o(),ye()).nullable(),renderer:l({module:o().trim().min(1).max(1e3).refine(Qh,"Renderer modules must use a safe relative path."),exportName:YM,configRef:o().trim().min(1).max(1e3).refine(Qh,"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"]})}),aj=l({schemaVersion:k("openpond.tasksetDraft.v1"),id:_s,revision:c().int().positive(),profileId:_s,name:o().trim().max(500),objective:o().trim().max(2e4),purpose:_y.default("general"),benchmark:wy.nullable().default(null),preferenceComparison:Iy.nullable().default(null),status:ej,sourceRefs:f(Py).max(1e5).default([]),datasetArtifact:Bp.nullable().optional(),policy:Vp,environment:Ly,output:nj.default({mode:"text",jsonSchema:null,renderer:null}),capabilities:Wp,metrics:zy,review:tj,tasks:f(QM).max(1e6).default([]),graders:f(Mc).max(1e3).default([]),graderFixtures:f(Uy).max(1e5).default([]),learningSignals:Dy,publishedTasksetRef:l({id:_s,revision:c().int().positive(),contentHash:JM}).nullable(),createdAt:Xh,updatedAt:Xh,metadata:XM}).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"]})}),Zi=o().trim().min(1).max(240),Hl=o().trim().min(1),Rm=o().trim().min(8).max(256),Wy=fe(o(),ye()).default({}),oj=b(["created","inspecting","awaiting_source_review","awaiting_mapping","awaiting_materialization_approval","materializing","validating","ready","cancelling","cancelled","failed"]),Ky=l({schemaVersion:k("openpond.huggingFaceDatasetLocator.v1"),repositoryId:o().trim().regex(/^[^/\s]+\/[^/\s]+$/).max(500),repositoryUrl:o().url().max(2e3),requestedRevision:o().trim().min(1).max(256).nullable()}),ij=l({path:o().trim().min(1).max(1e3),logicalType:o().trim().min(1).max(500),nullable:C(),sampleValues:f(ye()).max(5)}),rj=l({configuration:o().trim().min(1).max(500),split:o().trim().min(1).max(500),rowCount:c().int().nonnegative().nullable(),sizeBytes:c().int().nonnegative().nullable()}),sj=l({schemaVersion:k("openpond.huggingFaceDatasetInspection.v1"),id:Zi,locator:Ky,resolvedRevision:o().trim().min(7).max(256),title:o().trim().min(1).max(500),description:o().max(2e4).nullable(),declaredLicense:o().trim().min(1).max(500).nullable(),gated:C(),private:C(),configurations:f(o().trim().min(1).max(500)).min(1).max(1e3),splits:f(rj).min(1).max(1e4),columns:f(ij).min(1).max(1e4),previewRows:f(fe(o(),ye())).max(25),sourceFiles:f(l({path:o().trim().min(1).max(2e3),configuration:o().trim().min(1).max(500),split:o().trim().min(1).max(500),revision:o().trim().min(7).max(256),sizeBytes:c().int().nonnegative().nullable(),contentHash:Rm.nullable()})).max(1e5),inspectedAt:Hl,metadata:Wy}),lj=b(["row_id","cluster_id","prompt","messages","demonstration","chosen","rejected","expected_output","privileged_context","reward","feedback","tag","metadata"]),cj=l({sourcePath:o().trim().min(1).max(1e3),target:lj,transform:b(["identity","string","json","messages","numeric","math_final_answer"]),policy:b(["visible","privileged","metadata"]),required:C()}),Gy=l({schemaVersion:k("openpond.datasetImportMapping.v1"),sourceSchemaHash:Rm,configuration:o().trim().min(1).max(500),upstreamSplits:f(o().trim().min(1).max(500)).min(1).max(1e3),preset:b(["prompt_only","prompt_completion","messages","preference","prompt_expected_answer","prompt_privileged_solution","prompt_feedback"]),bindings:f(cj).min(1).max(1e4),nullPolicy:b(["reject","drop","preserve"]),invalidRowPolicy:b(["reject_import","drop_with_receipt"]),splitPolicy:l({seed:c().int(),assignments:fe(o(),No),validationPercent:c().min(0).max(100),frozenEvalPercent:c().min(0).max(100)}),importerVersion:o().trim().min(1).max(200),mappingHash:Rm}),dj=l({phase:b(["idle","metadata","download","mapping","parquet_write","verification","publish"]),completedBytes:c().int().nonnegative(),totalBytes:c().int().nonnegative().nullable(),completedRows:c().int().nonnegative(),totalRows:c().int().nonnegative().nullable(),message:o().trim().min(1).max(2e3).nullable()}),uj=l({schemaVersion:k("openpond.datasetImportJob.v1"),id:Zi,profileId:Zi,sourceKind:b(["huggingface","uploaded_file"]),status:oj,locator:Ky.nullable(),inspection:sj.nullable(),mapping:Gy.nullable(),progress:dj,targetStorageRoot:o().trim().min(1).max(4e3).nullable(),tasksetId:Zi.nullable(),tasksetRevision:c().int().positive().nullable(),artifactId:Zi.nullable(),error:o().trim().min(1).max(2e4).nullable(),cancellationRequested:C(),createdAt:Hl,updatedAt:Hl,completedAt:Hl.nullable(),metadata:Wy});l({profileId:Zi,url:o().trim().min(1).max(2e3)});l({name:o().trim().min(1).max(500),objective:o().trim().min(1).max(2e4),mapping:Gy,targetStorageRoot:o().trim().min(1).max(4e3).nullable(),licenseApproved:C().default(!1)});var Gt=o().trim().min(1).max(500),cr=o().regex(/^[a-f0-9]{64}$/),ka=o().datetime({offset:!0}),nc=l({id:Gt,contentHash:cr}).strict(),mj=nc.extend({revision:c().int().positive()}).strict(),jc=l({schemaVersion:k("openpond.baseModelPreference.v1"),modelId:Gt,revision:o().trim().min(1).max(256).nullable(),tokenizerRevision:o().trim().min(1).max(256).nullable(),chatTemplateHash:o().trim().min(8).max(256).nullable(),modelAssetId:Gt.nullable(),source:b(["managed","local","builtin"])}).strict(),Zy=b(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),pj=l({schemaVersion:o().regex(/^openpond\.[A-Za-z0-9]+Recipe\.v\d+$/),method:Zy,parameterization:b(["lora","full"])}).catchall(ye()),Jy=l({tasksetRef:mj.nullable().default(null),tasksetRelease:nc.nullable().default(null),harnessRelease:nc.nullable().default(null),baseModel:jc.nullable().default(null),method:Zy.nullable().default(null),destinationId:Gt.nullable().default(null),managedRolloutPlacement:b(["local","remote"]).default("remote"),managedGpuPlacementObjective:b(["fast","balanced","economical"]).default("balanced"),managedGpuRequirement:b(["any","h100_hbm3"]).default("any"),runPreset:b(["small","standard","custom","small_experiment"]).nullable().default(null),recipe:pj.nullable().default(null),preferredMaximumSpendUsd:c().nonnegative().nullable().default(null),preferredRetentionDays:c().int().nonnegative().nullable().default(null)}).strict(),Yy=Jy.omit({managedGpuRequirement:!0}),fj=l({schemaVersion:k("openpond.hostedModelProjectLink.v1"),teamId:Gt,projectId:Gt,portableProjectId:Gt,revision:c().int().positive(),etag:cr,syncedSourceRevision:c().int().positive(),syncedAt:ka,tasksets:f(l({localTasksetId:Gt,releaseId:Gt,releaseRevision:c().int().positive(),releaseHash:cr,hostedTasksetId:Gt,syncedAt:ka}).strict()).max(1e4).default([])}).strict(),hj=l({localTasksetId:Gt,releaseId:Gt,releaseRevision:c().int().positive(),releaseHash:cr,state:b(["syncing","synced","sync_failed"]),hostedTasksetId:Gt.nullable().default(null),lastAttemptAt:ka,syncedAt:ka.nullable().default(null),lastError:o().trim().min(1).max(5e3).nullable().default(null)}).strict(),gj=l({schemaVersion:k("openpond.modelProject.v2"),id:Gt,profileId:Gt,revision:c().int().positive().default(1),name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:jc.nullable(),defaultDestinationId:Gt.nullable(),trainingSetup:Jy,hosted:fj.nullable().default(null),tasksetSyncs:f(hj).max(1e4).default([]),createdAt:ka,updatedAt:ka}).strict();l({schemaVersion:k("openpond.hostedModelProjectSync.v2"),portableProjectId:Gt,name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:jc.nullable(),defaultDestinationId:Gt.nullable(),trainingSetup:Yy,sourceRevision:c().int().positive(),sourceUpdatedAt:ka,expectedEtag:cr.nullable().default(null)}).strict();var bj=l({id:Gt,teamId:Gt,portableProjectId:Gt,name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:jc.nullable(),defaultDestinationId:Gt.nullable(),trainingSetup:Yy,sourceRevision:c().int().positive(),sourceUpdatedAt:ka,revision:c().int().positive(),etag:cr,createdAt:ka,updatedAt:ka}).strict(),vj=l({kind:b(["taskset_release","harness_release","dataset_release","evidence_set","model_version","reward_model_version","evaluation_receipt"]),ref:nc,role:o().trim().min(1).max(200).nullable().default(null),updatedAt:ka}).strict();l({project:bj,resources:f(vj).max(1e4),jobCount:c().int().nonnegative(),latestJobIds:f(Gt).max(100)}).strict();l({schemaVersion:k("openpond.modelProjectApiError.v2"),code:o().trim().min(1).max(200),message:o().trim().min(1).max(5e3),retryable:C().default(!1),requestId:o().trim().min(1).max(500).nullable().default(null),details:fe(o(),ye()).default({})}).strict();const ko=L.nullable(),no=c().int().nonnegative(),yj=o().regex(/^[a-f0-9]{40}$/),Sj=l({name:o().trim().min(1).max(160),startedAt:ct,completedAt:ct,durationMs:c().nonnegative(),clock:b(["monotonic","provider","wall"]),outcome:b(["succeeded","failed","cancelled"])}).strict(),xj=l({schemaVersion:k("openpond.correlatedTelemetryReceipt.v1"),stage:b(["training","evaluation","deployment","inference"]),correlation:l({modelRunId:ko,modelVersionId:ko,policyVersion:no.nullable(),taskId:ko,rolloutGroupId:ko,providerResourceId:ko,deploymentId:ko,inferenceRequestId:ko}).strict(),spans:f(Sj).max(1e4),usage:l({promptTokens:no.nullable(),generatedTokens:no.nullable(),gpuSeconds:c().nonnegative().nullable(),workerActiveSeconds:c().nonnegative().nullable(),optimizerSteps:no.nullable(),rolloutGroups:no.nullable(),successfulTrajectories:no.nullable(),failedTrajectories:no.nullable(),peakGpuMemoryBytes:no.nullable(),peakGpuUtilizationPercent:c().min(0).max(100).nullable()}).strict(),resource:l({provider:L,resourceIds:f(L).max(1e3),gpuType:o().trim().min(1).max(300).nullable(),gpuCount:no.nullable(),baseProfileId:ko,baseRepository:o().trim().min(1).max(512).nullable(),baseRevision:yj.nullable(),adapterContentHash:Me.nullable()}).strict(),cost:l({currency:k("USD"),providerReportedUsd:c().nonnegative().nullable(),quotedHourlyUsd:c().nonnegative().nullable(),estimatedUsd:c().nonnegative().nullable(),methodologyVersion:o().trim().min(1).max(160),pricingInputs:fe(o().trim().min(1).max(160),c().finite()),unitEstimates:fe(o().trim().min(1).max(160),c().nonnegative())}).strict(),recordedAt:ct,contentHash:Me}).strict(),un=o().trim().min(1).max(240),mo=o().regex(/^[a-f0-9]{64}$/),wo=o().datetime({offset:!0}),gn=l({id:un,contentHash:mo}).strict(),kj=gn.extend({revision:c().int().positive()}).strict(),Xy=l({providerId:un,modelId:o().trim().min(1).max(300)}).strict(),Oc=b(["correction","sibling_verification","cumulative_known","development","retained","frozen_final","training_eligible"]),_j=l({taskId:un,taskContentHash:mo,panelRole:Oc,passLabel:un.nullable(),optimizerEligible:C(),criticalInvariantIds:f(un).max(100).default([])}).strict().superRefine((e,t)=>{e.optimizerEligible!==(e.panelRole==="correction")&&t.addIssue({code:"custom",path:["optimizerEligible"],message:"Only correction cases may be optimizer eligible."})}),wj=l({schemaVersion:k("openpond.continualBenchIssuePacket.v1"),id:un,revision:c().int().positive(),contentHash:mo,familyId:un,familyLabel:o().trim().min(1).max(500),severity:b(["low","medium","high","critical"]),cases:f(_j).min(2).max(1e4),duplicateEvidence:gn,leakageEvidence:gn,priorExposureEvidence:gn,observedAt:wo,reviewedAt:wo,queuedAt:wo.nullable(),runAt:wo.nullable(),createdBy:un,createdAt:wo}).strict().superRefine((e,t)=>{e.cases.some(n=>n.panelRole==="correction")||t.addIssue({code:"custom",path:["cases"],message:"An issue packet requires a correction case."}),e.cases.some(n=>n.panelRole==="sibling_verification")||t.addIssue({code:"custom",path:["cases"],message:"An issue packet requires a sibling-verification case."}),new Set(e.cases.map(n=>n.taskId)).size!==e.cases.length&&t.addIssue({code:"custom",path:["cases"],message:"Issue-packet task ids must be unique."})}),Ij=l({id:un,role:Oc,passLabel:un.nullable(),taskset:kj,familyIds:f(un).min(1).max(1e5),taskCount:c().int().positive().max(1e6),sealedAt:wo}).strict().superRefine((e,t)=>{const n=e.role==="correction"||e.role==="sibling_verification"||e.role==="cumulative_known";n!==(e.passLabel!==null)&&t.addIssue({code:"custom",path:["passLabel"],message:n?"This panel role requires a pass label.":"This panel role is series-wide and cannot carry a pass label."})}),Ou=Kt("kind",[l({kind:k("base_model"),id:un,revision:o().trim().min(1).max(500),contentHash:mo}).strict(),l({kind:k("model_version"),id:un,contentHash:mo}).strict(),l({kind:k("external_reference"),id:un,model:Xy,providerRevision:o().trim().min(1).max(500),contentHash:mo}).strict()]),Cj=l({scheduleEntryId:un,ordinal:c().int().nonnegative(),label:un,role:b(["seed","daily_residual","rank_candidate","weekly_rollup","full_refresh"]),parentRule:b(["base_model","previous_release","seed_release","accepted_daily_head","accepted_seed"]),trainableRank:c().int().positive().max(1024),correctionPanelIds:f(un).min(1).max(1e3),optimizerGroupsPerTask:c().int().positive().max(1e3),trajectoriesPerGroup:c().int().min(4).max(1e3)}).strict(),Rj=l({revision:c().int().positive(),requireAllAttemptsTerminal:k(!0),criticalCorrectionPassRate:c().min(0).max(1),siblingPassRate:c().min(0).max(1),behavioralRetentionRate:c().min(0).max(1),maximumRetainedRegressionPoints:c().min(0).max(100),blockCriticalPriorRegression:C(),authorizedClaims:f(b(["systems_complete","correction_absorbed","issue_generalized","continually_current","frontier_pareto_result"])).min(1).max(5)}).strict(),Aj=l({schemaVersion:k("openpond.continualBenchmarkProtocol.v1"),id:un,revision:c().int().positive(),contentHash:mo,ownerId:un,createdAt:wo,sealedAt:wo,creationReceipt:gn,predecessorSeries:l({id:un,revision:c().int().positive(),contentHash:mo}).strict().nullable(),scenarioPack:gn,issueFamilyLedger:gn,issuePacketRelease:gn,panels:f(Ij).min(6).max(1e4),grader:gn,judge:l({release:gn,rubricRelease:gn,calibrationRelease:gn,model:Xy}).strict().nullable(),policies:l({base:Ou,master:Ou.nullable(),externalReferences:f(Ou).min(1).max(20)}).strict(),invariants:l({systemPromptHash:mo,toolSchema:gn,application:gn,harness:gn,runtime:gn,workerImage:gn,autoRefiner:l({enabled:C(),release:gn.nullable()}).strict()}).strict(),schedule:f(Cj).min(1).max(1e3),evaluation:l({seeds:f(c().int()).min(3).max(100),repetitions:c().int().min(3).max(20),powerRule:gn,pairedBootstrapSamples:c().int().min(1e3).max(1e6),confidenceLevel:k(.95)}).strict(),resources:l({maximumTrainingGpuSeconds:c().int().positive(),maximumEvaluationGpuSeconds:c().int().positive(),maximumProviderSpendUsd:c().positive(),maximumTotalSpendUsd:c().positive(),maximumConcurrentGroups:c().int().positive().max(1e3)}).strict(),currencyThresholds:Rj}).strict().superRefine((e,t)=>{const n=e.panels.map(r=>r.id);new Set(n).size!==n.length&&t.addIssue({code:"custom",path:["panels"],message:"Protocol panel ids must be unique."});for(const r of["development","retained","frozen_final","training_eligible"])e.panels.filter(s=>s.role===r).length!==1&&t.addIssue({code:"custom",path:["panels"],message:`A protocol requires exactly one ${r} panel.`});[...e.schedule].sort((r,s)=>r.ordinal-s.ordinal).some((r,s)=>r.ordinal!==s)&&t.addIssue({code:"custom",path:["schedule"],message:"Protocol schedule ordinals must be contiguous from zero."});const i=new Set(n);e.schedule.some(r=>r.correctionPanelIds.some(s=>!i.has(s)))&&t.addIssue({code:"custom",path:["schedule"],message:"Every scheduled correction panel must belong to the protocol."})}),Pj=b(["draft","active","completed","archived"]),Tj=b(["draft","ready","queued","running","candidate","accepted","rejected","no_signal","failed","cancelled"]),Qy=b(["seed","daily_residual","rank_candidate","weekly_rollup","full_refresh"]),Ej=b(["base_model","previous_release","seed_release","accepted_daily_head","accepted_seed"]),Mj=b(["seed_taskset","nightly_selection","daily_cohort_union","eligible_task_pool"]),jj=b(["live_client","evaluation_attempt","replay_evidence","manual"]),Oj=l({id:L,ordinal:c().int().nonnegative(),label:o().trim().min(1).max(100),role:Qy,parentRule:Ej,taskSource:Mj,trainableRank:c().int().positive().max(1024),minimumTasks:c().int().nonnegative().max(1e5),maximumTasks:c().int().positive().max(1e5)}).strict().superRefine((e,t)=>{e.minimumTasks>e.maximumTasks&&t.addIssue({code:"custom",path:["minimumTasks"],message:"The minimum task count cannot exceed the maximum task count."});const n={seed:{parentRules:["base_model"],taskSource:"seed_taskset"},daily_residual:{parentRules:["previous_release","accepted_daily_head"],taskSource:"nightly_selection"},rank_candidate:{parentRules:["seed_release"],taskSource:"eligible_task_pool"},weekly_rollup:{parentRules:["seed_release","accepted_seed"],taskSource:"daily_cohort_union"},full_refresh:{parentRules:["base_model"],taskSource:"eligible_task_pool"}},{parentRules:a,taskSource:i}=n[e.role];a.includes(e.parentRule)||t.addIssue({code:"custom",path:["parentRule"],message:`${e.role} requires parent rule ${a.join(" or ")}.`}),e.taskSource!==i&&t.addIssue({code:"custom",path:["taskSource"],message:`${e.role} requires task source ${i}.`}),e.ordinal===0&&e.role!=="seed"&&t.addIssue({code:"custom",path:["role"],message:"The first series entry must be the seed."})}),Nj=l({id:L,version:c().int().positive(),requireCheckpoint:C(),requireAppliedOptimizerUpdate:C(),minimumCurrentCohortMeanImprovement:c().finite(),maximumRetainedMeanRegression:c().finite().nonnegative(),blockCriticalInvariantRegression:C(),automaticDailyAdvancement:C()}).strict(),$j=l({schemaVersion:k("openpond.modelComparisonSeries.v1"),id:L,profileId:L,modelProjectId:L,name:o().trim().min(1).max(500),objective:o().trim().min(1).max(2e4),status:Pj,revision:c().int().positive(),productionBinding:l({role:k("chat_manual"),roleTargetId:L}).strict(),baseModel:l({id:L,revision:o().trim().min(1).max(256)}).strict(),seedTaskset:Qt,eligibleTaskPool:Qt,evaluationTasksets:l({development:Qt,retained:Qt,frozenFinal:Qt}).strict(),grader:Ye,benchmarkProtocol:Aj.nullable().default(null),automaticEvaluation:l({enabled:C()}).strict().default({enabled:!1}),residualProfile:l({profileId:L,serializedEnvelopeRank:c().int().positive().max(1024),maximumEnabledRank:c().int().positive().max(1024),topology:k("uniform_block_masked")}).strict(),schedule:f(Oj).min(1).max(1e3),scheduleSealedAt:ct.nullable(),advancementPolicy:Nj,executionPolicy:l({startWhenReady:k(!1)}).strict(),acceptedSeedEntryId:L.nullable(),acceptedDailyHeadEntryId:L.nullable(),promotedBindingId:L.nullable(),createdBy:L,createdAt:ct,updatedAt:ct}).strict().superRefine((e,t)=>{[...e.schedule].sort((p,m)=>p.ordinal-m.ordinal).some((p,m)=>p.ordinal!==m)&&t.addIssue({code:"custom",path:["schedule"],message:"Schedule ordinals must be unique and contiguous from zero."}),(new Set(e.schedule.map(p=>p.id)).size!==e.schedule.length||new Set(e.schedule.map(p=>p.label)).size!==e.schedule.length)&&t.addIssue({code:"custom",path:["schedule"],message:"Schedule ids and labels must be unique."}),e.residualProfile.maximumEnabledRank>e.residualProfile.serializedEnvelopeRank&&t.addIssue({code:"custom",path:["residualProfile"],message:"Maximum enabled rank cannot exceed the serialized envelope."});const a=Object.values(e.evaluationTasksets);new Set(a.map(p=>`${p.id}:${p.revision}:${p.contentHash}`)).size!==a.length&&t.addIssue({code:"custom",path:["evaluationTasksets"],message:"Development, retained, and frozen-final cohorts require distinct immutable Taskset releases."});const i=e.schedule.find(p=>p.role==="seed");if(!i||e.schedule.filter(p=>p.role==="seed").length!==1){t.addIssue({code:"custom",path:["schedule"],message:"A series requires exactly one seed entry."});return}const r=e.schedule.filter(p=>p.role==="rank_candidate");r.length===1&&t.addIssue({code:"custom",path:["schedule"],message:"A causal rank comparison requires at least two rank candidates."}),new Set(r.map(p=>p.trainableRank)).size!==r.length&&t.addIssue({code:"custom",path:["schedule"],message:"Causal rank candidates must use distinct trainable ranks."}),[i.trainableRank+e.schedule.filter(p=>p.role==="daily_residual").reduce((p,m)=>p+m.trainableRank,0),...e.schedule.filter(p=>p.role==="weekly_rollup").map(p=>i.trainableRank+p.trainableRank),...e.schedule.filter(p=>p.role==="rank_candidate").map(p=>i.trainableRank+p.trainableRank),...e.schedule.filter(p=>p.role==="full_refresh").map(p=>p.trainableRank)].some(p=>p>e.residualProfile.maximumEnabledRank)&&t.addIssue({code:"custom",path:["schedule"],message:"A declared branch exceeds the maximum enabled rank."})}),eS=l({source:jj,taskIds:f(L).min(1).max(1e5),observedFrom:ct,observedTo:ct,reviewedAt:ct,reviewedBy:L,sourceTaskset:Qt}).strict(),Dj=eS.extend({derivedFamilyKeys:f(L).min(1).max(1e5),familyDerivation:l({algorithm:L,sourceTasksetHash:Me}).strict(),selectionHash:Me}).strict(),tS=Kt("kind",[l({kind:k("base_model"),id:L,revision:o().trim().min(1).max(256)}).strict(),l({kind:k("model_version"),id:L,contentHash:Me}).strict()]),Lj=l({id:L,branchOrdinal:c().int().nonnegative(),rank:c().int().positive().max(1024),offsetStart:c().int().nonnegative(),offsetEnd:c().int().positive(),optimizationRole:b(["frozen","trainable"]),artifactLineageId:L.nullable()}).strict().superRefine((e,t)=>{e.offsetEnd-e.offsetStart!==e.rank&&t.addIssue({code:"custom",path:["offsetEnd"],message:"Block offsets must span exactly the declared rank."})}),zj=l({disposition:b(["advance","hold","no_signal"]),policy:l({id:L,version:c().int().positive()}).strict(),reasonCodes:f(L).min(1).max(100),summary:o().trim().min(1).max(5e3),decidedBy:L,decidedAt:ct}).strict(),Uj=l({evaluationRunId:L,modelVersionId:L,taskset:Qt,grader:Ye,cohortRole:b(["current","correction","sibling_verification","cumulative_known","development","retained","prior_disclosed","frozen_final"]),panelId:L.nullable().default(null),protocol:l({id:L,revision:c().int().positive(),contentHash:Me}).strict().nullable().default(null)}).strict(),Hj=l({attemptOrdinal:c().int().positive(),trainingPlanId:L.nullable(),modelRunId:L.nullable(),terminalStatus:b(["failed","cancelled"]),queuedAt:ct.nullable(),startedAt:ct.nullable(),completedAt:ct}).strict(),dr=l({seriesId:L,entryId:L,scheduleEntryId:L,ordinal:c().int().nonnegative(),releaseHash:Me}).strict(),qj=l({schemaVersion:k("openpond.modelComparisonSeriesEntry.v1"),id:L,seriesId:L,profileId:L,modelProjectId:L,scheduleEntryId:L,releaseHash:Me,ordinal:c().int().nonnegative(),label:o().trim().min(1).max(100),role:Qy,branch:b(["daily","rank_candidate","weekly_rollup","full_refresh"]),status:Tj,parent:tS,taskset:Qt,sourceTasksets:f(Qt).min(1).max(1e3),taskSelection:Dj.nullable(),trainableRank:c().int().positive().max(1024),serializedEnvelopeRank:c().int().positive().max(1024),enabledCumulativeRank:c().int().positive().max(1024),trainableBlockId:L,residualBlocks:f(Lj).min(1).max(1024),attemptOrdinal:c().int().positive().default(1),priorRunAttempts:f(Hj).max(100).default([]),trainingPlanId:L.nullable(),modelRunId:L.nullable(),modelVersionId:L.nullable(),evaluations:f(Uj).max(1e5),decision:zj.nullable(),promotionBindingId:L.nullable(),queuedAt:ct.nullable(),startedAt:ct.nullable(),completedAt:ct.nullable(),createdAt:ct,updatedAt:ct}).strict().superRefine((e,t)=>{const n=[...e.residualBlocks].sort((s,d)=>s.offsetStart-d.offsetStart);n.some((s,d)=>s.offsetStart!==(d===0?0:n[d-1].offsetEnd))&&t.addIssue({code:"custom",path:["residualBlocks"],message:"Residual block offsets must be contiguous from zero."});const a=n.at(-1)?.offsetEnd??0;(a!==e.enabledCumulativeRank||a>e.serializedEnvelopeRank)&&t.addIssue({code:"custom",path:["enabledCumulativeRank"],message:"Enabled rank must match the block inventory and fit the envelope."});const i=e.residualBlocks.filter(s=>s.optimizationRole==="trainable");(i.length!==1||i[0]?.id!==e.trainableBlockId||i[0]?.rank!==e.trainableRank)&&t.addIssue({code:"custom",path:["trainableBlockId"],message:"Exactly one block must be trainable during the Run and match trainableRank."});const r=e.priorRunAttempts.map(s=>s.attemptOrdinal);(e.priorRunAttempts.length!==e.attemptOrdinal-1||r.some((s,d)=>s!==d+1))&&t.addIssue({code:"custom",path:["priorRunAttempts"],message:"Prior Run attempts must be a contiguous history before the active attempt."})});l({seriesId:L,scheduleEntryId:L,taskSelection:eS.nullable(),expectedSeriesRevision:c().int().positive()}).strict();const Bj=b(["base_reference","lora_adapter"]),nS=l({baseModel:l({source:k("huggingface"),repoId:L,revision:o().regex(/^[a-f0-9]{40}$/),configHash:Me,tokenizerHash:Me,licenseId:L,gated:C()}).strict(),processor:l({repository:L,revision:o().regex(/^[a-f0-9]{40}$/),configHash:Me}).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."})}),Fj=l({schemaVersion:k("openpond.modelVersion.v1"),id:L,modelId:L,profileId:L,version:c().int().nonnegative(),kind:Bj,status:b(["available","failed"]),baseModel:Gs,taskset:Qt,comparisonSeriesEntry:dr.nullable().optional(),releaseGraph:l({resolvedBundleHash:Me,profileRelease:Qt,harnessRelease:Ye,agentRelease:Ye.nullable(),grader:l({id:L,contentHash:Me}).strict()}).strict(),artifactLineageId:L.nullable(),adapterStatus:b(["not_trained","trained"]),createdAt:ct,contentHash:Me}).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."})}),Vj=l({schemaVersion:k("openpond.rewardModelVersion.v1"),id:L,modelId:L,profileId:L,version:c().int().positive(),role:k("reward"),status:b(["available","failed"]),scope:b(["synthetic_smoke","human_preference"]),baseModel:Gs,runtime:nS.nullable().default(null),taskset:Qt,preferenceDatasetRelease:Ye,releaseGraph:l({resolvedBundleHash:Me,profileRelease:Qt,harnessRelease:Ye,grader:l({id:L,contentHash:Me}).strict()}).strict(),artifacts:l({checkpoint:Ye.extend({objectRef:o().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/),files:f(l({path:o().trim().min(1).max(512),sizeBytes:c().int().positive(),sha256:Me}).strict()).min(4).max(128)}).strict(),adapter:Ye,scalarHead:Ye,bucketHead:Ye.nullable(),processorRelease:Ye}).strict(),qualificationReport:Ye.nullable(),createdAt:ct,contentHash:Me}).strict(),Wj=l({schemaVersion:k("openpond.rewardModelRunReceipt.v1"),provider:L,providerRunId:L,resolvedBundleHash:Me,finalCheckpoint:Ye.extend({objectRef:o().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/)}).strict(),adapter:Ye,scalarHead:Ye,bucketHead:Ye.nullable(),processorRelease:Ye,optimizerEvidence:Ye,managedExecutionReceipt:Ye.nullable().default(null),parameterDeltaHash:Me,cleanup:l({computeReleased:C(),providerTerminalObserved:C()}).strict(),contentHash:Me}).strict(),Kj=kR(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}}},l({schemaVersion:k("openpond.rewardModelRun.v1"),id:L,rewardModelId:L,rewardModelVersionId:L.nullable(),profileId:L,role:k("reward"),scope:b(["synthetic_smoke","human_preference"]),status:b(["prepared","running","succeeded","failed","cancelled"]),taskset:Qt,tasksetRelease:Ye,preferenceDatasetRelease:Ye,recipeRelease:Ye,destinationId:L,quote:l({maximumSpendUsd:c().positive(),hourlyCostUsd:c().nonnegative().nullable()}).strict(),managedRunId:L.nullable(),progress:l({completedSteps:c().int().nonnegative(),totalSteps:c().int().positive(),latestLoss:c().finite().nullable()}).strict(),receipt:Wj.nullable(),qualificationReport:Ye.nullable(),accruedSpendUsd:c().nonnegative().nullable(),failureOwner:b(["authoring","admission","provider","runner","artifact","qualification","cleanup"]).nullable(),failure:o().trim().min(1).max(5e3).nullable(),startedAt:ct,completedAt:ct.nullable(),updatedAt:ct}).strict()).superRefine((e,t)=>{e.status==="succeeded"&&!e.receipt&&t.addIssue({code:"custom",message:"A successful Reward Model Run requires a canonical receipt."}),e.status!=="succeeded"&&e.rewardModelVersionId!==null&&t.addIssue({code:"custom",message:"Only a successful Reward Model Run can publish a Reward Model Version."})}),Gj=l({schemaVersion:k("openpond.modelRunReceipt.v1"),provider:L,providerRunId:L,assignmentHash:Me,resultHash:Me,transcriptHash:Me,traceHash:Me.nullable(),resolvedBundleHash:Me,artifactPath:o().trim().min(1).max(2e3),cleanup:l({computeReleased:C(),tunnelClosed:C()}).strict(),telemetry:xj.nullable().default(null),contentHash:Me}).strict(),_o=l({inputTokens:c().int().nonnegative(),outputTokens:c().int().nonnegative(),totalTokens:c().int().nonnegative(),costUsd:c().nonnegative().nullable()}).strict(),eg=o().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),Zp=l({phase:b(["baseline","adaptation","candidate_adaptation","candidate"]),taskId:L,attemptId:L,sessionId:L.nullable(),turnId:L.nullable(),passed:C(),score:c().min(0).max(1).nullable(),failureClass:Kp.nullable(),inputTokens:c().int().nonnegative(),outputTokens:c().int().nonnegative(),totalTokens:c().int().nonnegative(),latencyMs:c().int().nonnegative(),costUsd:c().nonnegative().nullable(),startedAt:ct}).strict(),tg=l({targetTaskCount:c().int().nonnegative(),comparedTaskCount:c().int().nonnegative(),passedTaskCount:c().int().nonnegative(),failedTaskCount:c().int().nonnegative(),lowerTaskCount:c().int().nonnegative(),higherTaskCount:c().int().nonnegative(),unchangedTaskCount:c().int().nonnegative()}).strict(),aS=l({target:k("all_tasks_lower"),targetTaskCount:c().int().nonnegative(),comparedTaskCount:c().int().nonnegative(),passedTaskCount:c().int().nonnegative(),failedTaskCount:c().int().nonnegative(),lowerTaskCount:c().int().nonnegative(),higherTaskCount:c().int().nonnegative(),unchangedTaskCount:c().int().nonnegative(),baselineTokens:c().int().nonnegative(),refinedTokens:c().int().nonnegative(),tokenDelta:c().int(),tokenDeltaPercent:c().finite().nullable(),complete:C(),passed:C(),cohorts:l({adaptation:tg,heldOut:tg}).strict()}).strict(),Jp=l({baseline:_o,adaptation:_o,candidateAdaptation:_o,candidate:_o,refiner:_o,grader:_o}).strict(),Zj=l({usage:Jp,observedSpendUsd:c().nonnegative(),attempts:f(Zp).max(1e4)}).strict(),Jj=l({id:L,contentHash:Me,artifactPath:o().trim().min(1).max(2e3)}).strict(),Yj=l({schemaVersion:k("openpond.modelEvaluationReceipt.v1"),benchmarkId:L,resultManifest:l({id:L,contentHash:Me,artifactPath:o().trim().min(1).max(2e3)}).strict(),stages:l({baseline:Ye,adaptation:Ye,refiner:Ye,candidateAdaptation:Ye,candidate:Ye,comparison:Ye}).strict(),usage:Jp,quality:l({baselinePassRate:c().min(0).max(1),candidatePassRate:c().min(0).max(1),adaptationBaselinePassRate:c().min(0).max(1),adaptationCandidatePassRate:c().min(0).max(1),adaptationCandidatePassed:C(),heldOutCandidatePassed:C(),passed:C()}).strict(),foregroundTokenDelta:c().int(),foregroundTokenDeltaPercent:c().finite().nullable(),taskEfficiency:aS.optional(),efficiency:l({grossForegroundTokenSavings:c().int(),overheadTokens:c().int().nonnegative(),firstPassNetTokenSavings:c().int(),breakEvenReuseCount:c().int().nonnegative().nullable(),amortizedTokenSavings:c().int(),amortizedReuseCount:c().int().positive()}).strict(),budget:l({maximumSpendUsd:c().nonnegative(),observedSpendUsd:c().nonnegative(),enforced:C()}).strict(),evidenceSnapshot:Ye,lineage:l({adaptationEvidenceHash:Me,refinerInputHash:Me,refinerOutcomeHash:Me,validationHash:Me,applyReceiptHash:Me,candidateRelease:Ye,valid:C()}).strict(),invalidReasons:f(o().trim().min(1).max(2e3)).max(100),attempts:f(Zp).max(1e4).default([]),terminalClassification:b(["improved","no_improvement","regressed","inconclusive","cancelled","infrastructure_failure"]),profileGit:l({ref:o().trim().min(1).max(2e3),commit:eg,baseCommit:eg}).strict().nullable(),contentHash:Me}).strict(),Xj=l({schemaVersion:k("openpond.modelEvaluationStopReceipt.v1"),benchmarkId:L,terminalClassification:k("inconclusive"),stopReason:b(["candidate_harness_unchanged","candidate_lineage_invalid"]),reason:o().trim().min(1).max(5e3),stoppedAfter:k("refiner"),baselineHarness:Ye,candidateHarness:Ye,refiner:l({id:L,contentHash:Me,outcomeCount:c().int().nonnegative()}).strict(),usage:Jp,budget:l({maximumSpendUsd:c().nonnegative(),observedSpendUsd:c().nonnegative(),enforced:C()}).strict(),evidenceSnapshot:Ye,attempts:f(Zp).max(1e4),contentHash:Me}).strict(),ng=l({level:k(.95),lower:c().finite(),upper:c().finite()}).strict().superRefine((e,t)=>{e.lower>e.upper&&t.addIssue({code:"custom",message:"A confidence interval's lower bound cannot exceed its upper bound."})}),Qj=l({schemaVersion:k("openpond.modelComparisonBenchmarkReceipt.v1"),benchmarkId:k("model-comparison"),target:l({kind:b(["base_model","model_version","external_reference"]),label:o().trim().min(1).max(300),modelVersionId:L.nullable(),model:Jt.nullable()}).strict(),taskset:Qt,grader:Ye,sampling:l({seeds:f(c().int()).min(1).max(100),repetitions:c().int().positive().max(20)}).strict(),deterministic:l({attemptedTaskCount:c().int().nonnegative(),completedTaskCount:c().int().nonnegative(),passedTaskCount:c().int().nonnegative(),failedTaskCount:c().int().nonnegative(),meanScore:c().finite().nullable(),passRate:c().min(0).max(1).nullable(),passRateCi95:ng.nullable()}).strict(),judge:l({judgeModel:Jt,judgeRelease:Ye,rubricRelease:Ye,calibrationRelease:Ye,score:c().min(0).max(100),scoreCi95:ng,comparisonCount:c().int().positive(),wins:c().int().nonnegative(),ties:c().int().nonnegative(),losses:c().int().nonnegative(),referenceLabel:o().trim().min(1).max(300)}).strict().superRefine((e,t)=>{e.wins+e.ties+e.losses!==e.comparisonCount&&t.addIssue({code:"custom",message:"Judge win, tie, and loss counts must equal comparisonCount."})}).nullable(),attempts:f(l({attemptId:L.nullable().default(null),taskId:L,seed:c().int(),repetition:c().int().nonnegative(),status:b(["succeeded","failed"]),deterministicScore:c().finite().nullable(),passed:C().nullable(),judgeScore:c().min(0).max(100).nullable(),judgePreference:b(["win","tie","loss"]).nullable(),transcriptHash:Me.nullable(),traceHash:Me.nullable(),transcriptArtifact:l({artifactPath:o().trim().min(1).max(2e3),jsonPointer:o().trim().min(1).max(1e3)}).strict().nullable().default(null),traceArtifact:l({artifactPath:o().trim().min(1).max(2e3),jsonPointer:o().trim().min(1).max(1e3)}).strict().nullable().default(null),latencyMs:c().int().nonnegative().nullable().default(null),failureClass:Kp.nullable()}).strict()).max(1e5),usage:l({policy:_o.nullable(),judge:_o.nullable(),observedSpendUsd:c().nonnegative().nullable(),evaluationGpuSeconds:c().nonnegative().nullable().default(null)}).strict(),managedServing:l({jobId:L,terminalState:b(["completed","cancelled","failed","budget_exhausted"]),sourcePolicyVersion:c().int().nonnegative(),sourceAdapterSha256:Me.nullable(),servedPolicyVersion:c().int().nonnegative().nullable(),servedAdapterSha256:Me.nullable(),accruedSpendUsd:c().nonnegative(),cleanupAttestationHash:Me,resourceCount:c().int().nonnegative(),activeResourceCount:k(0)}).strict().nullable().default(null),evidenceSnapshot:l({id:L,contentHash:Me,artifactPath:o().trim().min(1).max(2e3)}).strict(),completedAt:ct,contentHash:Me}).strict().superRefine((e,t)=>{const n=e.deterministic;n.completedTaskCount>n.attemptedTaskCount&&t.addIssue({code:"custom",message:"Completed task count cannot exceed attempted task count."}),n.passedTaskCount+n.failedTaskCount!==n.completedTaskCount&&t.addIssue({code:"custom",message:"Passed and failed task counts must equal completed task count."}),n.completedTaskCount===0!=(n.meanScore===null)&&t.addIssue({code:"custom",message:"Deterministic mean score is available exactly when tasks completed."}),n.completedTaskCount===0!=(n.passRate===null)&&t.addIssue({code:"custom",message:"Deterministic pass rate is available exactly when tasks completed."})}),eO=l({benchmarkId:k("harness-refiner"),model:Jt,upstreamModel:l({providerId:L,modelId:o().trim().min(1).max(300),revision:o().trim().min(1).max(300),pricing:l({version:o().trim().min(1).max(300),source:o().trim().min(1).max(300),effectiveAt:ct,inputUsdPerMillionTokens:c().nonnegative(),cachedInputUsdPerMillionTokens:c().nonnegative(),outputUsdPerMillionTokens:c().nonnegative()}).strict().optional()}).strict(),reasoningEffort:o().trim().min(1).max(100).nullable(),seeds:f(c().int()).min(1).max(100),repetitions:c().int().positive().max(20),maximumSpendUsd:c().nonnegative(),attemptPlan:f(l({stage:b(["baseline","adaptation","candidate_adaptation","candidate"]),split:o().trim().min(1).max(100),taskIds:f(L).min(1).max(1e5),attemptCount:c().int().positive()}).strict()).length(4)}).strict(),tO=l({benchmarkId:k("model-comparison"),target:l({kind:b(["base_model","model_version","external_reference"]),label:o().trim().min(1).max(300),modelVersionId:L.nullable(),model:Jt.nullable()}).strict(),grader:Ye,judge:l({model:Jt,release:Ye,rubricRelease:Ye,calibrationRelease:Ye,referenceLabel:o().trim().min(1).max(300)}).strict().nullable(),seeds:f(c().int()).min(1).max(100),repetitions:c().int().positive().max(20),maximumSpendUsd:c().nonnegative(),series:l({id:L,protocol:l({id:L,revision:c().int().positive(),contentHash:Me}).strict()}).strict().nullable().default(null),panel:l({id:L,role:b(["correction","sibling_verification","cumulative_known","development","retained","frozen_final"]),passLabel:L.nullable()}).strict().nullable().default(null),comparisonPair:l({entryId:L,parent:tS,candidateModelVersionId:L}).strict().nullable().default(null),attemptPlan:f(l({stage:k("comparison"),split:o().trim().min(1).max(100),taskIds:f(L).min(1).max(1e5),attemptCount:c().int().positive()}).strict()).length(1)}).strict(),nO=mn([eO,tO]),aO=l({schemaVersion:k("openpond.modelRun.v1"),id:L,modelId:L,modelVersionId:L.nullable(),profileId:L,kind:b(["rollout_smoke","training","evaluation"]),status:b(["prepared","running","succeeded","failed","cancelled"]),method:b(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]).nullable(),destinationId:L.nullable(),taskset:Qt,comparisonSeriesEntry:dr.nullable().optional(),harnessRelease:Ye.nullable().optional(),quote:l({maximumSpendUsd:c().nonnegative(),hourlyCostUsd:c().nonnegative().nullable()}).strict().nullable(),evaluation:nO.nullable().default(null),evaluationProgress:l({stage:b(["baseline","adaptation","refiner","candidate_adaptation","candidate","comparison"]),completedAttempts:c().int().nonnegative(),totalAttempts:c().int().positive(),accounting:Zj.nullable().default(null),evidenceSnapshot:Jj.nullable().default(null)}).strict().nullable().default(null),reward:l({raw:c(),components:fe(o(),c())}).strict().nullable(),receipt:mn([Gj,Yj,Xj,Qj]).nullable(),adapterArtifactLineageId:L.nullable(),failure:o().trim().min(1).max(5e3).nullable(),startedAt:ct,completedAt:ct.nullable(),updatedAt:ct}).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"&&e.receipt.schemaVersion!=="openpond.modelComparisonBenchmarkReceipt.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 aW(e){const t=new Map;for(const R of e.attempts){const A=`${R.phase}\0${R.taskId}`,N=t.get(A);(!N||R.startedAt>N.startedAt||R.startedAt===N.startedAt&&R.attemptId>N.attemptId)&&t.set(A,R)}const n=[...t.values()],a=[["adaptation","adaptation","candidate_adaptation"],["held_out","baseline","candidate"]].flatMap(([R,A,N])=>{const O=new Map(n.filter(D=>D.phase===N).map(D=>[D.taskId,D]));return n.filter(D=>D.phase===A).flatMap(D=>{const x=O.get(D.taskId);return x?[{cohort:R,taskId:D.taskId,baseline:D,refined:x,tokenDelta:x.totalTokens-D.totalTokens}]:[]})}),i=new Set(n.filter(R=>R.phase==="baseline"||R.phase==="adaptation").map(R=>R.taskId)).size,r=e.targetTaskCount??i;if(!Number.isInteger(r)||r<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},d=(R,A)=>({targetTaskCount:A,comparedTaskCount:R.length,passedTaskCount:R.filter(N=>N.tokenDelta<0).length,failedTaskCount:R.filter(N=>N.tokenDelta>=0).length,lowerTaskCount:R.filter(N=>N.tokenDelta<0).length,higherTaskCount:R.filter(N=>N.tokenDelta>0).length,unchangedTaskCount:R.filter(N=>N.tokenDelta===0).length}),p=d(a,r),m=a.reduce((R,A)=>R+A.baseline.totalTokens,0),h=a.reduce((R,A)=>R+A.refined.totalTokens,0),S=h-m,y=a.length===r;return{summary:aS.parse({target:"all_tasks_lower",...p,baselineTokens:m,refinedTokens:h,tokenDelta:S,tokenDeltaPercent:m>0?S/m*100:null,complete:y,passed:y&&p.passedTaskCount===r,cohorts:{adaptation:d(a.filter(R=>R.cohort==="adaptation"),s.adaptation),heldOut:d(a.filter(R=>R.cohort==="held_out"),s.held_out)}}),pairs:a}}const oO=b(["measuring","up_to_date","needs_attention"]),iO=b(["fixed","retained","regressed","unresolved","unavailable"]),ag=l({evaluationRunId:L,attemptKey:L,artifactPath:o().trim().min(1).max(2e3),jsonPointer:o().trim().min(1).max(1e3),transcriptHash:Me.nullable(),traceHash:Me.nullable()}).strict(),Am=l({level:k(.95),lower:c().finite(),upper:c().finite()}).strict(),rO=l({panelId:L,panelRole:Oc,passLabel:L.nullable(),taskset:Qt,attempted:c().int().nonnegative(),available:c().int().nonnegative(),passed:c().int().nonnegative(),strictSuccess:c().min(0).max(1).nullable(),strictSuccessCi95:Am.nullable(),judgeScore:c().min(0).max(100).nullable(),judgeScoreCi95:Am.nullable()}).strict(),sO=l({schemaVersion:k("openpond.modelCurrencySnapshot.v1"),id:L,contentHash:Me,seriesId:L,protocol:l({id:L,revision:c().int().positive(),contentHash:Me}).strict(),entryId:L,passLabel:L,parent:Kt("kind",[l({kind:k("base_model"),id:L,revision:o().trim().min(1).max(500)}).strict(),l({kind:k("model_version"),id:L,contentHash:Me}).strict()]),candidate:l({kind:k("model_version"),id:L,contentHash:Me}).strict(),sources:l({evaluationRunIds:f(L).max(1e5),attemptIds:f(L).max(1e6),tasksets:f(Qt).max(1e4),grader:Ye,judge:Ye.nullable(),calibration:Ye.nullable()}).strict(),matches:f(l({key:L,panelId:L,panelRole:Oc,taskId:L,issueFamilyId:L,seed:c().int(),repetition:c().int().nonnegative(),classification:iO,parentPassed:C().nullable(),candidatePassed:C().nullable(),parentAttempt:ag.nullable(),candidateAttempt:ag.nullable()}).strict()).max(1e6),taskIds:l({fixed:f(L).max(1e6),retained:f(L).max(1e6),regressed:f(L).max(1e6),unresolved:f(L).max(1e6),unavailable:f(L).max(1e6)}).strict(),panels:f(rO).max(1e4),metrics:l({knownIssueCoverage:c().min(0).max(1).nullable(),issueFamilyGeneralization:c().min(0).max(1).nullable(),behavioralRetention:c().min(0).max(1).nullable(),currentAcquisitionDelta:c().finite().nullable(),retainedDeltaPoints:c().finite().nullable(),frontierStrictDelta:c().finite().nullable(),pairedPValue:c().min(0).max(1).nullable(),wins:c().int().nonnegative(),ties:c().int().nonnegative(),losses:c().int().nonnegative()}).strict(),statistics:l({matchedAttemptCount:c().int().nonnegative(),strictDelta:c().finite().nullable(),strictDeltaCi95:Am.nullable(),exactPairedBinaryPValue:c().min(0).max(1).nullable(),pairedBootstrapSamples:c().int().positive()}).strict(),criteria:l({allRequiredAttemptsTerminal:C(),criticalCorrectionPassRate:c().min(0).max(1).nullable(),siblingPassRate:c().min(0).max(1).nullable(),behavioralRetentionRate:c().min(0).max(1).nullable(),retainedRegressionPoints:c().finite().nullable(),criticalPriorRegressionCount:c().int().nonnegative(),thresholdRelease:Ye}).strict(),efficiency:l({inputTokens:c().int().nonnegative(),outputTokens:c().int().nonnegative(),totalTokens:c().int().nonnegative(),costUsd:c().nonnegative().nullable(),latencyMs:c().int().nonnegative(),tokensPerSuccess:c().nonnegative().nullable(),throughputPerHour:c().nonnegative().nullable(),gpuSeconds:c().nonnegative().nullable()}).strict(),invariants:l({systemPromptHash:Me,toolSchema:Ye,application:Ye,harness:Ye,runtime:Ye,grader:Ye,autoRefinerEnabled:C()}).strict(),evidenceState:oO,evidenceReasons:f(L).max(100),projectedAt:ct}).strict(),ql=Kt("kind",[l({kind:k("base_model"),id:L,revision:o().trim().min(1).max(500),label:o().trim().min(1).max(300)}).strict(),l({kind:k("model_version"),id:L,label:o().trim().min(1).max(300)}).strict(),l({kind:k("captured_model"),id:L,label:o().trim().min(1).max(300)}).strict()]),ws=mn([l({source:k("evaluation_run").default("evaluation_run"),evaluationRunId:L,attemptId:L,modelLabel:o().trim().min(1).max(300).nullable().default(null),modelVersionId:L.nullable().default(null),reward:c().finite().nullable(),components:fe(o(),c().finite()).default({})}).strict(),l({source:k("imported_response"),modelLabel:o().trim().min(1).max(300),modelVersionId:L.nullable().default(null),response:ye().refine(e=>e!==void 0,"An imported model response is required."),reward:c().finite().nullable().default(null),components:fe(o(),c().finite()).default({})}).strict()]),lO=mn([l({taskId:L,target:ql,attempt:ws}).strict(),l({taskId:L,target:b(["base","current"]).default("current"),attempt:ws}).strict(),l({taskId:L,target:b(["base","current"]).default("current"),evaluationRunId:L,attemptId:L,reward:c().finite().nullable(),components:fe(o(),c().finite()).default({})}).strict().transform(({taskId:e,target:t,...n})=>({taskId:e,target:t,attempt:{source:"evaluation_run",modelLabel:null,modelVersionId:null,...n}}))]);l({schemaVersion:k("openpond.continualLearningDailyBatchManifest.v1"),id:L,seriesId:L,scheduleEntryId:L,dayOrdinal:c().int().positive().max(1e4),sourceTaskset:Qt,taskIds:f(L).min(1).max(1e3),observedAttempts:f(lO).max(1e3).default([]),sourceFileName:o().trim().min(1).max(500).nullable().default(null),availableAt:ct}).strict().superRefine((e,t)=>{new Set(e.taskIds).size!==e.taskIds.length&&t.addIssue({code:"custom",path:["taskIds"],message:"A daily batch cannot repeat a task."}),new Set(e.observedAttempts.map(a=>`${a.taskId}:${uO(a.target)}`)).size!==e.observedAttempts.length&&t.addIssue({code:"custom",path:["observedAttempts"],message:"An intake batch cannot repeat a task and Policy target pair."});const n=new Set(e.taskIds);e.observedAttempts.some(a=>!n.has(a.taskId))&&t.addIssue({code:"custom",path:["observedAttempts"],message:"Observed attempts must belong to tasks in the daily batch."})});const cO=l({schemaVersion:k("openpond.continualLearningDailyBatch.v1"),id:L,seriesId:L,scheduleEntryId:L,dayOrdinal:c().int().positive().max(1e4),label:o().trim().min(1).max(100),runMode:b(["automatic","manual"]).optional(),source:b(["json_upload","sealed_fixture"]),sourceFileName:o().trim().min(1).max(500).nullable(),sourceTaskset:Qt,tasks:f(l({taskId:L,taskContentHash:Me,familyKey:L,disposition:b(["include","defer","exclude"]).nullable(),oracleReview:b(["pending","confirmed","needs_correction"]),note:o().trim().max(2e3),observedAttempt:ws.nullable(),baselineAttempt:ws.nullable().default(null),responses:f(l({target:ql,attempt:ws}).strict()).max(100).default([]),stagedAt:ct.nullable().default(null),queuedEntry:dr.nullable().default(null)}).strict()).min(1).max(1e3),intakeEvaluation:l({status:b(["awaiting","running","ready","failed"]),requestedTargets:f(b(["base","current"])).max(2).default(["base","current"]),requestedPolicies:f(ql).max(100).default([]),runs:f(l({target:ql,runId:L}).strict()).max(100).default([]),baselineRunId:L.nullable(),currentRunId:L.nullable(),currentPolicy:Kt("kind",[l({kind:k("base_model"),id:L}).strict(),l({kind:k("model_version"),id:L}).strict()]).nullable(),failure:o().trim().min(1).max(2e3).nullable()}).strict().default({status:"awaiting",requestedTargets:["base","current"],requestedPolicies:[],runs:[],baselineRunId:null,currentRunId:null,currentPolicy:null,failure:null}),status:b(["pending","reviewed","queued"]),queuedEntry:dr.nullable(),reviewedBy:L.nullable(),reviewedAt:ct.nullable(),availableAt:ct,revision:c().int().positive(),createdAt:ct,updatedAt:ct}).strict().superRefine((e,t)=>{new Set(e.tasks.map(a=>a.taskId)).size!==e.tasks.length&&t.addIssue({code:"custom",path:["tasks"],message:"A daily batch cannot repeat a task."});for(const[a,i]of e.tasks.entries()){const r=i.responses.map(s=>oS(s.target));new Set(r).size!==r.length&&t.addIssue({code:"custom",path:["tasks",a,"responses"],message:"A task cannot repeat a model response target."})}const n=e.tasks.every(a=>a.disposition!==null&&a.oracleReview!=="pending"&&(a.oracleReview!=="needs_correction"||a.note.length>0));e.status!=="pending"&&!n&&t.addIssue({code:"custom",path:["tasks"],message:"Every task requires a decision and oracle review before the day completes."}),e.status==="queued"!=(e.queuedEntry!==null)&&t.addIssue({code:"custom",path:["queuedEntry"],message:"Only a queued day carries an exact series-entry reference."}),e.status==="pending"&&(e.reviewedAt!==null||e.reviewedBy!==null)&&t.addIssue({code:"custom",path:["reviewedAt"],message:"A pending day cannot carry reviewer completion identity."}),e.status!=="pending"&&(e.reviewedAt===null||e.reviewedBy===null)&&t.addIssue({code:"custom",path:["reviewedAt"],message:"Reviewed identity is required after a day review completes."})}),dO=l({schemaVersion:k("openpond.continualBenchIssueReview.v1"),id:L,seriesId:L,scheduleEntryId:L,passLabel:L,packet:wj,splitManifest:l({id:L,contentHash:Me}).strict(),decisions:f(l({taskId:L,disposition:b(["include","defer","exclude"]).nullable(),note:o().trim().max(2e3)}).strict()).min(2).max(1e4),status:b(["pending","reviewed","queued"]),queuedEntry:dr.nullable(),reviewedBy:L.nullable(),reviewedAt:ct.nullable(),revision:c().int().positive(),createdAt:ct,updatedAt:ct}).strict().superRefine((e,t)=>{const n=[...e.packet.cases.map(r=>r.taskId)].sort(),a=[...e.decisions.map(r=>r.taskId)].sort();JSON.stringify(n)!==JSON.stringify(a)&&t.addIssue({code:"custom",path:["decisions"],message:"Review decisions must cover the exact issue-packet cases."});const i=e.decisions.every(r=>r.disposition!==null&&r.note.length>0);e.status!=="pending"&&!i&&t.addIssue({code:"custom",path:["decisions"],message:"Every case requires a disposition and note before review completes."}),e.status==="queued"!=(e.queuedEntry!==null)&&t.addIssue({code:"custom",path:["queuedEntry"],message:"Only a queued review carries an exact series-entry reference."})}).readonly();function oS(e){return`${e.kind}:${e.id}`}function uO(e){return typeof e=="string"?e:oS(e)}const xa=o().trim().min(1).max(240),la=o().trim().min(8).max(256),iS=b(["grpo","dapo","gspo-token"]),rS=l({name:k("adamw").default("adamw"),weightDecay:c().nonnegative().max(1).default(0),beta1:c().positive().lt(1).default(.9),beta2:c().positive().lt(1).default(.999),epsilon:c().positive().max(.01).default(1e-8)}).strict().default({name:"adamw",weightDecay:0,beta1:.9,beta2:.999,epsilon:1e-8}),Ts=l({id:xa,revision:o().trim().min(1).max(256),tokenizerRevision:o().trim().min(1).max(256),chatTemplateHash:la}),mO=l({maxRollouts:c().int().positive().max(1e6),maxEnvironmentExecutions:c().int().positive().max(1e6),maxInputTokens:c().int().positive(),maxOutputTokens:c().int().positive(),maxOptimizerSteps:c().int().positive().max(1e6),wallTimeMs:c().int().positive(),maximumCostUsd:c().nonnegative().nullable()}),pO=l({method:k("grpo"),groupSize:c().int().min(2).max(128),normalization:k("group_standardized"),advantageEpsilon:c().positive().max(.01).default(1e-8),loss:iS,clipRange:c().positive().max(1).default(.2),iterations:c().int().min(2).max(16).default(2),microbatchSize:c().int().positive().max(128).default(1),gradientAccumulationSteps:c().int().positive().max(128).default(1),adamw:rS}),sS=l({method:k("ppo"),valueModel:Ts,gamma:c().min(0).max(1),gaeLambda:c().min(0).max(1),policyClip:c().positive().max(1),valueClip:c().positive().max(10),valueLossCoefficient:c().nonnegative().max(10),ppoEpochs:c().int().positive().max(100),minibatchSize:c().int().positive().max(1e5)}),fO=Kt("method",[pO,sS]),lS=l({rewardModelVersion:l({id:xa,contentHash:la}).strict(),qualificationReport:l({id:xa,contentHash:la}).strict().nullable().default(null),evaluationReferences:f(l({id:xa,contentHash:la}).strict()).max(1e3).default([]),checkpoint:l({id:xa,contentHash:la,objectRef:o().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/),files:f(l({path:o().trim().min(1).max(512),sizeBytes:c().int().positive(),sha256:la}).strict()).min(4).max(128)}).strict(),runtime:nS,processorRelease:l({id:xa,contentHash:la}).strict(),rewardComposerRelease:l({id:xa,contentHash:la}).strict(),executionReceipt:l({id:xa,contentHash:la}).strict()}).strict(),cS=l({schemaVersion:k("openpond.policyOptimization.v1"),policyModel:Ts,referenceModel:Ts,dataset:l({tasksetId:xa,tasksetHash:la,split:k("train"),selectionStrategy:b(["stable_hash_top_n","rft_easy_curriculum_v1"]),selectionSeed:c().int(),maxExamples:c().int().positive().max(1e5)}),sampler:l({temperature:c().min(0).max(2),topP:c().min(0).max(1),maxOutputTokens:c().int().positive().max(32768),maxTurns:c().int().positive().max(1e3),concurrency:c().int().positive().max(1e3)}),environment:l({id:xa,version:o().trim().min(1).max(256),toolContractHash:la}),reward:l({graderId:xa,graderHash:la,learnedPreference:lS.nullable().default(null)}),kl:l({coefficient:c().nonnegative().nullable(),referenceConstraint:k("fixed_reference")}),budgets:mO,checkpointEverySteps:c().int().positive(),seed:c().int(),evaluationSplit:k("frozen_eval"),optimizer:fO}),Te=o().trim().min(1).max(240),It=o().trim().min(1),ht=o().trim().min(8).max(256),Zs=fe(o(),ye()).default({}),dS=l({schemaVersion:k("openpond.localModelChatConfiguration.v1").default("openpond.localModelChatConfiguration.v1"),profile:b(["efficient","full_harness","custom"]).default("efficient"),systemPromptMode:b(["lean","full_harness","custom"]).default("lean"),customSystemPrompt:o().max(2e4).nullable().default(null),contextWindowTokens:c().int().min(128).max(32768).default(1024),maxOutputTokens:c().int().min(1).max(512).default(64),temperature:c().min(0).max(2).default(0),repetitionPenalty:c().min(.5).max(2).default(1.1),noRepeatNgramSize:c().int().min(0).max(10).default(3),compaction:b(["off","when_needed"]).default("when_needed"),keepWarmSeconds:c().int().min(0).max(3600).default(300),updatedAt:It.nullable().default(null)}),hO=dS.parse({}),gO=l({schemaVersion:k("openpond.managedAdapterServingProjection.v1"),teamId:Te.nullable().default(null),source:k("sandbox_managed_rl"),sourceRef:Te,canonicalArtifactId:Te.nullable(),canonicalArtifactState:b(["imported_unvalidated","evaluating","promotable","rejected","deleted"]).nullable(),canonicalDeploymentId:Te.nullable(),canonicalDeploymentState:b(["requested","deploying","ready","degraded","deleting","deleted","failed"]).nullable(),state:b(["pending","imported","ready","failed"]),customerBindingAllowed:C().default(!1),artifactContentHash:ht.nullable().default(null),baseProfileId:Te.nullable().default(null),publishedAt:It.nullable(),lastSyncedAt:It,lastError:o().trim().min(1).max(5e3).nullable()});function oW(e){const t=e.managedServing;return!!(t?.source==="sandbox_managed_rl"&&t.canonicalArtifactState==="promotable"&&t.customerBindingAllowed)}function uS(e){return e.state==="ready"&&e.canonicalArtifactState==="promotable"&&e.canonicalDeploymentState==="ready"&&e.customerBindingAllowed&&!!e.teamId&&!!e.canonicalArtifactId&&!!e.canonicalDeploymentId}function iW(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"&&uS(t)&&t.canonicalArtifactId&&t.canonicalDeploymentId?{kind:"sandbox_customer_binding",evaluationArtifactId:null,canonicalArtifactId:t.canonicalArtifactId,canonicalDeploymentId:t.canonicalDeploymentId}:null}function rW(e){const t=e.managedServing;return t?uS(t)&&t.canonicalArtifactId&&t.canonicalDeploymentId?{kind:"sandbox_serving",canonicalArtifactId:t.canonicalArtifactId,canonicalDeploymentId:t.canonicalDeploymentId}:null:{kind:"source_artifact",canonicalArtifactId:null,canonicalDeploymentId:null}}const Yp="openpond.crossSystemOperations.v1",sW="1.0.0",mS="openpond.crossSystemTools.v1",bO=["search_crm","query_billing","search_support","run_python"],vO=b(["train","validation","frozen_eval"]),yO=b(["easy","medium","hard"]),SO=b(["renewal_risk_v2"]);b(["renewal_exposure","collections_prioritization","invoice_reconciliation","sla_escalation","contract_billing_mismatch"]);l({seed:c().int().nonnegative(),split:vO,difficulty:yO,scenarioProfile:SO.optional()});const Nu={anyOf:[{type:"string",minLength:1,maxLength:256},{type:"null"}],default:null},$u={type:"integer",minimum:1,maximum:50,default:25},pS=[{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:Nu,limit:$u}}},{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:Nu,limit:$u}}},{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:Nu,limit:$u}}},{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}}}}],Js=EO({schemaVersion:mS,tools:pS}),xO=[`Use only the four registered synthetic Cross-System Operations tools. Contract ${Js}.`,"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(" "),kO=15;function _O(e="auto"){return[xO,"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: ${kO}.`,`Registered tool signatures: ${pS.map(wO).join("; ")}`].join(`
125
- `)}_O();function wO(e){const t=ac(e.parameters),n=ac(t.properties),a=fS(t.required),i=Object.fromEntries(a.map(r=>[r,Bl(n[r])]));return`${e.name}(${JSON.stringify(i)})`}function Bl(e){const t=ac(e),n=Pm(t.anyOf);if(n.length)return n.map(Bl).join("|");const a=Pm(t.enum);if(a.length)return a.join("|");if(t.type==="array")return[Bl(t.items)];if(t.type==="object"){const i=ac(t.properties),r=fS(t.required);return Object.fromEntries(r.map(s=>[s,Bl(i[s])]))}return typeof t.type=="string"?t.type:"unknown"}function ac(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Pm(e){return Array.isArray(e)?e:[]}function fS(e){return Pm(e).filter(t=>typeof t=="string")}const oc=b(bO),IO=Kt("kind",[l({kind:k("model"),turn:c().int().nonnegative(),content:o().max(1e5)}),l({kind:k("tool_call"),turn:c().int().nonnegative(),callId:o().trim().min(1).max(240),name:oc,arguments:fe(o(),ye())}),l({kind:k("tool_result"),turn:c().int().nonnegative(),callId:o().trim().min(1).max(240),name:oc,ok:C(),result:ye(),rows:c().int().nonnegative(),bytes:c().int().nonnegative(),durationMs:c().int().nonnegative(),error:o().trim().min(1).max(2e4).nullable()}),l({kind:k("final"),turn:c().int().nonnegative(),content:o().max(1e5)})]),CO=l({schemaVersion:k(Yp),id:o().trim().min(1).max(240),worldId:o().trim().min(1).max(240),taskId:o().trim().min(1).max(240),toolContractHash:k(Js),modelRef:l({providerId:o().trim().min(1),modelId:o().trim().min(1)}).nullable(),status:b(["completed","budget_exhausted","cancelled","infrastructure_failure"]),steps:f(IO).max(1e3),startedAt:o().trim().min(1),completedAt:o().trim().min(1),infrastructureError:o().trim().min(1).max(2e4).nullable(),metadata:fe(o(),ye()).default({})}),RO=l({schemaVersion:k(Yp),trajectoryId:o().trim().min(1).max(240),outcome:b(["correct","incorrect","parse_failure","budget_exhausted","tool_schema_violation","infrastructure_failure","cancelled"]),reward:c().min(0).max(1.15).nullable(),rewardEligible:C(),exactAnswer:C(),components:l({exactAnswer:c().min(0).max(1),efficiency:c().min(0).max(.1),conciseOutput:c().min(0).max(.05)}),metrics:l({toolCalls:c().int().nonnegative(),rowsRead:c().int().nonnegative(),bytesRead:c().int().nonnegative(),consecutiveRetrievalCalls:c().int().nonnegative(),wallTimeMs:c().int().nonnegative(),parseFailures:c().int().nonnegative(),budgetExhausted:C()}),parsedAnswer:ye().nullable(),feedback:f(o().trim().min(1).max(5e3)).max(100)}),AO=l({id:o().trim().min(1).max(240),type:k("function"),function:l({name:oc,arguments:o().max(2e4)})}),hS=l({role:b(["system","user","assistant","tool"]),content:o().max(2e5).nullable(),tool_call_id:o().trim().min(1).max(240).optional(),tool_calls:f(AO).max(4).optional()});l({schemaVersion:k(Yp),id:o().trim().min(1).max(240),taskId:o().trim().min(1).max(240),worldId:o().trim().min(1).max(240),trajectoryId:o().trim().min(1).max(240),toolContractHash:k(Js),approval:l({status:k("approved"),approvedBy:o().trim().min(1).max(240),approvedAt:o().trim().min(1)}),messages:f(hS).min(3).max(1e3)});const PO=l({tasksetTaskId:o().trim().min(1).max(240),environmentTaskId:o().trim().min(1).max(240),family:b(["renewal_exposure","collections_prioritization","invoice_reconciliation","sla_escalation","contract_billing_mismatch"]),prompt:o().trim().min(1).max(1e5),finalAnswer:o().trim().min(1).max(2e5),trajectoryId:o().trim().min(1).max(240),trajectoryHash:o().trim().min(8).max(256),toolNames:f(oc).min(1).max(100),toolCallCount:c().int().positive(),messageCount:c().int().min(3),reward:c().min(0).max(1.15),messages:f(hS).min(3).max(1e3)}),TO=l({status:k("approved"),approvedBy:o().trim().min(1).max(240),approvedAt:o().trim().min(1),previewHash:o().trim().min(8).max(256),trajectoryCount:c().int().positive()});l({schemaVersion:k("openpond.crossSystemExpertBootstrapPreview.v1"),tasksetId:o().trim().min(1).max(240),tasksetHash:o().trim().min(8).max(256),tasksetRevision:c().int().positive(),previewHash:o().trim().min(8).max(256),toolContractHash:k(Js),status:b(["ready_for_review","approved"]),approval:TO.nullable(),tasks:f(PO).min(1).max(100)});function EO(e){const t=Tm(e);let n=2166136261,a=2654435769;for(let i=0;i<t.length;i+=1){const r=t.charCodeAt(i);n=Math.imul(n^r,16777619),a=Math.imul(a^r,2246822507)}return`${mS}:${og(n)}${og(a)}`}function Tm(e){return Array.isArray(e)?`[${e.map(Tm).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${Tm(n)}`).join(",")}}`:JSON.stringify(e)}function og(e){return(e>>>0).toString(16).padStart(8,"0")}const MO=l({schemaVersion:k("openpond.singleTurnPolicyTrajectory.v1"),id:Te,taskId:Te,status:b(["completed","infrastructure_failure"]),promptHash:ht,responseText:o().max(2e6),infrastructureError:o().trim().min(1).max(1e4).nullable(),startedAt:It,completedAt:It,metadata:Zs}),jO=l({schemaVersion:k("openpond.ppoTrajectory.v1"),id:Te,taskId:Te,policyModelId:Te,referenceModelId:Te,valueModelId:Te,steps:f(l({index:c().int().nonnegative(),observationHash:ht,actionTokenIds:f(c().int().nonnegative()).min(1),terminated:C(),truncated:C(),reward:c(),policyLogProbability:c(),referenceLogProbability:c(),valuePrediction:c(),return:c(),advantage:c(),mask:c().min(0).max(1)})).min(1).max(1e5),createdAt:It}),OO=l({schemaVersion:k("openpond.exactAnswerVerifierResult.v1"),outcome:b(["correct","incorrect","parse_failure","infrastructure_failure"]),graderSetHash:ht,score:c().min(0).max(1).nullable(),passed:C(),rewardEligible:C(),expectedAnswerHash:ht,extractedAnswer:o().max(2e4).nullable(),feedback:f(o().trim().min(1).max(2e4)).max(1e3)}),NO=l({schemaVersion:k("openpond.rolloutTrajectoryReceipt.v1"),id:Te,jobId:Te,planId:Te,tasksetId:Te,tasksetHash:ht,taskId:Te,split:k("train"),correlationId:Te,provider:Te,providerTrace:l({invocationId:Te,experimentId:Te,rolloutId:Te,runId:Te,rowId:Te}),optimizerMethod:b(["grpo","ppo"]).default("grpo"),evidenceLevels:l({requested:b(["trajectory","aggregate","provider_reported"]),observed:b(["trajectory","aggregate","provider_reported"]),providerReported:b(["trajectory","aggregate","provider_reported"])}).default({requested:"trajectory",observed:"trajectory",providerReported:"provider_reported"}),budgetUsage:l({rollouts:c().int().nonnegative(),environmentExecutions:c().int().nonnegative(),inputTokens:c().int().nonnegative(),outputTokens:c().int().nonnegative(),optimizerSteps:c().int().nonnegative(),costUsd:c().nonnegative()}).default({rollouts:0,environmentExecutions:0,inputTokens:0,outputTokens:0,optimizerSteps:0,costUsd:0}),environment:l({id:Te,version:o().trim().min(1).max(256),worldId:Te,worldHash:ht,toolContractHash:ht}),policy:l({modelId:Te,checkpointId:Te.nullable(),completionParametersHash:ht}),status:b(["received","running","succeeded","failed"]),failureClass:b(["policy_failure","parse_failure","tool_schema_violation","budget_exhausted","cancelled","environment_failure","infrastructure_failure"]).nullable(),reward:l({eligible:C(),raw:c().min(0).max(1.15).nullable(),normalized:c().min(0).max(1).nullable(),components:fe(o(),c())}),trajectory:mn([CO,MO,jO]).nullable(),verifier:mn([RO,OO]).nullable(),providerStatus:fe(o(),ye()).default({}),receivedAt:It,startedAt:It.nullable(),completedAt:It.nullable(),updatedAt:It}),lW="dataset-exact-answer",cW="dataset-exact-answer-v1",dW="no-tools-v1",$o=b(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),Nc=b(["lora","full"]),mi=b(["openpond_managed"]),$O=l({schemaVersion:k("openpond.sftRecipe.v1"),method:k("sft"),parameterization:k("lora"),baseModel:l({id:Te,revision:o().trim().min(1).max(256),tokenizerRevision:o().trim().min(1).max(256),chatTemplateHash:ht}),dataset:l({trainSplit:k("train"),validationSplit:b(["validation","frozen_eval"]),completionOnly:C(),maxSequenceLength:c().int().positive().max(32768),maxExamples:c().int().positive().max(1e5).default(1e3),selectionStrategy:k("stable_hash_top_n").default("stable_hash_top_n"),selectionSeed:c().int().default(17)}),lora:l({rank:c().int().positive().max(256),alpha:c().positive().max(1024),dropout:c().min(0).max(1),targetModules:f(Te).min(1).max(100)}),optimizer:l({learningRate:c().positive(),epochs:c().positive().max(100),maxSteps:c().int().positive().max(1e6),batchSize:c().int().positive().max(1e4),gradientAccumulationSteps:c().int().positive().max(1e4),seed:c().int()}),resourceLimits:l({cpuThreads:c().int().positive().max(256),memoryBytes:c().int().positive(),wallTimeMs:c().int().positive()})});l({id:Te,input:fe(o(),ye()),expectedOutput:fe(o(),ye()),tags:f(Te).max(100).default([])});l({id:Te,prompt:o().min(1).max(5e5),chosen:o().min(1).max(5e5),rejected:o().min(1).max(5e5),sourceRefs:f(Te).min(1).max(1e4)});l({id:Te,input:fe(o(),ye()),tags:f(Te).max(100).default([])});l({schemaVersion:k("openpond.rewardModelRecipe.v1"),method:k("reward_model"),parameterization:k("lora_with_scalar_head"),runScope:b(["synthetic_smoke","human_preference"]),baseModel:l({id:Te,revision:o().trim().min(1).max(256),tokenizerRevision:o().trim().min(1).max(256),processorRevision:o().trim().min(1).max(256),chatTemplateHash:ht}).strict(),tasksetRelease:Ye,preferenceDatasetRelease:Ye,processorRelease:Ye,input:l({kind:k("structured_text"),serialization:b(["scenario_input_and_candidate_json_v1","visible_agent_trajectory_v1"]),maxCharacters:c().int().positive().max(5e5)}).strict().default({kind:"structured_text",serialization:"scenario_input_and_candidate_json_v1",maxCharacters:32e3}),lora:l({rank:c().int().positive().max(256),alpha:c().positive().max(1024),dropout:c().min(0).max(1),targetModules:f(Te).min(1).max(100)}).strict(),heads:l({scalar:k("pooled_hidden_state_linear"),bucket:b(["none","three_class"]).default("three_class")}).strict(),loss:l({ranking:k("bradley_terry"),rankingWeight:c().positive(),bucketWeight:c().nonnegative(),tieWeight:c().nonnegative()}).strict(),optimizer:l({learningRate:c().positive(),maxSteps:c().int().positive().max(1e5),batchSize:c().int().positive().max(1e4),gradientAccumulationSteps:c().int().positive().max(1e4),seed:c().int(),checkpointEverySteps:c().int().positive().max(1e5)}).strict(),resourceLimits:l({wallTimeMs:c().int().positive().max(1440*60*1e3),maxExamples:c().int().positive().max(1e5),maxInputCharacters:c().int().positive().max(5e5).default(32e3),maxImagePixels:c().int().positive().max(1e8).optional(),maximumSpendUsd:c().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 DO=l({schemaVersion:k("openpond.rftRecipe.v1"),method:k("grpo"),parameterization:k("lora"),baseModel:l({id:Te,revision:o().trim().min(1).max(256),tokenizerRevision:o().trim().min(1).max(256),chatTemplateHash:ht}),dataset:l({trainSplit:k("train"),validationSplit:b(["validation","frozen_eval"]),maxPromptTokens:c().int().positive().max(32768),maxExamples:c().int().positive().max(1e5).default(1e3),selectionStrategy:b(["stable_hash_top_n","rft_easy_curriculum_v1"]).default("stable_hash_top_n")}),lora:l({rank:c().int().positive().max(256)}),rollout:l({groupSize:c().int().min(2).max(64),concurrency:c().int().positive().max(32),maxTurns:c().int().positive().max(100),maxOutputTokens:c().int().positive().max(8192),temperature:c().min(0).max(2),topP:c().positive().max(1),seed:c().int()}),optimizer:l({learningRate:c().positive(),maxSteps:c().int().positive().max(1e5),clipRange:c().positive().max(1).default(.2),iterations:c().int().min(2).max(16).default(2),microbatchSize:c().int().positive().max(64).default(1),gradientAccumulationSteps:c().int().positive().max(64).default(1),advantageEpsilon:c().positive().max(.01).default(1e-8),adamw:rS}),loss:l({method:iS.default("grpo"),klBeta:c().min(0).nullable().default(null)}).default({method:"grpo",klBeta:null}),reward:l({graderId:Te,graderHash:ht,environmentId:Te,environmentVersion:o().trim().min(1).max(256),toolContractHash:ht,learnedPreference:lS.nullable().optional()}),resourceLimits:l({wallTimeMs:c().int().positive().max(1440*60*1e3),maxGpuSeconds:c().int().positive().max(10800).optional(),maxRollouts:c().int().positive().max(1e5),maxPayloadBytes:c().int().positive().max(10*1024*1024)}),policyOptimization:cS.nullable().default(null),continuation:l({schemaVersion:k("openpond.crossJobContinuationRequest.v1"),parentArtifact:Ye,sourceArtifact:l({jobId:Te,artifactId:Te,checkpointId:Te,contentHash:ht}).strict(),optimizerMode:b(["continue","reset"])}).strict().optional()}),LO=l({schemaVersion:k("openpond.dpoRecipe.v1"),method:k("dpo"),parameterization:k("lora"),policyModel:Ts,referenceModel:Ts,dataset:l({trainSplit:k("train"),validationSplit:b(["validation","frozen_eval"]),maxPairs:c().int().positive().max(1e5),maxPromptTokens:c().int().positive().max(32768),maxCompletionTokens:c().int().positive().max(32768),selectionStrategy:k("stable_hash_top_n"),selectionSeed:c().int()}),lora:l({rank:c().int().positive().max(256),alpha:c().positive().max(1024),dropout:c().min(0).max(1),targetModules:f(Te).min(1).max(100)}),loss:l({variant:k("sigmoid"),beta:c().positive().max(10),labelSmoothing:c().min(0).max(.5).default(0)}),optimizer:l({learningRate:c().positive(),epochs:c().positive().max(100),maxSteps:c().int().positive().max(1e6),batchSize:c().int().positive().max(1e4),gradientAccumulationSteps:c().int().positive().max(1e4),seed:c().int()}),referenceLogprobs:l({cacheSchemaVersion:k("openpond.dpoReferenceLogprobs.v1"),cacheKey:ht,invalidationHash:ht}),resourceLimits:l({cpuThreads:c().int().positive().max(256),memoryBytes:c().int().positive(),wallTimeMs:c().int().positive()})}),zO=l({schemaVersion:k("openpond.ppoRecipe.v1"),method:k("ppo"),parameterization:k("lora"),policyOptimization:cS.extend({optimizer:sS}),lora:l({rank:c().int().positive().max(256),alpha:c().positive().max(1024),dropout:c().min(0).max(1),targetModules:f(Te).min(1).max(100)}),valueHead:l({initialization:k("policy_hidden_state_linear"),optimizerLearningRate:c().positive(),artifactName:k("value_head.safetensors")}),policyLearningRate:c().positive(),resume:l({checkpointId:Te.nullable(),policyHash:ht,referenceHash:ht,valueModelHash:ht,optimizerStateHash:ht.nullable()}),resourceLimits:l({cpuThreads:c().int().positive().max(256),memoryBytes:c().int().positive(),wallTimeMs:c().int().positive()})}),UO=l({schemaVersion:k("openpond.unsupportedRecipe.v1"),method:$o.exclude(["sft","dpo","grpo","ppo"]),parameterization:Nc,unsupportedReason:o().trim().min(1).max(5e3)}),gS=mn([$O,LO,DO,zO,UO]),HO=l({schemaVersion:k("openpond.trainingDestinationCapabilities.v1"),destinationId:mi,available:C(),methods:f($o),parameterizations:f(Nc),modelAllowlist:f(Te).default([]),maxDatasetBytes:c().int().nonnegative().nullable(),environmentPlacements:f(b(["none","local","remote","colocated","provider_native"])),nonProduction:C(),unavailableReason:o().trim().min(1).max(5e3).nullable(),checkedAt:It}),qO=l({destinationId:mi,available:C(),methods:f($o),parameterizations:f(Nc),nonProduction:C(),unavailableReason:o().trim().min(1).max(5e3).nullable()}),BO=l({schemaVersion:k("openpond.baseModelCandidate.v1"),selectionKey:Te,label:o().trim().min(1).max(500),sourceLabel:o().trim().min(1).max(500),preference:Gs,available:C(),nonProduction:C(),unavailableReason:o().trim().min(1).max(5e3).nullable(),methods:f($o),executionOptions:f(qO).min(1)}),FO=l({code:Te,severity:b(["warning","error"]),path:o().trim().max(2e3).nullable(),message:o().trim().min(1).max(5e3)}),VO=l({schemaVersion:k("openpond.trainingCompatibility.v1"),compatible:C(),destinationId:mi,tasksetId:Te,recipeMethod:$o,issues:f(FO),checkedAt:It}),WO=mn([qy,b(["destination_unavailable","destination_method_unsupported","destination_model_unsupported","destination_parameterization_unsupported","experimental_destination"])]);l({method:$o,state:b(["recommended","compatible","needs_dataset_work","destination_unavailable","experimental_destination"]),reasonCodes:f(WO).default([]),reasons:f(o().trim().min(1).max(5e3)).default([]),destinationId:mi.nullable().default(null)});b(["small","standard","custom","small_experiment"]);const KO=gj,bS=l({schemaVersion:k("openpond.trainingPlan.v1"),id:Te,modelId:Te,tasksetId:Te,tasksetHash:ht,comparisonSeriesEntry:dr.nullable().optional(),harnessRelease:Ye.nullable().optional(),modelImprovementQualification:Ye.nullable().optional(),destinationId:mi,recipe:gS,environmentPlacement:b(["none","local","remote","colocated","provider_native"]),compatibility:VO,dataPolicy:l({exportApproved:C(),approvedSourceIds:f(Te),retentionDays:c().int().nonnegative().nullable(),region:o().trim().min(1).max(200).nullable()}),estimatedCostUsd:c().nonnegative().nullable(),createdAt:It,contentHash:ht}),GO=l({path:o().trim().min(1).max(2e3),sha256:ht,sizeBytes:c().int().nonnegative(),role:b(["manifest","task_data","grader","environment","recipe","policy","provenance"])}),Xp=l({schemaVersion:k("openpond.trainingBundle.v1"),id:Te,planId:Te,tasksetId:Te,tasksetHash:ht,recipeHash:ht,files:f(GO).min(1).max(1e6),totalSizeBytes:c().int().nonnegative(),sourceIds:f(Te),excludedSourceIds:f(Te),containsRawChats:k(!1),containsSecrets:k(!1),containsHiddenGraderAssets:k(!1),createdAt:It,contentHash:ht});l({schemaVersion:k("openpond.trainingBundleExport.v1"),manifest:Xp,files:f(l({path:o().trim().min(1).max(2e3),sha256:ht,sizeBytes:c().int().nonnegative(),encoding:k("base64"),content:o()})).min(1),contentHash:ht});l({schemaVersion:k("openpond.trainingPreparedStart.v1"),plan:bS,bundle:Xp,approvalActor:Te.nullable(),preparedAt:It});l({schemaVersion:k("openpond.trainingApproval.v1"),id:Te,planId:Te,bundleHash:ht,harnessRelease:Ye.nullable().optional(),modelImprovementQualification:Ye.nullable().optional(),destinationId:mi,modelId:Te,method:$o,parameterization:Nc,maximumCostUsd:c().nonnegative().nullable(),approvedBy:Te,approvedAt:It});l({schemaVersion:k("openpond.trainingJobSourceSnapshot.v1"),modelProjectId:Te,sourceProjectRevision:c().int().positive(),profileId:Te,taskset:l({id:Te,revision:c().int().positive(),contentHash:ht}).strict(),tasksetRelease:Ye,harnessRelease:Ye,baseModel:Gs,method:$o}).strict();const ZO=b(["queued","starting","running","cancelling","cancelled","succeeded","failed","reconciling"]),vS=l({schemaVersion:k("openpond.trainingJob.v1"),id:Te,planId:Te,bundleHash:ht,approvalId:Te,destinationId:mi,status:ZO,nonProduction:C(),workerPid:c().int().positive().nullable(),startedAt:It.nullable(),completedAt:It.nullable(),error:o().trim().min(1).max(2e4).nullable(),createdAt:It,updatedAt:It,metadata:Zs}),JO=l({schemaVersion:k("openpond.trainingJobEvent.v1"),id:Te,jobId:Te,sequence:c().int().nonnegative(),type:b(["queued","start","progress","metric","checkpoint","cancel","complete","failure","reconcile"]),timestamp:It,payload:Zs}),YO=l({schemaVersion:k("openpond.sftStepMetric.v1"),step:c().int().nonnegative(),maxSteps:c().int().positive(),timestamp:It,epoch:c().nonnegative().nullable(),loss:c().nullable(),learningRate:c().nonnegative().nullable(),gradientNorm:c().nonnegative().nullable(),entropy:c().nonnegative().nullable(),meanTokenAccuracy:c().min(0).max(1).nullable(),preferenceAccuracy:c().min(0).max(1).nullable().default(null),preferenceMargin:c().nullable().default(null),chosenReward:c().nullable().default(null),rejectedReward:c().nullable().default(null),chosenLogProbability:c().nullable().default(null),rejectedLogProbability:c().nullable().default(null),reward:c().nullable().default(null),policyLoss:c().nullable().default(null),advantageLoss:c().nullable().default(null),inputTokensSeen:c().int().nonnegative().nullable(),memoryBytes:c().int().nonnegative().nullable(),elapsedSeconds:c().nonnegative().nullable()}),XO=l({schemaVersion:k("openpond.policyOptimizationMetric.v1"),method:b(["grpo","ppo"]),step:c().int().nonnegative(),timestamp:It,learningRate:c().nonnegative().nullable().default(null),policyLoss:c().nullable(),valueLoss:c().nullable(),gradientNorm:c().nonnegative().nullable().default(null),meanReward:c().nullable(),meanReturn:c().nullable(),kl:c().nullable(),behaviorPolicyKlPreUpdate:c().nonnegative().nullable().default(null),entropy:c().nullable(),policyClipFraction:c().min(0).max(1).nullable(),behaviorPolicyClipFractionPreUpdate:c().min(0).max(1).nullable().default(null),valueClipFraction:c().min(0).max(1).nullable(),explainedVariance:c().nullable(),rolloutLearnerLag:c().int().nonnegative().nullable(),inputTokens:c().int().nonnegative(),outputTokens:c().int().nonnegative(),environmentExecutions:c().int().nonnegative(),trajectoryCount:c().int().nonnegative().nullable().default(null),costUsd:c().nonnegative().nullable()}),QO=l({schemaVersion:k("openpond.managedTrainingRunEvidence.v2"),provider:Te,providerRunId:Te,state:Te,progress:l({targetOptimizerSteps:c().int().nonnegative(),committedOptimizerSteps:c().int().nonnegative(),skippedOptimizerSteps:c().int().nonnegative()}),reward:l({finalMean:c().nullable(),variance:c().nonnegative().nullable(),minimum:c().nullable(),maximum:c().nullable(),distinctValueCount:c().int().nonnegative(),noSignalGroupCount:c().int().nonnegative(),trajectoryCount:c().int().nonnegative(),eligibleTrajectoryCount:c().int().nonnegative()}),usage:l({inputTokens:c().int().nonnegative(),outputTokens:c().int().nonnegative(),environmentExecutions:c().int().nonnegative()}),resource:l({provider:Te,gpuType:o().trim().min(1).max(300).nullable(),gpuCount:c().int().nonnegative().nullable(),hourlyCostUsd:c().nonnegative().nullable(),durationSeconds:c().nonnegative().nullable(),gpuSeconds:c().nonnegative().nullable()}),cost:l({totalUsd:c().nonnegative().nullable()}),checkpoint:l({id:Te,policyVersion:c().int().nonnegative(),sha256:ht.nullable(),sizeBytes:c().int().nonnegative().nullable()}).nullable(),movement:l({adapterDeltaNorm:c().nonnegative().nullable()}),evaluations:f(l({kind:b(["baseline","candidate"]),policyVersion:c().int().nonnegative(),score:c().nullable(),threshold:c().nullable(),passed:C().nullable()})),canonicalPublication:l({state:Te.nullable(),artifactId:Te.nullable()}),syncedAt:It}),ig=l({count:c().int().nonnegative(),scoredCount:c().int().nonnegative(),meanScore:c().min(0).max(1).nullable(),passedCount:c().int().nonnegative(),passRate:c().min(0).max(1).nullable()}),rg=l({status:b(["scored","unavailable"]),score:c().min(0).max(1).nullable(),passed:C(),rewardEligible:C(),failureClass:b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),feedback:f(o().trim().min(1).max(2e4)).max(1e3),components:f(l({graderId:Te,score:c().min(0).max(1),passed:C(),feedback:o().trim().max(2e4).nullable()})).max(1e3)}),e2=l({taskId:Te,input:fe(o(),ye()),baseOutput:fe(o(),ye()).nullable(),trainedOutput:fe(o(),ye()).nullable(),baseGrade:rg.nullable(),trainedGrade:rg.nullable()}),t2=l({schemaVersion:k("openpond.trainingEvaluationSummary.v1"),jobId:Te,tasksetId:Te,base:ig,trained:ig,meanScoreDelta:c().min(-1).max(1).nullable(),examples:f(e2).max(1e6)});l({schemaVersion:k("openpond.trainingRunDetail.v1"),job:vS,events:f(JO),stepMetrics:f(YO),policyMetrics:f(XO).default([]),managedEvidence:QO.nullable().default(null),evaluation:t2.nullable(),generatedAt:It});const n2=l({schemaVersion:k("openpond.trainingArtifact.v1"),id:Te,jobId:Te,kind:b(["adapter","checkpoint","metrics","log","manifest","evaluation"]),path:o().trim().min(1).max(4e3),sha256:ht,sizeBytes:c().int().nonnegative(),baseModelId:Te.nullable(),baseModelRevision:o().trim().min(1).max(256).nullable(),tokenizerRevision:o().trim().min(1).max(256).nullable(),chatTemplateHash:ht.nullable(),nonProduction:C(),createdAt:It,metadata:Zs}),a2=l({schemaVersion:k("openpond.modelArtifactLineage.v1"),id:Te,modelId:Te,artifactId:Te,jobId:Te,tasksetId:Te,tasksetHash:ht,graderHash:ht,planHash:ht,bundleHash:ht,recipeHash:ht,workerVersion:o().trim().min(1).max(256),trainerVersion:o().trim().min(1).max(256),importedAt:It,frozenEvaluationArtifactId:Te.nullable(),promotable:C(),pinned:C().default(!1),status:b(["imported","rejected"]).default("imported"),rejectedAt:It.nullable().default(null),rejectionReason:o().trim().min(1).max(5e3).nullable().default(null),chatConfiguration:dS.default(hO),managedServing:gO.nullable().default(null)}),o2=b(["chat_manual","agent","extension","authoring_optimizer"]),i2=l({schemaVersion:k("openpond.modelBinding.v1"),id:Te,profileId:Te,role:o2,roleTargetId:Te,modelArtifactLineageId:Te,tasksetId:Te,evaluationArtifactId:Te.nullable(),status:b(["active","rolled_back"]),priorBindingId:Te.nullable(),rollbackTargetBindingId:Te.nullable(),promotedBy:Te,promotedAt:It,rolledBackAt:It.nullable(),metadata:Zs});l({schemaVersion:k("openpond.trainingActivity.v1"),profileId:Te,active:C(),activeCounts:l({jobs:c().int().nonnegative(),creations:c().int().nonnegative(),minerRuns:c().int().nonnegative(),datasetImports:c().int().nonnegative()}),revision:ht,generatedAt:It});l({schemaVersion:k("openpond.tasksetOperationalState.v1"),tasksetId:Te,attempts:f(DM),artifacts:f(LM),grades:f(UM),generatedAt:It});const r2=l({schemaVersion:k("openpond.trainingState.v1"),profileId:Te,sources:f(Ay),creations:f(Vy),tasksetDrafts:f(aj).default([]),tasksets:f(Yh),benchmarkRuns:f(iu()).default([]),benchmarkComparisons:f(iu()).default([]),datasetImports:f(uj).default([]),datasetArtifacts:f(oM).default([]),graderAuditReports:f(HM),evaluationResults:f(iu()).default([]),candidates:f(Sy),minerConfig:Ac,minerRuns:f(eM).default([]),modelProjects:f(KO).default([]),modelVersions:f(Fj).default([]),modelRuns:f(aO).default([]),comparisonSeries:f($j).default([]),comparisonSeriesEntries:f(qj).default([]),modelCurrencySnapshots:f(sO).default([]),continualBenchIssueReviews:f(dO).default([]),continualLearningDailyBatches:f(cO).default([]),rewardModelVersions:f(Vj).default([]),rewardModelRuns:f(Kj).default([]),modelTasksets:f(Yh).default([]),plans:f(bS),bundles:f(Xp),jobs:f(vS),artifacts:f(n2),models:f(a2),rolloutReceipts:f(NO).default([]),modelBindings:f(i2).default([]),destinations:f(HO),baseModelCandidates:f(BO).default([]),activityRevision:ht.optional(),generatedAt:It});var Zt=o().trim().min(1).max(500),ur=o().regex(/^[a-f0-9]{64}$/),_a=o().datetime({offset:!0}),Ht=l({id:Zt,contentHash:ur}).strict(),yS=Ht.extend({revision:c().int().positive()}).strict(),wr=l({schemaVersion:k("openpond.baseModelPreference.v1"),modelId:Zt,revision:o().trim().min(1).max(256).nullable(),tokenizerRevision:o().trim().min(1).max(256).nullable(),chatTemplateHash:o().trim().min(8).max(256).nullable(),modelAssetId:Zt.nullable(),source:b(["managed","local","builtin"])}).strict(),SS=b(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),xS=l({schemaVersion:o().regex(/^openpond\.[A-Za-z0-9]+Recipe\.v\d+$/),method:SS,parameterization:b(["lora","full"])}).catchall(ye()),kS=l({tasksetRef:yS.nullable().default(null),tasksetRelease:Ht.nullable().default(null),harnessRelease:Ht.nullable().default(null),baseModel:wr.nullable().default(null),method:SS.nullable().default(null),destinationId:Zt.nullable().default(null),managedRolloutPlacement:b(["local","remote"]).default("remote"),managedGpuPlacementObjective:b(["fast","balanced","economical"]).default("balanced"),managedGpuRequirement:b(["any","h100_hbm3"]).default("any"),runPreset:b(["small","standard","custom","small_experiment"]).nullable().default(null),recipe:xS.nullable().default(null),preferredMaximumSpendUsd:c().nonnegative().nullable().default(null),preferredRetentionDays:c().int().nonnegative().nullable().default(null)}).strict(),_S=kS.omit({managedGpuRequirement:!0}),s2=l({schemaVersion:k("openpond.hostedModelProjectLink.v1"),teamId:Zt,projectId:Zt,portableProjectId:Zt,revision:c().int().positive(),etag:ur,syncedSourceRevision:c().int().positive(),syncedAt:_a,tasksets:f(l({localTasksetId:Zt,releaseId:Zt,releaseRevision:c().int().positive(),releaseHash:ur,hostedTasksetId:Zt,syncedAt:_a}).strict()).max(1e4).default([])}).strict(),l2=l({localTasksetId:Zt,releaseId:Zt,releaseRevision:c().int().positive(),releaseHash:ur,state:b(["syncing","synced","sync_failed"]),hostedTasksetId:Zt.nullable().default(null),lastAttemptAt:_a,syncedAt:_a.nullable().default(null),lastError:o().trim().min(1).max(5e3).nullable().default(null)}).strict();l({schemaVersion:k("openpond.modelProject.v2"),id:Zt,profileId:Zt,revision:c().int().positive().default(1),name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:wr.nullable(),defaultDestinationId:Zt.nullable(),trainingSetup:kS,hosted:s2.nullable().default(null),tasksetSyncs:f(l2).max(1e4).default([]),createdAt:_a,updatedAt:_a}).strict();l({schemaVersion:k("openpond.hostedModelProjectSync.v2"),portableProjectId:Zt,name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:wr.nullable(),defaultDestinationId:Zt.nullable(),trainingSetup:_S,sourceRevision:c().int().positive(),sourceUpdatedAt:_a,expectedEtag:ur.nullable().default(null)}).strict();var c2=l({id:Zt,teamId:Zt,portableProjectId:Zt,name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:wr.nullable(),defaultDestinationId:Zt.nullable(),trainingSetup:_S,sourceRevision:c().int().positive(),sourceUpdatedAt:_a,revision:c().int().positive(),etag:ur,createdAt:_a,updatedAt:_a}).strict(),d2=l({kind:b(["taskset_release","harness_release","dataset_release","evidence_set","model_version","reward_model_version","evaluation_receipt"]),ref:Ht,role:o().trim().min(1).max(200).nullable().default(null),updatedAt:_a}).strict();l({project:c2,resources:f(d2).max(1e4),jobCount:c().int().nonnegative(),latestJobIds:f(Zt).max(100)}).strict();l({schemaVersion:k("openpond.modelProjectApiError.v2"),code:o().trim().min(1).max(200),message:o().trim().min(1).max(5e3),retryable:C().default(!1),requestId:o().trim().min(1).max(500).nullable().default(null),details:fe(o(),ye()).default({})}).strict();var kn=o().trim().min(1).max(500),na=o().regex(/^[a-f0-9]{64}$/),wa=o().datetime({offset:!0});l({schemaVersion:k("openpond.trainingInputArtifactUpload.v2"),kind:b(["portable_training_bundle","reward_model_dataset"]),idempotencyKey:o().trim().min(1).max(500),sourceManifest:Ht,payload:ye(),contentHash:na}).strict();l({schemaVersion:k("openpond.trainingInputArtifact.v2"),kind:b(["portable_training_bundle","reward_model_dataset"]),sourceManifest:Ht,artifactRef:o().trim().min(1).max(2e3),contentHash:na,sizeBytes:c().int().positive(),createdAt:wa}).strict();var wS=b(["reward_model_train","policy_optimize"]),u2=b(["queued","admitting","provisioning","running","stopping","cancelling","succeeded","failed","cancelled"]),m2=l({id:kn,version:o().trim().min(1).max(200).nullable().default(null),required:C().default(!0)}).strict(),p2=l({modelProject:l({id:kn,portableProjectId:kn,revision:c().int().positive(),contentHash:na}).strict(),harnessRunManifest:Ht,harnessRelease:Ht,taskset:yS,tasksetRelease:Ht,dataset:Ht,evidenceSets:f(Ht).max(1e4)}).strict(),f2=l({kind:k("reward_model_train"),baseModel:wr,preferenceDatasetRelease:Ht,processorRelease:Ht,recipe:l({schemaVersion:k("openpond.rewardModelRecipe.v1"),method:k("reward_model"),parameterization:k("lora_with_scalar_head")}).catchall(ye())}).strict(),h2=l({kind:k("deterministic"),grader:Ht,composer:Ht.nullable().default(null)}).strict(),g2=l({kind:k("learned_reward"),rewardModelVersion:Ht,qualificationReport:Ht.nullable().default(null),evaluationReferences:f(Ht).max(1e3).default([]),scorerArtifact:l({artifactRef:o().trim().min(1).max(2e3),contentHash:na,executionReceipt:Ht}).strict(),processorRelease:Ht,rewardComposerRelease:Ht}).strict(),b2=l({kind:k("policy_optimize"),baseModel:wr,recipe:xS,rewardSource:Kt("kind",[h2,g2]),resumeFrom:Ht.nullable().default(null)}).strict(),v2=Kt("kind",[f2,b2]),y2=l({approvalHash:na,approvedAt:wa,exportApproved:C(),maximumSpendUsd:c().nonnegative(),retentionDays:c().int().nonnegative().nullable(),region:o().trim().min(1).max(200).nullable().default(null)}).strict();l({schemaVersion:k("openpond.trainingJobSubmission.v2"),idempotencyKey:o().trim().min(1).max(500),name:o().trim().min(1).max(200),source:p2,job:v2,requestedCapabilities:f(m2).max(1e3),placementObjective:b(["fast","balanced","economical"]),budget:l({maximumSpendUsd:c().nonnegative(),maximumWallSeconds:c().int().positive()}).strict(),approval:y2,contentHash:na}).strict().superRefine((e,t)=>{e.approval.maximumSpendUsd!==e.budget.maximumSpendUsd&&t.addIssue({code:"custom",path:["approval","maximumSpendUsd"],message:"Approved spend must equal the immutable Job budget."})});var S2=l({schemaVersion:k("openpond.trainingJob.v2"),id:kn,teamId:kn,kind:wS,modelProjectId:kn,portableProjectId:kn,sourceProjectRevision:c().int().positive(),submissionHash:na,state:u2,phase:o().trim().min(1).max(200),version:c().int().nonnegative(),progress:c().min(0).max(1),rolloutProgress:l({groupsCompleted:c().int().nonnegative(),groupsTarget:c().int().nonnegative(),optimizerUpdatesApplied:c().int().nonnegative(),optimizerUpdatesSkipped:c().int().nonnegative()}).strict(),accruedSpendUsd:c().nonnegative(),terminalReason:o().trim().min(1).max(5e3).nullable(),createdAt:wa,updatedAt:wa,completedAt:wa.nullable()}).strict();l({schemaVersion:k("openpond.trainingJobPage.v2"),jobs:f(S2).max(1e3),nextCursor:o().trim().min(1).max(2e3).nullable()}).strict();l({schemaVersion:k("openpond.trainingJobEvent.v2"),id:kn,jobId:kn,sequence:c().int().nonnegative(),type:kn,phase:o().trim().min(1).max(200),message:o().trim().min(1).max(5e3).nullable(),data:fe(o(),ye()).default({}),createdAt:wa}).strict();l({schemaVersion:k("openpond.trainingJobLog.v2"),jobId:kn,sequence:c().int().nonnegative(),level:b(["debug","info","warning","error"]),message:o().max(2e4),createdAt:wa}).strict();l({expectedVersion:c().int().nonnegative()}).strict();var x2=l({schemaVersion:k("openpond.trainingJobOutput.v2"),id:kn,jobId:kn,kind:b(["checkpoint","adapter","scorer","metrics","evaluation","trace","receipt"]),artifactRef:o().trim().min(1).max(2e3),contentHash:na,sizeBytes:c().int().nonnegative(),metadata:fe(o(),ye()).default({}),createdAt:wa}).strict(),k2=l({schemaVersion:k("openpond.trainingExecutionReceipt.v2"),id:kn,teamId:kn,jobId:kn,submissionHash:na,manifestHash:na,recipeHash:na,capabilityHash:na,runtimeRelease:Ht,inputs:f(Ht).max(1e4),outputs:f(Ht).max(1e4),spendUsd:c().nonnegative(),durationSeconds:c().nonnegative(),cleanupComplete:C(),issuer:kn,issuedAt:wa,signature:o().trim().min(1).max(1e4).nullable()}).strict();l({schemaVersion:k("openpond.trainingJobOutputs.v2"),outputs:f(x2).max(1e4),receipt:k2.nullable()}).strict();l({schemaVersion:k("openpond.trainingApiError.v2"),code:o().trim().min(1).max(200),message:o().trim().min(1).max(5e3),retryable:C().default(!1),requestId:o().trim().min(1).max(500).nullable().default(null),details:fe(o(),ye()).default({})}).strict();l({schemaVersion:k("openpond.trainingCapabilities.v2"),capabilityHash:na,jobKinds:f(wS),methods:f(o().trim().min(1).max(200)),placements:f(b(["local","remote","colocated","provider_native"])),controls:l({cancel:C(),stopAfterGroup:C(),resumeFromCheckpoint:C()}).strict(),limits:l({maximumSpendUsd:c().nonnegative(),maximumWallSeconds:c().int().positive(),maximumArtifactBytes:c().int().positive()}).strict(),checkedAt:wa,expiresAt:wa}).strict();const po=o().trim().min(1).max(1e5),_2=b(["no_action","harness_maintenance","runtime","product","taskset","model_improvement"]),w2=b(["none","runtime_service","product_team","human_review","evaluation_system","training_system"]),IS=b(["observation","trigger","route_decision","refiner_outcome","proposal","validation","apply_receipt","harness_advance","rollback","work_outcome","taskset","evaluation","training_qualification","model_candidate"]),Qp=l({kind:b(["personal","team"]),id:ie}).strict(),ef=l({policy:de,state:b(["authorized","revoked","deleted","expired"]),checkedAt:nt}).strict(),Es=l({evidence:de,kind:IS,sourceRef:ie,sourcePolicy:ef,occurrenceKey:we,occurredAt:nt}).strict(),I2=l({evidence:de,sourcePolicy:ef.nullable(),reason:b(["outside_scope","before_watermark","duplicate","resolved","revoked","deleted","expired","sensitive","unverified","budget"])}).strict(),sg=l({cursor:we,throughCreatedAt:nt}).strict(),C2=l({fingerprint:we,recurrenceFamily:o().trim().min(1).max(1e3),statement:po,candidateDisposition:b(["observe","confirm"]).optional(),independentOccurrences:c().int().positive().max(1e6),unresolvedOccurrences:c().int().positive().max(1e6)}).strict().refine(e=>e.unresolvedOccurrences<=e.independentOccurrences,"unresolved occurrences cannot exceed independent occurrences"),CS=b(["harness","runtime","product","retrieval","tools","evaluation","model"]),R2=l({layer:CS,status:b(["not_applicable","unresolved","resolved","blocked"]),reason:po,evidenceRefs:f(de).max(1e3)}).strict(),RS=l({schemaVersion:k("openpond.harnessEvaluationReviewReceipt.v1"),id:ie,ownerScope:Qp,workspaceRef:ie,harnessRelease:de,previousWatermark:sg.nullable(),nextWatermark:sg,selectedEvidence:f(Es).max(1e4),excludedEvidence:f(I2).max(1e4),claim:C2.nullable(),classification:_2,triage:f(R2).max(16),reason:po,nextAuthority:w2,maxEstimatedCostUsd:c().finite().nonnegative(),tasksetProposal:de.nullable(),evaluation:de.nullable(),trainingQualification:de.nullable(),policyVersion:ie,createdAt:nt,metadata:Ct}).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"})}),A2=RS.extend({contentHash:we}).strict();function Ys(e){const t=RS.parse(e);return A2.parse({...t,contentHash:_t(t)})}l({id:ie,evidence:de,kind:IS,sourceRef:ie,occurredAt:nt,payload:fe(o(),ye())}).strict();const P2=l({schemaVersion:k("openpond.harnessEvaluationReviewModelDecision.v2"),decision:k("no_action"),reason:po,ignoredEvidence:f(l({id:ie,reason:o().trim().min(1).max(2e3)}).strict()).max(1e3)}).strict(),T2=l({schemaVersion:k("openpond.harnessEvaluationReviewModelDecision.v2"),decision:k("review"),classification:b(["harness_maintenance","runtime","product","taskset"]),selectedEvidenceIds:f(ie).min(1).max(1e3),ignoredEvidence:f(l({id:ie,reason:o().trim().min(1).max(2e3)}).strict()).max(1e3),recurrenceFamily:o().trim().min(1).max(1e3),statement:po,triageLayer:CS,expectedOutcome:po,counterevidence:o().trim().max(1e4),confidence:c().min(0).max(1),candidateDisposition:b(["observe","confirm"]).nullable(),reason:po}).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"]})}),E2=l({schemaVersion:k("openpond.harnessEvaluationReviewModelDecision.v2"),decision:k("resolve_candidate"),candidateId:ie,candidateFingerprint:we,selectedEvidenceIds:f(ie).min(1).max(1e3),ignoredEvidence:f(l({id:ie,reason:o().trim().min(1).max(2e3)}).strict()).max(1e3),confidence:c().min(0).max(1),reason:po}).strict();Kt("decision",[P2,T2,E2]);l({schemaVersion:k("openpond.harnessEvaluationReviewNavigationDecision.v1"),selectedEvidenceIds:f(ie).min(1).max(50),reason:po}).strict();const $c=l({name:o().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:o().trim().min(1).max(2e3),inputSchema:fe(o(),ye()),inputSchemaHash:we,sideEffect:b(["read","write"]),timeoutMs:c().int().positive().max(36e5)}).strict(),tf=l({id:ie,required:C(),scopes:f(o().trim().min(1).max(500)).max(100).default([]),portability:b(["portable","host_adapter","local_only","hosted_only"])}).strict(),M2=l({portable:C(),blockers:f(o().trim().min(1).max(2e3)).max(1e3),localOnlyAssetRefs:f(ie).max(1e4),hostPrivateAssetRefs:f(ie).max(1e4)}).strict(),j2=l({schemaVersion:k("openpond.agentSnapshot.v2"),id:ie,sourceRelease:de.nullable(),instructions:f(Gn).max(1e4),skills:f(Gn).max(1e4),agents:f(Gn).max(1e4),toolDeclarations:f($c).max(200),capabilityRequirements:f(tf).max(200),dependencyLock:Gn,portability:M2,metadata:Ct}).strict();j2.extend({contentHash:we}).strict();const AS=l({create:k(!0),reset:k(!0),step:k(!0),collect:k(!0),destroy:k(!0),resetScope:b(["task","attempt"])}).strict(),PS=l({visibleEvidence:f(ie).max(1e3),privilegedEvidence:f(ie).max(1e3),privateVerifierIsolation:C()}).strict(),O2=l({schemaVersion:k("openpond.harnessRelease.v2"),id:ie,agentSnapshot:de,program:Gn,tools:f($c).max(200),lifecycle:AS,graderInterface:PS,files:f(Gn).max(1e5),metadata:Ct}).strict();O2.extend({contentHash:we}).strict();const N2=l({id:ie,turn:c().int().nonnegative(),kind:b(["message","tool_call","terminal"]),name:ie.nullable(),arguments:fe(o(),ye()),content:o().max(1e6).nullable()}).strict(),$2=l({actionId:ie,turn:c().int().nonnegative(),terminal:C(),output:fe(o(),ye()),artifactRefs:f(Zn).max(1e5)}).strict(),D2=l({sequence:c().int().nonnegative(),type:b(["created","reset","action","observation","terminal","failure","collected","destroyed"]),payloadHash:we,metadata:Ct}).strict();l({schemaVersion:k("openpond.harnessTrace.v1"),manifest:de,taskId:ie,seed:o().trim().min(1).max(500),events:f(D2).max(1e6),actions:f(N2).max(1e5),observations:f($2).max(1e5),terminal:C(),failureClass:Cc.nullable(),output:fe(o(),ye()),contentHash:we}).strict();const Dc=o().trim().min(1).max(1e5),Xs=fe(o(),ye()).default({}),L2=b(["completed_tool_batch","before_model_step","turn_completed","turn_paused"]),TS=l({kind:L2,eventSequence:c().int().nonnegative(),occurredAt:nt}).strict(),ES=l({id:ie,sequence:c().int().nonnegative().nullable(),contentHash:we}).strict(),z2=b(["tool_failure","retry","recovery","validation","user_turn","reusable_success","completion_detour"]),U2=b(["open","recovered","terminal"]),H2=l({name:o().trim().min(1).max(500),invocationKey:we}).strict(),q2=l({schemaVersion:k("openpond.improvementObservation.v1"),id:ie,runRef:ie,turnId:ie,harnessRelease:de,overlay:co.nullable(),eventRefs:f(ES).min(1).max(100),kind:z2,state:U2,tool:H2.nullable(),deterministicClass:o().trim().min(1).max(500).nullable(),summary:Dc,createdAt:nt,metadata:Xs}).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"]})});q2.extend({contentHash:we}).strict();const B2=l({schemaVersion:k("openpond.refinementTriggerPolicy.v1"),maxEstimatedCostUsd:c().finite().nonnegative(),cooldownMs:c().int().nonnegative(),maxPendingPlans:c().int().min(1).max(100),maxEvidenceEvents:c().int().min(1).max(1e3),maxProposalEdits:c().int().min(1).max(1e3),maxProposalBytes:c().int().min(1).max(1e7)}).strict(),F2=b(["no_action","route_deterministically","queue_refiner"]),V2=l({schemaVersion:k("openpond.refinementTriggerDecision.v1"),id:ie,runRef:ie,turnId:ie,harnessRelease:de,overlay:co.nullable(),observations:f(de).max(100),decision:F2,deterministicRoute:sr.nullable(),suggestedRoutes:f(sr).max(8),reason:Dc,deduplicationKey:we,policy:B2,estimatedMaxCostUsd:c().finite().nonnegative(),pendingPlanCount:c().int().nonnegative(),boundary:TS,cooldownUntil:nt.nullable(),createdAt:nt,metadata:Xs}).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"]})});V2.extend({contentHash:we}).strict();const W2=b(["runtime_service","refiner_model","human_review","evaluation_system","training_system"]),K2=l({schemaVersion:k("openpond.improvementRouteDecision.v1"),id:ie,trigger:de,route:sr,authority:W2,automatic:C(),reason:Dc,createdAt:nt,metadata:Xs}).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"]})});K2.extend({contentHash:we}).strict();const G2=l({schemaVersion:k("openpond.harnessRefinerOutcome.v1"),id:ie,trigger:de,decision:b(["no_action","proposed"]),proposal:de.nullable(),reason:Dc,evidenceRefs:f(de).max(100),estimatedCostUsd:c().finite().nonnegative(),createdAt:nt,metadata:Xs}).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"]})});G2.extend({contentHash:we}).strict();const Z2=b(["applied","retained","declined","conflict","rolled_back"]),J2=l({schemaVersion:k("openpond.improvementApplyReceipt.v1"),id:ie,proposal:de,beforeOverlay:co,afterOverlay:co.nullable(),decision:Z2,boundary:TS,validationRefs:f(de).max(100),outcomeEvidenceRefs:f(ES).max(1e3),rollbackOf:de.nullable(),createdAt:nt,metadata:Xs}).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"]})});J2.extend({contentHash:we}).strict();const pi=l({provider:ie,model:ie,revision:o().trim().min(1).max(500).nullable().default(null),artifactHash:we.nullable().default(null),tokenizerRevision:o().trim().min(1).max(500).nullable().default(null),chatTemplateHash:we.nullable().default(null)}).strict(),Y2=b(["memory","prompt","skill","agent"]),X2=b(["runtime","product","taskset","training"]),Q2=l({id:o().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),text:o().trim().min(1).max(1e4)}).strict(),MS=l({schemaVersion:k("openpond.refinerReviewProfile.v1"),id:o().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),version:o().trim().min(1).max(120),name:o().trim().min(1).max(200),objective:o().trim().min(1).max(1e4),instructions:f(Q2).max(100),allowedProposalRoutes:f(Y2).max(4),allowedExternalRoutes:f(X2).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"]})}),lg=l({schemaVersion:k("openpond.refinerRelease.v1"),id:o().trim().min(1).max(240),coreVersion:o().trim().min(1).max(120),coreHash:we,profile:MS,profileHash:we,composedPromptHash:we,createdAt:nt,contentHash:we}).strict(),eN=l({schemaVersion:k("openpond.refinerBinding.v1"),channel:k("active"),revision:c().int().nonnegative(),release:de,updatedAt:nt}).strict(),tN=l({schemaVersion:k("openpond.refinerTransitionReceipt.v1"),id:o().trim().min(1).max(240),operation:b(["initialize","update","activate","rollback"]),bindingChanged:C(),previousRelease:de.nullable(),nextRelease:de,actor:o().trim().min(1).max(240),reason:o().trim().min(1).max(1e4),authoringSkillHash:we.nullable(),validation:l({valid:C(),messages:f(o().max(2e3)).max(100)}).strict(),createdAt:nt,contentHash:we}).strict(),nN=l({schemaVersion:k("openpond.localHarnessRefinerDecision.v1"),decision:k("no_action"),reason:o().trim().min(1).max(1e4)}).strip(),aN=l({schemaVersion:k("openpond.localHarnessRefinerDecision.v1"),decision:k("route"),route:b(["runtime","product","taskset","training"]),summary:o().trim().min(1).max(2e3),expectedOutcome:o().trim().min(1).max(1e4),reason:o().trim().min(1).max(1e4)}).strip(),oN=l({schemaVersion:k("openpond.localHarnessRefinerDecision.v1"),decision:k("propose"),route:b(["memory","prompt","skill","agent"]),operation:b(["create","update","delete"]),target:o().trim().min(1).max(2e3),summary:o().trim().min(1).max(2e3),createContent:o().min(1).max(2e4).nullable(),find:o().min(1).max(8e3).nullable(),replace:o().max(8e3).nullable(),expectedOutcome:o().trim().min(1).max(1e4),reason:o().trim().min(1).max(1e4)}).strip().superRefine((e,t)=>{e.operation==="create"&&(e.createContent===null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"create proposals require createContent and null find/replace",path:["createContent"]}),e.operation==="update"&&(e.createContent!==null||e.find===null||e.replace===null)&&t.addIssue({code:"custom",message:"update proposals require one exact find/replace edit and null createContent",path:["find"]}),e.operation==="delete"&&(e.createContent!==null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"delete proposals require null createContent/find/replace",path:["createContent"]})}),iN=Kt("decision",[nN,aN,oN]),rN=iN,nf=l({kind:b(["single_deterministic","recurrent_independent"]),supportingEvidenceIds:f(o().trim().min(1).max(2e3)).min(1).max(100),counterevidence:f(o().trim().min(1).max(2e3)).max(20)}).strict().superRefine((e,t)=>{new Set(e.supportingEvidenceIds).size!==e.supportingEvidenceIds.length&&t.addIssue({code:"custom",message:"supporting evidence IDs must be unique",path:["supportingEvidenceIds"]}),e.kind==="recurrent_independent"&&e.supportingEvidenceIds.length<2&&t.addIssue({code:"custom",message:"recurrent independent evidence requires at least two supplied incidents",path:["supportingEvidenceIds"]})}),sN=l({schemaVersion:k("openpond.localHarnessRefinerDecision.v2"),decision:k("no_action"),reason:o().trim().min(1).max(1e4)}).strict(),lN=l({schemaVersion:k("openpond.localHarnessRefinerDecision.v2"),decision:k("route"),route:b(["runtime","product","taskset","training"]),summary:o().trim().min(1).max(2e3),evidenceBasis:nf,expectedOutcome:o().trim().min(1).max(1e4),reason:o().trim().min(1).max(1e4)}).strict(),cN=l({schemaVersion:k("openpond.localHarnessRefinerDecision.v2"),decision:k("propose"),route:b(["memory","prompt","skill","agent"]),operation:b(["create","update","delete"]),target:o().trim().min(1).max(2e3),summary:o().trim().min(1).max(2e3),evidenceBasis:nf,createContent:o().min(1).max(2e4).nullable(),find:o().min(1).max(8e3).nullable(),replace:o().max(8e3).nullable(),expectedOutcome:o().trim().min(1).max(1e4),reason:o().trim().min(1).max(1e4)}).strict().superRefine((e,t)=>{e.operation==="create"&&(e.createContent===null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"create proposals require createContent and null find/replace",path:["createContent"]}),e.operation==="update"&&(e.createContent!==null||e.find===null||e.replace===null)&&t.addIssue({code:"custom",message:"update proposals require one exact find/replace edit and null createContent",path:["find"]}),e.operation==="delete"&&(e.createContent!==null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"delete proposals require null createContent/find/replace",path:["createContent"]})}),jS=Kt("decision",[sN,lN,cN]);mn([rN,jS]);const af=l({memory:C(),prompt:C(),skill:C(),agent:C()}).strict(),OS=b(["memory","instruction","skill","agent"]),cg=l({path:o().trim().min(1).max(2e3),kind:OS,content:o().max(6e4),loaded:C()}).strict(),dg=l({path:o().trim().min(1).max(2e3),kind:OS,loaded:C()}).strict(),dN=l({capabilities:af,trigger:fe(o(),ye()),observations:f(fe(o(),ye())).max(20),admissibleEvidenceIds:f(o().trim().min(1).max(2e3)).max(1e4),reviewPacket:l({currentTurn:l({id:o().trim().min(1).max(2e3),status:o().trim().min(1).max(100).nullable(),error:o().max(2100).nullable(),prompt:o().max(8100).nullable(),assistantOutput:o().max(8100).nullable(),assistantOutputLinkCount:c().int().nonnegative()}).strict(),priorConversation:f(l({turnId:o().trim().min(1).max(2e3),status:o().trim().min(1).max(100).nullable(),prompt:o().max(3100).nullable(),assistantOutput:o().max(3100).nullable()}).strict()).max(3),timeline:f(fe(o(),ye())).max(60),artifacts:f(fe(o(),ye())).max(30),artifactDiagnostics:f(fe(o(),ye())).max(20),executionProfile:l({modelRequestCount:c().int().nonnegative(),failedModelRequestCount:c().int().nonnegative(),promptTokens:c().int().nonnegative(),completionTokens:c().int().nonnegative(),totalTokens:c().int().nonnegative(),toolFailureCount:c().int().nonnegative(),retryCount:c().int().nonnegative(),recoveryCount:c().int().nonnegative()}).strict(),priorIncidents:f(fe(o(),ye())).max(3),truncation:l({timelineEventCount:c().int().nonnegative(),includedTimelineEventCount:c().int().nonnegative(),timelineTruncated:C()}).strict()}).strict(),runtimeActivation:l({admittedRelease:de,currentRelease:de,rebasedOntoCurrent:C(),admittedSourceFiles:f(cg).max(100),admittedSourceCatalog:f(dg).max(1e3)}).strict(),sourceFiles:f(cg).max(100),sourceCatalog:f(dg).max(1e3),additionalEvidence:ye().nullable().optional()}).strict(),uN=l({id:o().trim().min(1).max(240),revision:c().int().nonnegative(),contentHash:we}).strict();l({schemaVersion:k("openpond.hostedHarnessRefinerRequest.v2"),requestId:o().trim().min(1).max(240),idempotencyKey:o().trim().min(1).max(240),evidenceHash:we,harness:l({admittedRelease:de,currentRelease:de,overlay:uN,workspace:l({id:o().trim().min(1).max(240),revision:c().int().nonnegative(),sourceRevision:we,channelRevision:c().int().nonnegative()}).strict(),capabilities:af}).strict(),evidence:dN}).strict();const mN=l({promptTokens:c().int().nonnegative(),completionTokens:c().int().nonnegative(),totalTokens:c().int().nonnegative()}).strict();l({schemaVersion:k("openpond.hostedHarnessRefinerResponse.v2"),requestId:o().trim().min(1).max(240),evidenceHash:we,admittedRelease:de,currentRelease:de,decision:jS,serviceRevision:o().trim().min(1).max(240),usage:mN}).strict();const pN=o().trim().min(1).max(2e3),of=o().trim().min(1).max(1e5),fN=b(["create","update","delete"]),hN=b(["memory","prompt","skill","agent"]),gN=b(["runtime","product","taskset","training"]),bN=b(["no_action","routed","applied","retained","failed"]),vN=b(["not_applicable","pending","passed","rejected","failed"]),yN=b(["not_applicable","pending","passed","failed"]),SN=l({schemaVersion:k("openpond.harnessRefinerActivityReceipt.v1"),id:ie,runRef:ie,turnId:ie,result:bN,decision:b(["no_action","route","propose"]).nullable(),route:sr.nullable(),operation:fN.nullable(),target:o().trim().min(1).max(2e3).nullable(),summary:pN,evidenceBasis:nf.nullable(),critiqueStatus:vN,validationStatus:yN,trigger:de,outcome:de.nullable(),proposal:de.nullable(),applyReceipt:de.nullable(),inputHarness:de,outputHarness:de.nullable(),createdAt:nt}).strict().superRefine((e,t)=>{const n=e.result==="applied"||e.result==="retained";e.result==="no_action"?ug(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"||!gN.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"}),ug(t,e,{critiqueStatus:"not_applicable",validationStatus:"not_applicable"})):n?((e.decision!=="propose"||!hN.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"]})});SN.extend({contentHash:we}).strict();const xN=b(["unresolved","confirmed","resolved","rejected","expired"]),kN=l({kind:b(["applied_change","later_success","manual_rejection","source_revoked","expired"]),reason:of,evidenceRefs:f(de).max(1e3),resolvedAt:nt}).strict(),_N=l({schemaVersion:k("openpond.harnessRefinementCandidate.v1"),id:ie,ownerScope:Qp,workspaceRef:ie,fingerprint:we,recurrenceFamily:o().trim().min(1).max(1e3),statement:of,status:xN,occurrences:f(Es).max(1e3),counterevidence:f(Es).max(1e3),sourceReviews:f(de).min(1).max(100),relatedHarnessReleases:f(de).max(100),firstSeenAt:nt,lastSeenAt:nt,lastReviewedAt:nt,expiresAt:nt,resolution:kN.nullable(),createdAt:nt,updatedAt:nt}).strict().superRefine((e,t)=>{Qo(t,e.occurrences,"occurrences"),Qo(t,e.counterevidence,"counterevidence"),Qo(t,e.sourceReviews,"sourceReviews"),Qo(t,e.relatedHarnessReleases,"relatedHarnessReleases");const n=new Set(e.occurrences.map(i=>i.occurrenceKey));e.counterevidence.some(i=>n.has(i.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(i=>i.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"]}),AN(t,e)});_N.extend({contentHash:we}).strict();const wN=b(["created","merged","rejected","expired","reopened","resolved"]),IN=l({schemaVersion:k("openpond.harnessRefinementCandidateLifecycleReceipt.v1"),id:ie,candidateId:ie,decision:wN,beforeCandidate:de.nullable(),afterCandidate:de,review:de,addedEvidence:f(Es).max(1e3),removedEvidence:f(de).max(1e3),reason:of,createdAt:nt}).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"]}),Qo(t,e.addedEvidence,"addedEvidence"),Qo(t,e.removedEvidence,"removedEvidence");const n=new Set(e.removedEvidence.map(a=>Em(a)));e.addedEvidence.some(a=>n.has(Em(a.evidence)))&&t.addIssue({code:"custom",message:"candidate lifecycle evidence cannot be added and removed together",path:["removedEvidence"]})});IN.extend({contentHash:we}).strict();const CN=l({schemaVersion:k("openpond.harnessCrossRunRefinementRequest.v1"),id:ie,ownerScope:Qp,workspaceRef:ie,candidate:de,candidateFingerprint:we,review:de,admittedHarness:de,evidence:f(Es).min(1).max(1e3),capabilities:af,deduplicationKey:we,createdAt:nt}).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"]}),Qo(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=RN(e);e.deduplicationKey!==n&&t.addIssue({code:"custom",message:`cross-run refinement deduplicationKey is ${e.deduplicationKey}; expected ${n}`,path:["deduplicationKey"]})});CN.extend({contentHash:we}).strict();function RN(e){return _t({schemaVersion:"openpond.harnessCrossRunRefinementIdentity.v1",workspaceRef:e.workspaceRef,candidateFingerprint:e.candidateFingerprint,admittedHarness:e.admittedHarness})}function ug(e,t,n){for(const[a,i]of Object.entries(n))t[a]!==i&&e.addIssue({code:"custom",message:`${a} must be ${String(i)}`,path:[a]})}function Qo(e,t,n){const a=t.map(i=>Em(i));new Set(a).size!==a.length&&e.addIssue({code:"custom",message:`${n} references must be unique`,path:[n]})}function Em(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 AN(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 i=n[a-1],r=n[a];Date.parse(i[1])<=Date.parse(r[1])||e.addIssue({code:"custom",message:`${r[0]} must not precede ${i[0]}`,path:[r[0]]})}Date.parse(t.createdAt)>Date.parse(t.updatedAt)&&e.addIssue({code:"custom",message:"updatedAt must not precede createdAt",path:["updatedAt"]})}const PN=l({adapterId:ie,placement:b(["local","remote","colocated","provider_native"]),runtimeVersion:o().trim().min(1).max(200),capabilityReceipt:we}).strict(),TN=l({maxTurns:c().int().positive().max(1e5),timeoutMs:c().int().positive().max(864e5),maxOutputBytes:c().int().positive().max(25e7),maximumSpendUsd:c().nonnegative().nullable()}).strict(),EN=l({schemaVersion:k("openpond.runManifest.v1"),id:ie,harnessRelease:de,tasksetRelease:de,model:pi,runtimeTarget:PN,limits:TN,approval:l({id:ie,contentHash:we}).strict().nullable(),createdAt:nt,metadata:Ct}).strict();EN.extend({contentHash:we}).strict();const NS=l({schemaVersion:k("openpond.attemptReceipt.v1"),id:ie,runManifest:de,taskId:ie,seed:o().trim().min(1).max(500),terminal:C(),failureClass:Cc.nullable(),outputHash:we.nullable(),traceHash:we,artifactRefs:f(Zn).max(1e5),graderEvidenceRefs:f(Zn).max(1e4),startedAt:nt,completedAt:nt,latencyMs:c().int().nonnegative(),costUsd:c().nonnegative().nullable(),legacyAttemptRef:ie.nullable().default(null),metadata:Ct}).strict(),$S=NS.extend({contentHash:we}).strict(),MN=l({schemaVersion:k("openpond.evaluationResult.v1"),id:ie,runManifest:de,harnessRelease:de,tasksetRelease:de,model:pi,receiptRefs:f(de).min(1).max(1e6),attemptCount:c().int().positive(),rewardEligibleCount:c().int().nonnegative(),terminalCount:c().int().nonnegative(),meanScore:c().min(0).max(1).nullable(),failureCounts:fe(Cc,c().int().nonnegative()),metadata:Ct}).strict();MN.extend({contentHash:we}).strict();const jN=l({schemaVersion:k("openpond.harnessCompatibility.v1"),id:ie,baseHarnessRelease:de,candidateHarnessRelease:de,tasksetRelease:de,environmentHash:we,toolContractHash:we,policyHash:we,graderInterfaceHash:we,metadata:Ct}).strict();jN.extend({contentHash:we}).strict();function ON(e){const t=$S.safeParse(e);if(!t.success)return!1;const{contentHash:n,...a}=t.data;return _t(NS.parse(a))===n}const mr=b(["train","validation","test","frozen_eval"]),NN=l({path:o().trim().min(1).max(2e3).refine(FN),mediaType:o().trim().min(1).max(200),schemaRef:Gn.nullable().default(null),maxBytes:c().int().positive().max(25e7).nullable().default(null),metadata:Ct}).strict(),$N=l({policyVisibleFields:f(ie).max(1e3).default([]),privilegedFields:f(ie).max(1e3).default([]),hiddenGraderRefs:f(ie).max(1e3).default([]),connectedAppScopes:f(ie).max(100).default([])}).strict(),DS=l({protocolVersion:k("openpond.environment.v1"),kind:b(["text","agent","work","custom_program"]),entrypoint:o().trim().min(1).max(1e3),stateful:C(),deterministicSeeds:C(),lifecycle:f(b(["create","reset","step","collect","destroy"])).min(5).max(5),networkPolicy:b(["none","declared_read_only","declared_scoped"]),defaultTimeoutMs:c().int().positive().max(36e5)}).strict(),Lc=l({id:ie,version:o().trim().min(1).max(100),weight:c().nonnegative().max(1e3).default(1),hardGate:C().default(!1),rewardEligible:C().default(!1),privileged:C().default(!1)}),DN=Lc.extend({kind:b(["content","schema","artifact","runtime_event","state"]),config:fe(o(),ye())}).strict(),LN=Lc.extend({kind:k("model_judge"),rubricRef:Gn,calibrationStatus:b(["pending","passed","failed"])}).strict(),zN=Lc.extend({kind:k("custom_verifier"),verifierRef:Gn,timeoutMs:c().int().positive().max(3e5),networkPolicy:k("none")}).strict(),UN=Lc.extend({kind:k("human"),rubricRef:Gn,reviewerRole:o().trim().min(1).max(500)}).strict(),LS=mn([DN,LN,zN,UN]),HN=l({id:ie,clusterKey:ie,split:mr,input:fe(o(),ye()),expectedOutput:fe(o(),ye()).nullable(),policyVisibleContext:fe(o(),ye()).default({}),privilegedContextRef:ie.nullable(),artifactRefs:f(Gn).max(1e3).default([]),requiredOutputs:f(NN).max(1e3).optional(),tags:f(ie).max(100).default([])}).strict(),qN=l({schemaVersion:k("openpond.tasksetRelease.v2"),id:ie,revision:c().int().positive(),policy:$N,environment:DS,environmentRelease:l({id:ie,contentHash:we}).strict().optional(),tools:f($c).max(200),capabilities:f(tf).max(200),tasks:f(HN).min(1).max(1e6),graders:f(LS).min(1).max(1e3),verifierSetRelease:l({id:ie,contentHash:we}).strict().optional(),metadata:Ct}).strict(),BN=qN.extend({contentHash:we}).strict();function FN(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}BN.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 zS=b(["foreground_tokens","success_rate","latency_ms","cost_usd"]),US=b(["baseline","candidate"]),VN=l({split:mr,taskIds:f(ie).min(1).max(1e5),seeds:f(o().trim().min(1).max(500)).min(1).max(100),repetitions:c().int().positive().max(20),runtimeTargetHash:we,environmentHash:we,toolContractHash:we,limitsHash:we}).strict();l({schemaVersion:k("openpond.benchmarkDefinition.v1"),id:ie,title:o().trim().min(1).max(500),description:o().trim().min(1).max(5e3),tasksetRelease:de,adaptationSplit:mr,evaluationSplit:mr,primaryMetric:zS,qualityGate:b(["none","non_regression","all_pass"]),caseCounts:l({adaptation:c().int().nonnegative(),evaluation:c().int().positive()}).strict(),metadata:Ct}).strict();l({schemaVersion:k("openpond.benchmarkRunRequest.v1"),phase:US,model:pi,reasoningEffort:o().trim().min(1).max(100).nullable(),split:mr,seeds:f(o().trim().min(1).max(500)).min(1).max(100),repetitions:c().int().positive().max(20),metadata:Ct}).strict();const WN=l({inputTokens:c().int().nonnegative(),outputTokens:c().int().nonnegative(),totalTokens:c().int().nonnegative()}).strict(),KN=l({schemaVersion:k("openpond.benchmarkRunSummary.v1"),id:ie,phase:US,tasksetRelease:de,harnessRelease:de,evaluationResult:de,model:pi,reasoningEffort:o().trim().min(1).max(100).nullable(),protocol:VN,attemptCount:c().int().positive(),passedCount:c().int().nonnegative(),terminalCount:c().int().nonnegative(),usage:WN,costUsd:c().nonnegative().nullable(),latencyMs:c().int().nonnegative(),createdAt:nt,metadata:Ct}).strict();KN.extend({contentHash:we}).strict();const GN=l({schemaVersion:k("openpond.benchmarkComparison.v1"),id:ie,baseline:de,candidate:de,tasksetRelease:de,primaryMetric:zS,qualityPassed:C(),baselinePassRate:c().min(0).max(1),candidatePassRate:c().min(0).max(1),foregroundTokenDelta:c().int(),foregroundTokenDeltaPercent:c().finite().nullable(),improved:C(),createdAt:nt,metadata:Ct}).strict();GN.extend({contentHash:we}).strict();const rf=b(["scored","unscorable"]),zc=b(["policy","environment","collector","verifier","provider","host","user","scheduler"]),HS=b(["completed","policy_failure","incomplete_output","task_deadline","environment_failure","collector_failure","verifier_failure","provider_failure","host_failure","infrastructure_timeout","cancelled"]),ZN=l({schemaVersion:k("openpond.environmentRelease.v1"),id:ie,revision:c().int().positive(),contract:DS,actionSchemaRef:Gn.nullable(),observationSchemaRef:Gn.nullable(),stateSchemaRef:Gn.nullable(),artifactCollection:l({maxArtifacts:c().int().positive().max(1e5),maxTotalBytes:c().int().positive().max(1e10)}).strict(),adapterConformanceHashes:fe(ie,we),metadata:Ct}).strict();ZN.extend({contentHash:we}).strict();const JN=b(["collected","missing","skipped","failed"]),mg=b(["not_requested","passed","failed"]),YN=l({requiredOutputPath:o().trim().min(1).max(2e3).nullable(),collectedPath:o().trim().min(1).max(4e3).nullable(),declaredMediaType:o().trim().min(1).max(200).nullable(),detectedMediaType:o().trim().min(1).max(200).nullable(),artifact:Zn.nullable(),status:JN,parseStatus:mg,schemaStatus:mg,errorCode:ie.nullable(),failureOwner:zc.nullable(),evidenceRefs:f(Zn).max(1e4),metadata:Ct}).strict(),XN=l({schemaVersion:k("openpond.artifactManifest.v1"),id:ie,attemptRef:de,entries:f(YN).max(1e5),createdAt:nt,metadata:Ct}).strict();XN.extend({contentHash:we}).strict();const QN=l({schemaVersion:k("openpond.verifierSetRelease.v1"),id:ie,revision:c().int().positive(),graders:f(LS).min(1).max(1e3),isolation:l({processBoundary:b(["same_process","isolated_process","container"]),networkPolicy:k("none"),defaultTimeoutMs:c().int().positive().max(3e5)}).strict(),calibrationReceiptRefs:f(de).max(1e4),metadata:Ct}).strict();QN.extend({contentHash:we}).strict();const e$=l({verifierId:ie,verifierVersion:o().trim().min(1).max(100),status:rf,rawScore:c().finite().nullable(),normalizedScore:c().min(0).max(1).nullable(),weight:c().nonnegative().max(1e3),passed:C(),hardGate:C(),rewardEligible:C(),rewardContribution:c().min(0).max(1).nullable(),failureOwner:zc.nullable(),feedback:f(o().max(2e4)).max(1e3),visibleEvidenceRefs:f(Zn).max(1e4),privilegedEvidenceRefs:f(Zn).max(1e4),metadata:Ct}).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"]})}),qS=l({schemaVersion:k("openpond.rewardReceipt.v1"),id:ie,attemptRef:de,verifierSetRef:de,artifactManifestRef:de,status:rf,reward:c().min(0).max(1).nullable(),learningEligible:C(),passed:C(),outcomeClass:HS,failureOwner:zc.nullable(),components:f(e$).min(1).max(1e4),visibleEvidenceRefs:f(Zn).max(1e5),privilegedEvidenceRefs:f(Zn).max(1e5),supersedes:de.nullable(),createdAt:nt,metadata:Ct}).strict();function BS(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"]})}qS.superRefine(BS);qS.extend({contentHash:we}).strict().superRefine(BS);const t$="openpond.workEvidenceReceipt.v1",n$="openpond.workProcessTrace.v1",a$="openpond.workFeedbackReceipt.v1",FS="openpond.workEvidenceEligibility.v1",o$=o().regex(/^urn:openpond:work:[a-f0-9]{64}$/,"Work source references must be opaque SHA-256 URNs."),i$=o().regex(/^urn:openpond:workspace:[a-f0-9]{64}$/,"Workspace references must be opaque SHA-256 URNs."),r$=o().regex(/^urn:openpond:artifact:[a-f0-9]{64}$/,"Evidence artifacts must use content-addressed SHA-256 URNs."),Rn=Zn.extend({id:r$}).strict().superRefine((e,t)=>{e.id!==ZS(e.contentHash)&&t.addIssue({code:"custom",message:"Evidence artifact id must contain its content hash.",path:["id"]})}),s$=b(["tool","validation","state_transition","approval","question","artifact","cleanup"]),l$=b(["agent","environment"]),c$=b(["turn_started","turn_completed","turn_failed","turn_cancelled","turn_timed_out","tool_invoked","tool_completed","tool_failed","validation_completed","validation_failed","approval_requested","approval_resolved","question_asked","question_answered","question_dismissed","artifact_created","workspace_changed","environment_created","environment_reset","environment_destroyed","cleanup_completed","cleanup_failed"]),d$=b(["started","completed","failed","cancelled"]),u$=b(["filesystem","source_control","command","browser","connected_app","sandbox","agent","other"]),m$=b(["structural","visual","test","user_review","other"]),p$=b(["running","completed","failed","cancelled","timeout"]),f$=b(["requested","approved","denied","answered","dismissed"]),h$=b(["policy","validation","environment","infrastructure","timeout","cancelled","unknown"]),g$=b(["missing_start","missing_terminal","source_truncated","unsupported_events_dropped","uncorrelated_environment_step","artifact_unavailable"]),b$=l({sequence:c().int().nonnegative().max(1e6),timestamp:nt,layer:l$,kind:s$,action:c$,status:d$,inputHash:we.nullable(),outputHash:we.nullable(),receiptHash:we.nullable(),parentReceiptHash:we.nullable(),artifactRefs:f(Rn).max(1e3),attributes:l({toolCategory:u$.nullable(),validationKind:m$.nullable(),transitionState:p$.nullable(),interventionOutcome:f$.nullable(),artifactCount:c().int().nonnegative().max(1e5),exitCode:c().int().min(-1).max(255).nullable(),durationMs:c().int().nonnegative().max(31536e6).nullable(),cpuTimeMs:c().int().nonnegative().max(31536e6).nullable(),memoryPeakBytes:c().int().nonnegative().max(0x4000000000000).nullable(),errorClass:h$.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"]})}),VS=l({schemaVersion:k(n$),sourceRevisionHash:we,sanitationPolicyVersion:ie,incomplete:C(),incompleteReasons:f(g$).max(10),droppedEventCount:c().int().nonnegative().max(1e6),steps:f(b$).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"]})}),v$=VS.safeExtend({contentHash:we}).strict(),y$=b(["policy_failure","validation_failure","model_failure","environment_failure","infrastructure_failure","timeout","cancelled","unknown"]),S$=l({status:b(["completed","failed","cancelled","timeout"]),failureClass:y$.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"]})}),sf=l({schemaVersion:k(t$),id:o().regex(/^work-evidence-[a-f0-9]{24}$/),source:l({surface:b(["desktop","hosted"]),experience:b(["work","development"]),opaqueRef:o$,revisionHash:we}).strict(),agentSnapshot:de.nullable(),model:pi,runtime:l({adapterId:ie,adapterVersion:ie,capabilityRef:Rn.nullable()}).strict(),inputHash:we,terminal:S$,trace:l({sanitizedRef:Rn,traceHash:we,sanitationPolicyVersion:ie,incomplete:C()}).strict(),outputRefs:f(Rn).max(1e4),artifactRefs:f(Rn).max(1e5),validationEvidenceRefs:f(Rn).max(1e4),interventions:l({approvals:c().int().nonnegative().max(1e6),questions:c().int().nonnegative().max(1e6),steeringEvents:c().int().nonnegative().max(1e6),otherUserInterventions:c().int().nonnegative().max(1e6)}).strict(),timing:l({startedAt:nt,completedAt:nt,latencyMs:c().int().nonnegative().max(31536e6)}).strict(),usage:l({promptTokens:c().int().nonnegative().nullable(),completionTokens:c().int().nonnegative().nullable(),totalTokens:c().int().nonnegative().nullable()}).strict(),costUsd:c().nonnegative().max(1e6).nullable(),provenance:l({consentReceiptRef:Rn,consentScope:k("work_process_and_artifacts"),consentGrantedAt:nt,policyVersion:ie,projectorVersion:ie,disclosure:k("portable_sanitized"),ownershipScope:b(["personal","workspace"]),workspaceRef:i$.nullable(),participantPolicy:b(["creator_only","all_participants"]),retention:l({policy:k("source_bound"),deleteWithSource:k(!0),expiresAt:nt.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"]}),Du(e.outputRefs,["outputRefs"],t),Du(e.artifactRefs,["artifactRefs"],t),Du(e.validationEvidenceRefs,["validationEvidenceRefs"],t)}),WS=sf.safeExtend({contentHash:we}).strict(),x$=b(["accepted","needs_correction","not_useful"]),k$=b(["correct","complete","high_quality","incorrect","incomplete","wrong_format","unsafe","stale","irrelevant","other"]),KS=l({schemaVersion:k(a$),id:o().regex(/^work-feedback-[a-f0-9]{24}$/),evidenceReceiptRef:Rn,outputRevisionRef:Rn.nullable(),verdict:x$,reasonCodes:f(k$).max(16),correctionRef:Rn.nullable(),correctedOutputRevisionRef:Rn.nullable(),actor:k("user"),createdAt:nt}).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"]})}),GS=KS.safeExtend({contentHash:we}).strict();function ZS(e){return`urn:openpond:artifact:${e}`}function _$(e){return`urn:openpond:work:${_t(e)}`}function Qs(e){return Rn.parse({id:ZS(e.contentHash),contentHash:e.contentHash,mediaType:e.mediaType??null,sizeBytes:e.sizeBytes??null})}function JS(e){const t=VS.parse(e);return v$.parse({...t,contentHash:_t(t)})}function w$(e){const t=sf.parse(e);return WS.parse({...t,contentHash:_t(t)})}function YS(e,t){const n=KS.parse(e),a=GS.parse({...n,contentHash:_t(n)});return t&&R$(a,t),a}function I$(e){return A$(e,WS,sf)}function C$(e){return Qs({contentHash:e.contentHash,mediaType:"application/vnd.openpond.work-evidence+json",sizeBytes:null})}function R$(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 A$(e,t,n){const a=t.safeParse(e);if(!a.success)return!1;const{contentHash:i,...r}=a.data;return _t(n.parse(r))===i}function Du(e,t,n){const a=e.map(i=>i.contentHash);new Set(a).size!==a.length&&n.addIssue({code:"custom",message:"Artifact content hashes must be unique.",path:t})}const P$=b(["active","revoked","deleted","expired"]);b(["discovery_only","eval_candidate","demonstration_candidate","preference_candidate","reward_candidate"]);const T$=b(["invalid_evidence_receipt","consent_revoked","source_deleted","retention_expired","trace_incomplete","terminal_not_completed","infrastructure_failure","agent_snapshot_missing","input_not_reconstructable","environment_not_reconstructable","output_missing","validation_evidence_missing","verifier_missing","accepted_feedback_missing","correction_pair_missing","attempt_receipt_missing","attempt_receipt_invalid","attempt_receipt_unbound","attempt_not_reward_eligible"]),Hi=l({eligible:C(),blockers:f(T$).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."})}),XS=l({schemaVersion:k(FS),evidenceReceiptHash:we,policyState:P$,decisions:l({discovery_only:Hi,eval_candidate:Hi,demonstration_candidate:Hi,preference_candidate:Hi,reward_candidate:Hi}).strict()}).strict(),E$=XS.extend({contentHash:we}).strict();function QS(e){const t=I$(e.evidence),n=(e.feedback??[]).filter(x=>{if(!GS.safeParse(x).success)return!1;try{return YS(j$(x),e.evidence),!0}catch{return!1}}),a=M$(e.policyState),i=[...t?[]:["invalid_evidence_receipt"],...a],r=[...i,...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",d=n.some(x=>x.verdict==="accepted"),p=[...r,...s?[]:["terminal_not_completed"],...e.evidence.terminal.failureClass==="infrastructure_failure"?["infrastructure_failure"]:[],...e.evidence.validationEvidenceRefs.length?[]:["validation_evidence_missing"],...d?[]:["accepted_feedback_missing"]],m=new Set(n.filter(x=>x.verdict==="accepted").flatMap(x=>x.outputRevisionRef?.contentHash??[])),h=n.some(x=>x.verdict==="needs_correction"&&x.outputRevisionRef!==null&&x.correctedOutputRevisionRef!==null&&m.has(x.correctedOutputRevisionRef.contentHash)),S=[...r,...h?[]:["correction_pair_missing"]],y=e.replay??null,w=y?$S.safeParse(y.attemptReceipt):null,R=w?.success===!0&&ON(w.data),A=y?.sourceEvidenceReceiptHash===e.evidence.contentHash,N=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",O=[...i,...y?[]:["attempt_receipt_missing"],...y&&!R?["attempt_receipt_invalid"]:[],...y&&!A?["attempt_receipt_unbound"]:[],...y&&R&&A&&!N?["attempt_not_reward_eligible"]:[]],D=XS.parse({schemaVersion:FS,evidenceReceiptHash:e.evidence.contentHash,policyState:e.policyState,decisions:{discovery_only:ms(i),eval_candidate:ms(r),demonstration_candidate:ms(p),preference_candidate:ms(S),reward_candidate:ms(O)}});return E$.parse({...D,contentHash:_t(D)})}function M$(e){return e==="revoked"?["consent_revoked"]:e==="deleted"?["source_deleted"]:e==="expired"?["retention_expired"]:[]}function ms(e){const t=[...new Set(e)];return Hi.parse({eligible:t.length===0,blockers:t})}function j$(e){const{contentHash:t,...n}=e;return n}l({schemaVersion:k("openpond.workEvidenceAuthoringInput.v1"),evidenceReceiptRef:Rn,inputHash:we,agentSnapshot:de.nullable(),sanitizedTraceRef:Rn,outputRefs:f(Rn).max(1e4),validationEvidenceRefs:f(Rn).max(1e4),incomplete:C(),evalCandidate:C(),blockerCodes:f(o().trim().min(1).max(120)).max(32)}).strict();const Ms="2026-08-04T12:00:00.000Z",ex="2026-08-04T12:00:02.500Z",Mm=_t({fixture:"desktop-work",revision:1}),js=Qs({contentHash:_t("fixture output"),mediaType:"text/plain",sizeBytes:14}),tx=Qs({contentHash:_t({kind:"test",status:"passed"}),mediaType:"application/json",sizeBytes:null}),O$=Qs({contentHash:_t({scope:"work_process_and_artifacts",grantedAt:Ms}),mediaType:"application/json",sizeBytes:null}),lf=JS({schemaVersion:"openpond.workProcessTrace.v1",sourceRevisionHash:Mm,sanitationPolicyVersion:"openpond.desktop-work-sanitizer.v1",incomplete:!1,incompleteReasons:[],droppedEventCount:1,steps:[qi(0,Ms,"agent","state_transition","turn_started","started",{transitionState:"running"}),qi(1,"2026-08-04T12:00:00.500Z","agent","tool","tool_invoked","started",{toolCategory:"filesystem",inputHash:_t({path:"hashed-only"}),receiptHash:_t("fixture-tool-call")}),qi(2,"2026-08-04T12:00:01.000Z","environment","artifact","artifact_created","completed",{outputHash:js.contentHash,artifacts:[js],receiptHash:_t("fixture-environment-operation"),parentReceiptHash:_t("fixture-tool-call")}),qi(3,"2026-08-04T12:00:01.500Z","environment","validation","validation_completed","completed",{validationKind:"test",outputHash:tx.contentHash,receiptHash:_t("fixture-validation"),parentReceiptHash:_t("fixture-tool-call")}),qi(4,ex,"agent","state_transition","turn_completed","completed",{transitionState:"completed"})]}),N$=new TextEncoder().encode(P0(lf)).byteLength,Lu=Qs({contentHash:lf.contentHash,mediaType:"application/vnd.openpond.work-process-trace+json",sizeBytes:N$}),ni=w$({schemaVersion:"openpond.workEvidenceReceipt.v1",id:`work-evidence-${_t([Mm,Lu.contentHash]).slice(0,24)}`,source:{surface:"desktop",experience:"work",opaqueRef:_$(["fixture-session","fixture-turn"]),revisionHash:Mm},agentSnapshot:{id:"fixture-agent-snapshot",contentHash:_t("fixture-agent")},model:{provider:"fixture",model:"scripted",revision:"1",artifactHash:null,tokenizerRevision:null,chatTemplateHash:null},runtime:{adapterId:"desktop-work",adapterVersion:"1",capabilityRef:null},inputHash:_t("fixture prompt"),terminal:{status:"completed",failureClass:null},trace:{sanitizedRef:Lu,traceHash:Lu.contentHash,sanitationPolicyVersion:lf.sanitationPolicyVersion,incomplete:!1},outputRefs:[js],artifactRefs:[js],validationEvidenceRefs:[tx],interventions:{approvals:0,questions:0,steeringEvents:0,otherUserInterventions:0},timing:{startedAt:Ms,completedAt:ex,latencyMs:2500},usage:{promptTokens:12,completionTokens:8,totalTokens:20},costUsd:0,provenance:{consentReceiptRef:O$,consentScope:"work_process_and_artifacts",consentGrantedAt:Ms,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}}}),nx=YS({schemaVersion:"openpond.workFeedbackReceipt.v1",id:`work-feedback-${_t([ni.contentHash,"accepted"]).slice(0,24)}`,evidenceReceiptRef:C$(ni),outputRevisionRef:js,verdict:"accepted",reasonCodes:["correct","complete"],correctionRef:null,correctedOutputRevisionRef:null,actor:"user",createdAt:"2026-08-04T12:01:00.000Z"},ni);JS({schemaVersion:"openpond.workProcessTrace.v1",sourceRevisionHash:_t({fixture:"incomplete",revision:1}),sanitationPolicyVersion:"openpond.desktop-work-sanitizer.v1",incomplete:!0,incompleteReasons:["missing_terminal","unsupported_events_dropped"],droppedEventCount:2,steps:[qi(0,Ms,"agent","state_transition","turn_started","started",{transitionState:"running"})]});QS({evidence:ni,feedback:[nx],policyState:"active",reconstructability:{input:!0,environment:!0,verifier:!0}});QS({evidence:ni,feedback:[nx],policyState:"revoked",reconstructability:{input:!0,environment:!0,verifier:!0}});({...ni,source:{...ni.source}});function qi(e,t,n,a,i,r,s){return{sequence:e,timestamp:t,layer:n,kind:a,action:i,status:r,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 $$=l({schemaVersion:k("openpond.graderEvidence.v1"),graderId:ie,graderVersion:o().trim().min(1).max(100),score:c().min(0).max(1).nullable(),passed:C(),rewardEligible:C(),failureClass:Cc.nullable(),feedback:f(o().max(2e4)).max(1e3),visibleEvidenceRefs:f(ie).max(1e4),privilegedEvidenceRefs:f(ie).max(1e4)}).strict();$$.extend({contentHash:we}).strict();const D$=b(["calibration","training_reward","validation","frozen_eval"]);b(["human","model","deterministic","fixture"]);b(["production","synthetic_smoke"]);const L$=b(["markdown","text","code","json","image"]),z$=l({id:ie,label:o().trim().min(1).max(500),instruction:o().trim().min(1).max(1e4),weight:c().nonnegative().max(1e3)}).strict(),U$=l({source:b(["attempt_output","artifact"]),path:o().trim().min(1).max(2e3),renderer:L$}).strict(),H$=l({showTaskPrompt:C(),randomizeCandidateOrder:C(),hideModelIdentity:C(),parts:f(U$).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."})}),q$=l({strategy:k("randomized_blinded_v1"),maxAssignmentsPerCandidate:c().int().positive().max(1e4)}).strict(),B$=l({algorithm:k("mean_pairwise_win_fraction_v1"),quorum:c().int().positive().max(100),rejectAllThreshold:c().min(.5).max(1)}).strict(),F$=l({algorithm:k("pairwise_win_fraction_v1"),verifierId:ie,verifierVersion:o().trim().min(1).max(100),weight:c().positive().max(1e3)}).strict(),V$=l({minimumSamples:c().int().positive().max(1e5),minimumOrderAgreement:c().min(0).max(1),minimumTieAgreement:c().min(0).max(1),minimumOrderSwapAgreement:c().min(0).max(1)}).strict(),W$=l({schemaVersion:k("openpond.preferenceComparisonRelease.v1"),id:ie,revision:c().int().positive(),tasksetRelease:de,candidateCount:c().int().min(2).max(4),resultMode:k("ordered_tie_groups"),allowTies:C(),allowRejectAll:C(),presentation:H$,rubricRef:Zn,criteria:f(z$).max(20),assignment:q$,aggregation:B$,rewardProjection:F$,calibration:V$,metadata:Ct}).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."})});W$.extend({contentHash:we}).strict();const K$=l({id:ie,contentHash:we}).strict(),G$=l({tasksetRelease:de,harnessReleases:f(de).min(1).max(4),runManifestRefs:f(de).min(1).max(4),harnessCompatibilityReceiptRefs:f(de).max(6),environmentRelease:de,verifierSetRelease:de,toolContractHash:we,policyHash:we}).strict(),Z$=l({attemptRef:de,runManifestRef:de,artifactManifestRef:de,visibleArtifactIds:f(ie).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."})}),J$=l({schemaVersion:k("openpond.comparisonAssignment.v1"),id:ie,comparisonRelease:de,taskRef:K$,lineage:G$,candidates:f(Z$).min(2).max(4),presentedCandidateOrder:f(ie).min(2).max(4),purpose:D$,createdAt:nt,metadata:Ct}).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."})});J$.extend({contentHash:we}).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 ax=f(f(ie).min(1).max(4)).max(4),Y$=Kt("kind",[l({kind:b(["human","model","deterministic"]),releaseRef:de}).strict(),l({kind:k("fixture"),releaseRef:de,fixtureRelease:de,labelSource:k("synthetic"),qualificationEligibility:k("smoke_only")}).strict()]),X$=l({schemaVersion:k("openpond.preferenceReceipt.v1"),id:ie,assignmentRef:de,reviewer:Y$,order:ax,rejectAll:C(),criterionScores:fe(ie,fe(ie,c().finite().min(0).max(1))),feedbackArtifactRef:Zn.nullable(),startedAt:nt,completedAt:nt,metadata:Ct}).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."})});X$.extend({contentHash:we}).strict();const Q$=l({schemaVersion:k("openpond.preferenceAggregationReceipt.v1"),id:ie,assignmentRef:de,comparisonRelease:de,receiptRefs:f(de).min(1).max(100),order:ax,rejectAll:C(),pairwiseWinFractions:fe(ie,c().min(0).max(1)),quorum:c().int().positive().max(100),createdAt:nt,metadata:Ct}).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."})});Q$.extend({contentHash:we}).strict();const eD=l({schemaVersion:k("openpond.preferenceCalibrationReport.v1"),id:ie,comparisonRelease:de,automatedReviewer:de,humanReceiptRefs:f(de).min(1).max(1e5),modelReceiptRefs:f(de).min(1).max(1e5),sampleCount:c().int().positive().max(1e5),orderAgreement:c().min(0).max(1),tieAgreement:c().min(0).max(1),orderSwapAgreement:c().min(0).max(1),passed:C(),createdAt:nt,metadata:Ct}).strict();eD.extend({contentHash:we}).strict();const tD=b(["reward_train","reward_validation","reward_qualification"]),nD=b(["human","synthetic_fixture"]),aD=b(["synthetic_smoke","human_heldout"]),oD=l({id:ie,assignmentRef:de,scenarioRef:de,scenarioSplit:b(["train","validation"]),preferenceResultRef:de,receiptRefs:f(de).min(1).max(100),attemptRefs:f(de).min(2).max(4),artifactManifestRefs:f(de).min(2).max(4),orderedBuckets:f(f(ie).min(1).max(4)).max(4),rejectAll:C(),partition:tD,metadata:Ct}).strict().superRefine((e,t)=>{const n=e.attemptRefs.map(i=>i.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(i=>!n.includes(i)))&&t.addIssue({code:"custom",path:["orderedBuckets"],message:"Ordered buckets must contain every group Attempt exactly once."})}),iD=l({groupId:ie,preferredAttemptRef:de,dispreferredAttemptRef:de,relation:b(["preferred","tie"])}).strict().superRefine((e,t)=>{e.preferredAttemptRef.id===e.dispreferredAttemptRef.id&&e.preferredAttemptRef.contentHash===e.dispreferredAttemptRef.contentHash&&t.addIssue({code:"custom",message:"A derived preference pair must reference two different Attempts."})}),rD=l({schemaVersion:k("openpond.preferenceDatasetRelease.v1"),id:ie,revision:c().int().positive(),tasksetRelease:de,comparisonRelease:de,authority:nD,qualificationEligibility:b(["smoke_only","human_heldout"]),fixtureRelease:de.nullable(),groups:f(oD).min(1).max(1e5),derivedPairs:f(iD).max(1e6),createdAt:nt,metadata:Ct}).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(i=>i.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(i=>[i.id,i]));for(const[i,r]of e.derivedPairs.entries()){const s=a.get(r.groupId);if(!s){t.addIssue({code:"custom",path:["derivedPairs",i,"groupId"],message:"Derived preference pairs must reference a group in the same release."});continue}const d=new Set(s.attemptRefs.map(p=>p.id));(!d.has(r.preferredAttemptRef.id)||!d.has(r.dispreferredAttemptRef.id))&&t.addIssue({code:"custom",path:["derivedPairs",i],message:"Derived preference pairs must reference Attempts in their source group."})}});rD.extend({contentHash:we}).strict();const sD=l({sampleCount:c().int().positive(),finiteScoreRate:c().min(0).max(1),scoreVariance:c().nonnegative(),checkpointReloadPassed:C(),processorCompatibilityPassed:C(),invalidAttemptExclusionPassed:C(),orderedPairAccuracy:c().min(0).max(1).nullable(),bucketAccuracy:c().min(0).max(1).nullable(),tieAgreement:c().min(0).max(1).nullable()}).strict(),lD=l({schemaVersion:k("openpond.rewardModelQualificationReport.v1"),id:ie,kind:aD,rewardModelVersion:de,preferenceDatasetRelease:de,tasksetRelease:de,processorRelease:de,metrics:sD,passed:C(),productionRewardEligible:C(),createdAt:nt,metadata:Ct}).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."})});lD.extend({contentHash:we}).strict();const cD=o().trim().min(1).max(1e5),dD=b(["no_training","sft","preference","rl"]),uD=l({kind:b(["none","demonstrations","chosen_rejected","scalar_reward"]),strength:b(["absent","weak","usable"]),calibrated:C(),confounded:C(),variance:c().finite().nonnegative().nullable(),evidenceRefs:f(de).max(1e5)}).strict(),ox=l({schemaVersion:k("openpond.modelImprovementQualificationReceipt.v1"),id:ie,review:de,harnessRelease:de,tasksetRelease:de.nullable(),baselineEvaluation:de.nullable(),model:pi,environmentHash:we.nullable(),toolContractHash:we.nullable(),permissionContractHash:we.nullable(),policyHash:we.nullable(),verifierRef:de.nullable(),sourcePolicies:f(ef).max(1e4),trainingEvidenceRefs:f(de).max(1e5),frozenEvaluationEvidenceRefs:f(de).max(1e5),privacyApproval:de.nullable(),budgetApproval:de.nullable(),maximumCostUsd:c().finite().nonnegative(),signal:uD,decision:dD,reasons:f(cD).min(1).max(100),createdAt:nt,metadata:Ct}).strict().superRefine((e,t)=>{const n=new Set(e.trainingEvidenceRefs.map(pg));if(e.frozenEvaluationEvidenceRefs.some(i=>n.has(pg(i)))&&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(i=>i.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"]})}),mD=ox.extend({contentHash:we}).strict();function ix(e){const t=ox.parse(e);return mD.parse({...t,contentHash:_t(t)})}function pg(e){return`${e.id}:${e.contentHash}`}const el="2026-08-08T12:00:00.000Z",rx=nn("harness-release"),sx={policy:nn("source-policy"),state:"authorized",checkedAt:el},ai=(e,t)=>({evidence:nn(e),kind:t,sourceRef:`source-${e}`,sourcePolicy:sx,occurrenceKey:_t(`occurrence-${e}`),occurredAt:el}),pD={cursor:_t("review-watermark"),throughCreatedAt:el},Uc=(e,t=3)=>({fingerprint:_t(`claim-${e}`),recurrenceFamily:e,statement:`The ${e} behavior remains unresolved after smaller-layer triage.`,independentOccurrences:t,unresolvedOccurrences:t}),Hc=Ys({schemaVersion:"openpond.harnessEvaluationReviewReceipt.v1",id:"review-no-action",ownerScope:{kind:"personal",id:"owner-1"},workspaceRef:"workspace-1",harnessRelease:rx,previousWatermark:null,nextWatermark:pD,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:el,metadata:{}});Ys({...tl(Hc),id:"review-runtime",selectedEvidence:[ai("runtime-failure","observation")],claim:Uc("runtime-transport-failure",1),classification:"runtime",triage:[{layer:"runtime",status:"unresolved",reason:"The adapter failed before model policy could affect the result.",evidenceRefs:[nn("runtime-failure")]}],reason:"A deterministic runtime regression is the smallest correct fix.",nextAuthority:"runtime_service"});Ys({...tl(Hc),id:"review-product",selectedEvidence:[ai("product-routing","route_decision")],claim:Uc("product-routing-defect",1),classification:"product",triage:[{layer:"product",status:"unresolved",reason:"The product selected an unrelated Skill for an ordinary Work turn.",evidenceRefs:[nn("product-routing")]}],reason:"Product routing must be corrected before behavioral Evaluation.",nextAuthority:"product_team"});const fD=Ys({...tl(Hc),id:"review-taskset",selectedEvidence:[ai("failure-1","work_outcome"),ai("failure-2","work_outcome"),ai("failure-3","work_outcome")],claim:Uc("search-budget-allocation"),classification:"taskset",triage:[{layer:"harness",status:"unresolved",reason:"The active research Skill did not resolve three independent failures.",evidenceRefs:[nn("failure-1"),nn("failure-2"),nn("failure-3")]}],reason:"The repeated behavioral claim now needs controlled measurement.",nextAuthority:"human_review",tasksetProposal:nn("taskset-proposal"),maxEstimatedCostUsd:2}),hD=ix({schemaVersion:"openpond.modelImprovementQualificationReceipt.v1",id:"qualification-rl-blocked",review:jm(fD),harnessRelease:rx,tasksetRelease:nn("taskset-release"),baselineEvaluation:nn("baseline-evaluation"),model:gD(),environmentHash:_t("environment"),toolContractHash:_t("tools"),permissionContractHash:_t("permissions"),policyHash:_t("policy"),verifierRef:nn("verifier"),sourcePolicies:[sx],trainingEvidenceRefs:[nn("training-evidence")],frozenEvaluationEvidenceRefs:[nn("frozen-evidence")],privacyApproval:nn("privacy-approval"),budgetApproval:nn("budget-approval"),maximumCostUsd:25,signal:{kind:"scalar_reward",strength:"weak",calibrated:!0,confounded:!1,variance:0,evidenceRefs:[nn("reward-audit")]},decision:"no_training",reasons:["The observed reward is constant and cannot support RL."],createdAt:el,metadata:{blockedMethod:"rl"}}),fg=ix({...tl(hD),id:"qualification-rl-qualified",signal:{kind:"scalar_reward",strength:"usable",calibrated:!0,confounded:!1,variance:.18,evidenceRefs:[nn("reward-audit")]},decision:"rl",reasons:["The frozen baseline has usable variance and a calibrated sequential reward."]});Ys({...tl(Hc),id:"review-model-improvement",selectedEvidence:[ai("baseline-evaluation","evaluation"),ai("qualification-rl-qualified","training_qualification")],claim:Uc("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:[nn("baseline-evaluation"),jm(fg)]}],reason:"The qualified claim may proceed to a separately approved managed-training plan.",nextAuthority:"training_system",tasksetProposal:nn("taskset-proposal"),evaluation:nn("baseline-evaluation"),trainingQualification:jm(fg),maxEstimatedCostUsd:25});function nn(e){return{id:e,contentHash:_t(e)}}function jm(e){return{id:e.id,contentHash:e.contentHash}}function tl(e){const{contentHash:t,...n}=e;return n}function gD(){return{provider:"openpond",model:"openpond-chat",revision:"model-revision-1",artifactHash:_t("model-artifact"),tokenizerRevision:"tokenizer-1",chatTemplateHash:_t("chat-template")}}const lx=l({schemaVersion:k("openpond.optimizerTrainingSample.v1"),tokenIds:f(c().int().nonnegative()).min(2).max(32768),mask:f(C()).min(2).max(32768),logprobs:f(c().finite()).min(2).max(32768),temperatures:f(c().positive().finite()).min(2).max(32768),envName:o().trim().min(1).max(200),modelRequestId:o().trim().min(1).max(1e3),promptTokenCount:c().int().positive(),completionTokenCount:c().int().positive(),servedPolicyVersion:c().int().nonnegative()}).strict().superRefine((e,t)=>{const n=e.tokenIds.length;for(const[a,i]of[["mask",e.mask],["logprobs",e.logprobs],["temperatures",e.temperatures]])i.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"})}),bD=l({id:ie,environmentRelease:de,status:b(["completed","failed","timed_out","cancelled"]),startedAt:nt,completedAt:nt,traceRefs:f(Zn).max(1e4),metadata:Ct}).strict(),vD=l({receiptRef:de,status:rf,value:c().min(0).max(1).nullable(),learningEligible:C(),passed:C(),outcomeClass:HS,failureOwner:zc.nullable(),components:fe(ie,c().min(0).max(1).nullable())}).strict(),cx=l({schemaVersion:k("openpond.canonicalRolloutRecord.v1"),id:ie,attemptRef:de,artifactManifestRef:de,tasksetRelease:de,environmentRelease:de,verifierSetRelease:de,harnessRelease:de,taskId:ie,split:mr,model:pi,seed:o().trim().min(1).max(500),reward:vD,traceRef:Zn,optimizerSample:lx.nullable(),environmentExecutions:f(bD).min(1).max(1e5),startedAt:nt,completedAt:nt,metadata:Ct}).strict();function dx(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."})}cx.superRefine(dx);l({...cx.shape,contentHash:we}).strict().superRefine(dx);l({schemaVersion:k("openpond.rolloutQualification.v1"),rolloutCount:c().int().nonnegative(),scoredCount:c().int().nonnegative(),optimizerEligibleCount:c().int().nonnegative(),unscorableCount:c().int().nonnegative(),zeroRewardCount:c().int().nonnegative(),rewardMean:c().min(0).max(1).nullable(),rewardVariance:c().nonnegative().nullable(),distinctRewardCount:c().int().nonnegative(),eligibleForRl:C(),reasons:f(o().trim().min(1).max(1e3)).max(100)}).strict();const yD="openpond.runTelemetryEvent.v1",SD="openpond.metricDefinition.v1",ux="openpond.metricObservation.v1",cf=b(["policy_visible","team_visible","host_private"]),xD=b(["runtime","environment","grader","optimizer","control_plane","evaluation"]),kD=b(["run_started","run_state_changed","rollout_group_started","attempt_completed","grader_completed","reward_composed","optimizer_step_completed","checkpoint_committed","evaluation_completed","run_completed","run_failed","cleanup_completed"]),mx=l({modelProjectId:ie,runId:ie,modelVersionId:ie.nullable(),harnessReleaseHash:we,tasksetReleaseHash:we,environmentReleaseHash:we.nullable(),checkpointId:ie.nullable(),step:c().int().nonnegative().nullable(),rolloutGroupId:ie.nullable(),attemptId:ie.nullable(),scenarioId:ie.nullable()}).strict(),px=l({schemaVersion:k(yD),eventId:ie,sequence:c().int().nonnegative(),occurredAt:nt,source:xD,type:kD,visibility:cf,lineage:mx,attributes:Ct}).strict(),_D=b(["gauge","counter","distribution"]),wD=b(["ratio","count","seconds","milliseconds","tokens","bytes","usd","scalar"]),ID=b(["higher","lower","neutral"]),CD=b(["last","sum","mean","min","max","p50","p95"]),fx=l({schemaVersion:k(SD),id:ie,displayName:o().trim().min(1).max(200),description:o().trim().min(1).max(2e3),valueType:_D,unit:wD,direction:ID,aggregation:CD,visibility:cf,boundedDimensions:f(o().trim().min(1).max(100)).max(32)}).strict(),hx=l({schemaVersion:k(ux),observationId:ie,metricId:ie,eventId:ie,sequence:c().int().nonnegative(),observedAt:nt,value:c().finite(),lineage:mx,dimensions:fe(o().trim().min(1).max(100),o().max(500))}).strict();l({schemaVersion:k("openpond.runTelemetryBatch.v1"),events:f(px).max(1e3),observations:f(hx).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 i=a.schemaVersion===ux?a.observationId:a.eventId,r=`${a.lineage.runId}:${a.sequence}:${i}`;n.has(r)&&t.addIssue({code:"custom",message:"Telemetry batch contains a duplicate idempotency key."}),n.add(r)}});const ln=e=>fx.parse({schemaVersion:"openpond.metricDefinition.v1",...e}),RD=[ln({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"]}),ln({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"]}),ln({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"]}),ln({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"]}),ln({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"]}),ln({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"]}),ln({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"]}),ln({id:"optimizer.kl",displayName:"Policy update KL",description:"Sampled approximate KL between the frozen pre-update policy and the policy after the optimizer step.",valueType:"gauge",unit:"scalar",direction:"lower",aggregation:"mean",visibility:"team_visible",boundedDimensions:["split"]}),ln({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"]}),ln({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"]}),ln({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"]}),ln({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"]}),ln({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"]}),ln({id:"tokens.input",displayName:"Input tokens",description:"Input tokens processed.",valueType:"counter",unit:"tokens",direction:"neutral",aggregation:"sum",visibility:"team_visible",boundedDimensions:["split","source"]}),ln({id:"tokens.output",displayName:"Output tokens",description:"Output tokens generated.",valueType:"counter",unit:"tokens",direction:"neutral",aggregation:"sum",visibility:"team_visible",boundedDimensions:["split","source"]}),ln({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"]}),ln({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"]}),ln({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"]}),ln({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"]}),ln({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(RD.map(e=>[e.id,e]));const AD=f(fx).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."})});l({checkpointIds:f(ie).max(1e3),steps:f(c().int().nonnegative()).max(1e4),scenarioIds:f(ie).max(1e5),rolloutGroupIds:f(ie).max(1e5),attemptIds:f(ie).max(1e6),splits:f(o().trim().min(1).max(100)).max(32),failureOwners:f(o().trim().min(1).max(100)).max(32),graders:f(o().trim().min(1).max(200)).max(1e3),rewardEligible:C().nullable()}).strict();const PD=l({id:ie,contentHash:we,kind:b(["rollout","attempt","trace","grader","checkpoint","artifact"]),visibility:cf}).strict(),TD=l({schemaVersion:k("openpond.telemetryEvidenceCompleteness.v1"),runId:ie,status:b(["complete","partial","missing"]),expectedEventTypes:f(o().trim().min(1).max(100)).max(100),observedEventTypes:f(o().trim().min(1).max(100)).max(100),missingEventTypes:f(o().trim().min(1).max(100)).max(100),lastSequence:c().int().nonnegative().nullable(),sequenceGaps:f(c().int().nonnegative()).max(1e4)}).strict(),ED=l({step:c().int().nonnegative().nullable(),observedAt:nt,value:c().finite(),sampleCount:c().int().positive()}).strict();l({schemaVersion:k("openpond.runMetricSummary.v1"),runId:ie,metricId:ie,aggregation:b(["last","sum","mean","min","max","p50","p95"]),value:c().finite().nullable(),sampleCount:c().int().nonnegative(),series:f(ED).max(1e5)}).strict();const MD=l({schemaVersion:k("openpond.telemetryExportBundle.v1"),id:ie,runId:ie,exportedAt:nt,definitions:AD,events:f(px).max(1e6),observations:f(hx).max(1e7),evidenceRefs:f(PD).max(1e6),completeness:TD}).strict();MD.extend({contentHash:we}).strict();const jD=b(["trajectory","reward","demonstration","preference","correction","critique","targeted_feedback","grader_evidence","infrastructure_failure"]),OD=l({datasetRelease:Ye,harnessRelease:Ye,evidenceSetRelease:Ye.nullable(),profileRelease:Ye.nullable(),model:l({source:o().trim().min(1).max(200),revision:o().trim().min(1).max(500),artifactHash:Me.nullable()}).strict(),environmentHash:Me,graderHash:Me,toolContractHash:Me,verificationReceiptHash:Me.nullable()}).strict(),bo=l({schemaVersion:k("openpond.learningSignal.v1"),id:L,taskId:L.nullable(),episodeId:L.nullable(),policyVersion:c().int().nonnegative().nullable(),lineage:OD,approved:C(),verifier:b(["deterministic","model_judge","human","none"]),createdAt:ct,contentHash:Me,metadata:fe(o(),ye()).default({})}).strict(),ND=bo.extend({kind:k("trajectory"),payload:l({traceRef:o().trim().min(1).max(2e3),traceHash:Me,terminal:C(),failureClass:b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),optimizerSample:lx.nullable().optional()}).strict()}).strict(),$D=bo.extend({kind:k("reward"),payload:l({reward:c().finite(),components:fe(o(),c().finite()),eligible:C(),graderEvidenceRefs:f(L).max(1e3)}).strict()}).strict(),DD=bo.extend({kind:k("demonstration"),payload:l({prompt:o().max(5e5),response:o().max(1e6)}).strict()}).strict(),LD=bo.extend({kind:k("preference"),payload:l({prompt:o().max(5e5),chosen:o().max(1e6),rejected:o().max(1e6),rationale:o().max(5e5).nullable()}).strict()}).strict(),zD=bo.extend({kind:k("correction"),payload:l({original:o().max(1e6),corrected:o().max(1e6),rationale:o().max(5e5).nullable()}).strict()}).strict(),UD=bo.extend({kind:k("critique"),payload:l({response:o().max(1e6),critique:o().max(5e5),severity:b(["note","warning","error"])}).strict()}).strict(),HD=bo.extend({kind:k("targeted_feedback"),payload:l({turnIndex:c().int().nonnegative(),target:b(["reasoning","tool","answer","policy"]),feedback:o().max(5e5)}).strict()}).strict(),qD=bo.extend({kind:k("grader_evidence"),payload:l({graderId:L,score:c().finite().nullable(),passed:C(),privilegedArtifactRefs:f(o().trim().min(1).max(2e3))}).strict()}).strict(),BD=bo.extend({kind:k("infrastructure_failure"),approved:k(!1),verifier:k("none"),payload:l({code:L,phase:L,retryable:C(),rewardEligible:k(!1)}).strict()}).strict(),gx=Kt("kind",[ND,$D,DD,LD,zD,UD,HD,qD,BD]);l({schemaVersion:k("openpond.learningSignalBatch.v1"),manifestId:L,manifestHash:Me,sequence:c().int().nonnegative(),signals:f(gx).min(1).max(1e5),contentHash:Me}).strict();const df=l({adapterId:L,placement:b(["local","remote","colocated","provider_native"]),capabilityReceipt:Me,runtimeVersion:o().trim().min(1).max(200),dataPlane:l({provider:L,dataPlaneId:L,cellId:L,runnerPoolId:L,runtimeImageDigest:o().regex(/^sha256:[a-f0-9]{64}$/),capabilityReceipt:Me}).strict().nullable()}).strict(),uf=l({adapterId:L,kind:b(["local","ssh","managed","custom"]),deviceOrPool:o().trim().min(1).max(1e3),capabilityReceipt:Me,provider:L.nullable()}).strict(),mf=l({adapterId:L,workerVersion:o().trim().min(1).max(200),workerImageDigest:o().regex(/^sha256:[a-f0-9]{64}$/).nullable(),upstreamRevision:o().trim().min(1).max(500),capabilityReceipt:Me}).strict(),FD=l({schemaVersion:k("openpond.harnessRunManifest.v1"),id:L,harnessRelease:Ye,datasetRelease:Ye,evidenceSets:f(Ye).max(1e4),model:l({source:o().trim().min(1).max(200),revision:o().trim().min(1).max(500),artifactHash:Me.nullable(),tokenizerRevision:o().trim().min(1).max(500),chatTemplateHash:Me}).strict(),recipe:l({method:o().trim().min(1).max(100),version:o().trim().min(1).max(200),configHash:Me}).strict(),runtimeTarget:df,computeTarget:uf,engine:mf,resolvedBundleHash:Me,secretLeaseRefs:f(bM).max(1e3),approval:l({approvalHash:Me,approvedAt:ct,maximumSpendUsd:c().nonnegative().nullable()}).strict(),createdAt:ct}).strict(),VD=FD.extend({contentHash:Me}).strict(),WD=l({schemaVersion:k("openpond.resolvedTrainingBundle.v1"),projection:k("trainer"),harnessRelease:Ye,datasetRelease:Ye,evidenceSetRelease:Ye.nullable(),files:f(l({path:o().trim().min(1).max(2e3),sha256:Me,sizeBytes:c().int().nonnegative()}).strict()).max(1e5)}).strict();WD.extend({contentHash:Me}).strict();const KD=l({id:L,turn:c().int().nonnegative(),kind:b(["message","tool_call","terminal"]),name:L.nullable(),arguments:fe(o(),ye()),content:o().max(1e6).nullable(),contentHash:Me}).strict(),GD=l({actionId:L,turn:c().int().nonnegative(),terminal:C(),output:fe(o(),ye()),artifactRefs:f(o().trim().min(1).max(2e3)),contentHash:Me}).strict(),ZD=l({sequence:c().int().nonnegative(),type:b(["created","reset","action","observation","terminal","graded","feedback","failure","collected","destroyed"]),timestamp:ct,payloadHash:Me,metadata:fe(o(),ye()).default({})}).strict(),hg=l({graderId:L,graderVersion:o().trim().min(1).max(200),score:c().finite().nullable(),passed:C(),rewardEligible:C(),failureClass:b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),feedback:f(o().max(5e5)),visibleEvidenceRefs:f(o().trim().min(1).max(2e3)),privilegedEvidenceRefs:f(o().trim().min(1).max(2e3)),contentHash:Me}).strict();l({schemaVersion:k("openpond.harnessRunTrace.v1"),manifest:Ye,taskId:L,seed:o().trim().min(1).max(500),events:f(ZD).max(1e6),actions:f(KD).max(1e5),observations:f(GD).max(1e5),graderEvidence:f(hg).max(1e4),learningSignals:f(gx).max(1e5),terminal:C(),failureClass:hg.shape.failureClass,artifactHash:Me,contentHash:Me}).strict();const JD=o().trim().min(1).max(2e3).refine(e=>{const t=e.replaceAll("\\","/");return!t.startsWith("/")&&!t.includes("\0")&&!t.split("/").some(n=>!n||n==="."||n==="..")},"path must be a safe relative path"),YD=b(["instruction","skill","skill_resource","agent","dependency_lock","program","asset"]),XD=l({id:L,kind:YD,path:JD,parentId:L.nullable(),mediaType:o().trim().min(1).max(200),visibility:b(["policy","verifier","host_private"]),portability:b(["portable","local_only"])}).strict().superRefine((e,t)=>{e.kind==="skill_resource"!=(e.parentId!==null)&&t.addIssue({code:"custom",message:"only Skill resources require parentId",path:["parentId"]})});l({schemaVersion:k("openpond.harnessSourceManifest.v1"),name:o().trim().min(1).max(240),files:f(XD).min(2).max(1e5),toolDeclarations:f($c).max(200),capabilityRequirements:f(tf).max(200),lifecycle:AS,graderInterface:PS,runtimeProtocol:o().trim().min(1).max(500),metadata:fe(o(),ye()).default({})}).strict().superRefine((e,t)=>{const n=new Set,a=new Map,i=new Set;for(const[r,s]of e.files.entries())n.has(s.id)&&t.addIssue({code:"custom",message:"file ids must be unique",path:["files",r,"id"]}),i.has(s.path)&&t.addIssue({code:"custom",message:"file paths must be unique",path:["files",r,"path"]}),n.add(s.id),a.set(s.id,s.kind),i.add(s.path);for(const[r,s]of e.files.entries())s.parentId&&!n.has(s.parentId)?t.addIssue({code:"custom",message:"parentId must reference a declared Skill",path:["files",r,"parentId"]}):s.parentId&&a.get(s.parentId)!=="skill"&&t.addIssue({code:"custom",message:"parentId must reference a primary Skill file",path:["files",r,"parentId"]});e.files.filter(r=>r.kind==="dependency_lock").length!==1&&t.addIssue({code:"custom",message:"exactly one dependency lock is required",path:["files"]}),e.files.filter(r=>r.kind==="program").length!==1&&t.addIssue({code:"custom",message:"exactly one Harness program is required",path:["files"]})});l({rootPath:o(),sourcePath:o(),binding:eN,currentRelease:lg,releases:f(lg),transitions:f(tN)}).strict();l({profile:MS,activate:C().default(!0),reason:o().trim().min(1).max(1e4),actor:o().trim().min(1).max(240).default("local-user"),authoringSkillHash:o().regex(/^[a-f0-9]{64}$/).nullable().default(null)}).strict();l({release:de,reason:o().trim().min(1).max(1e4),actor:o().trim().min(1).max(240).default("local-user")}).strict();const QD=l({schemaVersion:k("openpond.trainingEngineCapabilities.v1"),adapterId:L,available:C(),methods:f(o().trim().min(1).max(100)),signalKinds:f(jD),modelFamilies:f(o().trim().min(1).max(200)),precisions:f(b(["fp32","fp16","bf16","tf32","int8","int4"])),topologies:f(o().trim().min(1).max(200)),workerProtocolVersion:o().trim().min(1).max(200),upstreamRevision:o().trim().min(1).max(500),workerImageDigest:o().regex(/^sha256:[a-f0-9]{64}$/).nullable().default(null),capabilityReceipt:Me,checkedAt:ct,unavailableReason:o().trim().min(1).max(5e3).nullable()}).strict(),eL=l({schemaVersion:k("openpond.computeTargetCapabilities.v1"),adapterId:L,kind:b(["local","ssh","managed","custom"]),provider:L.nullable(),available:C(),devices:f(l({id:L,kind:b(["cpu","gpu","accelerator"]),vendor:o().trim().min(1).max(200),name:o().trim().min(1).max(500),memoryBytes:c().int().nonnegative().nullable(),runtime:o().trim().min(1).max(200)}).strict()),supportsWorkerImages:C(),supportsArtifactTransfer:C(),supportsCancellation:C(),capabilityReceipt:Me,checkedAt:ct,unavailableReason:o().trim().min(1).max(5e3).nullable()}).strict(),tL=l({schemaVersion:k("openpond.harnessRuntimeCapabilities.v1"),adapterId:L,available:C(),placements:f(b(["local","remote","colocated","provider_native"])),lifecycle:f(b(["create","reset","step","grade","collect","destroy"])),deterministicReplay:C(),privilegedIsolation:C(),capabilityReceipt:Me,checkedAt:ct,unavailableReason:o().trim().min(1).max(5e3).nullable()}).strict();l({schemaVersion:k("openpond.resolvedTrainingPlan.v1"),manifest:VD,recipe:gS,runtime:df,compute:uf,engine:mf,execution:l({trainingPlanId:L,approvalId:L}).strict().nullable(),maximumSpendUsd:c().nonnegative().nullable(),approvalHash:Me,contentHash:Me}).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,i,r]of n)JSON.stringify(i)!==JSON.stringify(r)&&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"})});l({schemaVersion:k("openpond.adapterValidationReceipt.v1"),adapterId:L,valid:C(),issues:f(l({code:L,path:o().trim().max(2e3).nullable(),message:o().trim().min(1).max(5e3)}).strict()),capabilityReceipt:Me,planHash:Me,createdAt:ct,contentHash:Me}).strict();l({runId:L,adapterId:L,protocolVersion:b(["openpond.training.v2","adapter.native.v1"]).default("adapter.native.v1"),routeFamily:b(["training_v2","adapter_native"]).default("adapter_native"),routeId:L.optional(),providerJobId:o().trim().min(1).max(1e3).nullable(),tenantId:L.optional(),leaseId:L.nullable(),manifestHash:Me.optional(),inputBundleHash:Me.optional(),createdAt:ct}).strict();l({runId:L,state:b(["queued","preparing","running","cancelling","cancelled","succeeded","failed"]),phase:o().trim().min(1).max(200),progress:c().min(0).max(1).nullable(),rolloutProgress:l({groupsCompleted:c().int().nonnegative(),groupsTarget:c().int().nonnegative(),optimizerUpdatesApplied:c().int().nonnegative(),optimizerUpdatesSkipped:c().int().nonnegative()}).strict().optional(),updatedAt:ct,errorCode:L.nullable()}).strict();l({runId:L,manifestHash:Me,artifacts:f(l({kind:b(["checkpoint","adapter","metrics","trace","evaluation","receipt"]),objectRef:o().trim().min(1).max(2e3),sha256:Me,sizeBytes:c().int().nonnegative(),metadata:fe(o(),ye()).optional()}).strict()),contentHash:Me}).strict();const Om=b(["ready","model_download_required","compute_setup_required","provider_managed","unsupported"]),nL=l({id:L,label:o().trim().min(1).max(500),description:o().trim().min(1).max(2e3),destinationId:L,computeAdapterId:L,runtimeAdapterId:L,engineAdapterId:L,methods:f(o().trim().min(1).max(100)),capabilityPills:f(o().trim().min(1).max(100)),executionMode:b(["local_worker","provider_native"]),approvalPolicy:l({providerId:li,providerLabel:o().trim().min(1).max(200),settingsActionLabel:o().trim().min(1).max(500).nullable(),exportApprovalRequired:C(),exportDescription:o().trim().min(1).max(2e3).nullable(),preparationRequired:C(),minimumSpendUsd:c().nonnegative(),maximumSpendUsd:c().positive(),defaultMaximumSpendUsd:c().positive(),minimumRetentionDays:c().int().positive(),maximumRetentionDays:c().int().positive(),defaultRetentionDays:c().int().positive(),methodRequirement:o().trim().min(1).max(2e3).nullable()}).strict().nullable(),limits:l({maximumSequenceLength:c().int().positive(),maximumOutputTokens:c().int().positive(),maximumTrainingExamples:c().int().positive().nullable()}).strict(),defaults:l({loraRank:c().int().positive(),maxSteps:c().int().positive(),rolloutGroupSize:c().int().min(2).max(32),rolloutConcurrency:c().int().positive().max(32),rolloutOutputTokens:c().int().positive()}).strict(),available:C(),unavailableReason:o().trim().min(1).max(5e3).nullable()}).strict(),aL=l({selectionKey:L,label:o().trim().min(1).max(500),source:b(["local","builtin","huggingface","managed","search"]),modelId:o().trim().min(1).max(1e3),revision:o().trim().min(1).max(500).nullable(),tokenizerRevision:o().trim().min(1).max(500).nullable(),chatTemplateHash:Me.nullable(),modelAssetId:L.nullable(),expectedBytes:c().int().nonnegative().nullable(),cached:C(),known:C(),searchResolved:C(),computeAdapterIds:f(L),engineAdapterIds:f(L),preparationState:Om,reason:o().trim().min(1).max(5e3).nullable(),compatibilities:f(l({targetId:L,methods:f(o().trim().min(1).max(100)),state:Om,reason:o().trim().min(1).max(5e3).nullable()}).strict())}).strict();l({schemaVersion:k("openpond.trainingCatalog.v1"),models:f(aL).max(1e5),engines:f(QD),compute:f(eL),runtimes:f(tL),targets:f(nL),generatedAt:ct,contentHash:Me}).strict();l({schemaVersion:k("openpond.trainingPreparationPlan.v1"),modelRunId:L,state:Om,reason:o().trim().min(1).max(5e3).nullable(),runtime:df.nullable(),compute:uf.nullable(),engine:mf.nullable(),downloads:f(l({kind:k("model"),label:o().trim().min(1).max(500),expectedBytes:c().int().nonnegative(),digest:o().trim().min(8).max(500),cached:C(),state:b(["ready","required","downloading","cancelled","failed"]),progress:c().min(0).max(1).nullable(),cancellable:C(),diskImpactBytes:c().int().nonnegative()}).strict()),dataMovement:f(l({direction:b(["upload","download","none"]),label:o().trim().min(1).max(500),bytes:c().int().nonnegative().nullable()}).strict()),quoteUsd:c().nonnegative().nullable(),maximumSpendUsd:c().nonnegative().nullable(),retentionDays:c().int().nonnegative().nullable(),sideEffectsStarted:k(!1),contentHash:Me}).strict();function oL(e,t,n){const a=new Headers;a.set("Accept","text/event-stream"),a.set("Authorization",`Bearer ${e.token}`);const i=new URL(`${e.serverUrl.replace(/\/$/,"")}/v1/events`);return n!==void 0&&Number.isSafeInteger(n)&&n>0&&i.searchParams.set("afterSequence",String(n)),{url:i.toString(),init:{headers:a,signal:t}}}function iL(e){return Math.min(500*2**Math.max(0,e),1e4)}async function rL(e,t,n,a){bx(e);const i=e.body.getReader(),r=new TextDecoder;let s="";for(;!a?.aborted;){const{done:d,value:p}=await i.read();if(d){s+=r.decode();break}s+=r.decode(p,{stream:!0});let m=s.indexOf(`
126
-
127
- `);for(;m>=0;){const h=s.slice(0,m);s=s.slice(m+2),bg(h,t,n),m=s.indexOf(`
128
-
129
- `)}}!a?.aborted&&s.trim()&&bg(s,t,n)}function bx(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 sL(e,t,n,a,i={}){const r=new AbortController,s=i.fetchImpl??fetch,d=i.reconnectDelayMs??iL;let p=gg(i.afterSequence),m=!1;return(async()=>{let h=0;for(;!r.signal.aborted;)try{const S=oL(e,r.signal,p),y=await s(S.url,S.init);if(bx(y),m=!0,h=0,await rL(y,w=>{const R=gg(w.sequence);R>0&&R<=p||(R>0&&(p=R),t(w))},a,r.signal),m=!1,r.signal.aborted)break;throw new Error("event stream ended")}catch(S){if(m=!1,r.signal.aborted)break;n(S),await lL(d(h),r.signal),h+=1}})().catch(()=>{}),{close(){r.abort()},isOpen(){return m}}}function gg(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0?e:0}function bg(e,t,n){let a="message";const i=[];for(const r of e.split(`
130
- `))r.startsWith(":")||(r.startsWith("event: ")&&(a=r.slice(7).trim()),r.startsWith("data: ")&&i.push(r.slice(6)));if(a==="ready"){n?.();return}if(!(a!=="runtime"||i.length===0))try{t(JSON.parse(i.join(`
131
- `)))}catch{}}async function lL(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 vg(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 i=await fetch(`${e.serverUrl}${t}`,{...n,headers:a});if(!i.ok){const r=await i.json().catch(()=>({})),s=r&&typeof r=="object"&&"error"in r?String(r.error):i.statusText;throw new Error(s)}return await i.json()}function uW(e){const t=new URL("/v1/terminal",e.serverUrl);return t.protocol=t.protocol==="https:"?"wss:":"ws:",t.toString()}function mW(e){return["openpond-terminal",`openpond-token.${dL(e.token)}`]}function cL(e){const t=new TextEncoder().encode(e);let n="";for(let a=0;a<t.length;a+=32768){const i=t.subarray(a,a+32768);n+=String.fromCharCode(...i)}return btoa(n)}function dL(e){return cL(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function uL(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 mL={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"})},pL={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?${fL(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,n)=>B(e,`/v1/sessions/${t}/turns/interrupt`,{method:"POST",body:JSON.stringify({reason:n})}),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 fL(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 hL={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 i=new URLSearchParams({path:n});a.offsetBytes!==void 0&&i.set("offsetBytes",String(a.offsetBytes)),a.maxBytes!==void 0&&i.set("maxBytes",String(a.maxBytes));const r=await B(e,`/v1/sandboxes/${encodeURIComponent(t)}/files?${i.toString()}`);return{...r,contents:r.file.isBinary?"":uL(r.file.contentsBase64)}}},gL={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)})},bL={connectedAppStatus:(e,t={})=>{const n=vg(t);return n.set("status",t.status??"all"),B(e,`/v1/connected-apps/status${n.size>0?`?${n.toString()}`:""}`)},integrationConnections:(e,t={})=>{const n=vg(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})})},vL={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:i,...r}=n;return B(e,`/v1/sandbox-projects/${encodeURIComponent(t)}/source?${a.toString()}`,{method:"POST",body:JSON.stringify(r)})},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)})},yL={sandbox:(e,t)=>B(e,`/v1/sandboxes/${encodeURIComponent(t)}`)},SL={...bL,...vL,...yL,...gL,...hL},xL={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 i=new URLSearchParams;return a.beforeSequence!=null&&i.set("beforeSequence",String(a.beforeSequence)),a.limit!=null&&i.set("limit",String(a.limit)),B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages${i.size?`?${i}`:""}`)},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,i)=>B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages/${encodeURIComponent(a)}`,{method:"PATCH",body:JSON.stringify({body:i})}),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`)},pf="openpond-app-server-url",Os="openpond-app-token",kL=750;function vx(){return window.location.protocol!=="http:"&&window.location.protocol!=="https:"?null:window.location.origin&&window.location.origin!=="null"?window.location.origin:null}function Nm(e){const t=e.getItem(pf)?.trim(),n=e.getItem(Os)?.trim();return t&&n?{serverUrl:t,token:n}:null}function ic(e){if(!e)return null;try{const t="__openpond_storage_probe__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return null}}function zi(e,t){e.setItem(pf,t.serverUrl),e.setItem(Os,t.token)}function yg(e,t){const n=Nm(e);n?.serverUrl!==t.serverUrl||n.token!==t.token||(e.removeItem(pf),e.removeItem(Os))}function _L(){const e=window.__OPENPOND_WEB_CONNECTION__,t=e?.serverUrl?.trim(),n=e?.token?.trim();return t&&n?{serverUrl:t,token:n}:null}function wL(){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()||vx();return!a||!n?null:{serverUrl:a,token:n}}function IL(){window.location.hash&&window.history.replaceState(null,"",`${window.location.pathname}${window.location.search}`)}function Rl(e,t){t&&(e.some(n=>n.serverUrl===t.serverUrl&&n.token===t.token)||e.push(t))}function CL(){const e=[],t=ic(window.sessionStorage),n=ic(window.localStorage),a=vx(),i=t?.getItem(Os)??n?.getItem(Os);return Rl(e,null),Rl(e,a&&i?{serverUrl:a,token:i.trim()}:null),Rl(e,t?Nm(t):null),Rl(e,n?Nm(n):null),e}async function zu(e){const t=new AbortController,n=window.setTimeout(()=>t.abort(),kL);try{const a=await fetch(`${e}/health`,{signal:t.signal}),i=await a.json().catch(()=>null);return a.ok&&i?.server==="openpond-app-server"}catch{return!1}finally{window.clearTimeout(n)}}async function RL(){if(window.openpond)return window.openpond.getConnection();const e=ic(window.sessionStorage),t=ic(window.localStorage),n=wL();if(n&&await zu(n.serverUrl))return t&&zi(t,n),e&&zi(e,n),IL(),{...n,platform:navigator.platform};const a=_L();if(a&&await zu(a.serverUrl))return t&&zi(t,a),e&&zi(e,a),{...a,platform:navigator.platform};const i=CL();for(const r of i){if(await zu(r.serverUrl))return t&&zi(t,r),e&&zi(e,r),{...r,platform:navigator.platform};e&&yg(e,r),t&&yg(t,r)}throw new Error("No reachable OpenPond app server. Start `openpond ui` again and open the full printed URL.")}const J={...xL,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 i=new URLSearchParams({teamId:t});return a.beforeSequence!=null&&i.set("beforeSequence",String(a.beforeSequence)),a.limit!=null&&i.set("limit",String(a.limit)),B(e,`/v1/team-chat/threads/${encodeURIComponent(n)}?${i.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=Sg(t),a=n.size?`?${n.toString()}`:"";return B(e,`/v1/usage${a}`)},usageRecords:(e,t={})=>{const n=Sg(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}`)},usageTurnCache:(e,t)=>B(e,`/v1/usage/turn-cache?sessionId=${encodeURIComponent(t)}`),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,n={})=>B(e,`/v1/training/jobs/${encodeURIComponent(t)}/detail?evaluation=${n.includeEvaluation===!1?"false":"true"}`),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})}),chatWorkflows:(e,t)=>{const n=t?`?sessionId=${encodeURIComponent(t)}`:"";return B(e,`/v1/chat-workflows${n}`)},createChatWorkflow:(e,t)=>B(e,"/v1/chat-workflows",{method:"POST",body:JSON.stringify(t)}),updateChatWorkflow:(e,t,n)=>B(e,`/v1/chat-workflows/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),deleteChatWorkflow:(e,t)=>B(e,`/v1/chat-workflows/${encodeURIComponent(t)}`,{method:"DELETE"}),runChatWorkflow:(e,t)=>B(e,`/v1/chat-workflows/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify({})}),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 i=a.size?`?${a.toString()}`:"";return B(e,`/v1/local-agent-schedules/${encodeURIComponent(t)}/runs${i}`)},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)}),signOutOpenPondAccount:e=>B(e,"/v1/openpond/accounts/logout",{method:"POST",body:JSON.stringify({})}),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 i=a.size?`?${a.toString()}`:"";return B(e,`/v1/providers/${encodeURIComponent(t)}/models${i}`)},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,t={})=>B(e,"/v1/audio/transcriptions/status",{signal:t.signal}),transcribeVoice:(e,t,n={})=>B(e,"/v1/audio/transcriptions",{method:"POST",body:JSON.stringify(t),signal:n.signal}),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 i=a.size?`?${a.toString()}`:"";return B(e,`/v1/codex-history/${encodeURIComponent(t)}${i}`)},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`),...mL,...SL,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 i=a.toString()?`?${a.toString()}`:"";return B(e,`/v1/projects/${encodeURIComponent(t)}/cloud-source/preview${i}`)},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({})}),...pL,resolveApproval:(e,t,n)=>B(e,`/v1/approvals/${t}`,{method:"POST",body:JSON.stringify(n)})};function Sg(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 AL=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),PL=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,a)=>a?a.toUpperCase():n.toLowerCase()),xg=e=>{const t=PL(e);return t.charAt(0).toUpperCase()+t.slice(1)},yx=(...e)=>e.filter((t,n,a)=>!!t&&t.trim()!==""&&a.indexOf(t)===n).join(" ").trim(),TL=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var EL={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 ML=g.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:a,className:i="",children:r,iconNode:s,...d},p)=>g.createElement("svg",{ref:p,...EL,width:t,height:t,stroke:e,strokeWidth:a?Number(n)*24/Number(t):n,className:yx("lucide",i),...!r&&!TL(d)&&{"aria-hidden":"true"},...d},[...s.map(([m,h])=>g.createElement(m,h)),...Array.isArray(r)?r:[r]]));const pt=(e,t)=>{const n=g.forwardRef(({className:a,...i},r)=>g.createElement(ML,{ref:r,iconNode:t,className:yx(`lucide-${AL(xg(e))}`,`lucide-${e}`,a),...i}));return n.displayName=xg(e),n};const jL=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],OL=pt("activity",jL);const NL=[["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"}]],$L=pt("archive-restore",NL);const DL=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],LL=pt("arrow-left",DL);const zL=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}]],Sx=pt("bookmark",zL);const UL=[["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"}]],xx=pt("bookmark-x",UL);const HL=[["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"}]],kg=pt("book-open-text",HL);const qL=[["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"}]],_g=pt("boxes",qL);const BL=[["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"}]],FL=pt("calendar-clock",BL);const VL=[["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"}]],$m=pt("chart-column-stacked",VL);const WL=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],io=pt("check",WL);const KL=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],Dm=pt("circle-check",KL);const GL=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Mo=pt("chevron-down",GL);const ZL=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],ii=pt("chevron-right",ZL);const JL=[["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"}]],YL=pt("circle-alert",JL);const XL=[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]],qc=pt("cloud",XL);const QL=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],ez=pt("credit-card",QL);const tz=[["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"}]],nz=pt("download",tz);const az=[["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"}]],Uu=pt("external-link",az);const oz=[["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"}]],iz=pt("file-output",oz);const rz=[["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"}]],ff=pt("file-text",rz);const sz=[["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"}]],lz=pt("folder",sz);const cz=[["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"}]],Lm=pt("folder-git-2",cz);const dz=[["line",{x1:"6",x2:"6",y1:"3",y2:"15",key:"17qcm7"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["path",{d:"M18 9a9 9 0 0 1-9 9",key:"n2h4wq"}]],uz=pt("git-branch",dz);const mz=[["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"}]],pz=pt("github",mz);const fz=[["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"}]],kx=pt("earth",fz);const hz=[["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"}]],gz=pt("circle-question-mark",hz);const bz=[["path",{d:"M2 5h20",key:"1fs1ex"}],["path",{d:"M6 12h12",key:"8npq4p"}],["path",{d:"M9 19h6",key:"456am0"}]],vz=pt("list-filter",bz);const yz=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Sz=pt("loader-circle",yz);const xz=[["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"}]],kz=pt("maximize-2",xz);const _z=[["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"}]],Bc=pt("message-square",_z);const wz=[["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"}]],hf=pt("ellipsis",wz);const Iz=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],_x=pt("panel-left",Iz);const Cz=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],zm=pt("panel-right",Cz);const Rz=[["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"}]],gf=pt("pin",Rz);const Az=[["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"}]],bf=pt("pin-off",Az);const Pz=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],Tz=pt("power",Pz);const Ez=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Mz=pt("search",Ez);const jz=[["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"}]],vf=pt("settings",jz);const Oz=[["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"}]],wx=pt("shapes",Oz);const Nz=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]],$z=pt("shield",Nz);const Dz=[["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"}]],yf=pt("square-pen",Dz);const Lz=[["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"}]],Ix=pt("square-terminal",Lz);const zz=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],Um=pt("user-round",zz);const Uz=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Ir=pt("x",Uz);function Hz({platform:e}){return!Fc()||Sf(e)?null:v.jsxs("div",{className:"window-controls","aria-label":"Window controls",children:[v.jsx("button",{type:"button",className:"window-control minimize",title:"Minimize",onClick:()=>{Hu("minimize")},children:v.jsx(Mo,{size:14})}),v.jsx("button",{type:"button",className:"window-control maximize",title:"Maximize",onClick:()=>{Hu("toggleMaximize")},children:v.jsx(kz,{size:12})}),v.jsx("button",{type:"button",className:"window-control close",title:"Close",onClick:()=>{Hu("close")},children:v.jsx(Ir,{size:13})})]})}function Sf(e){const t=e?.toLowerCase()??"";return t==="darwin"||t.includes("mac")}function Fc(){if(typeof window>"u")return!1;const e=window.openpond;return!!(e?.minimizeWindow||e?.toggleMaximizeWindow||e?.closeWindow)}async function Hu(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 qz=[{destination:"walkthroughs",icon:kg,label:"Walkthroughs"},{destination:"external",icon:kg,label:"Docs",url:"https://openpond.ai/docs"},{destination:"external",icon:ff,label:"Blog",url:"https://openpond.ai/blog"},{destination:"external",icon:ez,label:"Pricing",url:"https://openpond.ai/pricing"},{destination:"external",icon:kx,label:"Web app",url:"https://openpond.ai/sandboxes"},{destination:"external",icon:pz,label:"GitHub",url:"https://github.com/openpond/openpond"},{destination:"external",icon:Bc,label:"Submit issue",url:"https://github.com/openpond/openpond/issues/new/choose"}];function Bz({onOpenWalkthroughs:e,walkthroughsActive:t}){const[n,a]=g.useState(!1),i=g.useRef(null);return g.useEffect(()=>{if(!n)return;function r(d){i.current?.contains(d.target)||a(!1)}function s(d){d.key==="Escape"&&a(!1)}return document.addEventListener("pointerdown",r),document.addEventListener("keydown",s),()=>{document.removeEventListener("pointerdown",r),document.removeEventListener("keydown",s)}},[n]),v.jsxs("div",{className:"sidebar-help-menu",ref:i,children:[v.jsx("button",{"aria-expanded":n,"aria-haspopup":"menu","aria-label":"Open docs and help menu",className:`sidebar-icon sidebar-help-trigger ${t?"active":""}`,"data-tooltip":"Help",onClick:()=>a(r=>!r),type:"button",children:v.jsx(gz,{size:17})}),n?v.jsx("div",{className:"sidebar-help-popover",role:"menu","aria-label":"Help",children:qz.map(r=>{const s=r.icon,d=v.jsxs(v.Fragment,{children:[v.jsx(s,{size:15}),v.jsx("span",{children:r.label})]});return r.destination==="walkthroughs"?v.jsx("button",{"aria-current":t?"page":void 0,className:"sidebar-help-item",onClick:()=>{a(!1),e()},role:"menuitem",type:"button",children:d},r.label):v.jsx("a",{className:"sidebar-help-item",href:r.url,onClick:p=>{p.preventDefault(),a(!1),Fz(r.url)},rel:"noreferrer",role:"menuitem",target:"_blank",children:d},r.label)})}):null]})}async function Fz(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-help",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const pW=[{value:"chat",label:"Chat"},{value:"work",label:"Work"}],qu=[{value:"chat",label:"Work",description:"Chat and complete tasks"},{value:"models",label:"Models",description:"Evaluate, train, and serve models"}];function Cx(e){return e==="chat"?"New chat":"New task"}const Vz=["overview","tasksets","evals","runs","versions","serving"],Wz=["projects","comparisons","tasksets","scorers","evaluations","reviews"],wg=new Set(Vz),Kz=new Set(Wz),Gz=new Set(["scoring"]),Zz={runs:new Set(["details","metrics","evaluation","rollouts","activity","artifacts"]),tasksets:new Set(["overview","tasks","scoring","graders","attempts","releases"]),evals:new Set(["overview","comparison","activity"]),versions:new Set(["overview","metrics","evaluation","rollouts","activity","artifacts","lineage"])},Jz={tasksets:new Set(["overview","tasks","scoring","graders","attempts","releases"]),evaluations:new Set(["overview","comparison","activity"])},Yz={evals:"evals",overview:"overview",rollouts:"runs",runs:"runs",serving:"serving",tasksets:"tasksets",training:"runs",versions:"versions"},Xz=new Set(["account","notifications","harness","harness-refiner","harness-continuous-review","harness-contents","harness-releases","profile","skills","defaults","context","training","subagents","editor","providers","dataset-storage","remote","usage","personalization","diagnostics"]),Rx={apps:"/apps",outputs:"/outputs",projects:"/projects",scheduled:"/workflows","get-started":"/get-started"},Qz=new Map(Object.entries(Rx).map(([e,t])=>[t,e])),Fl=new Set;let Al=!1,Hm="",Ig=null,qm="",Cg=null;function Ji(e){try{return decodeURIComponent(e)}catch{return e}}function eU(e){const t=e.lastIndexOf("models");if(t<0)return null;const[n,a,i,r,...s]=e.slice(t+1);if(!n)return{kind:"index"};if(Kz.has(n))return r||s.length||i&&n!=="comparisons"&&!Jz[n]?.has(i)?null:{kind:"library",section:n,resourceId:a?Ji(a):null,detailTab:i??null};if(wg.has(n)||Gz.has(n))return null;if(!a)return{kind:"project",projectId:Ji(n),section:"overview",resourceId:null,detailTab:null};const d=a;return!wg.has(d)||d==="overview"||s.length||d==="serving"&&(i||r)||r&&!Zz[d]?.has(r)?null:{kind:"project",projectId:Ji(n),section:d,resourceId:i?Ji(i):null,detailTab:r??null}}function Ax(e){const t=eU(e.pathname.split("/").filter(Boolean));if(t)return t;const n=new URLSearchParams(e.search??""),a=n.get("modelProjectId"),i=n.get("modelsTab");return!a&&!i?null:a?{kind:"project",projectId:a,section:i?Yz[i]??"overview":"overview",resourceId:null,detailTab:null}:{kind:"index"}}function tU(e){if(e.kind==="index")return"/models";if(e.kind==="library"){const n=["/models",e.section];return e.resourceId&&n.push(encodeURIComponent(e.resourceId)),e.resourceId&&e.detailTab&&n.push(e.detailTab),n.join("/")}const t=["/models",encodeURIComponent(e.projectId)];return e.section==="overview"||(t.push(e.section),e.resourceId&&t.push(encodeURIComponent(e.resourceId)),e.resourceId&&e.detailTab&&t.push(e.detailTab)),t.join("/")}function nU(e){const t=Ax(e);if(t)return{kind:"models",route:t};const n=e.pathname.split("/").filter(Boolean);if(n[0]==="settings"&&n.length===2){const i=Ji(n[1]);return Xz.has(i)?{kind:"settings",section:i}:null}if(n[0]==="chat"&&n.length<=2)return{kind:"chat",sessionId:n[1]&&n[1]!=="new"?Ji(n[1]):null};const a=Qz.get(e.pathname);return a?{kind:"view",view:a}:null}function aU(e){return e.kind==="models"?tU(e.route):e.kind==="settings"?`/settings/${e.section}`:e.kind==="chat"?e.sessionId?`/chat/${encodeURIComponent(e.sessionId)}`:"/chat/new":Rx[e.view]}function oU(e){return e.kind==="project"?e.section:"overview"}function fW(e,t){if(e.kind!=="index"||t.length===0)return e;const n=t.reduce((a,i)=>{const r=i.updatedAt.localeCompare(a.updatedAt);return r>0||r===0&&i.id.localeCompare(a.id)>0?i:a});return Fm(n.id)}function iU(e){return e.kind==="library"?e.section:null}function rU(){if(typeof window>"u")return null;const e=`${window.location.pathname}${window.location.search}`;return e!==Hm&&(Hm=e,Ig=Ax(window.location)),Ig}function sU(){if(typeof window>"u")return null;const e=`${window.location.pathname}${window.location.search}`;return e!==qm&&(qm=e,Cg=nU(window.location)),Cg}function Bm(){Hm="",qm="";for(const e of Fl)e()}function Px(e){return Fl.add(e),typeof window<"u"&&!Al&&(window.addEventListener("popstate",Bm),Al=!0),()=>{Fl.delete(e),Al&&Fl.size===0&&typeof window<"u"&&(window.removeEventListener("popstate",Bm),Al=!1)}}function lU(){return g.useSyncExternalStore(Px,rU,()=>null)}function cU(){return g.useSyncExternalStore(Px,sU,()=>null)}function an(e,t="push"){if(typeof window>"u")return;const n=aU(e);window.location.pathname===n&&!window.location.search||(window.history[t==="replace"?"replaceState":"pushState"](window.history.state,"",n),Bm())}function Ro(e,t="push"){an({kind:"models",route:e},t)}function Fm(e,t="overview"){return e?{kind:"project",projectId:e,section:t,resourceId:null,detailTab:null}:{kind:"index"}}function dU(e,t=null,n=null){return{kind:"library",section:e,resourceId:t,detailTab:n}}function uU({experience:e="work",productArea:t="chat",beginNewChat:n,setSectionMenuOpen:a,setSelectedAppId:i,setSelectedProjectId:r,setSelectedSessionId:s,setView:d,view:p,modelProjects:m=[],modelTrainingActivityByProjectId:h={}}){const S=lU(),y=S?.kind==="project"?S.projectId:null,w=oU(S??{kind:"index"}),R=iU(S??{kind:"index"});function A(){i(null),r(null),s(null),a(null)}function N(E){y&&(A(),d("labs"),Ro(Fm(y,E)))}function O(E){A(),d("labs"),Ro(dU(E))}function D(){A(),d("labs"),Ro({kind:"index"})}function x(E){A(),d("labs"),Ro(Fm(E||null))}function I(E){A(),d(E),an({kind:"view",view:E})}const P=y?h[y]??null:null;return v.jsxs("nav",{className:"sidebar-nav","aria-label":"Primary",children:[t==="models"?null:v.jsxs("button",{className:"nav-command nav-command-new-task",type:"button",onClick:()=>{an({kind:"chat",sessionId:null}),n(null)},children:[v.jsx(yf,{size:18}),v.jsx("span",{children:Cx(e)})]}),t==="models"?v.jsxs(v.Fragment,{children:[v.jsx("span",{className:"sidebar-nav-group-label",children:"Library"}),v.jsxs("button",{className:`nav-command ${p==="labs"&&S?.kind==="index"?"active":""}`,"aria-label":"Models Overview",type:"button",onClick:D,children:[v.jsx(OL,{size:16}),v.jsx("span",{children:"Overview"})]}),v.jsxs("button",{className:`nav-command ${p==="labs"&&R==="projects"?"active":""}`,"aria-label":"Model Projects",type:"button",onClick:()=>O("projects"),children:[v.jsx(Lm,{size:16}),v.jsx("span",{children:"Model Projects"})]}),v.jsxs("button",{className:`nav-command ${p==="labs"&&R==="tasksets"?"active":""}`,"aria-label":"Taskset Library",type:"button",onClick:()=>O("tasksets"),children:[v.jsx(_g,{size:16}),v.jsx("span",{children:"Taskset Library"})]}),v.jsxs("button",{className:`nav-command ${p==="labs"&&R==="scorers"?"active":""}`,"aria-label":"Scorers",type:"button",onClick:()=>O("scorers"),children:[v.jsx($z,{size:16}),v.jsx("span",{children:"Scorers"})]}),v.jsxs("button",{className:`nav-command ${p==="labs"&&R==="evaluations"?"active":""}`,"aria-label":"Evaluations",type:"button",onClick:()=>O("evaluations"),children:[v.jsx(Dm,{size:16}),v.jsx("span",{children:"Evaluations"})]}),v.jsxs("button",{className:`nav-command ${p==="labs"&&R==="reviews"?"active":""}`,"aria-label":"Evals",type:"button",onClick:()=>O("reviews"),children:[v.jsx(Um,{size:16}),v.jsx("span",{children:"Evals"})]}),v.jsx("span",{className:"sidebar-nav-group-label",children:"Current project"}),v.jsx("div",{className:"sidebar-model-project-picker",children:v.jsxs("select",{"aria-label":"Select Model Project",disabled:!m.length,value:y??"",onChange:E=>x(E.target.value),children:[v.jsx("option",{disabled:!0,value:"",children:"Select a Model Project"}),m.map(E=>v.jsx("option",{value:E.id,children:E.name},E.id))]})}),y?v.jsxs(v.Fragment,{children:[v.jsxs("button",{className:`nav-command ${p==="labs"&&w==="overview"?"active":""}`,"aria-label":"Overview",type:"button",onClick:()=>N("overview"),children:[v.jsx($m,{size:16}),v.jsx("span",{children:"Overview"})]}),v.jsxs("button",{className:`nav-command ${p==="labs"&&w==="tasksets"?"active":""}`,"aria-label":"Tasksets",type:"button",onClick:()=>N("tasksets"),children:[v.jsx(_g,{size:16}),v.jsx("span",{children:"Tasksets"})]}),v.jsxs("button",{className:`nav-command ${p==="labs"&&w==="evals"?"active":""}`,"aria-label":"Evals",type:"button",onClick:()=>N("evals"),children:[v.jsx(Dm,{size:16}),v.jsx("span",{children:"Evaluations"})]}),v.jsxs("button",{className:`nav-command ${P?"nav-command-training-live ":""}${p==="labs"&&w==="runs"?"active":""}`,"aria-label":P?`Runs, ${P.label}`:"Runs",type:"button",onClick:()=>N("runs"),children:[v.jsx($m,{size:16}),v.jsx("span",{children:"Runs"}),P?v.jsx("span",{className:"nav-command-training-status","aria-label":`Training ${P.label.toLowerCase()}`,title:`Training ${P.label.toLowerCase()}`,children:v.jsx("span",{className:"sidebar-running-dot","aria-hidden":"true"})}):null]}),v.jsxs("button",{className:`nav-command ${p==="labs"&&w==="versions"?"active":""}`,"aria-label":"Versions",type:"button",onClick:()=>N("versions"),children:[v.jsx(uz,{size:16}),v.jsx("span",{children:"Versions"})]}),v.jsxs("button",{className:`nav-command ${p==="labs"&&w==="serving"?"active":""}`,"aria-label":"Serving",type:"button",onClick:()=>N("serving"),children:[v.jsx(qc,{size:16}),v.jsx("span",{children:"Serving"})]})]}):null]}):null,t==="chat"?v.jsxs(v.Fragment,{children:[v.jsxs("button",{className:`nav-command nav-command-prominent ${p==="scheduled"?"active":""}`,"aria-label":"Workflows",type:"button",onClick:()=>{I("scheduled")},children:[v.jsx(FL,{size:18}),v.jsx("span",{children:"Workflows"})]}),v.jsxs("button",{className:`nav-command nav-command-prominent ${p==="outputs"?"active":""}`,"aria-label":"Outputs",type:"button",onClick:()=>{I("outputs")},children:[v.jsx(iz,{size:18}),v.jsx("span",{children:"Outputs"})]}),v.jsxs("button",{className:`nav-command nav-command-prominent ${p==="apps"?"active":""}`,"aria-label":"Apps",type:"button",onClick:()=>{I("apps")},children:[v.jsx(wx,{size:18}),v.jsx("span",{children:"Apps"})]}),v.jsxs("button",{className:`nav-command nav-command-prominent ${p==="projects"?"active":""}`,"aria-label":"Projects",type:"button",onClick:()=>{I("projects")},children:[v.jsx(Lm,{size:18}),v.jsx("span",{children:"Projects"})]})]}):null]})}function mU({setSectionMenuOpen:e,setSelectedAppId:t,setSelectedProjectId:n,setSelectedSessionId:a,setView:i,view:r}){function s(){t(null),n(null),a(null),e(null),i("get-started"),an({kind:"view",view:"get-started"})}return v.jsx("nav",{className:"sidebar-utility-nav","aria-label":"Resources",children:v.jsx(Bz,{onOpenWalkthroughs:s,walkthroughsActive:r==="get-started"})})}const Vl=5,xn=15,Vm=10,At={defaultChatProvider:oi,subagents:VR(),codexPermissionMode:_c,codexReasoningEffort:wc,openPondCommandAccessMode:qs,defaultBranchPrefix:"feat/",defaultNewProjectDirectory:"",advancedWorkspaceControls:!1,steerActiveResponses:!0,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:""}}}},hW={activeTemplateId:"default",customized:!1,soul:"",soulPath:null,updatedAt:null,templates:[]},Tx=[{value:"accounts/fireworks/models/deepseek-v4-pro",label:"DeepSeek V4 Pro",description:"reasoning"},{value:"accounts/fireworks/models/kimi-k3",label:"Kimi K3",description:"reasoning"},{value:"accounts/fireworks/models/glm-5p3",label:"GLM-5.3",description:"reasoning"},{value:"accounts/fireworks/models/deepseek-v4-flash",label:"DeepSeek V4 Flash",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"}],Bu=[{value:"openpond",label:"OpenPond Chat"},{value:"codex",label:"OpenAI Codex",description:"Codex login"}],pU=["openai","xai","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],fU=["openpond","codex",...pU],Ex=new Set(fU),Mx=[{value:Pp,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"}],gW=[{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."}],bW=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"xhigh",label:"Extra High",shortLabel:"Extra High"}],vW=[{value:"ask",label:"Ask",description:"Ask before running shell commands."},{value:"full-access",label:"Full access",description:"Run shell commands without approval prompts."}],yW=[{value:"auto",label:"Auto",description:"Use installed language servers when available."},{value:"off",label:"Off",description:"Disable editor language servers."}],SW=[{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 xf(e){return e.kind==="local"}function hU(e){return e.kind==="cloud"}function vt(e,t){return`${e}:${t}`}function jx(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),i=t.slice(n+1);return(a==="local"||a==="cloud")&&i?{kind:a,id:i}:{kind:"local",id:t}}function ei(e){return`${e.type}:${e.id}`}function rc(e){const t=e.currentTarget.getBoundingClientRect();return e.clientY<t.top+t.height/2?"before":"after"}function sc(e,t,n,a="before"){if(t===n)return e;const i=e.filter(s=>s!==t),r=i.indexOf(n);return r===-1?e:(i.splice(a==="after"?r+1:r,0,t),i)}function Rg(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function gU(e,t){if(!t)return e;const n=new Map(e.map(r=>[r.key,r])),a=t.map(r=>n.get(r)).filter(r=>!!r),i=new Set(a.map(r=>r.key));return[...a,...e.filter(r=>!i.has(r.key))]}function kf(e,t){return e?.statuses?.[t]??null}function Ox(e,t){return e?.providers?.[t]??null}function Nx(e,t){return e?.modelCaches?.[t]??null}function bU(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 vU(e){return e==="openpond"?Tx:e==="codex"||e==="openai"?Mx:[]}function yU(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 xW(e){return Ex.has(e)}function Wm(e,t={}){if(!e)return t.localOnly,Bu;const n=t.includeUnavailable??!1,a=t.enabledOnly??!1,i=[];for(const r of vp){if(!Ex.has(r)||t.localOnly&&r==="openpond")continue;const s=kf(e,r);s&&(!n&&(r==="codex"&&!s.available&&!s.credential.connected||r!=="openpond"&&r!=="codex"&&!s.enabled)||a&&r!=="openpond"&&!s.enabled||a&&r==="codex"&&!s.available&&!s.credential.connected||i.push({value:r,label:r==="openpond"?"OpenPond Chat":s.displayName,description:r==="openpond"?void 0:s.available?"Connected":s.credential.connected?"Configured":s.routing.localByok?"Set up key":s.enabled?"Enabled":void 0}))}return i.length>0?i:Bu}function Ns(e,t){const a=(Nx(t,e)?.models??[]).filter(s=>e!=="openpond"||s.id!==rr).map(bU),i=Ox(t,e),r=[...i?.modelOverrides??[],i?.defaultModel].filter(s=>!!s?.trim()&&(e!=="openpond"||s!==rr)).map(s=>({value:s,label:s}));return yU([...a,...r,...vU(e)])}function SU(e,t,n){if(e==="codex"||e==="openai")return!0;const a=t.trim();if(!a)return!1;const i=Nx(n,e)?.models.find(r=>r.id===a);return i?!!i.capabilities.reasoning:Ns(e,n).some(r=>r.value===a&&/\breasoning\b/i.test(r.description??""))}function lc(e,t){const n=Ox(t,e)?.defaultModel?.trim();if(n)return n;const a=kf(t,e)?.defaultModel?.trim();if(a)return a;const i=Ns(e,t)[0]?.value?.trim();return i||(e==="codex"?Pp:e==="openpond"?rr:"")}function Do(e,t,n){const a=t?.trim();if(e==="codex"&&(a==="codex-default"||a==="gpt-5.5"))return Pp;const i=Ns(e,n);return a&&i.some(r=>r.value===a)||a&&e!=="codex"&&i.length===0&&!n?a:lc(e,n)}function $x(e,t){const n=e.modelRef?.providerId??e.provider;return{provider:n,model:Do(n,e.modelRef?.modelId,t)}}function _f(e,t,n){return Do(e,t,n)||void 0}function Sa(e,t,n){const a=_f(e,t,n);return a?{providerId:e,modelId:a}:void 0}function Ag(e){return e==="full-access"?{approvalPolicy:"never",sandbox:"danger-full-access"}:{approvalPolicy:"on-request",sandbox:"workspace-write"}}function ta(e){const t=e?.defaultChatProvider??At.defaultChatProvider;return{defaultChatProvider:t,defaultChatModel:Do(t,e?.defaultChatModel),subagents:Rs.parse(e?.subagents??At.subagents),codexPermissionMode:e?.codexPermissionMode??At.codexPermissionMode,codexReasoningEffort:e?.codexReasoningEffort??At.codexReasoningEffort,openPondCommandAccessMode:e?.openPondCommandAccessMode??At.openPondCommandAccessMode,defaultBranchPrefix:Dx(e?.defaultBranchPrefix),defaultNewProjectDirectory:e?.defaultNewProjectDirectory??At.defaultNewProjectDirectory,defaultTeamId:e?.defaultTeamId?.trim()||null,advancedWorkspaceControls:e?.advancedWorkspaceControls??At.advancedWorkspaceControls,steerActiveResponses:e?.steerActiveResponses??At.steerActiveResponses,contextCompaction:{autoEnabled:e?.contextCompaction?.autoEnabled??At.contextCompaction.autoEnabled,triggerPercent:e?.contextCompaction?.triggerPercent??At.contextCompaction.triggerPercent,summaryModel:e?.contextCompaction?.summaryModel??At.contextCompaction.summaryModel},training:{defaultModelRef:e?.training?.defaultModelRef??At.training.defaultModelRef,creationMode:e?.training?.creationMode??At.training.creationMode,autoApproveEvidence:e?.training?.autoApproveEvidence??At.training.autoApproveEvidence},sidebarWidth:e?.sidebarWidth??At.sidebarWidth,diffPanelWidth:e?.diffPanelWidth??At.diffPanelWidth,sidebarSectionsCollapsed:{pinned:e?.sidebarSectionsCollapsed?.pinned??At.sidebarSectionsCollapsed.pinned,projects:e?.sidebarSectionsCollapsed?.projects??At.sidebarSectionsCollapsed.projects,cloudProjects:e?.sidebarSectionsCollapsed?.cloudProjects??At.sidebarSectionsCollapsed.cloudProjects,chats:e?.sidebarSectionsCollapsed?.chats??At.sidebarSectionsCollapsed.chats,savedForLater:e?.sidebarSectionsCollapsed?.savedForLater??At.sidebarSectionsCollapsed.savedForLater},editor:{languageServers:e?.editor?.languageServers??At.editor.languageServers,diagnosticsWhileEditing:e?.editor?.diagnosticsWhileEditing??At.editor.diagnosticsWhileEditing,checkOnSave:e?.editor?.checkOnSave??At.editor.checkOnSave,languages:{typescript:{mode:e?.editor?.languages?.typescript?.mode??At.editor.languages.typescript.mode,customCommand:e?.editor?.languages?.typescript?.customCommand??At.editor.languages.typescript.customCommand},python:{mode:e?.editor?.languages?.python?.mode??At.editor.languages.python.mode,customCommand:e?.editor?.languages?.python?.customCommand??At.editor.languages.python.customCommand},rust:{mode:e?.editor?.languages?.rust?.mode??At.editor.languages.rust.mode,customCommand:e?.editor?.languages?.rust?.customCommand??At.editor.languages.rust.customCommand}}}}}function Dx(e){const t=e?.trim()??At.defaultBranchPrefix;if(!t)return"";const a=t.toLowerCase().replace(/[^a-z0-9._/-]+/g,"-").replace(/\/{2,}/g,"/").replace(/^-+/,"").slice(0,48).split("/").map(i=>i.replace(/^-+|-+$/g,"")).filter(Boolean).join("/");return a?`${a}/`:""}function kW(e,t){return e==="openpond"?"OpenPond Chat":kf(t,e)?.displayName??(e==="codex"?"OpenAI Codex":e)}function _W(e,t,n){if(n){const a=Ns(n,t).find(i=>i.value===e);if(a)return a.label}if(t)for(const a of vp){const i=Ns(a,t).find(r=>r.value===e);if(i)return i.label}return[...Tx,...Mx].find(a=>a.value===e)?.label??e}function xU(e,t){return t==="chat"?e.filter(n=>n.experience==="chat"):e.filter(n=>n.experience==="work"||n.experience==="development")}function kU(e){return e.experience==="chat"?"Chat":"Work"}const wf="taskDraft";function Lx(e){if(e?.experience!=="work")return null;const t=e.metadata?.[wf];if(!t||typeof t!="object"||Array.isArray(t))return null;const n=t.prompt;return typeof n=="string"&&n.trim()?n:null}function $s(e){return Lx(e)!==null}function _U(e){return(e.split(/\r?\n/u).map(n=>n.trim()).find(Boolean)||"Task draft").slice(0,64)}function Fu(e,t,n=new Date().toISOString()){const a={version:1,prompt:t,savedAt:n};return{...e??{},[wf]:a}}function wU(e){const t={...e??{}};return delete t[wf],t}function Ao(e){const t=Pl(e.metadata?.trainingTasksetId)??Pl(e.metadata?.tasksetId);return t?{id:t,name:Pl(e.metadata?.trainingTasksetName)??Pl(e.metadata?.tasksetName)??IU(t)}:null}function IU(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 Pl(e){return typeof e=="string"&&e.trim()?e.trim():null}const CU="codex_history_";function Nt(e){return!!e?.startsWith(CU)}function zx(e){const t=[],n=new Set;for(const a of e)for(const i of[a.workspacePath,a.path]){const r=Vc(i);if(!r)continue;const s=`${a.id}:${r}`;n.has(s)||(n.add(s),t.push({projectId:a.id,path:r}))}return t.sort((a,i)=>i.path.length-a.path.length)}function RU(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 r=Ux(e.cwd,n);if(r)return r}if(e.cloudProjectId&&a.has(e.cloudProjectId))return e.cloudProjectId;if(!e.cwd||e.workspaceKind==="sandbox"||e.workspaceKind==="sandbox_template"||e.workspaceKind==="sandbox_app"||!Hx(e))return null;const i=Vc(e.cwd);if(!i)return null;for(const r of n)if(If(i,r.path))return r.projectId;return null}function Pg(e,t,n,a=new Set){if(e.localProjectId&&t.has(e.localProjectId))return vt("local",e.localProjectId);if(e.workspaceKind==="local_project"&&e.workspaceId&&t.has(e.workspaceId))return vt("local",e.workspaceId);if(e.metadata?.workspaceTarget==="hybrid"&&e.cwd){const r=Ux(e.cwd,n);if(r)return vt("local",r)}if(e.cloudProjectId&&a.has(e.cloudProjectId))return vt("cloud",e.cloudProjectId);if(!e.cwd||e.workspaceKind==="sandbox"||e.workspaceKind==="sandbox_template"||e.workspaceKind==="sandbox_app"||!Hx(e))return null;const i=Vc(e.cwd);if(!i)return null;for(const r of n)if(If(i,r.path))return vt("local",r.projectId);return null}function Ux(e,t){const n=Vc(e);if(!n)return null;for(const a of t)if(If(n,a.path))return a.projectId;return null}function Hx(e){return e.workspaceKind==="local_project"||e.provider==="codex"||Nt(e.id)}function Vc(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 If(e,t){const n=Tg(e),a=Tg(t);return n===a||n.startsWith(`${a}/`)}function Tg(e){return/^[A-Z]:\//.test(e)?e.toLowerCase():e}const Eg=[{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"}],AU=[{value:"recent",label:"Recent first"},{value:"manual",label:"Manual order"}];function Mg(e){const t=[];if(e.filter==="done")t.push(...e.doneSessions.filter(i=>!Ao(i)));else if(e.filter==="all")t.push(...e.activeSessions.filter(i=>!Ao(i)),...e.doneSessions.filter(i=>!Ao(i)));else if(e.filter==="tasksets")t.push(...e.activeSessions.filter(i=>jg(i,e.selectedTasksetId)),...e.doneSessions.filter(i=>jg(i,e.selectedTasksetId)));else for(const i of e.activeSessions)Ao(i)||(e.filter==="active"?i.savedForLater||t.push(i):e.filter==="in_progress"?!i.savedForLater&&e.inProgressSessionIds.has(i.id)&&t.push(i):e.filter==="pinned"?i.pinned&&!i.savedForLater&&t.push(i):e.filter==="saved_for_later"&&i.savedForLater&&t.push(i));const n=t.filter(i=>Bi(i,{inProgressSessionIds:e.inProgressSessionIds,onlyRunningTasks:e.onlyRunningTasks,showCodexChats:e.showCodexChats})),a=e.previewSessionIds?new Map(e.previewSessionIds.map((i,r)=>[i,r])):null;return e.sort==="recent"?n.sort((i,r)=>Ng(i,r,a)):n.sort((i,r)=>{const s=a?.get(i.id),d=a?.get(r.id);if(s!==void 0||d!==void 0){if(s===void 0)return 1;if(d===void 0)return-1;if(s!==d)return s-d}return i.order!==r.order?i.order-r.order:Ng(i,r)})}function Bi(e,t){return t.showCodexChats===!1&&(e.provider==="codex"||Nt(e.id))?!1:!t.onlyRunningTasks||t.inProgressSessionIds.has(e.id)}function jg(e,t){const n=Ao(e);return!!(n&&(!t||n.id===t))}function PU(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 TU(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 Og(e,t,n){const a=new Set(t);let i=0;return e.map(r=>{if(!a.has(r))return r;const s=n[i];return i+=1,s??r})}function Ng(e,t,n=null){const a=cc(e),i=cc(t);if(a!==i)return a?-1:1;if(a&&i){const s=n?.get(e.id),d=n?.get(t.id);if(s!==void 0||d!==void 0){if(s===void 0)return 1;if(d===void 0)return-1;if(s!==d)return s-d}if(e.order!==t.order)return e.order-t.order}const r=Date.parse(t.updatedAt)-Date.parse(e.updatedAt);return r!==0?r:e.title.localeCompare(t.title)}function cc(e){return e.pinned&&!e.savedForLater&&!e.archived}const Tl={showCodexChats:!0,onlyRunningTasks:!1},qx="openpond.sidebar-task-visibility.v1";function EU(e=Bx()){try{const t=e?.getItem(qx);if(!t)return Tl;const n=JSON.parse(t);return{showCodexChats:typeof n.showCodexChats=="boolean"?n.showCodexChats:Tl.showCodexChats,onlyRunningTasks:typeof n.onlyRunningTasks=="boolean"?n.onlyRunningTasks:Tl.onlyRunningTasks}}catch{return Tl}}function $g(e,t=Bx()){try{t?.setItem(qx,JSON.stringify(e))}catch{}}function Bx(){return typeof window>"u"?null:window.localStorage}function Fx(e){return`${e.kind}:${e.id}`}function Ds(e,t){return!!(e&&t&&e.kind===t.kind&&e.id===t.id)}function MU(e){return{kind:"session",id:e}}function jU(e){return{kind:"project",id:e}}function OU(e){return{kind:"draft",id:e}}function NU(e){return e.selectedSessionId?MU(e.selectedSessionId):e.selectedProjectId?jU(e.selectedProjectId):OU(e.selectedAppId?`app:${e.selectedAppId}`:"new-chat")}function $U(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 wW(e,t){return e.filter(n=>Ds(n.scope,t))}function IW(e,t){return!!(e&&Ds(e.scope,t))}function DU(e){const t={};for(const n of e){const a=Fx(n.scope),i=t[a]??{scope:n.scope,tabCount:0,runningCount:0,failedCount:0,lastExitCode:null,status:"none"};i.tabCount+=1,n.commandStatus==="running"&&(i.runningCount+=1),(n.commandStatus==="failed"||n.status==="error")&&(i.failedCount+=1),n.lastExitCode!==null&&(i.lastExitCode=n.lastExitCode),i.status=zU(i.status,n.status,n.commandStatus),t[a]=i}return t}function LU(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 zU(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 Vx(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"],i=HU(e),r=t?.linkedCloudSourceKnown===!1&&!!e.headCommit;return i?a.push(i):r?a.push("upload required"):e.diverged?(e.ahead>0&&a.push(Po("ahead",e.ahead)),e.behind>0&&a.push(Po("behind",e.behind)),a.push("diverged")):(e.ahead>0&&a.push(Po("ahead",e.ahead)),e.behind>0&&a.push(Po("behind",e.behind))),e.changedFilesCount>0?a.push(`${e.changedFilesCount} changed`):e.dirty&&a.push("dirty"),e.untrackedFilesCount>0&&a.push(`${e.untrackedFilesCount} untracked`),a.length===1&&a.push("synced"),a.join(" / ")}function Wx(e,t,n,a={}){const i=e?.linkedSandboxProject??null;if(!i?.projectId&&!t)return"upload required";if(i?.projectId&&a.cloudLinkTrusted===!1)return"uploaded to a different account";const r=i?.defaultBranch??t?.defaultBranch??"main",s=i?.manifestHash??null,d=e?.sandboxTemplate?.manifestHash??null,p=i?.syncedAt??t?.syncedAt??null,m=!!(s&&d&&s!==d),h=!!(i?.projectId&&n?.headCommit&&!i.lastUploadedCommit),S=qU(n);return S?`${r} / ${S}`:h?`${r} / upload required`:`${r} / ${m||!p?"needs sync":"setup ready"}`}function UU(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=[],i=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"),i>0&&a.push(Kx(i)),t.linkedSourceHeadCommit&&t.headCommit&&t.linkedSourceHeadCommit!==t.headCommit&&t.linkedSourceComparisonError&&i===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 HU(e){return e.linkedSourceHeadCommit?e.divergedFromLinkedSource?"diverged":e.aheadOfLinkedSource>0?Po("local ahead",e.aheadOfLinkedSource):e.behindLinkedSource>0?Po("cloud ahead",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"sync unknown":null:null}function qU(e){return e?.linkedSourceHeadCommit?e.dirty?"local dirty files not in cloud":e.divergedFromLinkedSource?"diverged from local":e.aheadOfLinkedSource>0?Po("cloud behind local",e.aheadOfLinkedSource):e.behindLinkedSource>0?Po("cloud ahead local",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"source check unavailable":"synced":null}function Po(e,t){return`${e} by ${Kx(t)}`}function Kx(e){return`${e} commit${e===1?"":"s"}`}function BU({size:e=14,className:t}){return v.jsxs("svg",{className:["lucide lucide-cloud-upload",t??""].filter(Boolean).join(" "),xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[v.jsx("path",{d:"M12 13v8"}),v.jsx("path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242"}),v.jsx("path",{d:"m8 17 4-4 4 4"})]})}function Gx({kind:e,linkedCloud:t=!1,open:n=!1,className:a,baseSize:i=15}){const r=e==="cloud"?"cloud":n?"folder-open":"folder";return v.jsx("span",{className:["project-kind-icon",e,t?"linked-cloud":"",a??""].filter(Boolean).join(" "),"aria-hidden":"true",children:v.jsxs("svg",{className:`lucide lucide-${r} project-kind-icon-svg`,xmlns:"http://www.w3.org/2000/svg",width:i,height:i,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e==="cloud"?v.jsx(WU,{}):n?v.jsx(VU,{}):v.jsx(FU,{}),t&&e==="local"?v.jsx(KU,{}):null]})})}function FU(){return v.jsx("path",{className:"project-kind-icon-base",d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"})}function VU(){return v.jsx("path",{className:"project-kind-icon-base",d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"})}function WU(){return v.jsx("path",{className:"project-kind-icon-base",d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z"})}function KU(){return v.jsxs("g",{className:"project-kind-icon-cloud-badge",children:[v.jsx("circle",{cx:"18",cy:"17",r:"5"}),v.jsx("path",{d:"M20.4 18.6h-4.2a2.2 2.2 0 1 1 2.08-2.9h.88a1.45 1.45 0 1 1 1.24 2.9Z"})]})}function GU({session:e,onSave:t,onClose:n}){const[a,i]=g.useState(e.title),r=g.useRef(null);g.useEffect(()=>{const p=r.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 d(p){p.key==="Enter"&&!p.shiftKey&&(p.preventDefault(),s())}return v.jsx("div",{className:"git-dialog-backdrop rename-chat-backdrop",role:"presentation",onMouseDown:n,children:v.jsxs("section",{className:"git-dialog rename-chat-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"rename-chat-title",onMouseDown:p=>p.stopPropagation(),children:[v.jsx("h2",{id:"rename-chat-title",children:"Rename chat"}),v.jsx("textarea",{ref:r,className:"rename-chat-input",value:a,rows:1,maxLength:200,onChange:p=>i(p.target.value),onKeyDown:d,"aria-label":"Chat title"}),v.jsxs("div",{className:"git-dialog-footer",children:[v.jsx("button",{type:"button",className:"git-dialog-secondary",onClick:n,children:"Cancel"}),v.jsx("button",{type:"button",className:"git-dialog-primary",autoFocus:!0,onClick:s,disabled:!a.trim(),children:"Save"})]})]})})}const ZU=24;function JU({title:e}){const t=g.useRef(e),[n,a]=g.useState(e);return g.useEffect(()=>{const i=t.current;if(t.current=e,!e){a("");return}if(i||window.matchMedia("(prefers-reduced-motion: reduce)").matches){a(e);return}const r=Array.from(e);let s=0;a("");const d=window.setInterval(()=>{s+=1,a(r.slice(0,s).join("")),s>=r.length&&window.clearInterval(d)},ZU);return()=>window.clearInterval(d)},[e]),v.jsx("span",{className:"sidebar-task-title-text","aria-label":e||"New task",children:n||"New task"})}const YU=2650,XU=304,QU=260,eH=new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric"}),tH=new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit"}),nH=new Intl.DateTimeFormat("en-US",{dateStyle:"medium",timeStyle:"short"});function aH(){return{animationDelay:`${-(Date.now()%YU)}ms`}}function oH(e){const t=e.currentTarget,n=t.firstElementChild;if(!(n instanceof HTMLElement))return;const a=Math.max(0,n.scrollWidth-t.clientWidth),i=a>2;t.dataset.overflowing=String(i),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 Dg({label:e,actions:t,actionsVisible:n=!1,className:a,titleAccessory:i,children:r,collapsed:s=!1,titleActive:d=!1,onTitleClick:p,onToggleCollapsed:m}){return v.jsxs("section",{className:["sidebar-section",a,n?"actions-visible":""].filter(Boolean).join(" "),children:[v.jsxs("div",{className:"section-header",children:[v.jsxs("div",{className:"section-title-row",children:[p?v.jsxs("div",{className:"section-title-combo",children:[v.jsx("button",{type:"button",className:`section-title-link${d?" active":""}`,onClick:p,children:v.jsx("span",{children:e})}),m&&v.jsx("button",{type:"button",className:"section-chevron-button","aria-label":`${s?"Expand":"Collapse"} ${e}`,"aria-expanded":!s,onClick:m,children:s?v.jsx(ii,{size:13}):v.jsx(Mo,{size:13})})]}):m?v.jsxs("button",{type:"button",className:"section-title-button","aria-label":`${s?"Expand":"Collapse"} ${e}`,"aria-expanded":!s,onClick:m,children:[v.jsx("span",{children:e}),s?v.jsx(ii,{size:13}):v.jsx(Mo,{size:13})]}):v.jsx("span",{children:e}),i]}),t&&v.jsx("div",{className:"section-actions",children:t})]}),!s&&v.jsx("div",{className:"sidebar-section-body",children:r})]})}function Lg({children:e,expanded:t=!1,onClick:n}){return v.jsx("button",{type:"button",className:"sidebar-show-more",onClick:n,children:e??(t?"Show less":"Show more")})}function Vu({session:e,selected:t,icon:n,archived:a=!1,hideIcon:i=!1,nested:r=!1,dragging:s,placeholder:d,running:p,goalRuntime:m,subagentRuntime:h,terminalIndicator:S,projectLabel:y,metadataPresentation:w,ariaDescribedBy:R,childSessionCount:A=0,childSessionsExpanded:N=!1,onSelect:O,onToggleChildSessions:D,onTogglePin:x,onToggleSaveForLater:I,onDockRight:P,onArchive:E,onDragStart:T,onDragEnd:z,onDragOver:U,onDrop:$,onRename:V}){const[re,Q]=g.useState(!1),Ie=m?.status==="queued",Se=m?.tone==="active"&&!Ie,G=(h?.activeCount??0)>0,Ee=A>0&&!!D,xe=i&&!Ee,le=G||Se||!Ie&&(p??e.status==="active"),ke=G&&h?h.label:Se&&m?rH(m):"Running",ae=w??(y?"hover-detail":"inline"),he=ae==="hover-detail",ve=ae==="inline",Ze=["sidebar-task-row",$s(e)?"is-draft":"",P?"actions-4":I?"actions-3":"",le?"has-running-dot":"",he?"has-project-detail":""].filter(Boolean).join(" "),Re=g.useMemo(aH,[]),se=v.jsxs("div",{className:`sidebar-row-actions${he?" sidebar-task-inline-actions":""}`,children:[P?v.jsx(To,{label:"Open in right panel",onClick:P,children:v.jsx(zm,{size:13})}):null,v.jsx(To,{label:e.pinned?"Unpin chat":"Pin chat",onClick:x,children:e.pinned?v.jsx(bf,{size:13}):v.jsx(gf,{size:13})}),I?v.jsx(To,{label:e.savedForLater?"Return to active":"Save for later",onClick:I,children:e.savedForLater?v.jsx(xx,{size:13}):v.jsx(Sx,{size:13})}):null,v.jsx(To,{label:a?"Reopen":"Mark done",onClick:E,children:a?v.jsx($L,{size:13}):v.jsx(io,{size:13})})]}),Ce=v.jsxs(Cf,{selected:t,dataSessionId:e.id,dragging:s,iconless:xe,nested:r,placeholder:d,className:Ze||void 0,ariaExpanded:Ee?N:void 0,ariaDescribedBy:R,onSelect:O,onDragStart:T,onDragEnd:z,onDragOver:U,onDrop:$,onDoubleClick:V?()=>Q(!0):void 0,children:[xe?null:Ee?v.jsx("button",{type:"button",className:"sidebar-child-toggle","data-tooltip":N?"Hide subagent conversations":"Show subagent conversations","aria-label":`${N?"Hide":"Show"} ${A} subagent ${A===1?"conversation":"conversations"}`,"aria-expanded":N,onClick:Qe=>{Qe.stopPropagation(),D?.()},children:N?v.jsx(Mo,{size:13}):v.jsx(ii,{size:13})}):n??v.jsx(Bc,{size:15}),v.jsxs("span",{className:`row-label-shell${he?" has-detail":""}`,children:[v.jsxs("span",{className:"sidebar-session-title-line",children:[v.jsx("span",{className:"row-label sidebar-task-title","data-overflowing":"false",onPointerEnter:oH,children:v.jsx(JU,{title:e.title})}),ve?v.jsx(Km,{value:e.updatedAt}):null]}),he?v.jsxs("span",{className:"sidebar-session-detail-line",children:[v.jsx("span",{className:"sidebar-session-project-label",children:y}),se,v.jsx(Km,{value:e.updatedAt})]}):null]}),v.jsxs("div",{className:"row-meta",children:[v.jsxs("span",{className:"row-meta-status",children:[S?v.jsx(Zx,{indicator:S}):null,le?v.jsx("span",{className:`sidebar-running-dot${G?" subagent":Se?" goal":""}`,style:Re,"aria-label":ke}):null]}),he?null:se]})]}),Le=re&&V?v.jsx(GU,{session:e,onSave:Qe=>V(e,Qe),onClose:()=>Q(!1)}):null;return v.jsxs(v.Fragment,{children:[Ce,Le]})}function iH({file:e,selected:t=!1,placeholder:n,onSelect:a,onTogglePin:i,onToggleSaveForLater:r,onDragStart:s,onDragEnd:d,onDragOver:p,onDrop:m}){const h=e.path.split("/").at(-1)??e.path,S=`${e.workspaceName} · ${e.path}`;return v.jsxs(Cf,{selected:t,placeholder:n,className:`sidebar-file-row actions-2${e.available?"":" unavailable"}`,onSelect:a,onDragStart:s,onDragEnd:d,onDragOver:p,onDrop:m,children:[e.available?v.jsx(ff,{size:15}):v.jsx(YL,{size:15}),v.jsx("span",{className:"row-label-shell",title:S,children:v.jsx("span",{className:"row-label",children:h})}),v.jsx("div",{className:"row-meta",children:v.jsxs("div",{className:"sidebar-row-actions",children:[v.jsx(To,{label:e.status==="pinned"?"Unpin file":"Pin file",onClick:i,children:e.status==="pinned"?v.jsx(bf,{size:13}):v.jsx(gf,{size:13})}),v.jsx(To,{label:e.status==="saved_for_later"?"Remove from Save for later":"Save file for later",onClick:r,children:e.status==="saved_for_later"?v.jsx(xx,{size:13}):v.jsx(Sx,{size:13})})]})})]})}function rH(e){return e.actionLabel}function sH({kind:e="local",project:t,pinned:n=!1,selected:a,expanded:i=!1,disclosure:r=!0,workspaceState:s,cloudLinkTrusted:d=!0,cloudLinkWarning:p=null,placeholder:m,terminalIndicator:h,onSelect:S,onNewChat:y,onMoveToCloud:w,onWorkspaceTargetSelect:R,onTogglePin:A,onRemove:N,onDragStart:O,onDragEnd:D,onDragOver:x,onDrop:I}){const[P,E]=g.useState(!1),T=g.useRef(null),[z,U]=g.useState({}),$=!!w||!!N,V=e==="local"&&d!==!1&&!!t.linkedSandboxProject?.projectId,re=g.useCallback(()=>{if(typeof window>"u")return;const Se=T.current?.getBoundingClientRect();if(!Se)return;const G=Math.max(12,window.innerWidth-XU-12),Ee=Math.max(12,window.innerHeight-QU),xe=Math.max(12,Math.min(Se.right+10,G)),le=Math.max(12,Math.min(Se.top-4,Ee)),ke={"--sidebar-project-locations-left":`${Math.round(xe)}px`,"--sidebar-project-locations-top":`${Math.round(le)}px`};U(ae=>ae["--sidebar-project-locations-left"]===ke["--sidebar-project-locations-left"]&&ae["--sidebar-project-locations-top"]===ke["--sidebar-project-locations-top"]?ae:ke)},[]),Q=g.useCallback(()=>{re(),S()},[S,re]);function Ie(){E(!1)}return v.jsxs("div",{ref:T,className:["sidebar-project-row-shell",P?"project-menu-open":""].filter(Boolean).join(" "),onFocusCapture:re,onPointerEnter:re,children:[v.jsxs(Cf,{selected:a,placeholder:m,className:["sidebar-project-row",P?"project-menu-open":""].filter(Boolean).join(" "),ariaExpanded:r?i:void 0,onSelect:Q,onDragStart:O,onDragEnd:D,onDragOver:x,onDrop:I,children:[v.jsx(Gx,{kind:e,linkedCloud:V,open:e==="local"&&i,className:"sidebar-row-icon",baseSize:15}),v.jsx("span",{className:"row-label-shell",children:v.jsxs("span",{className:"sidebar-project-title-line",children:[v.jsx("span",{className:"row-label",children:t.name}),v.jsx(Km,{value:t.updatedAt}),r?v.jsx("span",{className:"sidebar-project-caret","aria-hidden":"true",children:i?v.jsx(Mo,{size:13}):v.jsx(ii,{size:13})}):null]})}),v.jsxs("div",{className:"row-meta",children:[v.jsx("span",{className:"row-meta-status",children:h?v.jsx(Zx,{indicator:h}):null}),v.jsxs("div",{className:"sidebar-row-actions",children:[v.jsx(To,{label:n?"Unpin project":"Pin project",onClick:A,children:n?v.jsx(bf,{size:13}):v.jsx(gf,{size:13})}),$&&v.jsx(xH,{open:P,onToggleOpen:()=>E(Se=>!Se)}),v.jsx(To,{label:"New task",onClick:y,children:v.jsx(yf,{size:13})})]})]})]}),v.jsx(cH,{kind:e,project:t,workspaceState:s,cloudLinkTrusted:d,cloudLinkWarning:p,onWorkspaceTargetSelect:R,style:z}),P&&v.jsx(kH,{onClose:Ie,onMoveToCloud:w?()=>{Ie(),w()}:void 0,onRemove:()=>{Ie(),N()}})]})}function Km({value:e}){const t=lH(e);if(!t||!e)return null;const n=new Date(e);return v.jsx("time",{className:"sidebar-row-updated-at",dateTime:e,title:`Last updated ${nH.format(n)}`,children:t})}function lH(e,t=new Date){if(!e)return null;const n=new Date(e);if(Number.isNaN(n.getTime()))return null;const a=tH.format(n);return n.getFullYear()===t.getFullYear()&&n.getMonth()===t.getMonth()&&n.getDate()===t.getDate()?a:`${eH.format(n)} ${a}`}function Zx({indicator:e}){return v.jsx("span",{className:`sidebar-terminal-indicator ${e.status}`,"data-tooltip":e.label,"aria-label":e.label,title:e.label,children:v.jsx(Ix,{size:13})})}function cH({kind:e,project:t,workspaceState:n,cloudLinkTrusted:a,cloudLinkWarning:i,onWorkspaceTargetSelect:r,style:s}){const d=mH(e,t,n,a,i);return v.jsxs("aside",{className:"sidebar-project-locations-popover","aria-label":`${t.name} status`,style:s,children:[v.jsx("div",{className:"sidebar-project-locations-title",children:t.name}),v.jsx("div",{className:"sidebar-project-location-list",children:d.map(p=>{const m=["sidebar-project-location-row",p.tone??"",p.actionTarget?"clickable":""].filter(Boolean).join(" "),h=v.jsxs(v.Fragment,{children:[v.jsx("span",{className:["sidebar-project-location-icon",p.key].filter(Boolean).join(" "),"aria-hidden":"true",children:p.icon}),v.jsx("span",{className:"sidebar-project-location-copy",children:v.jsx(dH,{value:p.value})})]});return p.actionTarget?v.jsx("button",{type:"button",className:m,"data-workspace-target":p.actionTarget,disabled:p.disabled||!r,title:p.disabledReason??void 0,onClick:S=>{S.stopPropagation(),!p.disabled&&r?.(p.actionTarget)},children:h},p.key):v.jsx("div",{className:m,children:h},p.key)})})]})}function dH({value:e}){const t=uH(e);return v.jsxs("span",{className:"sidebar-project-location-value","aria-label":e,children:[t.branch?v.jsxs(v.Fragment,{children:[v.jsx("span",{className:"sidebar-project-location-branch",children:t.branch}),v.jsx("span",{className:"sidebar-project-location-separator","aria-hidden":"true",children:"/"})]}):null,v.jsx("span",{className:"sidebar-project-location-status",children:t.status})]})}function uH(e){const n=e.indexOf(" / ");return n===-1?{branch:null,status:e}:{branch:e.slice(0,n),status:e.slice(n+3)}}function mH(e,t,n,a=!0,i=null){return e==="cloud"?fH(t):pH(t,n,a,i)}function pH(e,t,n=!0,a=null){const i=hH(e,t,n),r=gH(t),s=vH(e,n),d=n===!1&&a;return[{key:"local",value:i,tone:r?"attention":"local",icon:e.source==="git"?v.jsx(Lm,{size:13}):v.jsx(lz,{size:13}),actionTarget:"local"},{key:"cloud",value:d||(s?yH(e,t,n):"not in cloud"),tone:d?"attention":"cloud",icon:v.jsx(qc,{size:13}),actionTarget:s?"cloud":"upload_cloud"}]}function fH(e){return[{key:"cloud",value:SH(e),tone:e.syncedAt?"cloud":"attention",icon:v.jsx(qc,{size:13}),actionTarget:"cloud"}]}function hH(e,t,n){const a=bH(e,t);return t?t.error?`${a} / status unavailable`:t.initialized?Vx(t,{branch:e.linkedSandboxProject?.defaultBranch??null,linkedCloudSourceKnown:e.linkedSandboxProject?.projectId&&n?!!e.linkedSandboxProject.lastUploadedCommit||!t.headCommit:!0}):`${a} / not checked out`:`${a} / available`}function gH(e){return!!(e?.dirty||(e?.changedFilesCount??0)>0||(e?.untrackedFilesCount??0)>0)}function bH(e,t){return t?.currentBranch??t?.defaultBranch??e.linkedSandboxProject?.defaultBranch??"local"}function vH(e,t=!0){return!!(t&&e.linkedSandboxProject?.projectId||e.linkedOpenPondApp?.appId)}function yH(e,t,n){return Wx(e,null,t,{cloudLinkTrusted:n})}function SH(e){const t=e.defaultBranch??"main",n=e.syncedAt?"setup ready":"needs setup";return`${t} / ${n}`}function xH({open:e,onToggleOpen:t}){return v.jsx("button",{type:"button",className:`sidebar-row-action ${e?"active":""}`,"data-tooltip":"More project actions","aria-label":"More project actions","aria-haspopup":"menu","aria-expanded":e,onClick:n=>{n.stopPropagation(),t()},children:v.jsx(hf,{size:13})})}function kH({onClose:e,onMoveToCloud:t,onRemove:n}){return v.jsxs(v.Fragment,{children:[v.jsx("button",{type:"button",className:"sidebar-project-menu-backdrop","aria-label":"Close project actions",onClick:a=>{a.stopPropagation(),e()}}),v.jsxs("div",{className:"section-menu-popover sidebar-project-row-popover",role:"menu",children:[t&&v.jsxs("button",{type:"button",role:"menuitem",onClick:a=>{a.stopPropagation(),t()},children:[v.jsx(BU,{size:13}),v.jsx("span",{children:"Move to Cloud"})]}),v.jsxs("button",{type:"button",role:"menuitem",onClick:a=>{a.stopPropagation(),n()},children:[v.jsx(Ir,{size:13}),v.jsx("span",{children:"Remove from Projects"})]})]})]})}function Cf({children:e,className:t,dataSessionId:n,dragging:a,iconless:i=!1,nested:r=!1,placeholder:s=!1,selected:d,ariaExpanded:p,ariaDescribedBy:m,onSelect:h,onDragStart:S,onDragEnd:y,onDragOver:w,onDrop:R,onDoubleClick:A}){const N=!!S;return v.jsx("div",{className:["sidebar-row",t??"",d?"selected":"",a?"dragging":"",i?"iconless":"",r?"nested":"",s?"placeholder":""].filter(Boolean).join(" "),draggable:N,"data-session-id":n,role:"button",tabIndex:0,"aria-expanded":p,"aria-describedby":m,onClick:h,onDoubleClick:A,onKeyDown:O=>{(O.key==="Enter"||O.key===" ")&&(O.preventDefault(),h())},onDragStart:S,onDragEnd:y,onDragEnter:O=>{w&&(O.preventDefault(),O.dataTransfer.dropEffect="move",w(O))},onDragOver:O=>{w&&(O.preventDefault(),O.dataTransfer.dropEffect="move",w(O))},onDrop:O=>{R&&(O.preventDefault(),R(O))},children:e})}function To({children:e,label:t,onClick:n}){return v.jsx("button",{type:"button",className:"sidebar-row-action","data-tooltip":t,"aria-label":t,onClick:a=>{a.stopPropagation(),n()},children:e})}function _H({filter:e,groupByProject:t,noun:n,onFilterChange:a,onGroupByProjectChange:i,onOnlyRunningTasksChange:r,onShowCodexChatsChange:s,onTasksetChange:d,onSortChange:p,onlyRunningTasks:m,openMenu:h,setOpenMenu:S,showCodexChats:y,sort:w,selectedTasksetId:R,tasksets:A}){const N=g.useRef(null),[O,D]=g.useState(!1),I=A.find(T=>T.id===R)?.name??Eg.find(T=>T.value===e)?.label??"Active",P=h==="tasks-filter",E=h==="chats";return g.useEffect(()=>{if(!P&&!E)return;function T(z){N.current?.contains(z.target)||S(null)}return document.addEventListener("pointerdown",T),()=>document.removeEventListener("pointerdown",T)},[P,S,E]),v.jsxs("div",{className:"sidebar-task-list-controls",ref:N,children:[v.jsxs("div",{className:"section-menu",children:[v.jsx("button",{type:"button",className:`section-icon ${E?"active":""}`,"aria-label":`${n==="tasks"?"Task":"Chat"} list options`,"aria-haspopup":"menu","aria-expanded":E,onClick:()=>S(T=>T==="chats"?null:"chats"),children:v.jsx(hf,{size:14})}),E?v.jsxs("div",{className:"section-menu-popover",role:"menu","aria-label":`${n==="tasks"?"Task":"Chat"} list options`,children:[v.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":y,onClick:()=>s(!y),children:[v.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:y?v.jsx(io,{size:13}):null}),v.jsx("span",{children:"Show Codex chats"})]}),v.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":m,onClick:()=>r(!m),children:[v.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:m?v.jsx(io,{size:13}):null}),v.jsx("span",{children:"Only running tasks"})]}),n==="tasks"?v.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":t,onClick:()=>i(!t),children:[v.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:t?v.jsx(io,{size:13}):null}),v.jsx("span",{children:"Group by project"})]}):null,AU.map(T=>v.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":w===T.value,onClick:()=>{p(T.value),S(null)},children:[v.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:w===T.value?v.jsx(io,{size:13}):null}),v.jsx("span",{children:T.label})]},T.value))]}):null]}),v.jsxs("div",{className:"section-menu",children:[v.jsx("button",{type:"button",className:`section-icon ${P?"active":""}`,"aria-label":`Filter ${n}: ${I}`,"aria-haspopup":"menu","aria-expanded":P,onClick:()=>S(T=>T==="tasks-filter"?null:"tasks-filter"),children:v.jsx(vz,{size:14})}),P?v.jsx("div",{className:"section-menu-popover",role:"menu","aria-label":`Filter ${n}`,children:Eg.map(T=>v.jsxs(g.Fragment,{children:[T.value==="tasksets"?v.jsxs("button",{type:"button",role:"menuitem","aria-expanded":O,onClick:()=>D(z=>!z),children:[v.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:O?v.jsx(Mo,{size:13}):v.jsx(ii,{size:13})}),v.jsx("span",{children:T.label})]}):v.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":e===T.value,onClick:()=>{a(T.value),S(null)},children:[v.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e===T.value?v.jsx(io,{size:13}):null}),v.jsx("span",{children:T.label})]}),T.value==="tasksets"&&O?v.jsxs(v.Fragment,{children:[v.jsxs("button",{className:"section-menu-taskset-option",type:"button",role:"menuitemradio","aria-checked":e==="tasksets"&&!R,onClick:()=>{d(null),S(null)},children:[v.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&!R?v.jsx(io,{size:13}):null}),v.jsx("span",{children:"All Tasksets"})]}),A.map(z=>v.jsxs("button",{className:"section-menu-taskset-option",type:"button",role:"menuitemradio","aria-checked":e==="tasksets"&&R===z.id,onClick:()=>{d(z.id),S(null)},children:[v.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&R===z.id?v.jsx(io,{size:13}):null}),v.jsx("span",{children:z.name}),v.jsx("span",{className:"section-menu-option-count","aria-hidden":"true",children:z.chatCount})]},z.id))]}):null]},T.value))}):null]})]})}const wH=288,IH=112;function CH(e,t){const n=Math.max(12,t.width-wH-12),a=Math.max(12,t.height-IH-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 RH({detail:e,onClose:t}){if(g.useEffect(()=>{if(!e||typeof window>"u")return;const i=d=>{d.key==="Escape"&&t()};let r=!1;const s=window.requestAnimationFrame(()=>{window.addEventListener("scroll",t,!0),r=!0});return window.addEventListener("keydown",i),()=>{window.cancelAnimationFrame(s),window.removeEventListener("keydown",i),r&&window.removeEventListener("scroll",t,!0)}},[e,t]),!e)return null;const n=new Date(e.updatedAt),a=new Intl.DateTimeFormat(void 0,{dateStyle:"full",timeStyle:"short"}).format(n);return v.jsxs("aside",{id:e.descriptionId,className:"sidebar-task-detail-popover",style:e.style,"aria-label":`${e.title} details`,children:[v.jsx("div",{className:"sidebar-task-detail-title",children:e.title}),v.jsx("div",{className:"sidebar-task-detail-project",children:e.projectLabel}),v.jsx("time",{dateTime:e.updatedAt,children:a})]})}function AH({children:e,expanded:t,groupKey:n,kind:a,label:i,onToggle:r,onNewTask:s,onOpenProject:d,onRemoveProject:p,project:m}){const h=`sidebar-task-group-${n.replace(/[^a-zA-Z0-9_-]/g,"-")}`,S=a==="draft"?ff:Bc,[y,w]=g.useState(!1),R=!!(s||d||p);return v.jsxs("section",{className:"sidebar-task-project-group",children:[v.jsxs("div",{className:`sidebar-task-project-group-header-shell${y?" menu-open":""}`,children:[v.jsxs("button",{type:"button",className:"sidebar-task-project-group-header","aria-controls":h,"aria-expanded":t,onClick:()=>{w(!1),r()},children:[m?v.jsx(Gx,{kind:m.kind,linkedCloud:!!(m.kind==="local"&&m.project.linkedSandboxProject?.projectId),open:m.kind==="local"&&t,className:"sidebar-task-project-group-icon",baseSize:14}):v.jsx(S,{className:"sidebar-task-project-group-icon",size:14,"aria-hidden":"true"}),v.jsx("span",{className:"sidebar-task-project-group-name",children:i}),v.jsx("span",{className:"sidebar-task-project-group-caret","aria-hidden":"true",children:t?v.jsx(Mo,{size:13}):v.jsx(ii,{size:13})})]}),m&&R?v.jsxs("div",{className:"sidebar-task-project-group-actions",children:[d||p?v.jsx("button",{type:"button",className:`sidebar-row-action${y?" active":""}`,"data-tooltip":"More project actions","aria-label":"More project actions","aria-expanded":y,"aria-haspopup":"menu",onClick:()=>w(A=>!A),children:v.jsx(hf,{size:13})}):null,s?v.jsx("button",{type:"button",className:"sidebar-row-action","data-tooltip":"New task","aria-label":"New task",onClick:s,children:v.jsx(yf,{size:13})}):null]}):null,y?v.jsxs(v.Fragment,{children:[v.jsx("button",{type:"button",className:"sidebar-task-project-group-menu-backdrop","aria-label":"Close project actions",onClick:()=>w(!1)}),v.jsxs("div",{className:"section-menu-popover sidebar-task-project-group-menu",role:"menu",children:[d?v.jsx("button",{type:"button",role:"menuitem",onClick:()=>{w(!1),d()},children:v.jsx("span",{children:"Open project"})}):null,p?v.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{w(!1),p()},children:[v.jsx(Ir,{size:13}),v.jsx("span",{children:"Remove from Projects"})]}):null]})]}):null]}),t?v.jsx("div",{id:h,className:"sidebar-task-project-group-content",children:e}):null]})}const PH={},TH=new Map,EH=new Map;function MH(e,t){return Math.min(Math.max(e,xn)+Vm,t)}function jH(e,t){const n=Math.max(xn,Math.min(e,t));if(n<=xn)return xn;const a=Math.ceil((n-xn)/Vm);return Math.max(xn,xn+(a-1)*Vm)}function OH(e,t){const n=new Map;for(const a of e){const i=t(a),r=n.get(i.key);r?r.sessions.push(a):n.set(i.key,{...i,sessions:[a]})}return[...n.values()]}function NH({activeSessions:e,archiveSession:t,archivedSessions:n,chatRowsVisibleCount:a,childSessionRowsByParentId:i={},cloudProjectRows:r,beginProjectChat:s,commitTaskDrop:d,commitTaskPreviewDrop:p,dockSessionRight:m,experience:h="work",goalRuntimeBySessionId:S=TH,localProjectRows:y,openSidebarFile:w,pinnedCollapsed:R,pinnedRows:A,previewTaskDrop:N,previewPinnedDrop:O,projectRows:D,renameSession:x,restoreSession:I,runningSessionIds:P,savedForLaterSessions:E,sectionMenuOpen:T,selectedProjectId:z,selectedSessionId:U,setChatRowsVisibleCount:$,setSectionMenuOpen:V,setSelectedAppId:re,setSelectedProjectId:Q,setSelectedSessionId:Ie,setView:Se,sidebarProjectIdBySessionId:G,startTaskDrag:Ee,startPinnedDrag:xe,subagentRuntimeBySessionId:le=EH,taskDragSessionId:ke,taskPreviewSessionIds:ae,terminalSummaries:he=PH,toggleSessionPinned:ve,toggleSessionSavedForLater:Ze,view:Re,clearTaskDrag:se,removeProject:Ce,toggleProjectPinned:Le,onTogglePinnedCollapsed:Qe,setSidebarFileStatus:it,commitPinnedDrop:ut,commitPinnedPreviewDrop:Fe,clearSidebarDrag:Ue,dragItem:ze}){const[M,H]=g.useState("active"),[X,pe]=g.useState("manual"),[Z,me]=g.useState(h!=="chat"),[_e,He]=g.useState(EU),{onlyRunningTasks:qe,showCodexChats:Xe}=_e,[at,Pe]=g.useState(null),[Ve,u]=g.useState(()=>new Set),[j,q]=g.useState(()=>new Map),[oe,ne]=g.useState(null),F=h==="chat"?"chats":"tasks",_=h==="chat"?"Chats":"Tasks",W=D??[...y,...r],Y=g.useMemo(()=>new Map(W.map(te=>[te.id,te.project.name])),[W]),ee=g.useMemo(()=>new Map(W.map(te=>[te.id,te])),[W]),K=g.useMemo(()=>{const te=new Set(P);for(const De of e){const Ke=S.get(De.id),et=le.get(De.id);(Ke?.tone==="active"&&Ke.status!=="queued"||(et?.activeCount??0)>0||St(De.id)?.status==="running")&&te.add(De.id)}return te},[e,S,P,le,he]),ce=g.useMemo(()=>e.filter(te=>Ao(te)===null&&Bi(te,{inProgressSessionIds:K,onlyRunningTasks:qe,showCodexChats:Xe})),[e,K,qe,Xe]),ue=g.useMemo(()=>E.filter(te=>Ao(te)===null&&Bi(te,{inProgressSessionIds:K,onlyRunningTasks:qe,showCodexChats:Xe})),[K,qe,E,Xe]),Ne=Math.max(0,ce.length-ue.length),je=PU({activeCount:Ne,filter:M,savedForLaterCount:ue.length}),$e=g.useMemo(()=>Mg({activeSessions:e,doneSessions:n,filter:"all",inProgressSessionIds:K,sort:"manual"}),[e,n,K]),Ge=g.useMemo(()=>Mg({activeSessions:e,doneSessions:n,filter:M,inProgressSessionIds:K,onlyRunningTasks:qe,selectedTasksetId:at,previewSessionIds:ae,showCodexChats:Xe,sort:X}),[e,n,K,qe,at,Xe,M,ae,X]),We=g.useMemo(()=>{const te=new Map;for(const De of[...e,...n]){if(!Bi(De,{inProgressSessionIds:K,onlyRunningTasks:qe,showCodexChats:Xe}))continue;const Ke=Ao(De);if(!Ke)continue;const et=te.get(Ke.id);et?et.chatCount+=1:te.set(Ke.id,{...Ke,chatCount:1})}return[...te.values()].sort((De,Ke)=>De.name.localeCompare(Ke.name))},[e,n,K,qe,Xe]),mt=g.useMemo(()=>A.filter(te=>te.type!=="session"||Bi(te.session,{inProgressSessionIds:K,onlyRunningTasks:qe,showCodexChats:Xe})),[K,qe,A,Xe]),qt=g.useMemo(()=>Ge.filter(te=>!cc(te)).slice(0,Math.max(xn,a)),[a,Ge]),jt=g.useMemo(()=>OH(qt,te=>{if($s(te))return{key:"draft",label:"Drafts",projectId:null,project:null,kind:"draft"};const De=G[te.id],Ke=on(te)??"No project";return{key:De?`project:${De}`:`projectless:${Ke}`,label:Ke,projectId:De??null,project:De?ee.get(De)??null:null,kind:De?"project":"projectless"}}),[Y,ee,G,qt]),_n=qt.length<Ge.length,bn=qt.length>xn,Xt=g.useMemo(()=>new Set(jt.filter(te=>te.sessions.some(De=>De.id===U||K.has(De.id))).map(te=>te.key)),[jt,K,U]),yt=$e.filter(te=>!cc(te)).map(te=>te.id),tn=qt.map(te=>te.id),Et=JSON.stringify(Object.entries(i).filter(([te,De])=>De.length>0&&(le.get(te)?.activeCount??0)>0).flatMap(([te,De])=>De.map(Ke=>[te,Ke.id])).sort(([te,De],[Ke,et])=>te.localeCompare(Ke)||De.localeCompare(et)));g.useEffect(()=>{const te=JSON.parse(Et);if(te.length===0)return;const De=new Set(te.map(([Ke])=>Ke));u(Ke=>[...De].every(et=>Ke.has(et))?Ke:new Set([...Ke,...De]))},[Et]);function St(te){return LU(he[Fx({kind:"session",id:te})])}function on(te){if($s(te))return"Draft";const De=G[te.id];return De?Y.get(De)??te.workspaceName??"Project":kU(te)}function Ot(te){an({kind:"chat",sessionId:te.id}),Ie(te.id);const De=G[te.id]??null;re(De?null:te.appId),Q(De),Se("chat")}function rn(te){return(i[te.id]??[]).filter(De=>Bi(De,{inProgressSessionIds:K,onlyRunningTasks:qe,showCodexChats:Xe}))}function Tn(te,De){return Ve.has(te.id)||De.some(Ke=>Ke.id===U)}function pn(te){u(De=>{const Ke=new Set(De);return Ke.has(te)?Ke.delete(te):Ke.add(te),Ke})}function Ca(te){const De=rn(te);return De.length===0||!Tn(te,De)?null:v.jsx("div",{className:"sidebar-child-session-group",children:De.map(Ke=>v.jsx(Vu,{session:Ke,selected:Re==="chat"&&U===Ke.id,hideIcon:!0,nested:!0,running:K.has(Ke.id),goalRuntime:S.get(Ke.id)??null,subagentRuntime:le.get(Ke.id)??null,terminalIndicator:St(Ke.id),projectLabel:on(te),onSelect:()=>Ot(Ke),onTogglePin:()=>ve(Ke),onToggleSaveForLater:()=>Ze(Ke),onDockRight:()=>m(Ke),onArchive:()=>Ke.archived?I(Ke):t(Ke),onRename:x},Ke.id))})}function Ra(te,De,Ke){typeof window>"u"||ne({descriptionId:`sidebar-task-detail-${te.id}`,projectLabel:De,sessionId:te.id,title:te.title,updatedAt:te.updatedAt,style:CH(Ke.getBoundingClientRect(),{width:window.innerWidth,height:window.innerHeight})})}function $t(te,De={}){const Ke=te.archived,et=ke===te.id,Rt=rn(te),bt="sidebar-session-group",lt=X==="manual"?{onDragStart:wt=>Ee(wt,{allSessionIds:yt,visibleSessionIds:tn,sessionId:te.id}),onDragEnd:se,onDragOver:wt=>{et||N(wt,te.id)},onDrop:wt=>{et?p():d(wt,te.id)}}:{};return v.jsxs("div",{className:bt,onPointerEnter:De.metadataPresentation==="flyout"&&De.projectLabel?wt=>Ra(te,De.projectLabel,wt.currentTarget):void 0,onPointerLeave:De.metadataPresentation==="flyout"?()=>ne(null):void 0,onFocusCapture:De.metadataPresentation==="flyout"&&De.projectLabel?wt=>Ra(te,De.projectLabel,wt.currentTarget):void 0,onBlurCapture:De.metadataPresentation==="flyout"?wt=>{wt.currentTarget.contains(wt.relatedTarget)||ne(null)}:void 0,children:[v.jsx(Vu,{session:te,selected:!Ke&&Re==="chat"&&U===te.id,archived:Ke,hideIcon:!0,placeholder:et,running:K.has(te.id),goalRuntime:S.get(te.id)??null,subagentRuntime:le.get(te.id)??null,terminalIndicator:St(te.id),projectLabel:De.projectLabel===void 0?on(te):De.projectLabel,metadataPresentation:De.metadataPresentation,ariaDescribedBy:De.metadataPresentation==="flyout"&&oe?.sessionId===te.id?oe.descriptionId:void 0,childSessionCount:Rt.length,childSessionsExpanded:Tn(te,Rt),onToggleChildSessions:()=>pn(te.id),onSelect:()=>{ne(null),Ke&&I(te),Ot(te)},onTogglePin:()=>ve(te),onToggleSaveForLater:()=>Ze(te),onDockRight:()=>m(te),onArchive:()=>Ke?I(te):t(te),onRename:x,...lt}),et?null:Ca(te)]},te.id)}function zn(te){te!=="tasksets"&&Pe(null),H(te),$(xn)}function st(te){Pe(te),H("tasksets"),$(xn)}function vn(te){pe(te),$(xn)}function Aa(){$(te=>MH(te,Ge.length))}function Pa(){$(te=>jH(te,Ge.length))}function aa(te){const De={id:te.id,type:te.type};return{onDragStart:Ke=>xe(Ke,De),onDragEnd:Ue,onDragOver:Ke=>O(Ke,De),onDrop:Ke=>{ze?.id===te.id&&ze.type===te.type?Fe():ut(Ke,De)}}}function Ta(te){const De=aa(te),Ke=ze?.id===te.id&&ze.type===te.type;if(te.type==="project"){const Rt=te.item;return v.jsx(sH,{kind:Rt.kind,project:Rt.project,pinned:!0,selected:Re==="chat"&&z===Rt.id,expanded:!1,disclosure:!1,placeholder:Ke,onSelect:()=>{re(null),Q(Rt.id),Ie(null),Se("chat")},onNewChat:()=>s(Rt.id),onTogglePin:()=>Le(Rt),onRemove:()=>Ce(Rt),...De},te.key)}if(te.type==="file")return v.jsx(iH,{file:te.file,placeholder:Ke,onSelect:()=>w(te.file),onTogglePin:()=>it(te.file,"none"),onToggleSaveForLater:()=>it(te.file,"saved_for_later"),...De},te.key);const et=te.session;return v.jsx(Vu,{session:et,selected:Re==="chat"&&U===et.id,hideIcon:!0,placeholder:Ke,running:K.has(et.id),goalRuntime:S.get(et.id)??null,subagentRuntime:le.get(et.id)??null,terminalIndicator:St(et.id),projectLabel:on(et),metadataPresentation:"flyout",onSelect:()=>Ot(et),onTogglePin:()=>ve(et),onToggleSaveForLater:()=>Ze(et),onDockRight:()=>m(et),onArchive:()=>t(et),onRename:x,...De},te.key)}return v.jsxs("div",{className:"sidebar-scroll",children:[v.jsxs(Dg,{label:_,className:`sidebar-task-section${h!=="chat"?" development":""}`,titleAccessory:h!=="chat"?v.jsx("div",{className:"sidebar-task-mode-buttons",children:v.jsxs("button",{type:"button",className:`section-icon sidebar-task-count-bubble${M==="saved_for_later"?" active":""}`,"aria-label":`Show ${je.count} ${je.targetLabel} ${je.count===1?"task":"tasks"}`,onClick:()=>zn(je.targetFilter),children:[v.jsx("span",{children:je.label}),v.jsx("span",{className:"sidebar-task-count-badge","aria-hidden":"true",children:je.count>99?"99+":je.count})]})}):null,actionsVisible:T==="chats"||T==="tasks-filter",actions:v.jsx(_H,{filter:M,groupByProject:Z,noun:F,onFilterChange:zn,onGroupByProjectChange:me,onOnlyRunningTasksChange:te=>{He(De=>{const Ke={...De,onlyRunningTasks:te};return $g(Ke),Ke}),$(xn)},onShowCodexChatsChange:te=>{He(De=>{const Ke={...De,showCodexChats:te};return $g(Ke),Ke}),$(xn)},onTasksetChange:st,onSortChange:vn,onlyRunningTasks:qe,openMenu:T,setOpenMenu:V,showCodexChats:Xe,sort:X,selectedTasksetId:at,tasksets:We}),children:[mt.length>0?v.jsx(Dg,{label:"Pinned",className:"sidebar-pinned-section",collapsed:R,onToggleCollapsed:Qe,children:mt.map(Ta)}):null,Z&&h!=="chat"?jt.map(te=>{const De=Xt.has(te.key)||j.get(te.key)!==!1;return v.jsx(AH,{expanded:De,groupKey:te.key,kind:te.kind,label:te.label,onToggle:()=>{q(Ke=>{const et=new Map(Ke);return et.set(te.key,!De),et})},onNewTask:te.project?()=>s(te.project.id):void 0,onOpenProject:te.project?()=>{re(null),Q(te.project.id),Ie(null),Se("chat")}:void 0,onRemoveProject:te.project?()=>Ce(te.project):void 0,project:te.project,children:te.sessions.map(Ke=>$t(Ke,{metadataPresentation:"flyout",projectLabel:te.label}))},te.key)}):qt.map(te=>$t(te)),Ge.length===0?v.jsx("div",{className:"empty-row",children:TU(M,F)}):null,Ge.length>xn&&(_n||bn)?v.jsxs("div",{className:"sidebar-pagination-controls","aria-label":`Showing ${qt.length} of ${Ge.length} ${F}`,children:[_n?v.jsx(Lg,{onClick:Aa,children:"Show more"}):null,bn?v.jsx(Lg,{onClick:Pa,children:"Show less"}):null]}):null]}),v.jsx(RH,{detail:oe,onClose:()=>ne(null)})]})}const $H="/";function Wn(e){return`${$H}${e.replace(/^\.?\//,"")}`}const DH=Wn("openpond-icon.png"),LH=Wn("openpond-wordlogo-white.png"),CW=Wn("tutorials/what-is-an-openpond-agent-poster.png"),RW=Wn("tutorials/what-is-an-openpond-agent.vtt"),AW=Wn("tutorials/how-to-make-an-agent-poster.png"),PW=Wn("tutorials/how-to-make-an-agent.vtt");function TW(e){return Wn(`tutorials/how-to-make-an-agent-${e}-poster.png`)}function EW(e){return Wn(`tutorials/how-to-make-an-agent-${e}.vtt`)}const zg={github:Wn("connected-apps/github.svg"),google:Wn("connected-apps/google.svg"),microsoft_teams:Wn("connected-apps/microsoft.svg"),mcp:Wn("connected-apps/openpond-mcp.svg"),slack:Wn("connected-apps/slack.svg"),x:Wn("connected-apps/x.svg")};function MW(e){return zg[e]??zg.mcp}function zH({value:e,onChange:t}){const[n,a]=g.useState(!1),i=g.useRef(null),r=g.useRef(null),s=g.useRef(null),d=qu.find(y=>y.value===e)??qu[0];g.useEffect(()=>{if(!n)return;const y=R=>{R.target instanceof Node&&!i.current?.contains(R.target)&&a(!1)},w=()=>a(!1);return window.addEventListener("pointerdown",y),window.addEventListener("blur",w),()=>{window.removeEventListener("pointerdown",y),window.removeEventListener("blur",w)}},[n]);const p=y=>{window.requestAnimationFrame(()=>{const w=Ug(s.current);if(!w.length)return;(y==="first"?w[0]:y==="last"?w.at(-1):w.find(A=>A.dataset.productArea===e))?.focus()})},m=y=>{a(!0),p(y)},h=y=>{y.key==="ArrowDown"?(y.preventDefault(),m("first")):y.key==="ArrowUp"&&(y.preventDefault(),m("last"))},S=y=>{const w=Ug(s.current),R=w.findIndex(O=>O===document.activeElement);if(y.key==="Escape"){y.preventDefault(),a(!1),r.current?.focus();return}if(y.key==="Home"||y.key==="End"){y.preventDefault(),w[y.key==="Home"?0:w.length-1]?.focus();return}if(y.key!=="ArrowDown"&&y.key!=="ArrowUp")return;y.preventDefault();const A=y.key==="ArrowDown"?1:-1,N=R<0?0:(R+A+w.length)%w.length;w[N]?.focus()};return v.jsxs("div",{className:"sidebar-experience-menu",ref:i,children:[v.jsxs("button",{ref:r,type:"button",className:"sidebar-wordmark-button sidebar-experience-trigger","aria-label":`OpenPond product: ${d.label}`,"aria-haspopup":"menu","aria-expanded":n,onClick:()=>{a(y=>!y)},onKeyDown:h,children:[v.jsx("img",{className:"sidebar-wordmark",src:LH,alt:""}),v.jsx("span",{className:"sidebar-experience-label",children:d.label}),v.jsx(Mo,{size:13,"aria-hidden":"true"})]}),n?v.jsx("div",{ref:s,className:"sidebar-experience-popover",role:"menu","aria-label":"Choose product",onKeyDown:S,children:qu.map(y=>{const w=y.value===e;return v.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":w,className:w?"active":"","data-product-area":y.value,onClick:()=>{a(!1),w||t(y.value)},children:[v.jsxs("span",{children:[v.jsx("strong",{children:y.label}),v.jsx("small",{children:y.description})]}),w?v.jsx(io,{size:14,"aria-hidden":"true"}):null]},y.value)})}):null]})}function Ug(e){return e?Array.from(e.querySelectorAll('[role="menuitemradio"]')):[]}function UH(...e){for(const t of e){const n=t?.trim();if(n)return n}return null}function HH(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"?UH(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 qH({account:e,open:t,organizations:n,selectedTeamId:a,onOpenActivity:i,onOpenChange:r,onOpenSettings:s,onSelectTeam:d,onLogOut:p}){const[m,h]=g.useState(null),[S,y]=g.useState(!1),w=g.useRef(null),R=g.useMemo(()=>HH(e),[e]),A=R.label.trim().slice(0,1).toUpperCase(),N=n.find(O=>O.teamId===a)??n[0]??null;return g.useEffect(()=>{if(!t)return;function O(x){w.current?.contains(x.target)||r(!1)}function D(x){x.key==="Escape"&&r(!1)}return document.addEventListener("pointerdown",O),document.addEventListener("keydown",D),()=>{document.removeEventListener("pointerdown",O),document.removeEventListener("keydown",D)}},[r,t]),v.jsxs("div",{className:"user-auth-footer",ref:w,children:[v.jsxs("button",{type:"button",className:`user-auth-trigger ${t?"active":""}`,"aria-haspopup":"menu","aria-expanded":t,"aria-label":`${R.label} account menu`,onClick:()=>r(!t),children:[v.jsx("span",{className:"user-auth-avatar","aria-hidden":"true",children:R.image?v.jsx("img",{src:R.image,alt:""}):A?v.jsx("span",{children:A}):v.jsx(Um,{size:16})}),v.jsx("span",{className:"user-auth-name",children:R.label})]}),t?v.jsxs("div",{className:"user-auth-menu",role:"menu","aria-label":"Account",children:[v.jsxs("div",{className:"user-auth-menu-header",children:[v.jsx("span",{className:"user-auth-menu-avatar","aria-hidden":"true",children:R.image?v.jsx("img",{src:R.image,alt:""}):A?v.jsx("span",{children:A}):v.jsx(Um,{size:17})}),v.jsx("span",{className:"user-auth-menu-identity",children:v.jsx("strong",{children:R.label})})]}),n.length>0&&d?v.jsxs("label",{className:"user-auth-team-picker",children:[v.jsx(wx,{size:15,"aria-hidden":"true"}),v.jsx("span",{className:"user-auth-team-picker-label",children:"Team"}),v.jsx("select",{"aria-label":"Active team",disabled:m!==null,value:N?.teamId??"",onChange:async O=>{const D=O.currentTarget.value;h(D);try{await d(D)}catch{}finally{h(null)}},children:n.map(O=>v.jsx("option",{value:O.teamId,children:O.displayName},O.teamId))})]}):null,v.jsx("div",{className:"user-auth-menu-divider"}),i?v.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",onClick:()=>{r(!1),i()},children:[v.jsx($m,{size:15}),v.jsx("span",{children:"Activity"})]}):null,v.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",onClick:()=>{r(!1),s()},children:[v.jsx(vf,{size:15}),v.jsx("span",{children:"Settings"})]}),e?.state==="signed_in"&&p?v.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",disabled:S,onClick:async()=>{y(!0);try{await p(),r(!1)}catch{}finally{y(!1)}},children:[v.jsx(Tz,{size:15}),v.jsx("span",{children:S?"Logging out…":"Log out"})]}):null]}):null]})}function Hg(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 BH(e,t){const n=Hg(e),a=Hg(t);if(!n||!a)return!1;for(let i=0;i<a.length;i+=1){if(a[i]>n[i])return!0;if(a[i]<n[i])return!1}return!1}function Jx(e){const t=e?.toLowerCase()??"";return t==="darwin"||t.includes("mac")?"mac":t==="linux"||t.includes("linux")?"linux":null}function FH(e){const t=e?.toLowerCase()??"";return t==="arm64"||t==="aarch64"?"arm64":t==="x64"||t==="x86_64"||t==="amd64"?"x64":null}function VH(e,t,n){const a=Jx(t),i=FH(n);if(a==="mac"){const r=e.filter(s=>/-mac-.*\.zip$/i.test(s.name));return i==="arm64"?r.find(s=>/-mac-arm64\.zip$/i.test(s.name))??null:i==="x64"?r.find(s=>/-mac-x64\.zip$/i.test(s.name))??r.find(s=>/-mac-universal\.zip$/i.test(s.name))??null:r.find(s=>/-mac-universal\.zip$/i.test(s.name))??r.find(s=>/-mac-arm64\.zip$/i.test(s.name))??r[0]??null}if(a==="linux"){const r=e.filter(s=>/\.AppImage$/i.test(s.name));return i==="arm64"?r.find(s=>/(?:arm64|aarch64).*\.AppImage$/i.test(s.name))??null:i==="x64"?r.find(s=>/(?:x86_64|x64|amd64).*\.AppImage$/i.test(s.name))??r[0]??null:r[0]??null}return null}function WH(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(!BH(e.currentVersion,a))return null;const i=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}]}),d=VH(s,e.platform,e.arch);return!d||!i?null:{version:a,releaseUrl:i,assetName:d.name,downloadUrl:d.downloadUrl}}const KH=3600*1e3,GH="https://api.github.com/repos/openpond/openpond/releases/latest";function ZH(e){const[t,n]=g.useState({status:"idle",update:null,lastCheckedAt:null}),a=e.currentVersion?.trim()??"",i=e.platform??"",r=e.arch??"",s=e.enabled&&!!a&&!!Jx(i);return g.useEffect(()=>{if(!s){n({status:"idle",update:null,lastCheckedAt:null});return}let d=!1;async function p(){n(h=>({...h,status:h.update?"available":"checking"}));try{const h=await fetch(GH,{headers:{Accept:"application/vnd.github+json"}});if(!h.ok)throw new Error(`GitHub release check failed: ${h.status}`);const S=await h.json(),y=WH({payload:S,currentVersion:a,platform:i,arch:r});if(d)return;n({status:y?"available":"current",update:y,lastCheckedAt:Date.now()})}catch{if(d)return;n(h=>({status:h.update?"available":"error",update:h.update,lastCheckedAt:Date.now()}))}}p();const m=window.setInterval(()=>{p()},KH);return()=>{d=!0,window.clearInterval(m)}},[r,a,s,i]),t}const Yx="openpond.sidebar.continuous-learning.dismissed.v1";function JH(e=Xx()){if(!e)return!1;try{return e.getItem(Yx)==="true"}catch{return!1}}function YH(e=Xx()){if(e)try{e.setItem(Yx,"true")}catch{}}function Xx(){return typeof window>"u"?null:window.localStorage}function XH({connection:e,onOpenSettings:t}){const[n,a]=g.useState(null),[i,r]=g.useState(JH),s=g.useCallback(async()=>{if(!e){a(null);return}try{a(await J.harnessHistory(e))}catch{a(null)}},[e]);if(g.useEffect(()=>{s()},[s]),i||!e||!n?.workspace)return null;const d=n.evaluationReviewSchedule,p=d.activityEnabled?`${d.activityBatchSize} outcomes${d.enabled?` + ${d.cadence}`:""}`:d.enabled?d.cadence:"Manual";return v.jsxs("section",{className:"sidebar-learning-notice","aria-label":"Continuous learning",children:[v.jsxs("header",{children:[v.jsx("strong",{children:"Continuous learning"}),v.jsxs("div",{className:"sidebar-learning-notice-actions",children:[v.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Open Continuous learning settings",onClick:t,type:"button",children:v.jsx(vf,{size:14})}),v.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Close continuous learning",onClick:()=>{r(!0),YH()},type:"button",children:v.jsx(Ir,{size:14})})]})]}),v.jsxs("div",{className:"sidebar-learning-status",children:[v.jsx("strong",{children:"Refiner"}),v.jsx("span",{children:n.backgroundReview.enabled?"On":"Off"})]}),v.jsxs("div",{className:"sidebar-learning-status",children:[v.jsx("strong",{children:"Continuous Review"}),v.jsx("span",{children:p})]})]})}function QH(e){const[t,n]=g.useState(!1),{beginNewChat:a,arch:i,currentVersion:r,experience:s,productArea:d,onProductAreaChange:p,onSidebarResizeStart:m,platform:h,setSectionMenuOpen:S,setSelectedAppId:y,setSelectedProjectId:w,setSelectedSessionId:R,setSidebarOpen:A,setSettingsSection:N,setView:O,view:D,modelProjects:x,modelTrainingActivityByProjectId:I}=e,P=g.useCallback(U=>{n(!1),S(U)},[S]),E=g.useCallback(U=>{n(U),U&&S(null)},[S]),T=ZH({currentVersion:r,platform:h,arch:i,enabled:Fc()}),z=T.status==="available"?T.update:null;return v.jsxs("aside",{className:"sidebar",children:[v.jsxs("div",{className:"sidebar-toolbar",children:[v.jsx("button",{className:"sidebar-icon","aria-label":"Hide sidebar",onClick:()=>A(!1),children:v.jsx(_x,{size:16})}),v.jsx(zH,{value:d,onChange:p}),z&&v.jsxs("button",{type:"button",className:"sidebar-update-pill",title:`Download OpenPond ${z.version}: ${z.assetName}`,"aria-label":`Download OpenPond ${z.version}`,onClick:()=>{eq(z.downloadUrl)},children:[v.jsx(nz,{size:14}),v.jsx("span",{children:"Update"})]})]}),v.jsx(uU,{productArea:d,experience:s,beginNewChat:a,setSectionMenuOpen:P,setSelectedAppId:y,setSelectedProjectId:w,setSelectedSessionId:R,setView:O,view:D,modelProjects:x,modelTrainingActivityByProjectId:I}),d==="models"?null:v.jsx(NH,{...e,setSectionMenuOpen:P}),v.jsxs("div",{className:"sidebar-bottom-stack",children:[d==="models"?null:v.jsx(XH,{connection:e.connection,onOpenSettings:()=>{S(null),N("harness"),O("settings"),an({kind:"settings",section:"harness"})}}),v.jsxs("div",{className:"sidebar-footer-row",children:[v.jsx(qH,{account:e.account,open:t,organizations:e.organizations,selectedTeamId:e.teamChatOrganization?.teamId??null,onOpenChange:E,onOpenActivity:()=>{S(null),N("usage"),O("settings"),an({kind:"settings",section:"usage"})},onOpenSettings:()=>{S(null),N("account"),O("settings"),an({kind:"settings",section:"account"})},onSelectTeam:e.onSelectTeam,onLogOut:e.onLogOut}),v.jsx(mU,{setSectionMenuOpen:P,setSelectedAppId:y,setSelectedProjectId:w,setSelectedSessionId:R,setView:O,view:D})]})]}),v.jsx("div",{className:"sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",onPointerDown:m})]})}async function eq(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-update",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const tq=[/^(?:(?:type)?error:\s*)?failed to fetch\.?$/i,/^networkerror when attempting to fetch resource\.?$/i,/^load failed\.?$/i];function Qx(e,t="Something went wrong."){const a=(e instanceof Error?e.message:String(e??"")).trim();return a?ek(a)?"Couldn’t connect to OpenPond.":a:t}function ek(e){const t=e.trim();return tq.some(n=>n.test(t))}const tk=g.createContext(null);function qg({children:e,showToast:t}){return v.jsx(tk.Provider,{value:t,children:e})}function nq(){return g.useContext(tk)}function Bg(e,t={}){const n=nq(),a=g.useRef(null),i=t.enabled??!0,r=t.fallback??"Something went wrong.",s=t.prefix?.trim()??"",d=e==null||e===""?null:`${s}${s?": ":""}${Qx(e,r)}`;g.useEffect(()=>{if(!i||!d){a.current=null;return}a.current!==d&&(a.current=d,n?.(d,"error",{dismissible:!0}))},[i,d,n])}function aq({state:e,onClose:t,onOpenBrowserUrl:n,onStart:a}){if(Bg(e?.previewError,{prefix:"Upload preview"}),Bg(e?.error,{prefix:"Cloud setup"}),!e)return null;const i=e.status==="uploading",r=e.status==="ready",s=e.status==="error",d=e.projectKind==="cloud",p=e.preview??null;return v.jsx("div",{className:"git-dialog-backdrop",role:"presentation",children:v.jsxs("section",{className:"git-dialog cloud-setup-dialog",role:"dialog","aria-modal":"true","aria-label":"Set up Cloud coding",children:[v.jsx("button",{className:"git-dialog-close",disabled:i,type:"button",onClick:t,"aria-label":"Close Cloud setup",title:"Close",children:v.jsx(Ir,{size:14})}),v.jsx("div",{className:"git-dialog-icon",children:r?v.jsx(Dm,{size:18}):v.jsx(qc,{size:18})}),v.jsx("h2",{children:r?"Cloud repo ready":"Set up Cloud coding"}),v.jsx("p",{children:r?"Your source is ready in OpenPond Git. Finish by creating the Cloud sandbox environment.":d?"This Cloud Project is ready for a sandbox environment.":"OpenPond will upload tracked and unignored files into OpenPond Git, then send you to the Cloud sandbox setup page."}),v.jsxs("div",{className:"cloud-setup-summary",children:[v.jsxs("div",{className:"git-dialog-row",children:[v.jsx("span",{children:"Project"}),v.jsx("strong",{children:e.projectName})]}),v.jsxs("div",{className:"git-dialog-row",children:[v.jsx("span",{children:"Source"}),v.jsx("strong",{children:d?"OpenPond Git":"Local project upload"})]}),v.jsxs("div",{className:"git-dialog-row",children:[v.jsx("span",{children:"Branch"}),v.jsx("strong",{children:p?.branch??e.branch??"main"})]}),!d&&v.jsxs("div",{className:"git-dialog-row",children:[v.jsx("span",{children:"Cloud project"}),v.jsx("strong",{children:p?.targetProjectId??e.cloudProjectId??"New on upload"})]})]}),!r&&!d&&v.jsx("div",{className:"cloud-setup-upload-preview",role:"status","aria-live":"polite",children:e.previewLoading?v.jsxs(v.Fragment,{children:[v.jsx("strong",{children:"Calculating upload preview"}),v.jsx("span",{children:"Checking tracked and unignored files before anything is pushed."})]}):e.previewError?v.jsxs(v.Fragment,{children:[v.jsx("strong",{children:"Preview unavailable"}),v.jsx("span",{children:"Close and reopen setup to try the preview again."})]}):p?v.jsxs(v.Fragment,{children:[v.jsx("strong",{children:p.initializedEmptyProject?"Will initialize an empty project":`Will upload ${p.fileCount} files`}),v.jsx("span",{children:Fg({byteCount:p.byteCount,skippedCount:p.skippedCount,headCommit:p.headCommit,targetProjectName:p.targetProjectName})})]}):v.jsxs(v.Fragment,{children:[v.jsx("strong",{children:"Upload preview pending"}),v.jsx("span",{children:"File count, byte count, and skipped files will appear here before upload."})]})}),i&&v.jsxs("div",{className:"cloud-setup-progress",role:"status","aria-live":"polite",children:[v.jsx(Sz,{className:"cloud-setup-spinner",size:16}),v.jsx("span",{children:"Uploading source to OpenPond Git..."})]}),r&&e.upload&&v.jsxs("div",{className:"cloud-setup-upload-result",children:[v.jsx("strong",{children:e.upload.initializedEmptyProject?"Initialized empty project":`Uploaded ${e.upload.fileCount} files`}),v.jsx("span",{children:Fg({byteCount:e.upload.byteCount,skippedCount:e.upload.skippedCount,headCommit:e.upload.headCommit,targetProjectName:e.upload.branch})})]}),r&&e.setupUrl&&v.jsxs("div",{className:"cloud-setup-next",children:[e.projectUrl?v.jsxs("span",{children:["Your repo is ready here:"," ",v.jsxs("a",{href:e.projectUrl,target:"_blank",rel:"noreferrer",onClick:m=>Wu(m,e.projectUrl,n,{newTab:!0}),children:["Project page",v.jsx(Uu,{size:13})]})]}):v.jsx("span",{children:"Your repo is ready. Next step:"}),v.jsxs("a",{href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:m=>Wu(m,e.setupUrl,n),children:["Setup the Cloud sandbox",v.jsx(Uu,{size:13})]})]}),v.jsxs("div",{className:"git-dialog-footer",children:[v.jsx("button",{className:"git-dialog-secondary",disabled:i,type:"button",onClick:t,children:r?"Done":"Cancel"}),r?e.setupUrl?v.jsxs("a",{className:"git-dialog-primary cloud-setup-primary-link",href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:m=>Wu(m,e.setupUrl,n),children:["Open setup",v.jsx(Uu,{size:13})]}):null:v.jsx("button",{className:"git-dialog-primary",disabled:i,type:"button",onClick:a,children:i?"Uploading":s?"Try again":d?"Show setup link":"Upload source"})]})]})})}function Wu(e,t,n,a={}){!t||!n||(e.preventDefault(),n(t,a))}function oq(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 Fg({byteCount:e,skippedCount:t,headCommit:n,targetProjectName:a}){const i=[oq(e),`${t} skipped`],r=iq(n);return r&&i.push(`local ${r}`),i.push(a),i.join(" · ")}function iq(e){const t=e?.trim();return t?t.slice(0,7):null}const rq=g.lazy(()=>ri(()=>import("./CommandMenu-Co6JnmTu.js"),__vite__mapDeps([0,1,2,3]),import.meta.url).then(e=>({default:e.CommandMenu}))),sq=g.lazy(()=>ri(()=>import("./SettingsView-QT_OLmDh.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}))),lq=g.lazy(()=>ri(()=>import("./NewProjectDialog-CzpHCAaC.js"),__vite__mapDeps([27,1,2,8,16]),import.meta.url).then(e=>({default:e.NewProjectDialog}))),cq=g.lazy(()=>ri(()=>import("./WorkspaceGitDialogs-_LHTrvh6.js"),__vite__mapDeps([28,1,2,13,14,29,26]),import.meta.url).then(e=>({default:e.CommitDialog}))),dq=g.lazy(()=>ri(()=>import("./WorkspaceGitDialogs-_LHTrvh6.js"),__vite__mapDeps([28,1,2,13,14,29,26]),import.meta.url).then(e=>({default:e.BranchDialog})));function uq({payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:i,onError:r,onToast:s,onBack:d,onOpenSourceSession:p,onStartRefinerAuthoring:m,onAcceptEvaluationReview:h,onOpenSkill:S,onOpenExtension:y,teamChatCurrentUserId:w,teamChatEnabled:R,teamChatNotificationMode:A,teamChatThreads:N,onTeamChatNotificationModeChange:O,onTeamChatThreadMuteChange:D,diffPanelWidth:x,diffPanelResizing:I,diffPanelExpanded:P,onDiffPanelResizeStart:E,onDiffPanelExpandedChange:T}){return v.jsx(g.Suspense,{fallback:null,children:v.jsx(sq,{payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:i,onError:r,onToast:s,onBack:d,onOpenSourceSession:p,onStartRefinerAuthoring:m,onAcceptEvaluationReview:h,onOpenSkill:S,onOpenExtension:y,teamChatCurrentUserId:w,teamChatEnabled:R,teamChatNotificationMode:A,teamChatThreads:N,onTeamChatNotificationModeChange:O,onTeamChatThreadMuteChange:D,diffPanelWidth:x,diffPanelResizing:I,diffPanelExpanded:P,onDiffPanelResizeStart:E,onDiffPanelExpandedChange:T})})}function mq({activeSessions:e,branchDialogName:t,branchDialogOpen:n,commitDialogOpen:a,commitDraft:i,commitIncludeUnstaged:r,commitMessage:s,commitNextStep:d,canPublishOpenPondProject:p,expandProject:m,newProjectBusy:h,newProjectDialogOpen:S,newProjectDirectory:y,newProjectMode:w,newProjectName:R,newProjectPath:A,projectRows:N,query:O,searchOpen:D,visibleWorkspaceDiff:x,visibleWorkspaceState:I,workspaceBusy:P,appDispatch:E,beginNewChat:T,openDefaultsSettingsFromBranchDialog:z,setBranchDialogName:U,setBranchDialogOpen:$,setCommitDialogOpen:V,setCommitDraft:re,setCommitIncludeUnstaged:Q,setCommitMessage:Ie,setCommitNextStep:Se,setNewProjectDialogOpen:G,setNewProjectName:Ee,setNewProjectPath:xe,setQuery:le,setSearchOpen:ke,submitCommitDialog:ae,submitCreateWorkspaceBranch:he,submitNewProjectDialog:ve}){return v.jsxs(v.Fragment,{children:[D&&v.jsx(g.Suspense,{fallback:null,children:v.jsx(rq,{open:D,query:O,projects:N,sessions:e,onQueryChange:le,onClose:()=>{ke(!1),le("")},onNewChat:()=>{ke(!1),le(""),T()},onOpenProject:Ze=>{E({type:"selectProject",projectId:Ze.id}),E({type:"patch",patch:{searchOpen:!1,query:""}}),m(Ze.id)},onOpenSession:Ze=>{E({type:"selectSession",sessionId:Ze.id,appId:Ze.appId,projectId:Ze.workspaceKind==="local_project"&&Ze.workspaceId?vt("local",Ze.workspaceId):null}),E({type:"patch",patch:{searchOpen:!1,query:""}})}})}),S&&v.jsx(g.Suspense,{fallback:null,children:v.jsx(lq,{open:S,mode:w,name:R,path:A,directory:y,busy:h,onNameChange:Ee,onPathChange:xe,onClose:()=>{h||G(!1)},onSubmit:ve})}),a&&v.jsx(g.Suspense,{fallback:null,children:v.jsx(cq,{open:a,branch:I?.currentBranch??null,filesChanged:x?.filesChanged??I?.changedFilesCount??0,additions:x?.additions??0,deletions:x?.deletions??0,message:s,includeUnstaged:r,nextStep:d,draft:i,busy:P,canPush:!!I?.remoteUrl,canPublish:p,onMessageChange:Ie,onIncludeUnstagedChange:Q,onNextStepChange:Se,onDraftChange:re,onClose:()=>{P||V(!1)},onSubmit:ae})}),n&&v.jsx(g.Suspense,{fallback:null,children:v.jsx(dq,{open:n,branchName:t,busy:P,onBranchNameChange:U,onSetPrefix:z,onClose:()=>{P||$(!1)},onSubmit:he})})]})}function nk({toast:e,onDismiss:t}){if(!e)return null;const n=!!(e.actionLabel&&e.onAction),a=!!(e.persistent||e.dismissible);return v.jsxs("div",{className:`app-toast ${e.tone} ${e.placement??"bottom-right"}`,role:e.tone==="error"?"alert":"status","aria-live":"polite",children:[v.jsx("span",{className:"app-toast-message",children:e.message}),(n||a)&&v.jsxs("div",{className:"app-toast-actions",children:[n&&v.jsx("button",{type:"button",className:e.actionIcon?"app-toast-icon-action":void 0,"aria-label":e.actionLabel,title:e.actionIcon?e.actionLabel:void 0,onClick:()=>{t(),e.onAction?.()},children:e.actionIcon==="settings"?v.jsx(vf,{size:15}):e.actionLabel}),a&&v.jsx("button",{type:"button",className:"app-toast-close","aria-label":"Dismiss notification",onClick:t,children:v.jsx(Ir,{size:14})})]})]})}async function pq(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 fq({activeView:e,onDiscoverCommunities:t,onOpenTeamChat:n}){return v.jsxs("div",{className:"titlebar-collaboration-actions",children:[v.jsx("button",{type:"button",className:`titlebar-icon${e==="team"?" active":""}`,"aria-label":"Team chat",title:"Team chat",onClick:n,children:v.jsx(Bc,{size:16})}),v.jsx("button",{type:"button",className:`titlebar-icon${e==="community"?" active":""}`,"aria-label":"Discover communities",title:"Discover communities",onClick:t,children:v.jsx(kx,{size:16})})]})}const hq=g.lazy(()=>ri(()=>import("./WorkspaceEnvironmentMenu-D8knAy1q.js"),__vite__mapDeps([30,1,2,22,10,14,6,31,29,32]),import.meta.url).then(e=>({default:e.WorkspaceEnvironmentMenu})));function gq({sidebarOpen:e,title:t,conversationId:n,breadcrumbs:a,backAction:i,workspaceName:r,workspaceId:s,busy:d,workspaceState:p,workspaceKind:m,selectedApp:h,selectedProject:S,workspaceDiff:y,managedWorkspace:w,workspaceBusy:R,defaultTeamId:A,showDiffControls:N,diffPanelOpen:O,terminalOpen:D,rightSidebarAvailable:x=!1,rightSidebarOpen:I=!1,onToggleDiffPanel:P,onToggleRightSidebar:E,onOpenSearch:T,onToggleTerminal:z,onRunTerminalCommand:U,onWorkspaceToolAction:$,onOpenCommitDialog:V,onWorkspaceBranchChange:re,onWorkspaceBranchCreate:Q,connection:Ie,onBootstrap:Se,onOpenSandboxWorkspace:G,onShowSidebar:Ee,onOpenTeamChat:xe,onDiscoverCommunities:le,collaborationView:ke=null,platform:ae,showWorkspaceControls:he=!0}){const ve=y?.filesChanged??0,Ze=Fc()&&!Sf(ae),Re=!!(xe||le)||he||x||Ze,[se,Ce]=g.useState(null);g.useEffect(()=>{if(!se)return;const it=()=>Ce(null);return window.addEventListener("pointerdown",it),window.addEventListener("blur",it),window.addEventListener("resize",it),()=>{window.removeEventListener("pointerdown",it),window.removeEventListener("blur",it),window.removeEventListener("resize",it)}},[se]);const Le=it=>{it.preventDefault(),it.stopPropagation();const ut=190,Fe=n?76:42;Ce({x:Math.min(it.clientX,window.innerWidth-ut-8),y:Math.min(it.clientY,window.innerHeight-Fe-8)})},Qe=it=>{pq(it),Ce(null)};return v.jsxs("header",{className:"app-titlebar",children:[v.jsxs("div",{className:"titlebar-left",children:[!e&&v.jsx("button",{className:"titlebar-icon",title:"Show sidebar",onClick:Ee,children:v.jsx(_x,{size:16})}),i?v.jsx("button",{className:"titlebar-icon",type:"button","aria-label":i.label,title:i.label,onClick:i.onSelect,children:v.jsx(LL,{size:16})}):null,a?.length?v.jsx("nav",{className:"titlebar-breadcrumbs","aria-label":"Breadcrumb",children:a.map((it,ut)=>{const Fe=ut===a.length-1;return v.jsxs("div",{className:"titlebar-breadcrumb-item",children:[it.onSelect&&!Fe?v.jsx("button",{type:"button",onClick:it.onSelect,children:it.label}):v.jsx("strong",{children:it.label}),!Fe&&v.jsx(ii,{size:14})]},`${it.label}-${ut}`)})}):v.jsxs("div",{className:"titlebar-title",children:[v.jsx("strong",{className:"titlebar-copy-target",title:"Double-click to select; right-click for copy options",onContextMenu:Le,children:t}),r&&v.jsx("span",{children:r})]})]}),Re&&v.jsxs("div",{className:"titlebar-right",children:[v.jsx(fq,{activeView:ke,onDiscoverCommunities:le,onOpenTeamChat:xe}),he&&v.jsxs("div",{className:"titlebar-actions",children:[v.jsx(g.Suspense,{fallback:null,children:v.jsx(hq,{mode:"topbar",busy:d,workspaceState:p,workspaceId:s,workspaceKind:m,selectedApp:h,selectedProject:S,workspaceBusy:R,defaultTeamId:A,workspaceDiff:y,managedWorkspace:w,showDiffControls:N,diffPanelOpen:O,onToggleDiffPanel:P,onRunTerminalCommand:U,onWorkspaceToolAction:$,onOpenCommitDialog:V,onWorkspaceBranchChange:re,onWorkspaceBranchCreate:Q,connection:Ie,onBootstrap:Se,onOpenSandboxWorkspace:G})}),v.jsx("button",{type:"button",className:"titlebar-icon",title:"Search chats and projects","aria-label":"Search chats and projects",onClick:T,children:v.jsx(Mz,{size:16})}),v.jsx("button",{type:"button",className:`titlebar-icon ${D?"active":""}`,title:`${D?"Hide":"Show"} terminal`,"aria-label":`${D?"Hide":"Show"} terminal`,"aria-pressed":D,onClick:z,children:v.jsx(Ix,{size:16})}),N&&v.jsx("button",{type:"button",className:`topbar-diff-button ${I?"active":""}`,title:`${I?"Hide":"Show"} sidebar${ve?`, ${ve} changed files`:""}`,"aria-label":`${I?"Hide":"Show"} sidebar`,"aria-pressed":I,onClick:P,children:v.jsx(zm,{size:16})})]}),x&&E&&!N?v.jsx("div",{className:"titlebar-actions",children:v.jsx("button",{type:"button",className:`topbar-diff-button ${I?"active":""}`,title:`${I?"Hide":"Show"} sidebar`,"aria-label":`${I?"Hide":"Show"} sidebar`,"aria-pressed":I,onClick:E,children:v.jsx(zm,{size:16})})}):null,v.jsx(Hz,{platform:ae})]}),se&&v.jsxs("div",{className:"titlebar-copy-menu",role:"menu","aria-label":"Conversation title actions",style:{left:se.x,top:se.y},onPointerDown:it=>it.stopPropagation(),children:[v.jsx("button",{type:"button",role:"menuitem",onClick:()=>Qe(t),children:"Copy title"}),n&&v.jsx("button",{type:"button",role:"menuitem",onClick:()=>Qe(n),children:"Copy conversation ID"})]})]})}function bq(){const[e,t]=g.useState(null),n=g.useRef(null),a=g.useCallback(r=>new Promise(s=>{n.current?.resolve(!1);const d={...r,cancelLabel:r.cancelLabel??"Cancel",tone:r.tone??"default",resolve:s};n.current=d,t(d)}),[]),i=g.useCallback(r=>{const s=n.current;n.current=null,t(null),s?.resolve(r)},[]);return{confirmAction:a,confirmDialog:e,resolveConfirmDialog:i}}function vq({state:e,onResolve:t}){const n=g.useId(),a=g.useId();if(g.useEffect(()=>{if(!e)return;function r(s){s.key==="Escape"&&t(!1)}return document.addEventListener("keydown",r),()=>document.removeEventListener("keydown",r)},[t,e]),!e)return null;const i=e.tone==="danger"?"git-dialog-primary danger":"git-dialog-primary";return v.jsx("div",{className:"git-dialog-backdrop",role:"presentation",onMouseDown:()=>t(!1),children:v.jsxs("section",{className:"git-dialog project-confirm-dialog",role:"alertdialog","aria-modal":"true","aria-labelledby":n,"aria-describedby":a,onMouseDown:r=>r.stopPropagation(),children:[v.jsx("h2",{id:n,children:e.title}),v.jsx("p",{id:a,children:e.body}),v.jsxs("div",{className:"git-dialog-footer",children:[v.jsx("button",{type:"button",className:"git-dialog-secondary",onClick:()=>t(!1),children:e.cancelLabel}),v.jsx("button",{type:"button",className:i,autoFocus:!0,onClick:()=>t(!0),children:e.confirmLabel})]})]})})}function yq(){const{confirmAction:e,confirmDialog:t,resolveConfirmDialog:n}=bq();return{confirmProjectAction:g.useCallback(i=>e({tone:"danger",...i}),[e]),projectConfirmDialog:t,resolveProjectConfirmDialog:n}}function Sq({state:e,onResolve:t}){return v.jsx(vq,{state:e,onResolve:t})}const dc=new Map,xq=(e,t,n)=>{const a=dc.get(e)??{commits:0,maxActualDurationMs:0,totalActualDurationMs:0};a.commits+=1,a.maxActualDurationMs=Math.max(a.maxActualDurationMs,n),a.totalActualDurationMs+=n,dc.set(e,a)};function kq({children:e,id:t}){return v.jsx(g.Profiler,{id:t,onRender:xq,children:e})}typeof window<"u"&&(window.__OPENPOND_RENDER_COMMITS__={get:()=>Object.fromEntries([...dc.entries()].map(([e,t])=>[e,{...t}])),reset:()=>dc.clear()});const _q=g.lazy(()=>ri(()=>import("./MainPane-BbknUzp3.js").then(e=>e.M),__vite__mapDeps([33,1,2,13,5,34,31]),import.meta.url).then(e=>({default:e.MainPane})));function wq({className:e,style:t,sidebar:n,topBar:a,mainPane:i,cloudSetup:r,projectConfirm:s,lazyPanels:d,toast:p}){return v.jsxs("div",{className:e,style:t,children:[v.jsx(kq,{id:"sidebar",children:v.jsx(QH,{...n})}),v.jsxs("div",{className:"content-shell",children:[v.jsx(gq,{...a}),v.jsx(g.Suspense,{fallback:v.jsx("main",{className:"main-pane","aria-busy":"true","aria-label":"Loading workspace"}),children:v.jsx(_q,{...i})})]}),v.jsx(aq,{...r}),v.jsx(Sq,{...s}),v.jsx(mq,{...d}),v.jsx(nk,{...p})]})}function Iq({settings:e,toast:t}){return v.jsxs(v.Fragment,{children:[v.jsx(uq,{...e}),v.jsx(nk,{...t})]})}const Wl="OpenPond".split("");function Cq({visibleLetterCount:e=Wl.length}){const t=Wl.slice(0,Math.max(0,Math.min(e,Wl.length)));return v.jsxs("div",{className:"app-splash-lockup",children:[v.jsx("div",{className:"app-splash-mark",children:v.jsx("img",{alt:"OpenPond",className:"app-splash-logo",decoding:"async",src:DH})}),v.jsx("span",{"aria-hidden":"true",className:`app-splash-wordmark${t.length>0?" is-visible":""}`,children:t.map((n,a)=>v.jsx("span",{className:"app-splash-letter",children:n},`${n}-${a}`))})]})}const Ku=Wl.length,Rq=520,Aq=240;function Vg(){return typeof window>"u"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Pq({startup:e}){const[t,n]=g.useState(()=>Vg()?Ku:0);return g.useEffect(()=>{if(Vg()){n(Ku);return}const a=Array.from({length:Ku},(i,r)=>window.setTimeout(()=>n(r+1),Rq+Aq*r));return()=>{a.forEach(i=>window.clearTimeout(i))}},[]),v.jsxs("main",{className:"app-splash","aria-busy":"true","aria-label":e.label,role:"status",children:[v.jsx(Cq,{visibleLetterCount:t}),v.jsx("span",{className:"app-splash-status",children:e.label})]})}const Rf=5e3;function so(e,t){if(e.length===0)return t;if(t.length===0)return e;const n=new Set,a=[];for(const i of[...e,...t])n.has(i.id)||(n.add(i.id),a.push(i));return a}function ro(e,t,n=Rf){return Kl(so(e,t),n)}function Kl(e,t=Rf){return e.length<=t?e:e.slice(e.length-t)}function Tq(e,t,n){return n.length===0?e:{...e,[t]:so(e[t]??[],n)}}function Eq(e,t){if(t.length===0)return Kl(e);if(e.length===0)return Kl(t);const n=new Map;let a=0;for(const i of[...e,...t])n.has(i.id)||n.set(i.id,{event:i,index:a}),a+=1;return Kl([...n.values()].sort((i,r)=>jq(i,r)).map(({event:i})=>i))}function uc(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 Mq(e){let t=null;for(const n of e)n.sequence!==void 0&&(t===null||n.sequence<t)&&(t=n.sequence);return t}function jq(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 i=Date.parse(e.event.timestamp),r=Date.parse(t.event.timestamp);if(Number.isFinite(i)&&Number.isFinite(r)){const s=i-r;if(s!==0)return s}return e.index-t.index}function Wg(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 Oq(e){return e===null?"unknown":e>=85?"high":e>=65?"medium":"low"}function Kg(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 Nq(e){return e==="codex"}function $q(e){return e==="openpond"}function ak(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="session.context.updated")continue;const a=wP.safeParse(n.data);if(a.success)return a.data}return null}function ok(e){if(e.snapshot&&e.snapshot.provider===e.provider){const n=e.snapshot.usedTokens,a=e.snapshot.maxContextTokens,i=Math.min(100,Math.round(e.snapshot.percentFull)),r=`${i}% full`,s=`${Wg(n)} / ${Wg(a)} tokens used`;return{usedTokens:n,maxTokens:a,percent:i,summary:r,tokensLabel:s,detail:Kg(e.preferences,i),tooltip:`Context window: ${r} ${s}. ${Kg(e.preferences,i)}`,tone:Oq(i)}}if(Nq(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(!$q(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 Af(e){let t=!1;const n=ik(e);for(let a=e.length-1;a>=0;a-=1){const i=e[a];if(Dq(i)){t=!0;continue}const r=pr(i?.data);if(!(i?.name!=="diagnostic"||!r)){if(r.kind==="thread_goal_cleared")return null;if(r.kind==="thread_goal"){const s=Pf(pr(r.goal),Fn(r.provider),n);if(s){const d=Ls(s);return t&&d.tone==="active"?null:d}}if(r.kind==="goal_context"){const s=sk(i.output??"",Fn(r.provider)??"codex",n);if(s){const d=Ls(s);return t&&d.tone==="active"?null:d}}}}return null}function mc(e){const t=ik(e);for(let n=e.length-1;n>=0;n-=1){const a=e[n],i=pr(a?.data);if(!(a?.name!=="diagnostic"||!i)){if(i.kind==="thread_goal_cleared"&&i.synthetic!==!0)return null;if(i.kind==="thread_goal"){const r=Pf(pr(i.goal),Fn(i.provider),t);if(!r)continue;const s=Ls(r);return s.tone==="active"?s:null}if(i.kind==="goal_context"){const r=sk(a.output??"",Fn(i.provider)??"codex",t);if(!r)continue;const s=Ls(r);return s.tone==="active"?s:null}}}return null}function Gu(e){const t=pr(pr(e)?.codexGoalRuntime),n=Pf(t,Fn(t?.provider)??"codex");if(!n)return null;const a=Ls(n);return a.tone==="active"?a:null}function Dq(e){return e?.name==="turn.completed"||e?.name==="turn.interrupted"||e?.name==="turn.failed"}function Ls(e){const t=lk(e.status),n=uk(e.timeUsedSeconds),a=`Goal ${n}`,i=e.tokensUsed===null?null:e.tokenBudget===null?`${Zu(e.tokensUsed)} tokens`:`${Zu(e.tokensUsed)} / ${Zu(e.tokenBudget)} tokens`,r=i?`${e.statusLabel} · ${i}`: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:r,tooltip:`Goal runtime: ${mk(e.timeUsedSeconds)}. ${r}. ${e.objective}`,tone:t.tone,observedAt:e.observedAt}}function Lq(e,t){if(!e||e.tone!=="active"||!e.observedAt)return e;const n=rk(e.observedAt,t);if(n<=0)return e;const a=e.timeUsedSeconds+n,i=uk(a);return{...e,timeUsedSeconds:a,timeLabel:i,label:`Goal ${i}`,tooltip:`Goal runtime: ${mk(a)}. ${e.detail}. ${e.objective}`,observedAt:t}}function Pf(e,t=null,n=null){if(!e)return null;const a=Fn(e.objective)??"Active goal",i=Fn(e.status)??"active";if((Gm(t)??Gm(Fn(e.provider)))!=="codex")return null;const s=n??Fn(e.updatedAt)??Fn(e.updated_at)??null,d=Ui(e.timeUsedSeconds)??Ui(e.time_used_seconds)??0,p=Fn(e.activeSinceAt)??Fn(e.active_since_at),m=lk(i).tone==="active"?rk(p??Fn(e.createdAt)??Fn(e.created_at),s):0,h=p?d+m:Math.max(d,m),S=Ui(e.tokensUsed)??Ui(e.tokens_used),y=Ui(e.tokenBudget)??Ui(e.token_budget);return{objective:a,status:i,statusLabel:dk(i),timeUsedSeconds:Math.max(0,Math.floor(h)),tokensUsed:S===null?null:Math.max(0,Math.floor(S)),tokenBudget:y===null?null:Math.max(0,Math.floor(y)),observedAt:s}}function ik(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 rk(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 sk(e,t=null,n=null){if(!e.trim()||Gm(t)!=="codex")return null;const a=ck(e,"Status")??"active",i=ps(e,"Tokens used"),r=ps(e,"Token budget"),s=ps(e,"Time used seconds")??ps(e,"Time spent pursuing goal")??ps(e,"Elapsed seconds")??0;return{objective:Gg(e,"objective")??Gg(e,"untrusted_objective")??"Active goal",status:a,statusLabel:dk(a),timeUsedSeconds:Math.max(0,Math.floor(s)),tokensUsed:i,tokenBudget:r,observedAt:n}}function lk(e){switch(zq(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 zq(e){return e.trim().toLowerCase().replace(/[-\s]+/g,"_")}function ck(e,t){const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^\\s*-?\\s*${n}:\\s*(.+?)\\s*$`,"im").exec(e)?.[1]?.trim()||null}function ps(e,t){const n=ck(e,t);if(!n)return null;const a=n.replace(/,/g,""),i=/-?\d+(?:\.\d+)?/.exec(a);if(!i)return null;const r=Number(i[0]);return Number.isFinite(r)?r:null}function Gg(e,t){return new RegExp(`<${t}>\\s*([\\s\\S]*?)\\s*<\\/${t}>`,"i").exec(e)?.[1]?.trim()||null}function dk(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function uk(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 mk(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 Zu(e){if(e<1e3)return String(e);if(e>=1e6){const n=e/1e6;return n<10?`${Zg(n,2)}M`:n<100?`${Zg(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 Zg(e,t){return e.toFixed(t).replace(/\.?0+$/,"")}function pr(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Fn(e){return typeof e=="string"&&e.trim()?e.trim():null}function Gm(e){return e?.trim().toLowerCase()||null}function Ui(e){return typeof e=="number"&&Number.isFinite(e)?e:null}const Uq=new Set(["planning","applying_source","running_checks","evaluating","pushing_hosted","running_hosted_checks"]),Hq=new Set(["awaiting_questions","awaiting_plan_approval","paused"]);function Zm(e){const t=pk(e);return t?Vq(t):null}function pk(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="create_improve.updated")continue;const a=Fq(Jq(n.data));if(a)return a}return null}function qq(e){if(e.events)return pk(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 Bq(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 Fq(e){const t=Vs.safeParse(e?.createImproveRun);return t.success?t.data:null}function Vq(e){const t=Wq(e);if(!t)return null;const n=Kq(e.createdAt,e.updatedAt),a=e.blockedReason??Gq(e.state);return{objective:e.objective,status:e.state,timeUsedSeconds:n,tokensUsed:null,tokenBudget:null,actionLabel:t.actionLabel,timeLabel:Zq(n),label:t.actionLabel,detail:a,tooltip:`${t.actionLabel}: ${a}. ${e.objective}`,tone:t.tone}}function Wq(e){const t=e.state,n=e.target.kind==="agent"?"Agent":"Work";return Uq.has(t)?{tone:"active",actionLabel:`${n} running`}:Hq.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 Kq(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 Gq(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function Zq(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 Jq(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function fk(e,t){if(!t)return null;const n=new Map,a=[];for(const I of e){if(!I.name.startsWith("subagent."))continue;const P=Qq(I);P&&a.push(P);const E=Xq(I);E?.parentSessionId===t&&n.set(E.id,E)}if(n.size===0)return null;const i=[...n.values()].sort((I,P)=>Fi(P).localeCompare(Fi(I))),r=i.filter(I=>I.status==="queued"||I.status==="running"),s=i.filter(I=>I.status==="completed"),d=i.filter(I=>I.status==="failed"),p=i.filter(I=>I.status==="cancelled"),m=i.filter(I=>I.status==="needs_resume"),h=[...s,...d,...p].sort((I,P)=>Fi(P).localeCompare(Fi(I))),S=i.reduce((I,P)=>{const E=fr(P.metadata?.usage);return I.totalTokens+=Ml(E?.totalTokens),I.promptTokens+=Ml(E?.promptTokens),I.completionTokens+=Ml(E?.completionTokens),I.requestCount+=Ml(E?.requestCount),I},{totalTokens:0,promptTokens:0,completionTokens:0,requestCount:0}),y=i.flatMap(I=>hk([...I.report?.blockers??[],I.error,I.progress.currentBlocker]).map(P=>({runId:I.id,roleId:I.roleId,status:I.status,message:P}))),w=i.flatMap(I=>gk([...I.report?.artifacts??[],I.report?.patchRef,I.report?.diffRef,...I.progress.patchRefs]).map(P=>({...P,runId:I.id,roleId:I.roleId}))),R=h.map(I=>Yq(I,a)),A=i[0]??null,N=A?{runId:A.id,roleId:A.roleId,status:A.status,message:A.progress.latestMeaningfulActivity||A.report?.summary||A.objective,updatedAt:Fi(A)}:null,O=r.length>0?`${r.length} ${r.length===1?"child":"children"} running`:`${h.length} ${h.length===1?"child":"children"} finished`,D=[r.length?`${r.length} active`:null,s.length?`${s.length} completed`:null,d.length?`${d.length} failed`:null,p.length?`${p.length} cancelled`:null,m.length?`${m.length} paused`:null].filter(Boolean).join(" · "),x=N?`${nB(N.roleId)}: ${N.message}`:"";return{sessionId:t,runs:i,activeRuns:r,completedRuns:s,failedRuns:d,cancelledRuns:p,needsResumeRuns:m,terminalRuns:h,latestRun:A,latestMeaningfulUpdate:N,activeCount:r.length,completedCount:s.length,failedCount:d.length,cancelledCount:p.length,needsResumeCount:m.length,terminalCount:h.length,usage:S,blockers:y,evidenceRefs:w,finalResults:R,testsRunCount:i.reduce((I,P)=>I+P.progress.validationAttempts.length,0),label:O,tooltip:[D,x].filter(Boolean).join(". ")}}function Yq(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:gk([...e.report?.artifacts??[],e.report?.patchRef,e.report?.diffRef]),testsRun:e.report?.testsRun??[],validationAttempts:e.progress.validationAttempts.map(n=>n.command),blockers:hk([...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:eB(e),updatedAt:Fi(e)}}function Xq(e){const t=fr(e.data),n=[t?.run,fr(t?.message)?.run];for(const a of n){const i=Wv.safeParse(a);if(i.success)return i.data}return null}function Qq(e){const t=FR.safeParse(fr(e.data)?.message);return t.success?t.data:null}function eB(e){const t=fr(fr(e.metadata?.workspaceHandoff)?.workspaceRetention);return t?.status!=="retained"?null:{status:"retained",reason:El(t.reason),retainedAt:El(t.retainedAt),expiresAt:El(t.expiresAt),retentionDays:tB(t.retentionDays),trigger:El(t.trigger),cleanupAfterExpiry:t.cleanupAfterExpiry===!0}}function Fi(e){return e.updatedAt??e.completedAt??e.startedAt??e.createdAt}function hk(e){return[...new Set(e.map(t=>t?.trim()).filter(t=>!!t))]}function gk(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 El(e){return typeof e=="string"&&e.trim()?e.trim():null}function Ml(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function tB(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function nB(e){return e.slice(0,1).toUpperCase()+e.slice(1).replace(/[-_]+/g," ")}const Jm=[];function Ym(e,t){return bk(e,t,null)}function bk(e,t,n){const a=n&&sB(n.events,e)?oB(n.indexes,n.events.length,e):aB(e),i=rB(t);return{...a,...i}}function aB(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 iB(t)}function oB(e,t,n){const a=new Map(e.eventsBySessionId),i=new Map(e.latestContextUsageBySessionId),r=new Map(e.latestGoalRuntimeBySessionId),s=new Map(e.latestSubagentRuntimeBySessionId),d=new Set(e.activeGoalSessionIds),p=new Set(e.activeSubagentSessionIds),m=new Set;for(let h=t;h<n.length;h+=1){const S=n[h];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 h of m){const S=a.get(h)??Jm,y=ak(S);y?i.set(h,y):i.delete(h);const w=yk(S);w?(r.set(h,w),w.tone==="active"?d.add(h):d.delete(h)):(r.delete(h),d.delete(h));const R=fk(S,h);R?(s.set(h,R),vk({sessionEvents:S,sessionId:h,latestGoalRuntimeBySessionId:r,activeGoalSessionIds:d}),R.activeCount>0?p.add(h):p.delete(h)):(s.delete(h),p.delete(h))}return{eventsBySessionId:a,latestContextUsageBySessionId:i,latestGoalRuntimeBySessionId:r,latestSubagentRuntimeBySessionId:s,activeGoalSessionIds:d,activeSubagentSessionIds:p}}function iB(e){const t=new Map,n=new Map,a=new Map,i=new Set,r=new Set;for(const[s,d]of e){const p=ak(d);p&&t.set(s,p);const m=yk(d);m&&(n.set(s,m),m.tone==="active"&&i.add(s))}for(const[s,d]of e){const p=fk(d,s);p&&(a.set(s,p),vk({sessionEvents:d,sessionId:s,latestGoalRuntimeBySessionId:n,activeGoalSessionIds:i}),p.activeCount>0&&r.add(s))}return{eventsBySessionId:e,latestContextUsageBySessionId:t,latestGoalRuntimeBySessionId:n,latestSubagentRuntimeBySessionId:a,activeGoalSessionIds:i,activeSubagentSessionIds:r}}function vk(e){if(e.latestGoalRuntimeBySessionId.has(e.sessionId))return;const t=mc(e.sessionEvents);t&&(e.latestGoalRuntimeBySessionId.set(e.sessionId,t),t.tone==="active"&&e.activeGoalSessionIds.add(e.sessionId))}function yk(e){return Zm(e)??Af(e)??mc(e)}function rB(e){const t=new Map,n=new Map,a=new Map,i=new Map;for(const r of e){t.set(r.id,r);const s=n.get(r.status);if(s?s.push(r):n.set(r.status,[r]),r.status!=="pending")continue;const d=a.get(r.sessionId);d?d.push(r):a.set(r.sessionId,[r]);const p=i.get(r.sessionId);(!p||Jg(r.createdAt)>Jg(p.createdAt))&&i.set(r.sessionId,r)}return{approvalsById:t,approvalsByStatus:n,pendingApprovalsBySessionId:a,latestPendingApprovalBySessionId:i}}function sB(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 nl(e,t){return t?e.eventsBySessionId.get(t)??Jm:Jm}function Sk(e,t){return t?e.latestContextUsageBySessionId.get(t)??null:null}function xk(e,t){return t?e.latestGoalRuntimeBySessionId.get(t)??null:null}function lB(e,t){return t?e.latestSubagentRuntimeBySessionId.get(t)??null:null}function cB(e,t){return t?e.latestPendingApprovalBySessionId.get(t)??null:null}function Jg(e){const t=Date.parse(e);return Number.isFinite(t)?t:Number.NEGATIVE_INFINITY}function dB(e,t){return e?.conversationId===t}function uB(e,t){return e?.id===t?null:e}function mB(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("/"),i=a>=0?n.relativePath.slice(0,a):"";for(const r of n.resourceFiles)t.add(i?`${i}/${r}`:r)}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 pB(e){return JSON.stringify([e.source,e.repositoryId,e.profileId])}function jW(e,t){return e.profiles.find(n=>pB(n.ref)===t)?.ref??null}function fB(e,t){return!!(e&&t&&e.source===t.source&&e.repositoryId===t.repositoryId&&e.profileId===t.profileId)}function OW(e,t){return e.profiles.find(n=>fB(n.ref,t))?.state??null}function hB(e,t){const n=new Map(LT.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 i of a.skills)i.validationStatus!=="valid"||n.has(i.name)||n.set(i.name,{name:i.name,description:i.description,path:i.relativePath,scope:"profile",enabled:!0,sourcePath:a.sourcePath,charCount:i.charCount,sourceHash:i.sourceHash,validationStatus:"valid",validationMessages:[],resourceFiles:i.resourceFiles});return[...n.values()].sort((a,i)=>a.name.localeCompare(i.name))}function gB(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 NW(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 kk="openpond:last-chat-task-mode";function bB(e,t){return e==="labs"?"models":"chat"}function vB(e){try{return e.getItem(kk)==="work"?"work":"chat"}catch{return"chat"}}function _k(){if(typeof window>"u")return"chat";try{return vB(window.localStorage)}catch{return"chat"}}function yB(e,t){try{e.setItem(kk,t==="chat"?"chat":"work")}catch{}}function SB(e){if(!(typeof window>"u"))try{yB(window.localStorage,e)}catch{}}const xB="uploaded to a different account";function wk(e,t){const n=e?.linkedSandboxProject??null;if(!n?.projectId||!n.teamId)return{state:"none",linked:null,cloudProject:null};const a=t?.find(i=>i.id===n.projectId&&i.teamId===n.teamId)??null;return a?{state:"confirmed",linked:n,cloudProject:a}:{state:"different_account",linked:n,cloudProject:null}}function ma(e,t){const n=wk(e,t);return n.state==="confirmed"?n.cloudProject:null}function kB(e,t){return wk(e,t).state==="different_account"?xB:null}function Va(e){return e==="sandbox"||e==="sandbox_template"||e==="sandbox_app"}function Ik(e={}){return{...e,workspaceTarget:"hybrid"}}function _B(e={}){return{...e,workspaceTarget:"local"}}function Wa(e){return e?.metadata?.workspaceTarget==="hybrid"}function wB(e){return!!(e&&e.provider==="openpond"&&e.workspaceKind==="local_project"&&e.cloudProjectId&&e.title.trim().endsWith(" Cloud"))}function Ck({cloudProjects:e,selectedCloudProject:t,selectedProject:n}){const a=n?.linkedSandboxProject??null,i=e?ma(n,e):null,r=t?.id??i?.id??(e?null:a?.projectId??null),s=t?.teamId??i?.teamId??(e?null:a?.teamId??null);return!r||!s?{kind:"missing_cloud_project",message:"Upload/sync this Project to Cloud before using Hybrid."}:{kind:"ready",cloudProjectId:r,cloudTeamId:s,cwd:n?.workspacePath??null,localProjectId:n?.id??null,workspaceName:t?.name??i?.name??a?.projectName??n?.name??"Hybrid workspace"}}function Rk({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:Ik(),cwd:n.cwd,title:a}}function IB(e){return g.useEffect(()=>{const t=Lx(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=_U(n);try{let i;const r=e.selectedSession;if(r&&$s(r))i=await J.patchSession(e.connection,r.id,{title:a,metadata:Fu(r.metadata,n)}),e.setSessions(s=>s.map(d=>d.id===i.id?i:d));else{const s=r?.metadata?.workspaceTarget==="hybrid"?"hybrid":r?.metadata?.workspaceTarget==="local"?"local":null,d=r?.provider??(e.selectedCloudProject?"openpond":e.activeProvider),p=r?.modelRef??(d==="openpond"?{providerId:"openpond",modelId:rr}:{providerId:d,modelId:e.activeModel}),m=s?{workspaceTarget:s}:!r&&e.workspaceTarget==="local"?{workspaceTarget:"local"}:{};let h;if(!r&&e.workspaceTarget==="hybrid"){const S=Ck({cloudProjects:e.cloudProjects,selectedCloudProject:e.selectedCloudProject,selectedProject:e.selectedProject});if(S.kind!=="ready")throw new Error(S.message);const y=Rk({modelRef:p,provider:d,target:S,title:a});h={...y,experience:"work",metadata:Fu(y.metadata,n)}}else h={experience:"work",provider:d,modelRef:p,openPondCommandAccessMode:r?.openPondCommandAccessMode??e.activeOpenPondCommandAccessMode,appId:r?.appId??null,appName:r?.appName??null,workspaceKind:r?.workspaceKind??(e.selectedCloudProject?"sandbox":e.selectedProject?"local_project":void 0),workspaceId:r?.workspaceId??e.selectedCloudProject?.id??e.selectedProject?.id??null,workspaceName:r?.workspaceName??e.selectedCloudProject?.name??e.selectedProject?.name??null,localProjectId:r?.localProjectId??e.selectedProject?.id??null,cloudProjectId:r?.cloudProjectId??e.selectedCloudProject?.id??null,cloudTeamId:r?.cloudTeamId??e.selectedCloudProject?.teamId??null,cwd:r?.cwd??e.selectedProject?.workspacePath??null,metadata:Fu(m,n),title:a};i=await J.createSession(e.connection,h),e.setSessions(S=>[i,...S])}return e.composerDraftStore.set(""),e.setMentionedAppId(null),e.setSelectedSessionId(null),e.setView("chat"),e.requestComposerFocus(),e.showToast("Task draft saved.","success"),!0}catch(i){return e.showToast(i instanceof Error?i.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 CB=[];function RB({primary:e,secondary:t}){const[n,a]=g.useState(!1),i=cU(),{composerDraftStore:r,appDispatch:s,pendingTerminalCommand:d,setPendingTerminalCommand:p,terminalTabs:m,setTerminalTabs:h,trainingDetailTasksetId:S,setTrainingDetailTasksetId:y,mentionedAppId:w,setMentionedAppId:R,cloudSetupDialog:A,setCloudSetupDialog:N,rightPanelTabRequest:O,workspaceDiffPanelViewState:D,mainComposerFocusRequestId:x,requestMainComposerFocus:I,projectConfirmDialog:P,resolveProjectConfirmDialog:E,query:T,searchOpen:z,archivedChatsOpen:U,sectionMenuOpen:$,cloudProjectsExpanded:V,sidebarOpen:re,view:Q,selectedAppId:Ie,selectedProjectId:Se,selectedSessionId:G,codexPermissionMode:Ee,codexReasoningEffort:xe,busy:le,diffPanelOpen:ke,diffPanelExpanded:ae,rightPanelMode:he,activeExperience:ve,changeNewExperience:Ze,terminalOpen:Re,settingsSection:se,newProjectDialogOpen:Ce,newProjectMode:Le,newProjectName:Qe,newProjectPath:it,newProjectBusy:ut,commitDialogOpen:Fe,commitMessage:Ue,commitIncludeUnstaged:ze,commitNextStep:M,commitDraft:H,branchDialogOpen:X,branchDialogName:pe,toast:Z,labDetailNavigation:me,setQuery:_e,setSearchOpen:He,setArchivedChatsOpen:qe,setSectionMenuOpen:Xe,setCloudProjectsExpanded:at,setChatRowsVisibleCount:Pe,setSidebarOpen:Ve,setView:u,setSelectedAppId:j,setSelectedProjectId:q,setSelectedSessionId:oe,setPrompt:ne,setDraftProvider:F,setDraftModel:_,setDraftExperience:W,setDiffPanelOpen:Y,setDiffPanelExpanded:ee,setRightPanelMode:K,setTerminalOpen:ce,setSettingsSection:ue,setNewProjectDialogOpen:Ne,setNewProjectName:je,setNewProjectPath:$e,setCommitDialogOpen:Ge,setCommitMessage:We,setCommitIncludeUnstaged:mt,setCommitNextStep:qt,setCommitDraft:jt,setBranchDialogOpen:_n,setBranchDialogName:bn,setError:Xt,showToast:yt,applyBootstrapPayload:tn,bootstrap:Et,connection:St,startup:on,training:Ot,pinnedCollapsed:rn,cloudProjectsCollapsed:Tn,chatsCollapsed:pn,savedForLaterCollapsed:Ca,sidebarWidth:Ra,sidebarResizing:$t,diffPanelWidth:zn,diffPanelResizing:st,togglePinnedCollapsed:vn,toggleCloudProjectsCollapsed:Aa,toggleChatsCollapsed:Pa,toggleSavedForLaterCollapsed:aa,startSidebarResize:Ta,startDiffPanelResize:te,selectedApp:De,selectedCloudProject:Ke,selectedProject:et,selectedProjectLinkedApp:Rt,selectedSession:bt,sidebarSessions:lt,runtimeIndexes:wt,runtimeEventStore:oa,chatMentionApps:Un,connectedAppMentions:tt,pendingApproval:Sn,pendingChatUserMessages:xt,account:yn,activeModel:En,activeProvider:wn,appDefaults:Ea,startMessage:ha,organizations:Ka,teamChatOrganization:Ma,teamChatTeamId:Yn,teamChat:kt,publishTeamProfileAgent:ja,communitySidebar:ia,communityView:fi,teamAiThreadId:zo,toggleTeamAiSidebar:Uo,activeOpenPondCommandAccessMode:Ga,viewWorkspaceAppId:hi,viewWorkspaceId:gi,viewWorkspaceKind:bi,viewWorkspaceName:vi,selectedActionCatalog:Cr,expandedProjectIds:Rr,expandProject:Oa,toggleProjectExpanded:Ar,changeCodexPermissionMode:yi,changeCodexReasoningEffort:Si,changeOpenPondCommandAccessMode:xi,resolveApproval:Pr,beginNewChat:Xn,beginNewChatWithTrainingModel:Tr,dismissTrainingChatHandoff:Er,trainingChatHandoff:Mr,selectTrainingChatTaskForComposer:ki,chatHistoryLoadStates:_i,loadMoreSelectedChatHistory:wi,selectedPagedSessionEvents:jr,activeSessions:Na,archivedSessions:Za,pinnedSessions:Hn,savedForLaterSessions:Or,savedForLaterFiles:Nr,sidebarFileBookmarks:fn,setSidebarFileStatus:Ii,setSessions:qn,projectRows:ga,localProjectRows:Ja,cloudProjectRows:$a,projectSessionRowsByProjectId:$r,childSessionRowsByParentId:Dr,sidebarProjectIdBySessionId:Ya,chatRows:Ho,visibleChatRows:Ci,chatRowsVisibleCount:qo,sessionEvents:Ri,goalRuntime:Bo,subagentRuntime:Ai,visibleChatMessages:ra,activeTerminalScope:vo,terminalSummaries:Fo,runningSessionIds:Xa,selectedSessionRunning:Pi,sidebarGoalRuntimeBySessionId:Da,sidebarSubagentRuntimeBySessionId:Ti,taskDragSessionId:Lr,taskPreviewSessionIds:Vo,startTaskDrag:Ei,clearTaskDrag:Mi,previewTaskDrop:ji,commitTaskDrop:zr,commitTaskPreviewDrop:Wo,dragItem:Oi,startPinnedDrag:yo,clearSidebarDrag:La,previewPinnedDrop:Ur,commitPinnedDrop:Hr,commitPinnedPreviewDrop:qr,commandProjectRows:Br,contextWindowStatus:ba,pinnedRows:Ni,workspaceBusy:Ko,diffBusy:Fr,visibleWorkspaceState:Qa,visibleWorkspaceDiff:Mn,refreshVisibleWorkspaceDiff:Vr,managedWorkspace:Wr,canSyncActiveWorkspace:Kr,canPublishOpenPondProject:Gr,projectTarget:ft,workspaceTarget:Dt}=e,{title:Bn,browserConversationId:sn,handleWorkspaceDiffPanelViewStateChange:Qn,openSessionInChat:In,changeProjectTarget:ed,submitNewProjectDialog:td,changeWorkspaceBranch:nd,openCommitDialog:Zr,openCreateWorkspaceBranchDialog:il,openDefaultsSettingsFromBranchDialog:ad,runWorkspaceTool:od,submitCommitDialog:id,submitCreateWorkspaceBranch:rd,syncWorkspaceLocally:sd,answerCreateImproveQuestion:ld,applyCreateImproveCandidate:cd,approveCreateImproveRun:dd,cancelCreateImproveRun:ud,changeDraftProvider:rl,openCreateImprovePullRequest:md,reconcileCreateImprovePullRequest:sl,rejectCreateImproveCandidate:pd,pauseCreateImproveRun:fd,resumeCreateImproveRun:hd,reviseCreateImproveRun:ll,stopTurn:Jr,archiveSession:gd,restoreSession:bd,renameSession:cl,toggleSessionPinned:dl,toggleProjectPinned:ul,toggleSessionSavedForLater:Yr,moveProjectToCloud:vd,startCloudSetupUpload:ml,changeWorkspaceTarget:yd,sendPromptFromMainComposer:Xr,openSandboxWorkspace:Sd,openCloudProjectDialog:pl,openUrlInBrowserPanel:xd,showBrowserPanel:fl,showChangesPanel:kd,showGoalSidebarTab:_d,rightChatTrainingLaunchRequest:hl,setRightChatTrainingLaunchRequest:wd,closeRightChatPanel:Id,openRightChatPanel:Qr,rightChatPanelViews:Cd,showRightChatPanel:Rd,showRightPanelDiffTab:So,submitRightChatPrompt:gl,activateRightChatPanel:Ad,updateRightChatModel:Pd,updateRightChatPrompt:Td,updateRightChatProvider:Ed,updateRightChatScrollState:Md,openProfileSettings:jd,diagnosticEvents:Od,toggleRightSidebar:bl,removeProject:Nd}=t,$i=g.useCallback(Oe=>{j(null),q(Oe),oe(null),u("chat"),Oa(Oe),I()},[Oa,I,j,q,oe,u]),$d=g.useCallback((Oe=null)=>{const dt=G?Ya[G]??null:null;if(!Oe&&dt){$i(dt);return}Xn(Oe)},[Xn,$i,G,Ya]),Dd=g.useCallback(async Oe=>{if(!(!St||!Et))try{const dt=await J.savePreferences(St,{defaultTeamId:Oe});tn({...Et,preferences:dt.preferences})}catch(dt){const Pt=dt instanceof Error?dt.message:String(dt);throw Xt(Pt),yt("Could not switch teams","error"),dt}},[tn,Et,St,Xt,yt]),Ld=g.useCallback(async()=>{if(St)try{const Oe=await J.signOutOpenPondAccount(St);tn(Oe);const dt=await J.savePreferences(St,{defaultTeamId:null});tn({...Oe,preferences:dt.preferences}),yt("Logged out","success")}catch(Oe){const dt=Oe instanceof Error?Oe.message:String(Oe);throw Xt(dt),yt("Could not log out","error"),Oe}},[tn,St,Xt,yt]),es=Yn??Ea.defaultTeamId??null,zd=g.useMemo(()=>ga.filter(Oe=>Oe.kind==="local"||es!==null&&Oe.project.teamId===es),[ga,es]),Ud=g.useMemo(()=>{const Oe={};for(const dt of Na){const Pt=Ya[dt.id];Pt&&(Oe[Pt]=(Oe[Pt]??0)+1)}for(const dt of Ja){if(dt.kind!=="local")continue;const Pt=dt.project.linkedSandboxProject?.projectId;if(!Pt||!dt.cloudLinkTrusted)continue;const sa=vt("cloud",Pt);Oe[dt.id]=(Oe[dt.id]??0)+(Oe[sa]??0)}return Oe},[Na,Ja,Ya]),[ts,ns]=g.useState(null),[as,os]=g.useState(null),Hd=hB(Et?.profile,Et?.extensionCatalog),[is,rs]=g.useState(null),[ss,vl]=g.useState(null),[za,ls]=g.useState(null),yl=g.useCallback(()=>{j(null),q(null),oe(null),Xe(null),u("team")},[Xe,j,q,oe,u]),qd=g.useCallback(()=>{j(null),q(null),oe(null),Xe(null),ia.discoverCommunities()},[ia.discoverCommunities,Xe,j,q,oe]),cs=IB({activeExperience:ve,activeModel:En,activeOpenPondCommandAccessMode:Ga,activeProvider:wn,cloudProjects:Et?.cloudProjects??CB,composerDraftStore:r,connection:St,requestComposerFocus:I,selectedCloudProject:Ke,selectedProject:et,selectedSession:bt,setMentionedAppId:R,setSelectedSessionId:oe,setSessions:qn,setView:u,showToast:yt,workspaceTarget:Dt.value}),Bd=g.useCallback(async Oe=>{if(!St)throw new Error("OpenPond is not connected.");let dt=wn,Pt=En;dt==="codex"&&(dt=Wm(Et?.providers,{enabledOnly:!0}).find(hn=>hn.value!=="codex")?.value??oi,Pt=lc(dt,Et?.providers)??Ps);const sa=lt.find(hn=>hn.id===Oe.sourceSessionId),eo=await J.createSession(St,{experience:Oe.target,provider:dt,modelRef:{providerId:dt,modelId:Pt},openPondCommandAccessMode:Ga,appId:null,appName:null,workspaceId:null,workspaceName:null,localProjectId:null,cloudProjectId:null,cloudTeamId:null,cwd:null,title:`Continue ${sa?.title??"task"}`.slice(0,120),metadata:{experienceHandoff:gB({sourceTaskId:Oe.sourceSessionId,sourceExperience:sa?.experience??null,targetExperience:Oe.target,sourceMessageIds:Oe.sourceMessageIds??[],sourceContext:Oe.sourceContext,output:Oe.output})}});return qn(hn=>[eo,...hn]),W(Oe.target),F(dt),_(Pt),r.set(Oe.prompt),an({kind:"chat",sessionId:eo.id}),s({type:"selectSession",sessionId:eo.id,appId:null,projectId:null}),j(null),q(null),ce(!1),u("chat"),K("home"),Y(Oe.target==="work"),ee(!1),eo},[En,Ga,wn,s,Et?.providers,r,St,ee,Y,W,_,F,K,j,q,qn,ce,u,lt]),Sl=g.useCallback(Oe=>{rs(Oe),vl(null),Xn(null),Ve(!0)},[Xn,Ve]),Fd=g.useCallback(Oe=>{Xn(null),W("work"),r.set(`$openpond-refiner-authoring ${Oe}`),u("chat"),Ve(!0)},[Xn,r,W,Ve,u]),Go=g.useCallback(Oe=>{vl(mB(Oe)),rs(null),Xn(null),Ve(!0)},[Xn,Ve]);g.useEffect(()=>{!is&&!ss||Q!=="chat"||G||Se||Ie||(ns(is),os(ss),rs(null),vl(null),K("home"),ee(!1),Y(!0))},[is,ss,Ie,Se,G,ee,Y,K,Q]),g.useEffect(()=>{!ts&&!as||Q==="chat"&&ke&&he==="home"||(ns(null),os(null))},[ke,as,ts,he,Q]);const Vd=g.useCallback(()=>{ns(null),os(null),ee(!1),Y(!1)},[ee,Y]),Wd=g.useCallback(Oe=>{let dt;if(Oe.workspaceKind==="local"){const Pt=vt("local",Oe.workspaceId);dt=`draft:${Pt}`,j(null),q(Pt),oe(null),Oa(Pt),u("chat")}else{const Pt=lt.find(sa=>sa.id===Oe.sourceSessionId||sa.workspaceId===Oe.workspaceId);if(!Pt){yt("This saved file's cloud chat is no longer available.","error");return}dt=Pt.id,In(Pt.id)}K("changes"),Y(!0),ls({id:Date.now(),conversationId:dt,file:Oe}),Oe.available||yt(`File unavailable: ${Oe.path}`,"error")},[Oa,In,Y,K,j,q,oe,u,yt,lt]);g.useEffect(()=>{if(!dB(za,sn))return;const Oe=window.setTimeout(()=>{K("changes"),Y(!0),ls(dt=>uB(dt,za.id))},0);return()=>window.clearTimeout(Oe)},[sn,Y,K,za]);const Kd=bB(Q);g.useEffect(()=>{if(i){if(i.kind==="models"){Q!=="labs"&&u("labs");return}if(i.kind==="settings"){j(null),q(null),oe(null),ue(i.section),Q!=="settings"&&u("settings");return}if(i.kind==="view"){j(null),q(null),oe(null),Q!==i.view&&u(i.view);return}i.sessionId!==null&&(j(null),q(null)),oe(i.sessionId),Q!=="chat"&&u("chat")}},[i,j,q,oe,ue,u,Q]);const Gd=g.useCallback(Oe=>{if(Xe(null),j(null),q(null),oe(null),Oe==="models"){Ro({kind:"index"}),u("labs");return}Oe==="chat"&&an({kind:"chat",sessionId:null}),Ze(_k())},[Ze,an,Xe,j,q,oe,u]),Zd=g.useCallback(async(Oe,dt)=>{const Pt=await Ot.actions.acceptHarnessReview(Oe,dt,{providerId:wn,modelId:En},xe);return Pt?(y(Pt.materializedTasksetId??null),Ro({kind:"index"}),u("labs"),!0):(yt("Taskset review could not be opened.","error"),!1)},[En,wn,xe,Ro,y,u,yt,Ot.actions]);if(!on.ready)return v.jsx(Pq,{startup:on});if(Q==="settings")return v.jsx(qg,{showToast:yt,children:v.jsx(Iq,{settings:{payload:Et,connection:St,diagnostics:Od,initialSection:se,onPayload:tn,onError:Xt,onToast:yt,onOpenSourceSession:In,onStartRefinerAuthoring:Fd,onAcceptEvaluationReview:Zd,onOpenSkill:Sl,onOpenExtension:Go,teamChatCurrentUserId:kt.currentUserId,teamChatEnabled:Yn!==null,teamChatNotificationMode:kt.notificationMode,teamChatThreads:kt.threads,onTeamChatNotificationModeChange:kt.setNotificationMode,onTeamChatThreadMuteChange:kt.setThreadMuted,diffPanelWidth:zn,diffPanelResizing:st,diffPanelExpanded:ae,onDiffPanelResizeStart:te,onDiffPanelExpandedChange:ee,onBack:()=>{an({kind:"chat",sessionId:null}),u("chat"),Ve(!0)}},toast:{toast:Z,onDismiss:()=>s({type:"field",key:"toast",value:null})}})});const Jd=Fc(),ds=St?.platform??navigator.platform,xl=Jd&&Sf(ds),us=vo,Yd=Qa?.initialized?Qa.repoPath:bt?.cwd??null,Xd={"--sidebar-width":`${Ra}px`,"--diff-panel-width":`${zn}px`},Qd=Q==="chat"&&ve!=="chat"||Q==="labs"||Q==="scheduled"&&n||Q==="team"&&!!zo,eu=["app-shell",xl?"platform-macos":"",re?"sidebar-open":"sidebar-closed",$t?"sidebar-resizing":"",st?"diff-panel-resizing":""].filter(Boolean).join(" "),rt=G?_i[G]:null,Bt=G?rt?.cursorSequence??Mq(ro(jr,nl(wt,G))):null,zt=!!G&&!!St&&(Nt(G)?!0:!!Et?.eventWindow?.hasMoreBefore&&!!Bt)&&(rt?.hasMore??!0),va=!!rt?.loading,tu=(()=>{const Oe=Ot.payload;if(!Oe)return{};const dt=new Map(Oe.plans.map(hn=>[hn.id,hn])),Pt=new Set(["queued","starting","running","cancelling","reconciling"]),sa={queued:"Queued",starting:"Starting",running:"Running",cancelling:"Cancelling",reconciling:"Reconciling"},eo={};for(const hn of[...Oe.modelRuns].sort((ya,Di)=>Di.updatedAt.localeCompare(ya.updatedAt))){if(hn.kind==="evaluation"||!["prepared","running"].includes(hn.status))continue;const ya=Oe.jobs.filter(nu=>nu.metadata.modelRunId===hn.id).sort((nu,N_)=>N_.updatedAt.localeCompare(nu.updatedAt))[0];if(ya&&!Pt.has(ya.status))continue;const Di=ya?.status??(hn.status==="prepared"?"starting":"running");eo[hn.modelId]={label:sa[Di]??"Running",status:Di}}for(const hn of[...Oe.jobs].sort((ya,Di)=>Di.updatedAt.localeCompare(ya.updatedAt))){if(!Pt.has(hn.status))continue;const ya=dt.get(hn.planId)?.modelId;!ya||eo[ya]||(eo[ya]={label:sa[hn.status]??"Active",status:hn.status})}return eo})();return v.jsx(qg,{showToast:yt,children:v.jsx(wq,{className:eu,style:Xd,sidebar:{productArea:Kd,modelProjects:(Ot.payload?.modelProjects??[]).filter(Oe=>Oe.hosted===null||Oe.hosted.teamId===(Ea.defaultTeamId?.trim()??null)),modelTrainingActivityByProjectId:tu,onProductAreaChange:Gd,experience:ve,view:Q,selectedAppId:Ie,selectedProjectId:Se,selectedSessionId:G,selectedTeamThreadId:kt.selectedThreadId,teamChatEnabled:Yn!==null,organizations:Ka,teamChatOrganization:Ma,teamChatLoading:kt.loading,currentUserId:kt.currentUserId,teamMembers:kt.members,teamThreads:kt.threads,...ia,account:yn,connection:St,profile:Et?.profile,pinnedCollapsed:rn,cloudProjectsCollapsed:Tn,chatsCollapsed:pn,savedForLaterCollapsed:Ca,archivedChatsOpen:U,cloudProjectsExpanded:V,sectionMenuOpen:$,dragItem:Oi,taskDragSessionId:Lr,taskPreviewSessionIds:Vo,activeSessions:Na,archivedSessions:Za,pinnedRows:Ni,pinnedSessions:Hn,savedForLaterSessions:Or,savedForLaterFiles:Nr,projectRows:ga,localProjectRows:Ja,cloudProjectRows:$a,projectSessionRowsByProjectId:$r,childSessionRowsByParentId:Dr,sidebarProjectIdBySessionId:Ya,terminalSummaries:Fo,runningSessionIds:Xa,goalRuntimeBySessionId:Da,subagentRuntimeBySessionId:Ti,visibleChatRows:Ci,chatRows:Ho,chatRowsVisibleCount:qo,expandedProjectIds:Rr,currentVersion:Et?.server.version??null,platform:ds,arch:St?.arch??null,onSidebarResizeStart:Ta,setSidebarOpen:Ve,setView:u,setSelectedAppId:j,setSelectedProjectId:q,setSelectedSessionId:oe,setSearchOpen:He,setSectionMenuOpen:Xe,setSettingsSection:ue,onSelectTeam:Dd,onLogOut:Ld,onTogglePinnedCollapsed:vn,onToggleCloudProjectsCollapsed:Aa,onToggleChatsCollapsed:Pa,onToggleSavedForLaterCollapsed:aa,setArchivedChatsOpen:qe,setCloudProjectsExpanded:at,setChatRowsVisibleCount:Pe,beginNewChat:$d,beginProjectChat:$i,dockSessionRight:Qr,selectTeamThread:Oe=>{u("team"),kt.selectThread(Oe)},openTeamDm:Oe=>{u("team"),kt.openDm(Oe)},toggleSessionPinned:dl,toggleProjectPinned:ul,toggleSessionSavedForLater:Yr,openSidebarFile:Wd,setSidebarFileStatus:(Oe,dt)=>{Ii(Oe,dt)},archiveSession:gd,restoreSession:bd,renameSession:cl,removeProject:Nd,expandProject:Oa,toggleProjectExpanded:Ar,startPinnedDrag:yo,clearSidebarDrag:La,previewPinnedDrop:Ur,commitPinnedDrop:Hr,commitPinnedPreviewDrop:qr,startTaskDrag:Ei,clearTaskDrag:Mi,previewTaskDrop:ji,commitTaskDrop:zr,commitTaskPreviewDrop:Wo},topBar:{sidebarOpen:re,title:Bn,backAction:me.backAction,breadcrumbs:me.breadcrumbs,conversationId:Q==="chat"?G:null,workspaceName:vi,workspaceId:gi,busy:le,workspaceState:Qa,workspaceKind:bi,selectedApp:Rt??De,selectedProject:et,workspaceDiff:Mn,managedWorkspace:Wr,workspaceBusy:Ko,defaultTeamId:Ea.defaultTeamId,showDiffControls:Q==="chat"&&ve==="development",diffPanelOpen:ke,terminalOpen:Re,rightSidebarAvailable:Qd,rightSidebarOpen:Q==="scheduled"?n:ke,onToggleDiffPanel:bl,onToggleRightSidebar:Q==="scheduled"?()=>a(Oe=>!Oe):Q==="team"&&zo?Uo:bl,onOpenSearch:()=>{Xe(null),He(!0)},onToggleTerminal:()=>ce(Oe=>!Oe),onRunTerminalCommand:Oe=>{p({id:Date.now(),scope:us,command:Oe}),ce(!0)},onWorkspaceToolAction:od,onOpenCommitDialog:Zr,onWorkspaceBranchChange:nd,onWorkspaceBranchCreate:il,connection:St,onBootstrap:tn,onOpenSandboxWorkspace:Sd,onShowSidebar:()=>Ve(!0),onOpenTeamChat:yl,onDiscoverCommunities:qd,collaborationView:Q==="team"||Q==="community"?Q:null,platform:ds,showWorkspaceControls:Q!=="team"&&Q!=="community"&&Q!=="labs"&&Q!=="scheduled"&&Q!=="outputs"&&Q!=="projects"&&(ve==="development"||ve==="work"&&!!(et||bt?.localProjectId||bt?.cloudProjectId||bt?.workspaceKind==="local_project"))},mainPane:{experience:ve,onNewExperienceChange:Ze,view:Q,teamChat:{currentUserId:kt.currentUserId,members:kt.members,agents:kt.agents,profile:Et?.profile??null,teamId:Yn,teamName:Ma?.displayName??null,detail:kt.detail,aiThread:kt.aiThread,agentConversation:kt.agentConversation,loading:kt.loading,busy:kt.busy,error:kt.error,connection:St,providerSettings:Et?.providers??null,provider:wn,model:En,codexPermissionMode:Ee,codexReasoningEffort:xe,openPondCommandAccessMode:Ga,contextWindowStatus:ba,showToast:yt,onProviderChange:rl,onModelChange:_,onCodexPermissionModeChange:yi,onCodexReasoningEffortChange:Si,onOpenPondCommandAccessModeChange:xi,onOpenProviderSettings:()=>{ue("providers"),u("settings"),an({kind:"settings",section:"providers"})},onSendMessage:kt.sendMessage,onPublishProfileAgent:ja,onOpenAiThread:async Oe=>{await kt.openAiThread(Oe),K("chat"),Y(!0)},onOpenAgentConversation:async Oe=>{await kt.openAgentConversation(Oe),K("chat"),Y(!0)},onCloseAiThread:()=>Y(!1),onCloseAgentConversation:()=>{kt.closeAgentConversation(),Y(!1)},onSendAgentTurn:kt.sendAgentTurn,onSendAiTurn:kt.sendAiTurn,onStopAiTurn:kt.stopAiTurn,onEditMessage:kt.editMessage,onDeleteMessage:kt.deleteMessage,onRetryMessage:kt.retryMessage,onDismissFailedMessage:kt.dismissFailedMessage,onLoadMoreMessages:kt.loadMoreMessages,onRetryLoad:kt.refresh},community:fi,bootstrap:Et,runtimeEvents:Ri,chatMessages:ra,pendingUserMessage:G?xt[G]??null:null,contextWindowStatus:ba,goalRuntime:Bo,subagentRuntime:Ai,selectedSessionId:G,composerDraftStore:r,mainComposerFocusRequestId:x,labCloseDetailRequestId:me.closeDetailRequestId,labCloseDetailKind:me.closeDetailKind,sideChatTrainingLaunchRequest:hl,onSideChatTrainingLaunchHandled:Oe=>wd(dt=>dt?.id===Oe?null:dt),mentionApps:Un,connectedAppMentions:tt,profileSkills:Hd,selectedMentionAppId:w,busy:le,turnRunning:Pi,activeProvider:wn,activeModel:En,codexPermissionMode:Ee,codexReasoningEffort:xe,openPondCommandAccessMode:Ga,pendingApproval:Sn,activeWorkspaceAppId:hi,activeWorkspaceId:gi,activeWorkspaceKind:bi,projectTarget:ft,actionCatalog:Cr,workspaceTarget:Dt,connection:St,workspaceName:vi,workspaceState:Qa,workspaceDiff:Mn,workspaceBusy:Ko,diffBusy:Fr,forceChatThread:!!G,diffPanelOpen:ke,diffPanelExpanded:ae,rightPanelMode:he,rightPanelTabRequest:O,rightChatPanels:Cd,runtimeEventStore:oa,nativeSkillSidebar:ts,extensionSkillSidebar:as,workspaceDiffPanelViewState:D,sidebarFileOpenRequest:za,sidebarFileBookmarks:fn,onSetSidebarFileStatus:(Oe,dt)=>{Ii(Oe,dt)},browserConversationId:sn,terminalScope:us,terminalTabs:m,terminalCwd:Yd,pendingTerminalCommand:d,terminalOpen:Re,onToggleTerminal:()=>ce(Oe=>!Oe),onWorkspaceDiffPanelViewStateChange:Qn,training:Ot,trainingSessions:lt,trainingChatHandoff:Mr,trainingDetailTasksetId:S,onTrainingDetailTasksetIdChange:y,onTrainingChatTaskSelect:ki,onTrainingChatHandoffDismiss:Er,onOpenSession:In,onExperienceHandoff:Bd,cloudProjects:Et?.cloudProjects??[],projects:zd,projectsAccountBaseUrl:yn?.baseUrl??yn?.activeProfile?.baseUrl??null,projectsTeamName:Ma?.displayName??null,projectTaskCounts:Ud,onNewCloudProject:pl,onNewProjectTask:Oe=>$i(Oe.id),onToggleProjectPinned:ul,onUploadLocalProject:vd,chatHistoryHasMore:zt,chatHistoryLoading:va,onDiffPanelResizeStart:te,onToggleDiffPanelExpanded:()=>ee(Oe=>!Oe),onShowDiffPanel:kd,onShowBrowserPanel:fl,onShowFilesPanel:()=>So("files"),onShowGoalSidebarTab:_d,onShowTrainingDraftPanel:()=>{K("training"),Y(!0)},onShowRightChatPanel:Rd,onAddRightChat:()=>Qr(null),onOpenRightChatForSession:(Oe,dt)=>{const Pt=dt??lt.find(sa=>sa.id===Oe)??null;Pt&&Qr(Pt,{preserveView:!0})},onLabDetailOpenChange:me.onDetailOpenChange,scheduledDetailOpen:n,onScheduledDetailOpenChange:a,onTerminalTabsChange:h,onCloseRightChatPanel:Id,onCloseNativeSkillSidebar:Vd,onActivateRightChatPanel:Ad,onRightChatModelChange:Pd,onRightChatPromptChange:Td,onRightChatScrollStateChange:Md,onRightChatProviderChange:Ed,onSubmitRightChat:gl,onStopRightChat:Oe=>Jr(Oe),onCloseTerminal:()=>ce(!1),onLoadMoreChatHistory:wi,canSyncWorkspace:Kr,startMessage:ha,onPayload:tn,onError:Xt,setView:u,onOpenProfileSettings:jd,onOpenProviderSettings:()=>{ue("providers"),u("settings"),an({kind:"settings",section:"providers"})},onOpenTrainingSettings:()=>{ue("training"),u("settings"),an({kind:"settings",section:"training"})},onOpenDatasetStorageSettings:()=>{ue("dataset-storage"),u("settings"),an({kind:"settings",section:"dataset-storage"})},changeDraftProvider:rl,changeProjectTarget:ed,changeWorkspaceTarget:yd,setDraftProvider:F,setDraftModel:_,onBeginNewChatWithModel:Tr,changeCodexPermissionMode:yi,changeCodexReasoningEffort:Si,changeOpenPondCommandAccessMode:xi,resolveApproval:Pr,answerCreateImproveQuestion:ld,applyCreateImproveCandidate:cd,approveCreateImproveRun:dd,cancelCreateImproveRun:ud,openCreateImprovePullRequest:md,reconcileCreateImprovePullRequest:sl,rejectCreateImproveCandidate:pd,pauseCreateImproveRun:fd,resumeCreateImproveRun:hd,reviseCreateImproveRun:ll,setMentionedAppId:R,showToast:yt,onSaveTaskDraft:cs,sendPrompt:Xr,stopTurn:Oe=>Jr(void 0,Oe),syncWorkspaceLocally:sd,refreshWorkspaceDiff:Vr},cloudSetup:{state:A,onClose:()=>N(null),onOpenBrowserUrl:xd,onStart:()=>{ml()}},projectConfirm:{state:P,onResolve:E},lazyPanels:{activeSessions:Na,branchDialogName:pe,branchDialogOpen:X,commitDialogOpen:Fe,commitDraft:H,commitIncludeUnstaged:ze,commitMessage:Ue,commitNextStep:M,canPublishOpenPondProject:Gr,connection:St,expandProject:Oa,newProjectBusy:ut,newProjectDialogOpen:Ce,newProjectDirectory:Ea.defaultNewProjectDirectory,newProjectMode:Le,newProjectName:Qe,newProjectPath:it,projectRows:Br,query:T,searchOpen:z,visibleWorkspaceDiff:Mn,visibleWorkspaceState:Qa,workspaceBusy:Ko,appDispatch:s,beginNewChat:()=>Xn(null),openDefaultsSettingsFromBranchDialog:ad,setBranchDialogName:bn,setBranchDialogOpen:_n,setCommitDialogOpen:Ge,setCommitDraft:jt,setCommitIncludeUnstaged:mt,setCommitMessage:We,setCommitNextStep:qt,setNewProjectDialogOpen:Ne,setNewProjectName:je,setNewProjectPath:$e,setPrompt:ne,setQuery:_e,setSearchOpen:He,submitCommitDialog:id,submitCreateWorkspaceBranch:rd,submitNewProjectDialog:td},toast:{toast:Z,onDismiss:()=>s({type:"field",key:"toast",value:null})}})})}const Yi=new Map,Gl=new Map;function Xm(e){if(!e||e.state!=="signed_in")return null;const t=e.accounts.find(i=>i.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 AB(e){const t=e?.trim();if(!t)return null;const n=Yi.get(t);return n?.updatedAt?n.organizations:null}function PB(e,t){const n=e?.trim();if(n){Yi.set(n,{organizations:t,promise:null,updatedAt:Date.now()});for(const a of Gl.get(n)??[])a()}}function TB(e,t){const n=e?.trim();if(!n)return()=>{};const a=Gl.get(n)??new Set;return a.add(t),Gl.set(n,a),()=>{a.delete(t),a.size===0&&Gl.delete(n)}}function Yg(e){const t=e.accountKey?.trim();if(!t)return Promise.resolve([]);const n=Yi.get(t);if(!e.force){if(n?.updatedAt)return Promise.resolve(n.organizations);if(n?.promise)return n.promise}const a=e.fetchOrganizations().then(i=>(PB(t,i),i)).catch(i=>{const r=Yi.get(t);throw r?.promise===a&&Yi.set(t,{organizations:r.organizations,promise:null,updatedAt:r.updatedAt}),i});return Yi.set(t,{organizations:n?.organizations??[],promise:a,updatedAt:n?.updatedAt??0}),a}const $W="openpond.config.json";function DW(e,t,n){return t<=0?-1:n==="Home"?0:n==="End"?t-1:n==="ArrowRight"?(e+1)%t:(e-1+t)%t}function Ak(){return{activeTab:"files",openFilePaths:[],selectedPath:null}}function Ju(e){return{activeTab:e.activeTab,openFilePaths:[...e.openFilePaths],selectedPath:e.selectedPath}}function LW(e,t=null){const n=MB(e.openFilePaths.map(i=>Qg(i,t)).filter(Boolean)),a=e.selectedPath&&Qg(e.selectedPath,t)||null;return{activeTab:e.activeTab==="file"&&!a?"files":e.activeTab,openFilePaths:n,selectedPath:a}}function Xg(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 Qg(e,t=null){let n=EB(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 i=a.split("/").filter(Boolean).at(-1);return i&&n.startsWith(`${i}/`)&&(n=n.slice(i.length+1)),n}function zW(e){return e.startsWith("/")||/^[A-Za-z]:\//.test(e)}function UW(e){return{path:e,status:"unchanged",additions:0,deletions:0,patch:"",content:null}}function HW(e,t){const n=eb(e.path);return!n||e.path.endsWith("/")||e.content==null&&/Could not access .+\/null['"]?/.test(e.patch)?!0:t.some(a=>{const i=eb(a);return!!(i&&i.startsWith(`${n}/`))})}function qW(e){return/\.(?:md|markdown|mdx)$/i.test(e)||/(?:^|\/)readme$/i.test(e)}function BW(e){return/\.(?:doc|docx|pdf)$/i.test(e)}function EB(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 MB(e){return Array.from(new Set(e))}function eb(e){const n=e.replace(/\\/g,"/").replace(/^\.\/+/,"").split("/").filter(Boolean);return n.length===0?null:n.join("/")}function jB(e){if(!e||e.state!=="signed_in")return null;const t=e.accounts.find(d=>d.isActive)??null,n=e.profile?.id?.trim()??"",a=e.activeProfile?.handle?.trim()||t?.handle?.trim()||e.label.trim()||"signed_in",i=e.activeProfile?.baseUrl??t?.baseUrl??e.baseUrl??"",r=e.apiBaseUrl??t?.apiBaseUrl??"",s=e.chatApiBaseUrl??t?.chatApiBaseUrl??"";return[n?`profile:${n}`:"profile:unknown",a,i,r,s].join("|")}function Pk(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"cloud-project"}function OB(e){const t=new TextEncoder().encode(e);let n="";for(const a of t)n+=String.fromCharCode(a);return btoa(n)}function Wc(e){const t=e,n=t.teamId||t.id||"";if(!n)return null;const a=t.displayName||t.name||n,i=t.workspaceKind==="personal"||t.isPersonalDefault===!0||t.kind==="personal_default"||t.name?.trim().toLowerCase()==="personal";return{teamId:n,slug:t.slug||Pk(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:i?"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:i,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 NB(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 $B(e,t){const n=e.filter(i=>i.status==="active"&&i.workspaceKind==="shared"),a=t?.trim()??"";if(a){const i=n.find(r=>r.teamId===a);if(i)return i}return n.find(i=>i.role==="owner")??n.find(i=>i.role==="admin")??n[0]??null}function DB(...e){for(const t of e){const n=t?.trim();if(n)return n}return""}function LB({draftProvider:e,hasSelectedCloudProject:t,selectedSessionHybridWorkspace:n}){return t&&!n?"openpond":e}const zB=[{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 UB(...e){return DB(...e.map(t=>{const n=t?.trim();return n&&!n.includes("@")?n:null}))}function HB(e){if(e?.state!=="signed_in")return"";const t=e.accounts.find(n=>n.isActive)??null;return UB(e.profile?.name,e.label,t?.displayLabel,e.profile?.handle,t?.handle,e.activeProfile?.handle)}function qB({bootstrap:e,draftModel:t,draftProvider:n,selectedApp:a,selectedAppId:i,selectedCloudProject:r,selectedProject:s,selectedSession:d,selectedSessionId:p,selectedSessionLinkedProject:m}){const h=d?.workspaceKind==="local_project"?d.workspaceId??null:m?.id??null,S=Nt(p)&&!d,y=d?Va(d.workspaceKind):!1,w=Wa(d),R=d?wB(d):!1,A=d?.cwd&&(!y||w)?y0(d.cwd):null,N=e?.providers??null,O=ma(s,e?.cloudProjects??[]),D=LB({draftProvider:n,hasSelectedCloudProject:!!r,selectedSessionHybridWorkspace:w}),x=Do(D,t,N),I=ta(e?.preferences),P=S?null:d?y?d.workspaceKind??"sandbox":R?"sandbox":h?"local_project":d.workspaceKind??(d.appId?"sandbox_app":A?"local_project":null):r?"sandbox":s?"local_project":i?"sandbox_app":null,E=S?null:d?y&&!w||R?null:h||(d.workspaceId??d.appId??A):r?null:s?.id??i,T=S?null:d?y?d.workspaceId??null:R?null:h??d.workspaceId??d.appId??A:r?null:s?.id??i,z=e?.account??null,U=!e||z?.state==="loading"||z?.state==="switching",$=!U&&z?.state==="signed_out",V=U?null:$?"Sign in":z?.label??z?.activeProfile?.handle??"Account",re=HB(z),Q=re?`Welcome, ${re}`:"Welcome",Ie=d?.workspaceName??d?.appName??r?.name??s?.name??a?.name??null,Se=Va(P)?"cloud":"local",G=s?.name??m?.name??(d?.workspaceKind==="local_project"?d.workspaceName:null)??"Local workspace",Ee=(Se==="cloud"?Ie:null)??r?.name??O?.name??s?.name??"Cloud workspace",xe=!!(r?.id||O?.id||d?.cloudProjectId||Se==="cloud");return{account:z,accountLabel:V,accountPending:U,accountSignedOut:$,activeModel:x,activeProvider:D,activeWorkspaceAppId:E,activeWorkspaceId:T,activeWorkspaceKind:P,activeWorkspaceLocation:Se,appDefaults:I,cloudLinked:xe,cloudTargetName:Ee,localTargetName:G,selectedCodexHistoryPending:S,selectedSessionCloudWorkspace:y,selectedSessionLocalPathWorkspaceId:A,selectedSessionPendingCloudStart:R,selectedSessionProjectId:h,startMessage:Q,workspaceName:Ie}}function BB({accountPending:e,accountSignedOut:t,activeWorkspaceLocation:n,bootstrap:a,busy:i,cloudLinked:r,selectedCloudProject:s,selectedProject:d,selectedSession:p,pendingWorkspaceTarget:m,workspaceStates:h,workspaceBusy:S}){const y=ma(d,a?.cloudProjects??[]),R=!!!d?.linkedSandboxProject?.projectId||!!y,A=g.useMemo(()=>{const T=(a?.localProjects??[]).map(V=>({value:`local:${V.id}`,label:V.name,detail:V.workspacePath,kind:"local"})),z=(a?.cloudProjects??[]).map(V=>({value:`cloud:${V.id}`,label:V.name,detail:V.organizationName??V.sourceLabel??"OpenPond Cloud",kind:"cloud"})),U=d?`local:${d.id}`:s?`cloud:${s.id}`:"none",$=[...T,...z].find(V=>V.value===U)??null;return{value:U,label:$?.label??"Select Project",detail:$?.detail??"Choose a project for local or cloud work",busy:S||i,options:[...T,...z,...zB,{value:"none",label:"Don't work in a project",detail:"General chat without project files",kind:"none"}]}},[a?.cloudProjects,a?.localProjects,i,s,d,S]),N=!!(r||d),O=!!(s?.id||y?.id||p?.cloudProjectId||Wa(p)),D=d?h[d.id]??null:null,x=Vx(D,{branch:d?.linkedSandboxProject?.defaultBranch??null,path:d?.workspacePath??p?.cwd??null,linkedCloudSourceKnown:d?.linkedSandboxProject?.projectId&&R?!!d.linkedSandboxProject.lastUploadedCommit||!D?.headCommit:!0}),I=Wx(d,s??y,D,{cloudLinkTrusted:R}),P=UU(d,D,{cloudLinkTrusted:R}),E=g.useMemo(()=>{const T={value:"local",label:d?"Local checkout":"Local",detail:d?"Use the selected checkout on this machine.":"Use an app-managed task workspace on this machine.",stateNote:d?x:"App-managed local task workspace",disabled:!1,disabledReason:null},z={value:"hybrid",label:"Hybrid",detail:"Use your selected model with hosted sandbox edits.",stateNote:O?I:"upload required",disabled:e||t||!O,disabledReason:t?"Add an OpenPond account before using Hybrid.":"Upload/sync this Project to Cloud before using Hybrid."},U={value:"cloud",label:"Hosted",detail:"Run with hosted compute, with or without a Project.",stateNote:d||s?I:"Projectless hosted task",disabled:e||t,disabledReason:t?"Add an OpenPond account before using Cloud.":e?"Checking OpenPond account.":null},$={value:"upload_cloud",label:"Upload/sync to cloud",detail:"Push local source to OpenPond Git before cloud work.",stateNote:P,disabled:e||t||!d,disabledReason:t?"Add an OpenPond account before uploading source.":"Select a local Project before uploading source."},V=n==="cloud"?"local":"cloud",re=V==="local"?T:U;let Q=n==="cloud"?U:T;return m==="cloud"?Q=U:m==="local"?Q=T:(Wa(p)||m==="hybrid")&&(Q=z),{value:Q.value,label:Q.label,detail:Q.stateNote||Q.detail,busy:S,action:{...re,label:V==="cloud"?"Hosted":d?"Local checkout":"Check out locally"},uploadAction:d?$:null,options:[T,z,U]}},[n,e,t,r,N,I,O,x,m,d,p,P,S]);return{projectTarget:A,workspaceTarget:E}}function An(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")}function Tk(e){return An(e.name||e.gitRepo||e.id)}function FW(e){return`@${Tk(e)}`}function Ek(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>An(t[1]??"")).filter(Boolean)}function FB(e,t){const n=Ek(e);if(n.length===0)return!1;const a=new Set([An(t.id),Tk(t),t.gitRepo?An(t.gitRepo):""].filter(Boolean));return n.some(i=>a.has(i))}function Mk(e){return e.filter(t=>t.sandbox)}function VB(e,t){const n=Ek(e);if(n.length===0)return null;const a=new Map;for(const i of n){const r=t.find(s=>{const d=An(s.id),p=An(s.name),m=s.gitRepo?An(s.gitRepo):"";return i===d||i===p||i===m});r&&a.set(r.id,r)}return a.size===1?Array.from(a.values())[0]??null:null}function VW(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 i=n.slice(a.index).indexOf("@");return i<0?null:{query:An(a[1]??""),start:a.index+i}}function WB(e){return new Set(e.map(t=>t.id))}function tb(e,t){const n=e?.linkedOpenPondApp??null;return n?.appId&&t.has(n.appId)?n:null}function KB({bootstrap:e,codexHistorySessions:t,selectedProjectId:n,selectedSessionId:a,selectedAppId:i,sessions:r}){const s=g.useMemo(()=>e?.apps.find($=>$.id===i)??null,[e?.apps,i]),d=g.useMemo(()=>new Map((e?.localProjects??[]).map($=>[$.id,$])),[e?.localProjects]),p=g.useMemo(()=>new Map((e?.cloudProjects??[]).map($=>[$.id,$])),[e?.cloudProjects]),m=g.useMemo(()=>jx(n),[n]),h=g.useMemo(()=>m?.kind==="local"?d.get(m.id)??null:null,[d,m]),S=g.useMemo(()=>m?.kind==="cloud"?p.get(m.id)??null:null,[p,m]),y=g.useMemo(()=>WB(e?.apps??[]),[e?.apps]),w=g.useMemo(()=>Mk(e?.apps??[]),[e?.apps]),R=g.useMemo(()=>{const $=[];for(const V of e?.localProjects??[]){const re=tb(V,y);re&&$.push([re.appId,V.id])}return new Map($)},[e?.localProjects,y]),A=g.useMemo(()=>new Set((e?.localProjects??[]).map($=>$.id)),[e?.localProjects]),N=g.useMemo(()=>zx(e?.localProjects??[]),[e?.localProjects]),O=g.useRef([]),D=g.useMemo(()=>GB(r,t,O.current),[t,r]),x=g.useMemo(()=>D.find($=>$.id===a)??null,[D,a]),I=g.useMemo(()=>{if(!x)return null;if(x.localProjectId)return d.get(x.localProjectId)??null;if(x.workspaceKind==="local_project")return x.workspaceId?d.get(x.workspaceId)??null:null;const $=RU(x,A,N);if($)return d.get($)??null;if(!x.appId)return null;const V=R.get(x.appId);return V?d.get(V)??null:null},[R,d,A,N,x]),P=g.useMemo(()=>x?.cloudProjectId?p.get(x.cloudProjectId)??null:null,[p,x]),E=h??I,T=S??P,z=g.useMemo(()=>tb(E,y),[y,E]),U=g.useMemo(()=>z?e?.apps.find($=>$.id===z.appId)??null:null,[e?.apps,z]);return{cloudProjectById:p,currentAppIds:y,linkedProjectByAppId:R,localProjectById:d,mentionableSandboxApps:w,selectedApp:s,selectedCloudProject:T,selectedProject:E,selectedProjectLinkedApp:U,selectedProjectLinkedOpenPondApp:z,selectedSession:x,selectedSessionLinkedProject:I,sidebarSessions:D}}function GB(e,t,n){const a=new Map;for(const m of e){const h=nb(m);a.set(h,m)}for(const m of t){const h=nb(m),S=a.get(h);a.set(h,S?ZB(S,m):m)}const i=Array.from(a.entries());if(!n)return i.sort((m,h)=>ab(m[1],h[1])).map(m=>m[1]);const r=[],s=new Set;for(const m of n){const h=a.get(m);h&&(r.push([m,h]),s.add(m))}const p=[...i.filter(([m])=>!s.has(m)).sort((m,h)=>ab(m[1],h[1])),...r];return n.splice(0,n.length,...p.map(([m])=>m)),p.map(m=>m[1])}function ZB(e,t){return{...e,metadata:JB(e.metadata,t.metadata),status:e.status==="active"||t.status==="active"?"active":e.status,updatedAt:YB(e.updatedAt,t.updatedAt)}}function nb(e){return e.codexThreadId?`codex:${e.codexThreadId}`:`session:${e.id}`}function ab(e,t){const n=ob(t)-ob(e);return n!==0?n:e.title.localeCompare(t.title)}function JB(e,t){const n={...e??{},...t??{}};return Object.keys(n).length>0?n:void 0}function YB(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 ob(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 XB(e){return!!(e&&Va(e.workspaceKind)&&!Wa(e)&&e.provider!=="openpond")}function QB(e,t){const n=$x(e,t);return`${e.id}\0${n.provider}\0${n.model}`}function e5({activeWorkspaceId:e,activeWorkspaceKind:t,appDispatch:n,connection:a,expandProject:i,linkedProjectByAppId:r,providerSettings:s,selectedAppId:d,selectedSession:p,selectedSessionId:m,selectedSessionProjectId:h,setDiffPanelExpanded:S,setDraftModel:y,setDraftProvider:w,setError:R,setSelectedAppId:A,setSelectedProjectId:N,setSessions:O,setTerminalOpen:D,toast:x}){const I=g.useRef(null);g.useEffect(()=>{if(!d)return;const P=h??(m?null:r.get(d)??null);if(!P)return;const E=vt("local",P);A(null),N(E),i(E)},[i,r,d,m,h,A,N]),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(E){(E.metaKey||E.ctrlKey)&&E.key==="`"&&(E.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=QB(p,s);if(I.current===P)return;I.current=P;const E=$x(p,s);w(E.provider),y(E.model)},[s,p,m,y,w]),g.useEffect(()=>{!a||!p||!XB(p)||J.patchSession(a,p.id,{provider:"openpond"}).then(P=>{O(E=>E.map(T=>T.id===P.id?P:T)),w("openpond"),y(E=>Do("openpond",E))}).catch(P=>{R(P instanceof Error?P.message:String(P))})},[a,p,y,w,R,O])}function t5({connection:e,setError:t}){return g.useCallback(async(n,a)=>{if(!e){const i=new Error("OpenPond App server is not connected.");throw t(i.message),i}t(null);try{await J.resolveApproval(e,n,{decision:a})}catch(i){const r=i instanceof Error?i.message:String(i);throw t(r),i}},[e,t])}function n5({activeProvider:e,contextCompaction:t,contextUsage:n,pinnedItems:a,pinnedPreviewKeys:i,pinnedProjects:r,projectRows:s,visibleProjectRows:d}){const p=g.useMemo(()=>gU(a,i),[a,i]),m=g.useMemo(()=>ok({provider:e,snapshot:n,preferences:t}),[e,t,n]),h=g.useMemo(()=>Array.from(new Set([...r,...d].filter(xf).map(y=>y.project.id))),[r,d]);return{commandProjectRows:g.useMemo(()=>s,[s]),contextWindowStatus:m,pinnedRows:p,sidebarWorkspaceAppIds:h}}function a5({appDispatch:e,expandProject:t,linkedProjectByAppId:n,requestComposerFocus:a,onBeginNewChat:i,setMentionedAppId:r}){return g.useCallback((s=null)=>{i?.();const d=s?.id?n.get(s.id)??null:null;if(d){const p=vt("local",d);r(null),e({type:"selectProject",projectId:p}),t(p),a();return}r(null),e({type:"beginNewChat",appId:s?.id??null}),a()},[e,t,n,i,a,r])}const jk={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 WW(e){return`@${e.token}`}function o5(e){return`@${c5(e)}`}function i5(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 i=a[0],r=Vi(a.flatMap(S=>S.capabilities.map(y=>y.id))),s=Vi(a.flatMap(S=>S.capabilityLabels)),d=Vi(a.flatMap(S=>S.connections.map(y=>y.id).filter(u5))),p=Vi(a.map(S=>S.id)),m=Vi(a.map(S=>S.setupSurface)),h=l5(n);return{provider:n,label:i.providerLabel,detail:s.length>0?s.slice(0,4).join(", "):i.description,token:h,tokens:s5(a),ref:{kind:"integration",provider:n,appIds:p,setupSurfaces:m,...d.length>0?{connectionIds:d}:{},...r.length>0?{capabilities:r}:{}}}})}function KW(e,t){const n=An(t);return e.filter(a=>n?a.tokens.some(i=>i.includes(n)):!0).slice(0,8)}function r5(e,t){const n=d5(e);if(n.length===0)return[];const a=new Map;for(const i of n){const r=t.find(s=>s.tokens.includes(i));r&&a.set(r.provider,r)}return Array.from(a.values())}function GW(e,t){if(t.length===0)return[];const n=[];for(const a of e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)){const i=a[1]??"",r=An(i);if(!r)continue;const s=t.find(S=>S.tokens.includes(r));if(!s)continue;const p=(a[0]??"").indexOf("@");if(p<0||typeof a.index!="number")continue;const m=a.index+p,h=`@${i}`;n.push({detail:s.detail,displayText:o5(s),end:m+h.length,label:s.label,provider:s.provider,start:m,text:h})}return n}function s5(e){return Vi(e.flatMap(t=>[...jk[t.providerFamily],t.providerFamily,t.id,t.label,t.shortLabel]).map(An).filter(Boolean))}function l5(e){return An(jk[e][0]??e)}function c5(e){return e.provider==="github"?"GitHub":e.provider==="x"?"X":e.provider==="mcp"?"MCP":e.label}function d5(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>An(t[1]??"")).filter(Boolean)}function Vi(e){return Array.from(new Set(e))}function u5(e){return typeof e=="string"&&e.length>0}function m5({bootstrap:e,connectedAppRows:t,mentionableSandboxApps:n,runtimeIndexes:a,selectedApp:i,selectedCloudProject:r,selectedProject:s,selectedSession:d,selectedSessionId:p}){const m=g.useMemo(()=>{const R=new Map;for(const A of e?.cloudProjects??[]){const N=R.get(A.teamId)??[];N.push(A.id),R.set(A.teamId,N)}return R},[e?.cloudProjects]),S=!!(d||i||s||r)?[]:n,y=g.useMemo(()=>i5(t),[t]),w=g.useMemo(()=>cB(a,p),[a,p]);return{chatMentionApps:S,cloudProjectIdsByTeam:m,connectedAppMentions:y,pendingApproval:w}}const Ok="openpond.codexPermissionMode",Nk="openpond.codexReasoningEffort";function al(){if(typeof window>"u")return null;try{return window.localStorage}catch{return null}}function p5(e){return e==="default"||e==="auto-review"||e==="full-access"?e:null}function f5(e){return e==="low"||e==="medium"||e==="high"||e==="xhigh"?e:null}function $k(e=al()){if(!e)return{};const t=p5(e.getItem(Ok)),n=f5(e.getItem(Nk));return{...t?{codexPermissionMode:t}:{},...n?{codexReasoningEffort:n}:{}}}function h5(e,t=al()){try{t?.setItem(Ok,e)}catch{}}function g5(e,t=al()){try{t?.setItem(Nk,e)}catch{}}function ib(e,t=al()){const n=ta(e),a=$k(t);return{codexPermissionMode:a.codexPermissionMode??n.codexPermissionMode??_c,codexReasoningEffort:a.codexReasoningEffort??n.codexReasoningEffort??wc}}function b5(e,t=al()){const n=ta(e),a=$k(t),i={};return a.codexPermissionMode&&a.codexPermissionMode!==n.codexPermissionMode&&(i.codexPermissionMode=a.codexPermissionMode),a.codexReasoningEffort&&a.codexReasoningEffort!==n.codexReasoningEffort&&(i.codexReasoningEffort=a.codexReasoningEffort),i}function v5({connection:e,setBootstrap:t,setCodexPermissionMode:n,setCodexReasoningEffort:a,setError:i}){const r=g.useCallback(d=>{n(d),h5(d),e&&J.savePreferences(e,{codexPermissionMode:d}).then(()=>{t(p=>p&&{...p,preferences:{...p.preferences,codexPermissionMode:d}})}).catch(p=>{i(p instanceof Error?p.message:String(p))})},[e,t,n,i]),s=g.useCallback(d=>{a(d),g5(d),e&&J.savePreferences(e,{codexReasoningEffort:d}).then(()=>{t(p=>p&&{...p,preferences:{...p.preferences,codexReasoningEffort:d}})}).catch(p=>{i(p instanceof Error?p.message:String(p))})},[e,t,a,i]);return{changeCodexPermissionMode:r,changeCodexReasoningEffort:s}}const y5=6e4;function Tf(e,t){if(!e)return t;const n=x5(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 Lk(e,n)?e:n}function S5(e,t){const n=Tf(e,t),a=e?{...n,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order,updatedAt:e.updatedAt}:n;return e&&Lk(e,a)?e:a}function Ss(e,t){let n=!1,a=!1;const i=e.map(r=>{if(r.id!==t.id)return r;n=!0;const s=Tf(r,t);return s!==r&&(a=!0),s});return n?a?i:e:[t,...e]}function Kc(e,t){let n=!1,a=!1;const i=e.map(r=>{if(r.id!==t.id)return r;n=!0;const s=S5(r,t);return s!==r&&(a=!0),s});return n?a?i:e:[t,...e]}function Qm(e,t,n,a=Date.now()){const i=new Map(e.map(r=>[r.id,r]));return t.map(r=>{const s=i.get(r.id);if(s&&n){const d=_5(s,r,n,a);if(d)return d}return Tf(s,r)})}function rb(e,t,n,a=Date.now()){const i=new Map(e.map(m=>[m.id,m])),r=new Map(Qm(e,t,n,a).map(m=>[m.id,m])),s=new Set(i.keys()),d=t.filter(m=>!s.has(m.id)).map(m=>r.get(m.id)??m),p=e.map(m=>{const h=r.get(m.id);return h||(Dk(m,t)?m:null)}).filter(m=>!!m);return[...d,...p]}function Dk(e,t){const n=Date.parse(e.updatedAt);if(!Number.isFinite(n))return!1;const a=k5(t);return a===null||n>=a}function sb(e,t,n,a=Date.now()){const i=new Map(t.map(r=>[r.id,r]));for(const r of n){const s=i.get(r.id);s&&(zk(s,r)||(e[r.id]=a))}}function x5(e,t){const n=Date.parse(e),a=Date.parse(t);return Number.isFinite(n)&&Number.isFinite(a)&&n>a}function Lk(e,t){return JSON.stringify(e)===JSON.stringify(t)}function k5(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 _5(e,t,n,a){const i=n[t.id];return i===void 0?null:a-i>y5||zk(e,t)?(delete n[t.id],null):{...t,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order}}function zk(e,t){return e.pinned===t.pinned&&e.savedForLater===t.savedForLater&&e.archived===t.archived&&e.order===t.order}const Uk=800,w5=5e3,lb=5e4,I5=16,C5=3e4,Vn=new Map;function R5(e,t){return Vn.get(qk(e,t))?.payload??null}async function Hk(e,t,n={}){const a=qk(e,t),i=Vn.get(a),r=n.limit??Uk,s=n.tail??!0;if(i?.promise)return i.promise;if(!n.force&&s&&i?.payload&&Date.now()-i.fetchedAt<=C5)return cb(a,i),i.payload;const d=!!(n.force&&s&&i?.payload),p=d?i?.payload?.events.at(-1)?.id:void 0,m=J.codexHistoryThreadIncremental(e,t,{afterEventId:p,limit:r,revision:d?i?.revision:void 0,tail:s}).then(h=>{const S=Vn.get(a)?.payload??i?.payload;if(h.unchanged){if(!S)throw new Error("Codex history revision matched without a cached thread.");return Vn.set(a,{fetchedAt:Date.now(),payload:S,revision:h.revision}),cb(a,Vn.get(a)),S}const y={session:h.session,events:h.events},w=s&&S&&!h.reset?{...y,events:A5(S.events,y.events)}:y;return Vn.set(a,{fetchedAt:Date.now(),payload:w,revision:h.revision}),db(),w}).catch(h=>{throw Vn.get(a)?.promise===m&&Vn.delete(a),h});return Vn.set(a,{fetchedAt:i?.fetchedAt??0,payload:i?.payload,promise:m,revision:i?.revision}),db(),m}function qk(e,t){return`${e.serverUrl}
132
- ${e.token}
133
- ${t}`}function cb(e,t){Vn.delete(e),Vn.set(e,t)}function db(){for(;Vn.size>I5;){const e=Vn.keys().next().value;if(!e)return;Vn.delete(e)}}function A5(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 P5=500,T5=2500,E5=15e3;function M5(e){return e.active?P5:e.surface==="thread"?T5:E5}function Ef(e,t){return!t||e.session.status==="active"?e:{...e,session:{...e.session,status:"active"}}}function j5(e={}){const t={cachedPayload:e.cachedPayload??R5,clearTimer:e.clearTimer??(m=>globalThis.clearTimeout(m)),loadPayload:e.loadPayload??Hk,now:e.now??Date.now,setTimer:e.setTimer??((m,h)=>globalThis.setTimeout(m,h))},n=new Map;let a=1;function i(m){const h=N5(m.connection,m.sessionId);let S=n.get(h);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(h,S));const y=a++;return S.subscribers.set(y,m),S.latestPayload&&m.onPayload(S.latestPayload),r(S,0),()=>{const w=n.get(h);if(w){if(w.subscribers.delete(y),w.subscribers.size>0){r(w,d(w));return}w.disposed=!0,p(w),n.delete(h)}}}function r(m,h){if(m.disposed||m.subscribers.size===0||m.inFlight)return;const S=t.now()+Math.max(0,h);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,h)))}async function s(m){if(m.disposed||m.subscribers.size===0||m.inFlight)return;const h=t.loadPayload(m.connection,m.sessionId,{force:!!m.latestPayload});m.inFlight=h;try{const S=await h;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===h&&(m.inFlight=null),m.disposed||r(m,d(m))}}function d(m){const h=[...m.subscribers.values()],S=h.some(w=>w.locallyActive||w.reportedActive)||m.latestPayload?.session.status==="active"||Af(m.latestPayload?.events??[])?.tone==="active",y=h.some(w=>w.surface==="thread")?"thread":"sidebar";return M5({active:S,surface:y})}function p(m){m.timer&&t.clearTimer(m.timer),m.timer=null,m.nextRefreshAt=null}return{subscribe:i}}const O5=j5();function Mf(e){return O5.subscribe(e)}function N5(e,t){return`${e.serverUrl}
134
- ${e.token}
135
- ${t}`}function $5({connection:e,selectedSessionId:t,selectedSessionLocallyActive:n,selectedSessionStatus:a,setCodexHistorySessions:i,setError:r}){const[s,d]=g.useState({events:[],sessionId:null}),p=Nt(t)?t:null,m=p&&s.sessionId===p?s.events:[],h=g.useCallback(S=>{d(y=>{if(!p)return{events:[],sessionId:null};const w=y.sessionId===p?y.events:[];return{events:typeof S=="function"?S(w):S,sessionId:p}})},[p]);return g.useEffect(()=>{if(!e||!p){d(w=>w.sessionId===null&&w.events.length===0?w:{events:[],sessionId:null});return}r(w=>w==="Session not found"?null:w);const S=n;return Mf({connection:e,locallyActive:S,onError:w=>r(w instanceof Error?w.message:String(w)),onPayload:w=>{const R=Ef(w,S);d(A=>A.sessionId!==p?{events:R.events,sessionId:p}:{events:ro(A.events,R.events),sessionId:p}),r(A=>A==="Session not found"?null:A),i(A=>Kc(A,R.session))},reportedActive:a==="active",sessionId:p,surface:"thread"})},[e,p,n,a,i,r]),{codexHistoryEvents:m,setCodexHistoryEvents:h}}function Bk(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 D5({connection:e,appPreferences:t,sessions:n,pinnedItems:a,setAppPreferences:i,setCodexHistorySessions:r,setSessions:s,sidebarFileBookmarks:d,setSidebarFileBookmarks:p,setError:m}){const[h,S]=g.useState(null),[y,w]=g.useState(null),R=g.useRef(null),A=g.useRef(null);function N(E,T){E.dataTransfer.effectAllowed="move",E.dataTransfer.setData("text/plain",`${T.type}:${T.id}`),Bk(E);const z=a.map(U=>U.key);R.current=T,A.current=z,S(T),w(z)}function O(){R.current=null,A.current=null,S(null),w(null)}function D(E,T){const z=R.current;if(!z)return;const U=rc(E),$=A.current??a.map(re=>re.key),V=sc($,ei(z),ei(T),U);Rg($,V)||(A.current=V,w(V))}function x(E){if(!e)return;const T=a.map(Se=>Se.key),z=new Set(T),U=[...E.filter(Se=>z.has(Se)),...T.filter(Se=>!E.includes(Se))];if(Rg(T,U))return;const $=t,V=new Map(n.map(Se=>[Se.id,Se])),re=d,Q=new Map(a.map(Se=>[Se.key,Se]));i(Se=>{const G={...Se};return U.forEach((Ee,xe)=>{const le=Q.get(Ee);le?.type==="project"&&(G[le.id]={...G[le.id]??{},pinned:!0,archived:!1,order:xe})}),G});const Ie=Se=>{const G=new Map(Se.map(le=>[le.id,le])),Ee=U.map((le,ke)=>{const ae=Q.get(le),he=ae?.type==="session"?G.get(ae.id):null;return he?{...he,order:ke}:null}).filter(le=>!!le),xe=new Map(Ee.map(le=>[le.id,le]));return Se.map(le=>xe.get(le.id)??le)};s(Ie),r(Ie),p(Se=>{const G=new Map;return U.forEach((Ee,xe)=>{const le=Q.get(Ee);le?.type==="file"&&G.set(le.id,xe)}),Se.map(Ee=>{const xe=G.get(Ee.id);return xe===void 0?Ee:{...Ee,order:xe}})}),Promise.all(U.map((Se,G)=>{const Ee=Q.get(Se);return Ee?Ee.type==="project"?J.patchSidebarAppPreference(e,Ee.id,{pinned:!0,archived:!1,order:G}):Ee.type==="session"?J.patchSession(e,Ee.id,{order:G}):J.patchSidebarFile(e,{workspaceKind:Ee.file.workspaceKind,workspaceId:Ee.file.workspaceId,workspaceName:Ee.file.workspaceName,path:Ee.file.path,status:"pinned",order:G,sourceSessionId:Ee.file.sourceSessionId}):Promise.resolve(null)})).catch(Se=>{m(Se instanceof Error?Se.message:String(Se)),i($);const G=Ee=>Ee.map(xe=>V.get(xe.id)??xe);s(G),r(G),p(re)})}function I(E,T){const z=R.current;if(z){const U=A.current??a.map(V=>V.key),$=sc(U,ei(z),ei(T),rc(E));x($)}O()}function P(){R.current&&x(A.current??a.map(T=>T.key)),O()}return{dragItem:h,pinnedPreviewKeys:y,startPinnedDrag:N,clearSidebarDrag:O,previewPinnedDrop:D,commitPinnedDrop:I,commitPinnedPreviewDrop:P}}function L5({connection:e,sessions:t,setCodexHistorySessions:n,setError:a,setSessions:i}){const[r,s]=g.useState(null),[d,p]=g.useState(null),m=g.useRef(null),h=g.useRef(null);function S(O,D){O.dataTransfer.effectAllowed="move",O.dataTransfer.setData("text/plain",`session:${D.sessionId}`),Bk(O),m.current=D,h.current=D.visibleSessionIds,s(D.sessionId),p(D.visibleSessionIds)}function y(O,D){const x=m.current;if(!x)return;const I=h.current??x.visibleSessionIds,P=sc(I,x.sessionId,D,rc(O));z5(I,P)||(h.current=P,p(P))}function w(){m.current=null,h.current=null,s(null),p(null)}function R(O,D){const x=m.current;if(!x){w();return}const I=h.current??x.visibleSessionIds,P=sc(I,x.sessionId,D,rc(O));N(Og(x.allSessionIds,x.visibleSessionIds,P)),w()}function A(){const O=m.current;O&&N(Og(O.allSessionIds,O.visibleSessionIds,h.current??O.visibleSessionIds)),w()}function N(O){const D=new Map(O.map((E,T)=>[E,T])),x=new Map(t.map(E=>[E.id,E.order])),I=O.filter((E,T)=>x.get(E)!==T);if(I.length===0)return;const P=E=>E.map(T=>{const z=D.get(T.id);return z===void 0||z===T.order?T:{...T,order:z}});i(P),n(P),e&&Promise.all(I.map(E=>J.patchSession(e,E,{order:D.get(E)}))).catch(E=>{const T=z=>z.map(U=>{const $=x.get(U.id);return $===void 0||$===U.order?U:{...U,order:$}});i(T),n(T),a(E instanceof Error?E.message:String(E))})}return{clearTaskDrag:w,commitTaskDrop:R,commitTaskPreviewDrop:A,previewTaskDrop:y,startTaskDrag:S,taskDragSessionId:r,taskPreviewSessionIds:d}}function z5(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function ub({afterMessageId:e=null,attachments:t,content:n,sessionId:a}){const i=new Date().toISOString(),r=`pending_user_${a}_${i}_${Math.random().toString(36).slice(2,8)}`,s=U5(t);return{id:r,role:"user",content:n,sessionId:a,afterMessageId:e,timestamp:i,turnId:r,...s.length>0?{attachments:s}:{}}}function Fk(e,t){return!t||Vk(e,t)?e:[...e,t]}function Vk(e,t){const n=t.afterMessageId?e.findIndex(r=>r.id===t.afterMessageId):-1,a=n>=0?n+1:0,i=Date.parse(t.timestamp);for(let r=a;r<e.length;r+=1){const s=e[r];if(s.role!=="user"||s.content!==t.content)continue;if(n>=0||!t.afterMessageId)return!0;const d=Date.parse(s.timestamp);if(!Number.isFinite(i)||!Number.isFinite(d)||d>=i)return!0}return!1}function U5(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 Lo(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 fo(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];if(t(a))return a}return null}function H5(e,t,n){if(t.name==="workspace_action_result"){const a=fo(e,i=>i.role==="assistant"&&i.turnId===t.turnId&&i.actionRun?.actionName===n.actionName);if(a?.actionRun){a.id=t.id,a.timestamp=t.timestamp,a.actionRun={...a.actionRun,...n,refs:ep([...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 q5(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"])??Yu(t)??Yu(Ae(t?.run))??Yu(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 r=Ae(t?.run)??Ae(t?.agentRun),s=Ae(r?.metadata),d=Ae(t?.actionSummary)??Ae(r?.actionSummary)??Ae(s?.actionSummary),p=Ae(t?.action)??d??Ae(s?.selectedAction)??null,m=Ae(t?.responseSummary)??Ae(r?.responseSummary)??Ae(s?.responseSummary),h=Ae(t?.sourceSummary)??Ae(r?.sourceSummary)??Ae(s?.sourceSummary),S=Ae(t?.traceSummary)??Ae(r?.traceSummary)??Ae(s?.traceSummary),y=Ae(t?.evalSummary)??Ae(r?.evalSummary)??Ae(s?.evalSummary),w=ep([...ao("artifact",t?.artifactRefs,"Artifact"),...ao("artifact",p?.artifactRefs,"Artifact"),...ao("artifact",d?.artifactRefs,"Artifact"),...ao("artifact",m?.artifactRefs,"Artifact"),...ao("trace",t?.traceArtifactRefs,"Trace"),...ao("trace",S?.artifactRefs,"Trace"),...ao("eval",t?.evalResultArtifactRefs,"Eval"),...ao("eval",y?.artifactRefs,"Eval"),...ao("output",t?.outputRefs,"Output")]),R=be(h,["sourceRef","ref"]);return R&&w.push({id:tp("source",R),kind:"source",label:"Source",target:R}),{actionName:a,title:be(p,["label","title","name"])??be(s,["selectedActionLabel"])??G5(a),status:B5(e,m,r),responseText:be(m,["text","summary","message"])??(e.name==="workspace_action_result"&&e.output?.trim()||null),runId:be(r,["id","runId"])??be(t,["runId","agentRunId"])??null,projectId:be(r,["projectId"])??be(t,["projectId"])??be(n,["projectId"])??null,agentId:be(r,["agentId"])??be(t,["agentId"])??be(n,["agentId"])??null,agentName:be(Ae(p?.implementation),["agentName"])??be(p,["agentName"])??be(s,["selectedAgentName"])??null,sandboxId:be(r,["sandboxId"])??be(t,["sandboxId"])??be(Ae(t?.sandbox),["id"])??be(Ae(t?.createdSandbox),["id"])??be(n,["sandboxId"])??null,runtimeId:be(r,["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(h,["manifestHash"])??be(t,["manifestHash"])??be(s,["manifestHash"])??null,refs:ep(w),childCalls:V5(t,r,s)}}function Yu(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 B5(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 i=be(n,["status"]);return i==="failed"?"failed":i==="succeeded"||i==="completed"?"completed":i==="queued"||i==="running"||i==="runtime_created"?"running":e.status==="pending"?"pending":e.status==="started"||e.name==="workspace_action"?"running":"unknown"}function ao(e,t,n){return(Array.isArray(t)?t:t?[t]:[]).flatMap(i=>{const r=F5(e,i,n);return r?[r]:[]})}function F5(e,t,n){if(typeof t=="string"&&t.trim()){const s=t.trim();return{id:tp(e,s),kind:e,label:n,target:s}}const a=Ae(t);if(!a)return null;const i=be(a,["url","webUrl","artifactPath","path","ref"])??be(Ae(a.artifact),["url","webUrl","path","ref"]);if(!i)return null;const r=be(a,["label","title","name","type","kind"])??n;return{id:tp(e,i),kind:e,label:r,target:i}}function ep(e){const t=new Set,n=[];for(const a of e){const i=`${a.kind}:${a.target}`;t.has(i)||(t.add(i),n.push(a))}return n}function tp(e,t){return`${e}:${t}`}function V5(e,t,n){return[e?.childCalls,e?.childRuns,e?.implementationCalls,t?.childCalls,t?.childRuns,n?.childCalls,n?.childRuns].flatMap(i=>W5(i)).slice(0,6)}function W5(e){return(Array.isArray(e)?e:e?[e]:[]).flatMap((n,a)=>{const i=Ae(n);if(!i)return[];const r=be(i,["id","runId","callId"])??`child_${a+1}`,s=be(i,["label","title","actionName","name","tool"])??be(Ae(i.action),["label","name"])??"Implementation call",d=be(i,["detail","summary","runId","sandboxId","runtimeId"])??null;return[{id:r,label:s,status:K5(i),detail:d}]})}function K5(e){const t=be(e,["status","state"]);return t==="running"||t==="completed"||t==="failed"||t==="pending"?t:t==="succeeded"?"completed":"unknown"}function G5(e){const t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e}const Z5=new Set([".avif",".gif",".jpeg",".jpg",".png",".webp"]);function Wk(e){if(!e)return!1;const t=e.split("?")[0]?.split("#")[0]??e,n=t.lastIndexOf(".");return n<0?!1:Z5.has(t.slice(n).toLowerCase())}function Kk(e){return e.split("/").filter(Boolean).pop()??e}function J5(e){if(!ap(e))return;const t=Ae(e.data),a=(typeof t?.openpondImagePreviewPath=="string"?t.openpondImagePreviewPath:null)??ti(e.data)??ti(e.args)??ti(e.output);if(!(!a||!Wk(a)))return{path:a,appId:e.appId??null,title:Kk(a)}}function Y5(e){if(e.name!=="tool.completed"&&e.name!=="workspace_action_result")return[];const t=[],n=new Set;return np(e.data,t,n),t.slice(0,12)}function np(e,t,n,a=0){if(a>7||e==null)return;if(Array.isArray(e)){for(const d of e)np(d,t,n,a+1);return}const i=Ae(e);if(!i)return;const r=be(i,["path","artifactRef"]),s=be(i,["contentType","mimeType"]);r&&s&&!n.has(r)&&(n.add(r),t.push({path:r,title:be(i,["title","name"])??Kk(r),contentType:s,sizeBytes:typeof i.sizeBytes=="number"?i.sizeBytes:null}));for(const d of Object.values(i))np(d,t,n,a+1)}function ap(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 ti(e,t=0,n=""){if(t>5||e==null)return null;if(typeof e=="string"){if(Xu(n)&&Wk(e.trim()))return e.trim();const i=Lo(e);if(i!==null){const r=ti(i,t+1,n);if(r)return r}return X5(e)}if(Array.isArray(e)){for(const i of e){const r=ti(i,t+1,n);if(r)return r}return null}const a=Ae(e);if(!a)return null;for(const[i,r]of Object.entries(a)){if(!Xu(i))continue;const s=ti(r,t+1,i);if(s)return s}for(const[i,r]of Object.entries(a)){if(Xu(i))continue;const s=ti(r,t+1,i);if(s)return s}return null}function Xu(e){return/^(path|filePath|filepath|imagePath|image|localPath|uri|url)$/i.test(e)}function X5(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 Q5(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=tF(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 eF(e){if(e.action!=="connected_app_search"&&e.action!=="connected_app_read"&&e.action!=="connected_app_write")return null;const t=Gk(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 tF(e){return Gk(e).providerLabel}function Gk(e){const t=Ae(e.args),n=Ae(e.data),a=Ae(n?.result),i=kc(be(t,["provider"])??be(a,["provider"])??be(n,["provider"])??void 0),r=be(a,["providerLabel"])??be(n,["providerLabel"])??(i?Ap(i)?.label:null)??"connected app",s=be(t,["operation"]),d=be(a,["operation"])??be(n,["operation"]),p=Qu(t?.capabilityIds)||Qu(a?.capabilityIds)||Qu(n?.capabilityIds);return{providerLabel:r,providerOperation:s,operation:d,capabilityCount:p}}function Qu(e){return Array.isArray(e)?e.length:0}function Zk(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()||em(a)}}return t==="<turn_aborted>"?{kind:"turn_aborted",text:em("turn_aborted")}:t==="<goal_context>"?{kind:"goal_context",text:em("goal_context")}:null}function em(e){return e==="turn_aborted"?"The previous turn was interrupted.":"Goal context updated."}function Gc(e){return e.name==="diagnostic"&&Ae(e.data)?.kind==="goal_context"}const nF="Steered by user";function aF(e){return e?.trim().toLowerCase()===nF.toLowerCase()}function oF(e,t){if(!t.turnId)return;cF(e,t.turnId);const n=iF(t);if(!n)return;const a=lF(e,t.turnId);if(a){a.refinerActivity=n;return}const i={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},r=e.findIndex(s=>s.role==="assistant"&&s.turnId===t.turnId);r>=0?e.splice(r,0,i):e.push(i)}function iF(e){const t=Ae(e.data),n=Ae(t?.activity);return n?rF(n,e):sF(e,t)}function ZW(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 · ${pF(e.route??"external")} issue routed`;const t=e.result==="applied"?"Applied":"Needs review";return`Refiner · ${e.summary} — ${t}`}function rF(e,t){const n=Fa(e.state,["running","completed","failed"]);if(!n)return null;const a=n==="failed"?"failed":Fa(e.result,["no_action","routed","applied","retained"]),i=Nn(e.reason)??t.output??t.error??null;return{state:n,visibility:Fa(e.visibility,["always","material_only"])??"material_only",result:n==="running"?null:a,workspaceId:Nn(e.workspaceId),decision:Fa(e.decision,["no_action","route","propose"]),route:Nn(e.route),operation:Fa(e.operation,["create","update","delete"]),target:Nn(e.target),summary:Nn(e.summary)??Jk(n,a),expectedOutcome:Nn(e.expectedOutcome),reason:i,evidenceBasis:dF(e.evidenceBasis),critiqueStatus:Fa(e.critiqueStatus,["not_applicable","pending","passed","rejected","failed"])??(n==="running"?"pending":"not_applicable"),validationStatus:Fa(e.validationStatus,["not_applicable","pending","passed","failed"])??(n==="running"?"pending":"not_applicable"),validations:uF(e.validationReceipts),edits:mF(e.edits),refs:{trigger:Ba(e.trigger),outcome:Ba(e.outcome),proposal:Ba(e.proposal),applyReceipt:Ba(e.applyReceipt),advanceReceipt:Ba(e.advanceReceipt),inputHarness:Ba(e.inputHarness),outputHarness:Ba(e.outputHarness)}}}function sF(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",i=Ae(t?.outcome),r=Ae(t?.proposal),s=i?.routed===!0,d=Nn(t?.workspaceAdvance),p=n?"failed":a?r?d==="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:r?"propose":s?"route":a?"no_action":null,route:Nn(i?.route),operation:null,target:null,summary:Jk(n?"failed":a?"completed":"running",p),expectedOutcome:null,reason:e.output??e.error??null,evidenceBasis:null,critiqueStatus:r?"passed":"not_applicable",validationStatus:r?"pending":"not_applicable",validations:[],edits:[],refs:{trigger:Ba(t?.trigger),outcome:Ba(i),proposal:Ba(r),applyReceipt:null,advanceReceipt:null,inputHarness:null,outputHarness:null}}}function lF(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(i=>i.subagentMessage))return a}return null}function cF(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 dF(e){const t=Ae(e),n=Fa(t?.kind,["single_deterministic","recurrent_independent"]);return!t||!n?null:{kind:n,supportingEvidenceIds:mb(t.supportingEvidenceIds),counterevidence:mb(t.counterevidence)}}function uF(e){return Array.isArray(e)?e.flatMap(t=>{const n=Ae(t),a=Nn(n?.id),i=Fa(n?.status,["passed","failed","blocked","skipped"]),r=Nn(n?.summary);return a&&i&&r?[{id:a,status:i,summary:r}]:[]}):[]}function mF(e){return Array.isArray(e)?e.flatMap(t=>{const n=Ae(t),a=Nn(n?.id),i=Fa(n?.operation,["create","update","delete"]),r=Nn(n?.target),s=Nn(n?.summary);return!a||!i||!r||!s?[]:[{id:a,operation:i,target:r,summary:s,content:typeof n?.content=="string"?n.content:null}]}):[]}function Ba(e){const t=Ae(e),n=Nn(t?.id),a=Nn(t?.contentHash);return n&&a?`${n} · ${a.slice(0,12)}`:null}function mb(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()):[]}function Nn(e){return typeof e=="string"&&e.trim()?e.trim():null}function Fa(e,t){return typeof e=="string"&&t.includes(e)?e:null}function Jk(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 pF(e){return e.length>0?`${e[0].toUpperCase()}${e.slice(1)}`:e}const pb=64*1024,fb=8*1024;function hb(e,t){const n=Yk(t);if(n.subagentMessage){e.push({id:t.id,role:"activity_group",activities:[n],timestamp:t.timestamp,turnId:t.turnId});return}const a=fF(e,t.turnId);if(a){a.activities=bF(a.activities??[],t,n),a.timestamp=t.timestamp;return}Zl(e,t),e.push({id:t.id,role:"activity_group",activities:[n],timestamp:t.timestamp,turnId:t.turnId,traceState:"running",traceStartedAt:t.timestamp})}function Zl(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];a.role!=="activity_group"||a.activities?.some(i=>i.subagentMessage)||a.traceState==="running"&&(a.traceState="settled",a.traceCompletedAt=t.timestamp)}}function fF(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(i=>i.subagentMessage))return a}return null}function op(e,t,n){if(!t.turnId)return;const a=e.filter(d=>d.role==="activity_group"&&d.turnId===t.turnId&&!d.activities?.some(p=>p.subagentMessage)),i=a.filter(d=>d.traceState==="running"),r=i.length>0?i:a.length>0?[a[a.length-1]]:[];for(const d of r)d.traceState=n;const s=r.at(-1);s&&(s.traceCompletedAt=t.timestamp,s.timestamp=t.timestamp)}function hF(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 i=a.activities?.filter(r=>r.controlKind!=="turn_aborted")??[];i.length!==a.activities?.length&&(i.length===0?e.splice(n,1):a.activities=i)}op(e,t,"interrupted"),!aF(t.output)&&e.push({id:t.id,role:"status_divider",content:gF(t),timestamp:t.timestamp,turnId:t.turnId,statusKind:"interruption",statusState:"failed",statusTone:"danger"})}function gF(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 bF(e,t,n=Yk(t)){const a=[...e];return RF(a,t,n)||wF(a,t,n)||IF(a,t,n)||CF(a,t,n)?a:[...a,n]}function vF(e){return e.name==="session.compaction.started"||e.name==="session.compaction.completed"||e.name==="session.compaction.failed"}function yF(e,t){const n={id:t.id,role:"status_divider",content:SF(t),timestamp:t.timestamp,turnId:t.turnId,statusKind:"compaction",statusState:xF(t),statusTone:kF(t)};if(t.name!=="session.compaction.started"){const a=fo(e,i=>i.role==="status_divider"&&i.statusKind==="compaction"&&i.statusState==="running"&&i.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 SF(e){const t=_F(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 xF(e){return e.name==="session.compaction.started"?"running":e.name==="session.compaction.completed"?"completed":"failed"}function kF(e){return e.name==="session.compaction.failed"?"danger":e.name==="session.compaction.completed"?"success":"info"}function _F(e){return Ae(e.data)?.reason==="auto"?"auto":"manual"}function Yk(e){const t=J5(e),n=e.name==="assistant.reasoning.delta"?"reasoning":DF(e),a=LF(e),i=HF(e),r=UF(e),s=qF(e),d=BF(e),p=Y5(e);return{id:e.id,label:d?d.direction==="received"?"Child message received":"Child message sent":TF(e),content:d?.summary??MF(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:jf(e)??void 0}:{},...n&&e.name==="command.output"?{detail:ip(e)}:{},...n==="command"?{terminal:ZF(e)}:{},...r?{meta:r}:{},...i?{receipt:i}:{},...s?{openSession:s}:{},...d?{subagentMessage:d}:{},state:PF(e),...t?{imagePreview:t}:{},...p.length>0?{artifacts:p}:{}}}function wF(e,t,n){if(t.name==="tool.completed"){const a=gb(e,t);if(!a)return!1;const i=JF(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,...i!==null?{durationMs:i}:{}};const r=ip(t);return r&&r!==a.content&&(a.detail=pc(a.detail,r)),!0}if(t.name==="command.output"){const a=gb(e,t);if(!a)return!1;const i=ip(t);return i&&(a.detail=pc(a.detail,i)),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 IF(e,t,n){if(t.name!=="tool.completed"||n.kind==="command")return!1;const a=jf(t),i=fo(e,s=>s.state==="running"&&s.kind!=="command"&&(a?s.callId===a:!!t.action&&s.action===t.action));if(!i)return!1;const r=n.content.trim();return i.id=n.id,i.label=n.label,i.timestamp=n.timestamp,i.state=n.state,r&&r!==i.content.trim()&&(i.content.trim()===i.action?i.content=r:i.detail=pc(i.detail,r)),n.detail&&(i.detail=pc(i.detail,n.detail)),i.meta=n.meta,i.receipt=n.receipt,i.imagePreview=n.imagePreview??i.imagePreview,i.artifacts=n.artifacts,!0}function CF(e,t,n){if(t.name!=="workspace_action_result")return!1;const a=AF(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 RF(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 gb(e,t){const n=jf(t);if(n){const a=fo(e,i=>i.kind==="command"&&i.callId===n);if(a)return a}return fo(e,a=>a.kind==="command")}function AF(e,t){const n=t.action??"",a=Xk[n]??{started:"Running workspace action"};return fo(e,i=>i.state==="running"&&i.label===a.started&&i.kind!=="command"&&!i.controlKind)}function PF(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 TF(e){if(e.name==="assistant.reasoning.delta")return be(Ae(e.data),["kind"])==="commentary"?"Update":"Reasoning";if(Gc(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(ap(e)&&e.name==="tool.started")return"Reading image";if(ap(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=Q5(e);if(t)return t;const n=OF(e);if(n)return n;const a=jF(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"?EF(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 Xk={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 EF(e){const t=e.action??"",n=Xk[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 MF(e,t){if(e.name==="assistant.reasoning.delta")return e.output??"";if(t)return t.path;const n=Zk(e.output??"");if(n)return n.text;if(Gc(e)||e.name==="turn.interrupted")return e.output??e.error??"";const a=NF(e);if(a)return a;const i=$F(e);if(i)return i;const r=eF(e);if(r)return r;const s=Qk(e);if(s)return s;if(e.name==="command.output")return t_(e.output??"");if(e.name==="tool.started"||e.name==="tool.completed"){const d=e.data;if(d&&typeof d=="object"){const p=d.command;if(typeof p=="string"&&p.trim())return p;const m=d.tool;if(typeof m=="string"&&m.trim())return m;const h=d.type;if(typeof h=="string"&&h.trim())return h}}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 jF(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 OF(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 NF(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(Lo(e.output??"")),i=be(a,["output"]);if(i)return i;const r=Ae(e.args),s=be(r,["url"]);return s||(e.action==="openpond_browser_type"?"Text redacted":e.error??e.output??e.action)}function $F(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(Lo(e.output??"")),i=be(a,["output"]);if(i)return i;const r=Ae(e.args),s=be(r,["reason"]);if(s)return s;const d=be(r,["objective"]);return d||(e.error??null)}function DF(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"||Qk(e)||a&&/(^|[._-])exec_command$/i.test(a))return"command"}function LF(e){if(e.name==="turn.interrupted")return"turn_aborted";if(Gc(e))return"goal_context"}function Qk(e){const t=Ae(e.data),n=be(t,["type"]),a=be(t,["tool","toolName","tool_name","name","functionName","function_name"]),i=Ae(t?.result),r=Ae(Lo(e.output??"")),s=Ae(r?.data),d=be(t,["command","cmd"])??be(Ae(t?.input),["command","cmd"])??be(Ae(t?.arguments),["command","cmd"])??be(Ae(t?.args),["command","cmd"])??zF(be(t,["arguments","args","input"]))??be(Ae(e.args),["command","cmd"])??be(i,["command","cmd"])??be(s,["command","cmd"]);return d||e.name==="tool.started"&&(e.action==="commandExecution"||n==="commandExecution"||/(^|[._-])exec_command$/i.test(a??""))&&e.output?.trim()||null}function zF(e){if(!e)return null;const t=Lo(e),n=Ae(t);return be(n,["command","cmd"])}function jf(e){const t=Ae(e.data);return be(t,["callId","call_id","toolCallId","tool_call_id","id","itemId","item_id"])}function UF(e){const t=Ae(e.data);if(!t)return null;const n=[],a=Ae(t.workspaceToolTiming),i=typeof a?.durationMs=="number"?a.durationMs:null;i!==null&&n.push(WF(i));const r=Ae(t.workspaceExecutionTarget),s=be(r,["target"]);if(s==="sandbox"){const m=r?.hybrid===!0,h=be(r,["sandboxId","workspaceId"]);n.push(`${m?"Hybrid ":""}sandbox${h?` ${bb(h)}`:""}`)}else s==="local"&&n.push("local workspace");const d=Ae(t.sourcePreservation);if(d?.attempted===!0)if(d.ok!==!0)n.push("checkpoint failed");else if(d.preserved===!0){const m=be(d,["preservedSha"]);n.push(m?`checkpoint ${GF(m)}`:"checkpoint saved")}else n.push("checkpoint clean");const p=e_(t);return p&&(n.push(`receipt ${bb(p.id)}`),n.push(`${KF(p.totalUsd)} ${p.status}`)),n.length>0?n.join(" · "):null}function HF(e){const t=e_(Ae(e.data));return t?{id:t.id,status:t.status,totalUsd:t.totalUsd}:void 0}function qF(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 i=be(n,["roleId"])??be(t,["roleId"]),r=be(n,["status"])??be(t,["status"]);return{sessionId:a,label:"Open conversation",...i?{roleId:i}:{},...r?{status:r}:{}}}function BF(e){if(e.name!=="subagent.message")return;const t=Ae(e.data),n=Ae(t?.message);if(!n)return;const a=be(n,["id"]),i=be(n,["kind"]),r=be(n,["fromRunId"]),s=be(n,["body"]);if(!a||!i||!r||!s)return;const d=Ae(t?.delivery??n.delivery),p=Ae(t?.modelRef),m=be(p,["providerId"]),h=be(p,["modelId"]),y=be(d,["deliveredParentSessionId"])===e.sessionId&&!r.startsWith("parent:")?"received":"sent",w=Array.isArray(n.refs)?n.refs.flatMap(R=>{const A=Ae(R),N=be(A,["kind"]),O=be(A,["id"]),D=be(A,["label"]);return N&&O&&D?[{kind:N,id:O,label:D}]:[]}):[];return{direction:y,summary:FF(s),body:s,messageId:a,kind:i,fromRunId:r,toRunId:be(n,["toRunId"]),toRole:be(n,["toRole"]),childSessionId:be(t,["childSessionId"]),roleId:be(t,["roleId"]),modelRef:m&&h?{providerId:m,modelId:h}:null,deliveryStatus:be(d,["status"]),wakeReason:be(d,["wakeParentReason"]),createdAt:be(n,["createdAt"]),refs:w}}function FF(e){const t=e.replace(/\s+/g," ").trim();if(!t)return"No message body";const n=/^(.*?[.!?])(?:\s|$)/.exec(t)?.[1]??t;return VF(n,96)}function VF(e,t){if(e.length<=t)return e;const n=e.slice(0,t-1),a=n.lastIndexOf(" "),i=a>=Math.floor(t*.55)?a:t-1;return`${n.slice(0,i).trimEnd()}...`}function e_(e){const t=Ae(e?.sandbox),n=Array.isArray(t?.receipts)?t.receipts:[];for(let a=n.length-1;a>=0;a-=1){const i=Ae(n[a]),r=be(i,["id"]),s=be(i,["status"]),d=be(i,["totalUsd","retailTotalUsd"]);if(r&&s&&d)return{id:r,status:s,totalUsd:d}}return null}function WF(e){return e<1e3?`${Math.max(0,Math.round(e))} ms`:e<1e4?`${(e/1e3).toFixed(1)} s`:`${Math.round(e/1e3)} s`}function KF(e){const t=e.trim();return t.startsWith("$")?t:`$${t}`}function GF(e){return e.length>12?e.slice(0,12):e}function bb(e){const t=e.trim();return t.length<=14?t:`${t.slice(0,6)}...${t.slice(-4)}`}function t_(e){let t=e.replace(/\r\n/g,`
136
- `).trim();if(!t)return"";const n=YF(t);if(n!==null)return ar(n);const a=`
137
- Output:
138
- `,i=t.indexOf(a);return i>=0&&XF(t.slice(0,i))&&(t=t.slice(i+a.length).trim()),t=t.replace(/^Total output lines: \d+\n\n/,""),ar(t.trim())}function ip(e){const t=t_(e.output??"");if(t)return t;const n=Ae(Ae(e.data)?.result);return n?ar(n_(n)):""}function ZF(e){const t=Ae(e.data),n=Ae(t?.result),a=Ae(Lo(e.output??"")),i=Ae(a?.data),r=Ae(t?.workspaceToolTiming),s=[n?.exitCode,i?.exitCode,t?.exitCode].find(p=>typeof p=="number"),d=r?.durationMs;return{...typeof s=="number"?{exitCode:s}:{},...typeof d=="number"?{durationMs:d}:{}}}function JF(e,t){const n=Date.parse(t)-Date.parse(e);return Number.isFinite(n)&&n>0?n:null}function YF(e){const t=Ae(Lo(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?n_(a,be(t,["output"])):typeof t.output=="string"?t.output.trim():""}function n_(e,t=null){const n=be(e,["stdout"])?.replace(/\r\n/g,`
139
- `).trimEnd()??"",a=be(e,["stderr"])?.replace(/\r\n/g,`
140
- `).trimEnd()??"",i=[n,a].filter(Boolean);return i.length>0?i.join(`
141
- `):t?.replace(/\r\n/g,`
142
- `).trim()??""}function XF(e){return/^(Chunk ID|Exit code):/m.test(e)&&/Wall time:/m.test(e)}function pc(e,t){const n=e??"";if(!n)return ar(t);if(n===t||n.includes(t))return n;if(t.includes(n))return ar(t);const a=n.endsWith(`
143
- `)||t.startsWith(`
144
- `)?"":`
145
- `;return ar(`${n}${a}${t}`)}function ar(e){if(e.length<=pb)return e;const t=`
146
-
147
- … output omitted from live view; full output remains in task history …
148
-
149
- `,n=Math.max(0,pb-fb-t.length);return`${e.slice(0,fb)}${t}${e.slice(-n)}`}const QF=/\bopenpond\s+opchat\b/i,e4=/\b(?:50[0-9]|52[0-9]|53[0-9])\b|bad\s+gateway|gateway\s+timeout|service\s+unavailable/i;function a_(e){const t=e?.trim()||"Turn failed";return QF.test(t)&&e4.test(t)?"Server connection lost. Retry your message.":t}function t4(e,t){if((jl(t,"code")??jl(t,"errorCode"))==="opchat_quota_exceeded")return"opchat_quota_exceeded";const a=t&&typeof t=="object"?t.error:null;if(a&&typeof a=="object"&&(jl(a,"code")??jl(a,"errorCode"))==="opchat_quota_exceeded")return"opchat_quota_exceeded";const i=e??"";return/\bopchat_quota_exceeded\b/i.test(i)||/OpChat token allowance is exhausted/i.test(i)?"opchat_quota_exceeded":null}function jl(e,t){if(!e||typeof e!="object")return null;const a=e[t];return typeof a=="string"&&a.trim()?a.trim():null}function n4(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(d=>d.subagentMessage))continue;const i=a4(a.activities??[]);if(i.length===0){a.deliverables=void 0;continue}const r=t.get(a.turnId)??"",s=r?o4(i,r):[];if(s.length>0){a.deliverables=s;continue}a.deliverables=n.has(a.turnId)?[i[i.length-1]]:void 0}}function a4(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 i of a.artifacts??[])t.has(i.path)||(n.delete(i.path),n.set(i.path,i));return[...n.values()]}function o4(e,t){const n=o_(t);return e.filter(a=>i4(a).some(i=>t.includes(i)||n.includes(i)))}function i4(e){const t=new Set;for(const n of[e.path,e.title,r4(e.path)]){const a=n.trim();a&&(t.add(a),t.add(o_(a)))}return[...t]}function r4(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).at(-1)??e}function o_(e){try{return decodeURIComponent(e)}catch{return e}}const i_=8;function s4(e){if(e.name!=="tool.completed"||e.status==="failed")return[];if(e.action!=="web_search"&&e.action!=="web_fetch")return[];const t=sp(e.data),n=e.output?sp(Lo(e.output)):null;return l4(t??n)}function rp(e,t){if(t.length===0)return e;const n=[],a=new Set;for(const i of[...e??[],...t]){const r=r_(i.url);if(!(!r||a.has(r))&&(a.add(r),n.push(i),n.length>=i_))break}return n.length>0?n:void 0}function sp(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 i of["result","data","output"]){const r=sp(n[i],t+1);if(r)return r}return null}function l4(e){if(!e)return[];const t=[],n=new Set;for(let a=0;a<e.results.length;a+=1){const i=c4(e.results[a],a,e.provider);if(!i)continue;const r=r_(i.url);if(!(!r||n.has(r))&&(n.add(r),t.push(i),t.length>=i_))break}return t}function c4(e,t,n){const a=Ae(e);if(!a)return null;const i=be(a,["url","href"]);if(!i||!d4(i))return null;const r=be(a,["title"])??vb(i)??`Source ${t+1}`;return{id:be(a,["id"])??`source_${t+1}`,title:r,url:i,sourceName:be(a,["sourceName","source_name","source"])??vb(i),snippet:be(a,["snippet","description"]),provider:n,faviconUrl:u4(be(a,["faviconUrl","favicon_url","iconUrl","icon_url"]))??m4(i),publishedAt:be(a,["publishedAt","published_at"]),updatedAt:be(a,["updatedAt","updated_at"])}}function d4(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function r_(e){try{const t=new URL(e);return t.hash="",t.toString()}catch{return null}}function u4(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 m4(e){try{return new URL("/favicon.ico",e).toString()}catch{return null}}function vb(e){try{return new URL(e).hostname.replace(/^www\./i,"")}catch{return null}}const yb=new WeakMap;function Zc(e){const t=yb.get(e);if(t)return t;const n=p4(e);return yb.set(e,n),n}function p4(e){const t=[],n=new Map;for(const a of e){if(a.name==="turn.started"){Zl(t,a),f4(t,a);const i=v4(a.args);if(i){const r=Zk(i);if(r){hb(t,{...a,name:r.kind==="turn_aborted"?"turn.interrupted":"diagnostic",output:r.text,data:{...Ae(a.data)??{},kind:r.kind}});continue}t.push({id:a.id,role:"user",content:i,attachments:y4(a.args),timestamp:a.timestamp,turnId:a.turnId});const s=xb(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 i=xb(a.data);if(!i)continue;const r=fo(t,s=>s.turnId===a.turnId&&!!s.createImproveRun);r?(r.createImproveRun=i,r.timestamp=a.timestamp):t.push({id:`${a.id}:create-improve`,role:"assistant",timestamp:a.timestamp,turnId:a.turnId,createImproveRun:i});continue}if(a.name==="assistant.delta"){const i=a.output??"";if(!i)continue;Zl(t,a);const r=t[t.length-1];if(r?.role==="assistant"&&r.turnId===a.turnId&&!r.createImproveRun)r.content=`${r.content??""}${i}`,r.timestamp=a.timestamp,r.sources=rp(r.sources,Sb(n,a.turnId)??[]);else{const s=Sb(n,a.turnId);t.push({id:a.id,role:"assistant",content:i,timestamp:a.timestamp,turnId:a.turnId,...s?.length?{sources:s}:{}})}continue}if(a.name==="assistant.reasoning.delta"){const i=a.output??"";if(!i)continue;Zl(t,a);const r=t[t.length-1];r?.role==="assistant"&&r.turnId===a.turnId&&r.reasoningContent!==void 0&&!r.createImproveRun?(r.reasoningContent=`${r.reasoningContent}${i}`,r.timestamp=a.timestamp):r?.role==="assistant"&&r.turnId===a.turnId&&!r.reasoningContent&&!r.createImproveRun?(r.reasoningContent=i,r.timestamp=a.timestamp):t.push({id:a.id,role:"assistant",reasoningContent:i,timestamp:a.timestamp,turnId:a.turnId});continue}if(a.name==="user_question.asked"){const i=Ae(a.data),r=ZR.safeParse(i?.question);if(!r.success)continue;t.push({id:a.id,role:"assistant",timestamp:a.timestamp,turnId:a.turnId,userQuestion:r.data});continue}if(a.name==="user_question.answered"||a.name==="user_question.dismissed"){const i=Ae(a.data),r=JR.safeParse(i?.resolution);if(!r.success)continue;const s=fo(t,d=>d.userQuestion?.id===r.data.questionId);if(!s?.userQuestion||s.userQuestion.status!=="pending")continue;s.userQuestion={...s.userQuestion,status:r.data.action==="answer"?"answered":"dismissed",answer:r.data.action==="answer"?{optionId:r.data.optionId,text:r.data.text}:null,answeredAt:a.timestamp},s.timestamp=a.timestamp;continue}if(a.name==="turn.completed"){op(t,a,"completed");continue}if(a.name==="turn.failed"){op(t,a,"failed");const i=a.error??"Turn failed",r=t4(i,a.data);t.push({id:a.id,role:"error",content:a_(i),...r?{errorKind:r}:{},timestamp:a.timestamp,turnId:a.turnId});continue}if(a.name==="turn.interrupted"){hF(t,a);continue}if(vF(a)){yF(t,a);continue}if(a.name.startsWith("harness.refiner.")){oF(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.")||Gc(a)){if(g4(a))continue;const i=q5(a);if(i){H5(t,a,i);continue}const r=s4(a);r.length>0&&h4(t,n,a.turnId,r),hb(t,a)}if(a.name==="workspace.diff"){const i=b4(a.data);if(!i||i.filesChanged===0)continue;const r=fo(t,s=>s.role==="assistant"&&s.turnId===a.turnId);r&&(r.changeSummary=i,r.timestamp=a.timestamp)}}return n4(t),t}function f4(e,t){if(Ae(t.args)?.interactionKind!=="steer")return;const n=e.at(-1);n?.role==="status_divider"&&n.statusKind==="interruption"&&n.content==="Stopped by user"&&e.pop()}function h4(e,t,n,a){if(!n)return;const i=e[e.length-1];if(i?.role!=="assistant"||i.turnId!==n){t.set(n,rp(t.get(n),a));return}i.sources=rp(i.sources,a)}function Sb(e,t){if(!t)return;const n=e.get(t);return n&&e.delete(t),n}function g4(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 b4(e){const t=cP.safeParse(e);return t.success?t.data:null}function v4(e){if(!e||typeof e!="object"||!("prompt"in e))return"";const t=e.prompt;return typeof t=="string"?t:""}function y4(e){if(!e||typeof e!="object"||!("attachments"in e))return;const t=pE.array().safeParse(e.attachments);return t.success&&t.data.length>0?t.data:void 0}function xb(e){const t=Ae(e);if(!t)return null;const n=Vs.safeParse(t.createImproveRun);return n.success?n.data:null}function JW(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 i=Math.floor(a/60);return i<48?`${i}h`:`${Math.floor(i/24)}d`}function YW(e){const t=s_(e);return t?t.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):""}function XW(e){const t=s_(e);return t?t.toLocaleString():""}function s_(e){if(!e)return null;const t=new Date(e);return Number.isNaN(t.getTime())?null:t}function S4(e){const{chatMessages:t,runtimeIndexes:n,selectedSessionId:a}=e,[i,r]=g.useState({}),s=g.useCallback(p=>{r(m=>({...m,[p.sessionId]:p}))},[]);g.useEffect(()=>{r(p=>{let m=p;for(const[h,S]of Object.entries(p)){const y=Zc(nl(n,h));Vk(y,S)&&(m===p&&(m={...p}),delete m[h])}return m})},[n]);const d=g.useMemo(()=>Fk(t,a?i[a]:null),[t,i,a]);return{pendingChatUserMessages:i,recordPendingChatUserMessage:s,visibleChatMessages:d}}const l_="openpond.commandAccessMode";function Jc(){if(typeof window>"u")return null;try{return window.localStorage}catch{return null}}function x4(e){return e==="ask"||e==="full-access"||e==="disabled"?e:null}function c_(e=Jc()){if(!e)return{};const t=x4(e.getItem(l_));return{...t?{openPondCommandAccessMode:t}:{}}}function k4(e,t=Jc()){try{t?.setItem(l_,e)}catch{}}function _4(e,t=Jc()){const n=ta(e);return{openPondCommandAccessMode:c_(t).openPondCommandAccessMode??n.openPondCommandAccessMode??qs}}function w4(e,t=Jc()){const n=ta(e),a=c_(t),i={};return a.openPondCommandAccessMode&&a.openPondCommandAccessMode!==n.openPondCommandAccessMode&&(i.openPondCommandAccessMode=a.openPondCommandAccessMode),i}function I4({connection:e,selectedSession:t,setBootstrap:n,setError:a,setOpenPondCommandAccessMode:i,setSessions:r}){return{changeOpenPondCommandAccessMode:g.useCallback((d,p=t)=>{i(d),k4(d);const m=p?.provider==="codex"?null:p;m&&r(h=>h.map(S=>S.id===m.id?{...S,openPondCommandAccessMode:d}:S)),e&&(J.savePreferences(e,{openPondCommandAccessMode:d}).then(()=>{n(h=>h&&{...h,preferences:{...h.preferences,openPondCommandAccessMode:d}})}).catch(h=>{a(h instanceof Error?h.message:String(h))}),m&&J.patchSession(e,m.id,{openPondCommandAccessMode:d}).then(h=>{r(S=>S.map(y=>y.id===h.id?h:y))}).catch(h=>{a(h instanceof Error?h.message:String(h))}))},[e,t,n,a,i,r])}}function C4({localProjects:e,cloudProjects:t,sessions:n,runtimeIndexes:a,appPreferences:i,selectedSessionId:r,selectedProjectId:s,archivedChatsOpen:d,projectsExpanded:p,chatRowsVisibleCount:m,sidebarFileBookmarks:h=[]}){const S=g.useMemo(()=>e.filter(se=>!se.hiddenFromDefaultSidebar),[e]),y=g.useMemo(()=>n.filter(se=>!se.archived&&kb(se)),[n]),w=g.useMemo(()=>y.filter(se=>se.pinned),[y]),R=g.useMemo(()=>y.filter(se=>!!se.savedForLater),[y]),A=g.useMemo(()=>n.filter(se=>se.archived&&kb(se)),[n]),N=g.useMemo(()=>new Set(e.map(se=>se.id)),[e]),O=g.useMemo(()=>new Set(t.map(se=>se.id)),[t]),D=g.useMemo(()=>zx(e),[e]),x=g.useMemo(()=>{const se={};for(const Ce of[...y,...A]){const Le=Pg(Ce,N,D,O);Le&&(se[Ce.id]=Le)}return se},[y,A,O,N,D]),I=g.useMemo(()=>y.filter(se=>!se.pinned&&!se.savedForLater&&!se.appId&&!x[se.id]),[y,x]),P=g.useMemo(()=>A.filter(se=>!se.appId&&!Pg(se,N,D,O)),[A,O,N,D]),E=g.useMemo(()=>{const se={};for(const Ce of y){if(Ce.pinned||Ce.savedForLater)continue;const Le=x[Ce.id];if(!Le)continue;const Qe=se[Le];Qe?Qe.push(Ce):se[Le]=[Ce]}return se},[y,x]),T=g.useMemo(()=>{const se={};for(const Ce of n){if(Ce.archived||!d_(Ce))continue;const Le=se[Ce.parentSessionId];Le?Le.push(Ce):se[Ce.parentSessionId]=[Ce]}for(const Ce of Object.values(se))Ce.sort((Le,Qe)=>Date.parse(Qe.updatedAt)-Date.parse(Le.updatedAt));return se},[n]),z=g.useMemo(()=>S.map((se,Ce)=>{const Le=vt("local",se.id),Qe=kB(se,t);return{id:Le,kind:"local",project:se,pinned:!!i[Le]?.pinned,order:i[Le]?.order??Ce,cloudLinkTrusted:!Qe,cloudLinkWarning:Qe}}).sort(tm),[i,t,S]),U=g.useMemo(()=>t.map((se,Ce)=>{const Le=vt("cloud",se.id);return{id:Le,kind:"cloud",project:se,pinned:!!i[Le]?.pinned,order:i[Le]?.order??Ce,cloudLinkTrusted:!0,cloudLinkWarning:null}}).sort(tm),[i,t]),$=g.useMemo(()=>new Set(S.map(se=>ma(se,t)?.id??null).filter(se=>!!se)),[t,S]),V=g.useMemo(()=>U.filter(se=>!$.has(se.project.id)),[U,$]),re=g.useMemo(()=>[...z,...V].sort(tm),[V,z]),Q=g.useMemo(()=>re.filter(se=>se.pinned),[re]),Ie=g.useMemo(()=>h.filter(se=>se.status==="pinned"),[h]),Se=g.useMemo(()=>h.filter(se=>se.status==="saved_for_later"),[h]),G=re,Ee=g.useMemo(()=>R4(G,p,s),[G,p,s]),xe=g.useMemo(()=>[...Q.map(se=>({type:"project",key:ei({type:"project",id:se.id}),id:se.id,item:se,order:se.order})),...w.map(se=>({type:"session",key:ei({type:"session",id:se.id}),id:se.id,session:se,order:se.order})),...Ie.map((se,Ce)=>({type:"file",key:ei({type:"file",id:se.id}),id:se.id,file:se,order:se.order??Q.length+w.length+Ce}))].sort((se,Ce)=>{if(se.order!==Ce.order)return se.order-Ce.order;if(se.type!==Ce.type){const it={project:0,session:1,file:2};return it[se.type]-it[Ce.type]}const Le=se.type==="project"?se.item.project.name:se.type==="session"?se.session.title:se.file.path,Qe=Ce.type==="project"?Ce.item.project.name:Ce.type==="session"?Ce.session.title:Ce.file.path;return Le.localeCompare(Qe)}),[Ie,Q,w]),le=g.useMemo(()=>d?[...I,...P]:I,[d,P,I]),ke=g.useMemo(()=>le.slice(0,Math.max(xn,m)),[le,m]),ae=g.useMemo(()=>nl(a,r),[a,r]),he=g.useMemo(()=>Zc(ae),[ae]),ve=Sk(a,r),Ze=xk(a,r),Re=lB(a,r);return{activeSessions:y,pinnedSessions:w,savedForLaterSessions:R,pinnedFiles:Ie,savedForLaterFiles:Se,chatSessions:I,archivedSessions:A,pinnedProjects:Q,pinnedItems:xe,projectRows:G,localProjectRows:z,visibleProjectRows:Ee,cloudProjectRows:V,projectSessionRowsByProjectId:E,childSessionRowsByParentId:T,sidebarProjectIdBySessionId:x,chatRows:le,visibleChatRows:ke,sessionEvents:ae,chatMessages:he,contextUsage:ve,goalRuntime:Ze,subagentRuntime:Re}}function kb(e){return d_(e)?!1:e.hiddenFromDefaultSidebar?e.metadata?.benchmarkRuntime==="desktop_local_work":!0}function d_(e){return!!(e.parentSessionId&&e.subagentRunId)}function tm(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 R4(e,t,n){if(t||e.length<=Vl)return e;const a=e.slice(0,Vl);if(!n||a.some(r=>r.id===n))return a;const i=e.find(r=>r.id===n);return i?[...a.slice(0,Vl-1),i]:a}function A4(e){return e.name==="turn.completed"||e.name==="turn.failed"||e.name==="turn.interrupted"}function u_(e){let t=-1,n=null;for(let a=e.length-1;a>=0;a-=1){const i=e[a];if(i?.name==="turn.started"){t=a,n=i.turnId??null;break}}if(t===-1)return"none";for(let a=e.length-1;a>t;a-=1){const i=e[a];if(!(!i||!A4(i))&&!(n&&i.turnId&&i.turnId!==n))return i.name==="turn.completed"?"completed":"blocked"}return"pending"}function _b(e,t){if(e.systemKind)return!1;const n=nl(t,e.id);if(n.length===0)return!1;const a=u_(n);return a==="pending"||a==="none"&&m_(n)==="pending"}function wb(e,t){if(e.systemKind||e.status!=="active")return!1;const n=nl(t,e.id);if(n.length===0)return!0;const a=u_(n);return a==="pending"||a==="none"&&m_(n)!=="terminal"}function m_(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 P4({goalRuntime:e,goalRuntimeBySessionId:t,runtimeIndexes:n,selectedSession:a,selectedSessionId:i,sidebarSessions:r,subagentRuntimeBySessionId:s}){const d=g.useMemo(()=>new Map(r.map(y=>[y.id,y])),[r]),p=g.useMemo(()=>{const y=new Set;for(const[w,R]of t??[]){const A=d.get(w);R.tone==="active"&&!A?.systemKind&&y.add(w)}for(const w of n.activeGoalSessionIds)d.get(w)?.systemKind||y.add(w);return i&&!a?.systemKind&&e?.tone==="active"&&y.add(i),y},[e,t,n,a,i,d]),m=g.useMemo(()=>{const y=new Set(p);for(const[w,R]of s??[]){const A=d.get(w);R.activeCount>0&&!A?.systemKind&&y.add(w)}for(const w of n.activeSubagentSessionIds)d.get(w)?.systemKind||y.add(w);for(const w of r)w.systemKind||_b(w,n)&&y.add(w.id);return a&&_b(a,n)&&y.add(a.id),y},[p,n,a,r,d,s]),h=g.useMemo(()=>{const y=new Set(m);for(const w of r)wb(w,n)&&y.add(w.id);return a&&wb(a,n)&&y.add(a.id),y},[m,n,a,r]),S=!!(a&&!a.systemKind&&m.has(a.id));return{runningSessionIds:h,selectedSessionRunning:S}}const T4=1e3;function E4(e){const[t,n]=g.useState(()=>new Date().toISOString());return g.useEffect(()=>{if(!e)return;const a=()=>n(new Date().toISOString());a();const i=window.setInterval(a,T4);return()=>window.clearInterval(i)},[e]),t}function M4(e){const{codexHistoryEvents:t,codexHistorySessions:n,connection:a,expandedProjectIds:i,goalRuntime:r,locallyActiveCodexHistorySessionIds:s,pinnedSessions:d,savedForLaterSessions:p,projectSessionRowsByProjectId:m,rightChatHistoryEvents:h,runtimeIndexes:S,selectedSession:y,selectedSessionId:w,serverId:R,setCodexHistorySessions:A,sidebarSessions:N,subagentRuntime:O,visibleChatRows:D,visibleProjectRows:x}=e,[I,P]=g.useState({});g.useEffect(()=>{P({})},[R]);const E=g.useMemo(()=>{const le=[],ke=new Set,ae=ve=>{!ve||ve.id===w||!Nt(ve.id)||ke.has(ve.id)||(ke.add(ve.id),le.push(ve.id))};for(const ve of n)(ve.status==="active"||s.has(ve.id))&&ae(ve);const he=le.length;for(const ve of x)for(const Ze of(m[ve.id]??[]).slice(0,2))ae(Ze);for(const ve of i)for(const Ze of(m[ve]??[]).slice(0,Vl))ae(Ze);for(const ve of d)ae(ve);for(const ve of p)ae(ve);for(const ve of D)ae(ve);return[...le.slice(0,he),...le.slice(he,he+8)].join(`
150
- `)},[n,i,s,d,p,m,w,D,x]),T=g.useCallback(le=>{P(ke=>ke[le.session.id]===le.events?ke:{...ke,[le.session.id]:le.events}),A(ke=>Kc(ke,le.session))},[A]),z=g.useMemo(()=>{if(!E)return"";const le=new Set(E.split(`
151
- `).filter(Boolean));return N.filter(ke=>le.has(ke.id)&&ke.status==="active").map(ke=>ke.id).join(`
152
- `)},[E,N]),U=g.useMemo(()=>E?E.split(`
153
- `).filter(le=>s.has(le)).join(`
154
- `):"",[E,s]);g.useEffect(()=>{!y||!w||!Nt(w)||t.length===0||T({session:y,events:t})},[T,t,y,w]),g.useEffect(()=>{if(!a||!E)return;const le=a,ke=E.split(`
155
- `).filter(Boolean),ae=new Set(z.split(`
156
- `).filter(Boolean)),he=new Set(U.split(`
157
- `).filter(Boolean)),ve=ke.map(Ze=>Mf({connection:le,locallyActive:he.has(Ze),onPayload:Re=>T(Ef(Re,he.has(Ze))),reportedActive:ae.has(Ze),sessionId:Ze,surface:"sidebar"}));return()=>ve.forEach(Ze=>Ze())},[T,z,U,E,a]);const $=g.useMemo(()=>new Map(N.map(le=>[le.id,le])),[N]),V=g.useMemo(()=>{const le=new Map(S.latestGoalRuntimeBySessionId);for(const ke of N){const ae=ke.status==="active"?Gu(ke.metadata):null;ae&&le.set(ke.id,ae)}for(const ke of[I,h])for(const[ae,he]of Object.entries(ke)){const ve=$.get(ae),Ze=ve?.status==="active"?Gu(ve.metadata):null,Re=Zm(he)??Af(he)??(ve?.status==="active"?mc(he)??Ze:null);Re?le.set(ae,Re):le.delete(ae)}if(w)if(r)le.set(w,r);else if(y?.status==="active"&&t.length>0){const ke=Zm(t)??mc(t)??Gu(y.metadata);ke?le.set(w,ke):le.delete(w)}else(!Nt(w)||t.length>0)&&le.delete(w);return le},[t.length,I,r,h,S.latestGoalRuntimeBySessionId,y?.status,y?.metadata,w,$,N]),re=g.useMemo(()=>[...V.values()].some(le=>le.tone==="active"&&!!le.observedAt),[V]),Q=E4(re),Ie=g.useMemo(()=>re?new Map([...V].map(([le,ke])=>[le,Lq(ke,Q)??ke])):V,[V,Q,re]),Se=w?Ie.get(w)??r:r,G=g.useMemo(()=>{const le=new Map(S.latestSubagentRuntimeBySessionId);return w&&(O?le.set(w,O):le.delete(w)),le},[S.latestSubagentRuntimeBySessionId,w,O]),{runningSessionIds:Ee,selectedSessionRunning:xe}=P4({goalRuntime:Se,goalRuntimeBySessionId:Ie,runtimeIndexes:S,selectedSession:y,selectedSessionId:w,sidebarSessions:N,subagentRuntimeBySessionId:G});return{goalRuntime:Se,runningSessionIds:Ee,selectedSessionRunning:xe,sidebarGoalRuntimeBySessionId:Ie,sidebarSubagentRuntimeBySessionId:G}}function j4({searchOpen:e,sectionMenuOpen:t,setSectionMenuOpen:n,setSearchOpen:a,setQuery:i}){g.useEffect(()=>{const r=s=>{if((s.metaKey||s.ctrlKey)&&s.key.toLowerCase()==="k"){s.preventDefault(),n(null),a(d=>!d);return}if(s.key==="Escape"&&e){s.preventDefault(),a(!1),i(""),n(null);return}s.key==="Escape"&&t&&(s.preventDefault(),n(null))};return document.addEventListener("keydown",r),()=>document.removeEventListener("keydown",r)},[e,t,i,a,n])}function O4({afterSequence:e,appendEvents:t,connection:n,setApprovals:a,setSessions:i,setError:r,onDisconnected:s}){g.useEffect(()=>{if(!n?.token||e===null)return;const d=n;let p=null,m=[],h=null,S=null,y=!1;const w=new Map;let R=0;const A=16;function N(){p!==null&&(window.clearTimeout(p),p=null)}function O(){r($=>$==="Event stream disconnected"?null:$)}function D(){h=null;const $=m;if(m=[],$.length===0)return;R=Date.now(),t($);const V=N4($);V.length>0&&i(re=>V.reduce(Ss,re)),a(re=>{let Q=re;for(const Ie of $)if(Ie.name==="approval.requested"&&Ie.data&&(Q=[Ie.data,...Q]),Ie.name==="approval.resolved"&&Ie.data&&typeof Ie.data=="object"){const Se=Ie.data;Se.approvalId&&(Q=Q.filter(G=>G.id!==Se.approvalId))}return Q})}function x(){const $=Date.now()-R;if($>=A){h!==null&&(window.clearTimeout(h),h=null),D();return}h===null&&(h=window.setTimeout(D,A-$))}function I($){P($),m.push($),x()}function P($){if(!(!$.sessionId||!$.name.startsWith("harness.refiner."))){if($.name==="harness.refiner.completed"||$.name==="harness.refiner.failed"){w.delete($.sessionId);return}($.name==="harness.refiner.queued"||$.name==="harness.refiner.started")&&(w.set($.sessionId,typeof $.sequence=="number"?$.sequence:0),E())}}function E(){S!==null||w.size===0||(S=window.setTimeout(()=>{S=null,T()},1e3))}async function T(){if(!(y||w.size===0)){y=!0;try{await Promise.all([...w].map(async([$,V])=>{const re=await J.runtimeEventsPage(d,{sessionId:$,afterSequence:V,limit:100});for(const Q of re.events){const Ie=Q.event;w.set($,Math.max(w.get($)??0,Q.sequence)),I(Ie)}}))}catch{}finally{y=!1,E()}}}function z(){h!==null&&(window.clearTimeout(h),h=null),D()}document.addEventListener("visibilitychange",z);const U=sL(n,$=>{N(),O(),I($)},()=>{N(),p=window.setTimeout(()=>{U.isOpen()||(r("Event stream disconnected"),s?.())},2e3)},()=>{N(),O()},{afterSequence:e});return()=>{N(),h!==null&&window.clearTimeout(h),S!==null&&window.clearTimeout(S),h=null,S=null,m=[],document.removeEventListener("visibilitychange",z),U.close()}},[e,t,n,s,a,r,i])}function N4(e){const t=new Map;for(const n of e){const a=n.data;if(!a||typeof a!="object"||Array.isArray(a))continue;const i=n.name==="session.started"||n.name==="session.title.updated"?"session":n.name==="subagent.started"||n.name==="subagent.failed"?"childSession":null;if(!i)continue;const r=Im.safeParse(a[i]);r.success&&t.set(r.data.id,r.data)}return[...t.values()]}function nm(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function $4(e){return typeof e=="string"&&e.trim()?e.trim():null}function D4(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n.name!=="create_improve.updated")continue;const a=nm(n.data),i=nm(a?.createImproveRun);if(i?.state!=="ready_local"&&i?.state!=="released"||nm(i.adapter)?.kind!=="local")continue;const s=$4(i.id)??n.id;return[n.sessionId??"global",n.turnId??"turn",s].join(":")}return null}const L4=332,Ib=244,Cb=560,z4=560,Rb=320,Ab=2400,U4=440;function am(e){const t=typeof window>"u"?Cb:Math.min(Cb,Math.max(Ib,window.innerWidth-420));return Math.min(t,Math.max(Ib,Math.round(e)))}function om(e){const t=typeof window>"u"?Ab:Math.min(Ab,Math.max(Rb,window.innerWidth-U4));return Math.min(t,Math.max(Rb,Math.round(e)))}function H4(e,t){return!!(e&&e.serverUrl===t.serverUrl&&e.token===t.token&&e.platform===t.platform)}const Xi=new Map;function Of(e,t){const n=e?.trim();return n?`${t?.trim()||"global"}|${n}`:null}function p_(e,t){const n=Of(e,t);if(!n)return null;const a=Xi.get(n);return a?.updatedAt?a.agents:null}function q4(e,t,n){const a=Of(e,n);a&&Xi.set(a,{agents:t,promise:null,updatedAt:Date.now()})}function Nf(e){const t=e.teamId?.trim();if(!t)return Promise.resolve([]);const n=Of(t,e.accountKey);if(!n)return Promise.resolve([]);const a=Xi.get(n);if(!e.force){if(a?.updatedAt)return Promise.resolve(a.agents);if(a?.promise)return a.promise}const i=e.fetchAgents(t).then(r=>(q4(t,r,e.accountKey),r)).catch(r=>{const s=Xi.get(n);throw s?.promise===i&&Xi.set(n,{agents:s.agents,promise:null,updatedAt:s.updatedAt}),r});return Xi.set(n,{agents:a?.agents??[],promise:i,updatedAt:a?.updatedAt??0}),i}const B4=6e4,F4=6e4,V4=6e4,$f=["pinned","projects","cloudProjects","chats","savedForLater"];function W4(e,t,n,a=Date.now()){for(const i of J4(t,n))f_(t[i],n[i])||(e[i]=a)}function K4(e,t,n,a=Date.now()){const i={...t};for(const[r,s]of Object.entries(n)){if(a-s>B4){delete n[r];continue}const d=X4(e,r),p=e[r];!d||f_(p,t[r])||(i[r]=p)}return i}function G4(e,t,n,a=Date.now()){for(const i of $f)t[i]!==n[i]&&(e[i]=a)}function Z4(e,t,n,a=Date.now()){const i={...t};for(const r of $f){const s=n[r];if(s!==void 0){if(a-s>F4){delete n[r];continue}if(e[r]===t[r]){delete n[r];continue}i[r]=e[r]}}return Y4(e,i)?e:i}function Pb(e,t,n=Date.now()){return e===t?null:{value:t,changedAt:n}}function Tb(e,t,n=Date.now()){return t?n-t.changedAt>V4?{value:e,localChange:null}:e===t.value?{value:e,localChange:t}:{value:t.value,localChange:t}:{value:e,localChange:null}}function J4(e,t){return new Set([...Object.keys(e),...Object.keys(t)])}function f_(e,t){return e?.pinned===t?.pinned&&e?.archived===t?.archived&&e?.order===t?.order}function Y4(e,t){return $f.every(n=>e[n]===t[n])}function X4(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const Q4=5e4,Io="\0openpond-unscoped-runtime-events",qa=[];class e6{perSessionLimit;totalLimit;entries=new Map;eventKeyById=new Map;listenersByKey=new Map;allListeners=new Set;summaryListeners=new Set;retainedKeys=new Set;allEventsSnapshot=qa;summaryEventsSnapshot=qa;clock=0;eventCount=0;constructor(t={}){if(this.perSessionLimit=jb(t.perSessionLimit??Rf,"perSessionLimit"),this.totalLimit=jb(t.totalLimit??Q4,"totalLimit"),this.totalLimit<this.perSessionLimit)throw new Error("totalLimit must be greater than or equal to perSessionLimit")}append(t){if(t.length===0)return Mb();const n=new Map;let a=0;for(const m of t){if(this.eventKeyById.has(m.id)){a+=1;continue}const h=m.sessionId||Io,S=n.get(h);S?S.push(m):n.set(h,[m]),this.eventKeyById.set(m.id,h)}if(n.size===0)return{...Mb(),duplicateEventCount:a};const i=new Set;let r=0,s=0,d=!1;for(const[m,h]of n){h.some(Ob)&&(d=!0);const S=this.entries.get(m),y=S?.snapshot.events??qa,w=Math.max(0,Math.min(y.length,this.perSessionLimit-h.length)),R=h.length>this.perSessionLimit?h.slice(h.length-this.perSessionLimit):h,A=w===y.length?y:y.slice(y.length-w),N=A.length===0?R:[...A,...R],O=y.slice(0,y.length-A.length);O.some(Ob)&&(d=!0);for(const I of O)this.eventKeyById.delete(I.id);for(const I of h.slice(0,h.length-R.length))this.eventKeyById.delete(I.id);const x={eventIds:new Set(N.map(I=>I.id)),lastTouched:++this.clock,retained:S?.retained??this.retainedKeys.has(m),snapshot:{events:N,latestSequence:uc(N),revision:(S?.snapshot.revision??0)+1}};this.entries.set(m,x),this.eventCount+=N.length-y.length,r+=R.length,s+=O.length+h.length-R.length,i.add(m)}const p=this.enforceTotalLimit(i);return s+=p,this.publish(i,d||p>0),n6({acceptedEventCount:r,duplicateEventCount:a,evictedEventCount:s,changedKeys:i})}mergeBootstrap(t){const n=t6(t),a=new Set([...this.entries.keys(),...n.keys()]),i=[];for(const r of a){const s=n.get(r)??qa,d=this.entries.get(r)?.snapshot.events??qa;i.push(...Eq(s,d))}return this.replace(i)}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=qa,this.summaryEventsSnapshot=qa;const i=this.append(t);for(const p of this.retainedKeys){const m=this.entries.get(p);m&&(m.retained=!0)}const r=this.eventKeyById;let s=0;for(const p of n)r.has(p)||(s+=1);const d=new Set([...a].filter(p=>!this.entries.has(p)));return d.size>0&&this.publish(d,!0),{...i,evictedEventCount:i.evictedEventCount+s,changedSessionIds:new Set([...i.changedSessionIds,...[...d].filter(p=>p!==Io)]),unscopedEventsChanged:i.unscopedEventsChanged||d.has(Io)}}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=qa,this.summaryEventsSnapshot=qa,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??Eb:Eb;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(a6),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!==Io&&a.retained&&(t+=1);return{eventCount:this.eventCount,retainedSessionCount:t,sessionCount:this.entries.size-(this.entries.has(Io)?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[i,r]=a,s=this.eventCount-this.totalLimit;if(!r.retained||r.snapshot.events.length<=s){n+=r.snapshot.events.length,this.removeEntry(i),t.add(i);continue}const d=r.snapshot.events.slice(0,s),p=r.snapshot.events.slice(s);for(const m of d)this.eventKeyById.delete(m.id);r.eventIds=new Set(p.map(m=>m.id)),r.snapshot={events:p,latestSequence:uc(p),revision:r.snapshot.revision+1},this.eventCount-=d.length,n+=d.length,t.add(i)}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 i of this.listenersByKey.get(a)??[])i();for(const a of this.allListeners)a();if(n)for(const a of this.summaryListeners)a()}}}const Eb=Object.freeze({events:qa,latestSequence:null,revision:0});function t6(e){const t=new Map;for(const n of e){const a=n.sessionId||Io,i=t.get(a);i?i.push(n):t.set(a,[n])}return t}function n6(e){return{acceptedEventCount:e.acceptedEventCount,duplicateEventCount:e.duplicateEventCount,evictedEventCount:e.evictedEventCount,changedSessionIds:new Set([...e.changedKeys].filter(t=>t!==Io)),unscopedEventsChanged:e.changedKeys.has(Io)}}function Mb(){return{acceptedEventCount:0,duplicateEventCount:0,evictedEventCount:0,changedSessionIds:new Set,unscopedEventsChanged:!1}}function a6(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 jb(e,t){if(!Number.isInteger(e)||e<=0)throw new Error(`${t} must be a positive integer`);return e}function Ob(e){return e.name!=="assistant.delta"&&e.name!=="assistant.reasoning.delta"&&e.name!=="command.output"}const o6=256,i6=15e3,r6=5e3,s6=3e4;class l6{constructor(t={}){this.options=t}options;entries=new Map;connection=null;accountScope=null;generation=0;activateConnection(t){c6(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,d6(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 i=this.now(),r=this.entries.get(t);if(r?.state==="loading"&&!this.expired(r,i))return r.promise;if(r?.state==="failed"&&!this.expired(r,i))return Promise.resolve(null);const s=this.generation,d=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??r6),lastAccessedAt:p}),this.prune(),null});return this.entries.set(t,{state:"loading",promise:d,expiresAt:i+(this.options.loadingTtlMs??s6),lastAccessedAt:i}),this.prune(),d}clear(){this.generation+=1,this.entries.clear()}size(){return this.prune(),this.entries.size}prune(){const t=this.now();for(const[a,i]of this.entries)this.expired(i,t)&&this.entries.delete(a);const n=this.options.maxEntries??o6;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??i6:0;return t.expiresAt<=n+a}now(){return(this.options.now??Date.now)()}}const Nb=new l6;function QW(e,t,...n){return[t,e.serverUrl,...n].join("\0")}function c6(e,t){return e?.serverUrl===t?.serverUrl&&e?.token===t?.token&&e?.platform===t?.platform}function d6(e,t,n){e.delete(t),e.set(t,n)}const u6={connecting:"Connecting to OpenPond",account:"Loading account",team:"Loading default team",ready:"Ready"};function m6(e){return{label:u6[e],ready:e==="ready",stage:e}}const p6=650,f6=1200,h6=6e4;function g6(e){const{setDraftModel:t,setDraftProvider:n,setCodexPermissionMode:a,setCodexReasoningEffort:i,setOpenPondCommandAccessMode:r,setError:s,setSelectedAppId:d,setSelectedProjectId:p,setSelectedSessionId:m}=e,[h,S]=g.useState(null),[y,w]=g.useState(null),[R]=g.useState(()=>new e6),A=g.useSyncExternalStore(R.subscribeSummary,R.getSummaryEvents,R.getSummaryEvents),N=g.useCallback(Z=>{const me=R.getAllEvents(),_e=typeof Z=="function"?Z(me):Z;_e!==me&&R.replace(_e)},[R]),O=g.useCallback(Z=>{R.append(Z)},[R]),[D,x]=g.useState(null),[I,P]=g.useState([]),[E,T]=g.useState([]),[z,U]=g.useState([]),[$,V]=g.useState({}),[re,Q]=g.useState("connecting"),Ie=Xm(y?.account),Se=g.useRef({}),G=g.useRef({}),Ee=g.useRef({}),xe=g.useRef([]),le=g.useRef([]),ke=g.useRef(null),ae=g.useRef(null),he=g.useRef(null),ve=g.useRef(null),Ze=g.useRef(""),Re=g.useRef(!1),se=g.useRef(Date.now()),Ce=g.useRef(null),Le=g.useRef(null);g.useEffect(()=>{Nb.activateConnection(h),Nb.activateAccountScope(Ie)},[h,Ie]);const Qe=g.useCallback(Z=>{Re.current||Q(Z)},[]),it=g.useCallback(Z=>{V(me=>{const _e=typeof Z=="function"?Z(me):Z;return W4(Se.current,me,_e),_e})},[]),ut=g.useCallback(Z=>{P(me=>{const _e=typeof Z=="function"?Z(me):Z;return sb(G.current,me,_e),xe.current=_e,_e})},[]),Fe=g.useCallback(Z=>{T(me=>{const _e=typeof Z=="function"?Z(me):Z;return sb(Ee.current,me,_e),le.current=_e,_e})},[]),Ue=g.useCallback(()=>{if(Re.current||Ce.current!==null)return;const Z=()=>{Ce.current=null,!Re.current&&(Re.current=!0,Q("ready"))},me=Date.now()-se.current,_e=b6(me);if(_e===0){Z();return}Ce.current=window.setTimeout(Z,_e)},[]);g.useEffect(()=>()=>{Ce.current!==null&&window.clearTimeout(Ce.current)},[]);const ze=g.useCallback(Z=>{const me=ke.current,_e=!me||me===Z.server.id;ke.current=Z.server.id,x(He=>He?.serverId===Z.server.id?He:{afterSequence:Z.eventWindow?.latestSequence??uc(Z.events)??0,serverId:Z.server.id}),Ze.current=Z.preferences.defaultTeamId?.trim()??"",w(Z),_e?R.mergeBootstrap(Z.events):R.replace(Z.events),P(He=>{const qe=_e?rb(He,Z.sessions,G.current):Qm(He,Z.sessions,G.current);return xe.current=qe,qe}),T(He=>{const qe=_e?rb(He,Z.codexHistorySessions??[],Ee.current):Qm(He,Z.codexHistorySessions??[],Ee.current);return le.current=qe,qe}),U(Z.approvals),V(He=>K4(He,Z.sidebarAppPreferences,Se.current)),d(He=>He&&Z.apps.some(qe=>qe.id===He)?He:null),p(He=>{if(!He)return null;const qe=jx(He);return qe?.kind==="local"&&Z.localProjects.some(Xe=>Xe.id===qe.id)?vt("local",qe.id):qe?.kind==="cloud"&&(Z.cloudProjects??[]).some(Xe=>Xe.id===qe.id)?vt("cloud",qe.id):Z.localProjects.some(Xe=>Xe.id===He)?vt("local",He):(Z.cloudProjects??[]).some(Xe=>Xe.id===He)?vt("cloud",He):null}),m(He=>{if(!He)return null;const qe=[...Z.sessions,...Z.codexHistorySessions??[]];if(qe.some(at=>at.id===He&&!at.archived))return He;if(!_e)return null;const Xe=xe.current.find(at=>at.id===He)??le.current.find(at=>at.id===He)??null;return Xe&&!Xe.archived&&Dk(Xe,qe)?He:null})},[R,d,p,m]),M=g.useCallback(Z=>{Ze.current=Z.preferences.defaultTeamId?.trim()??"",w(me=>me&&{...me,preferences:Z.preferences})},[]);g.useEffect(()=>{const Z=ta(y?.preferences);n(Z.defaultChatProvider),t(Z.defaultChatModel)},[y?.preferences.defaultChatProvider,y?.preferences.defaultChatModel,t,n]),g.useEffect(()=>{a(ib(y?.preferences).codexPermissionMode)},[y?.preferences.codexPermissionMode,a]),g.useEffect(()=>{i(ib(y?.preferences).codexReasoningEffort)},[y?.preferences.codexReasoningEffort,i]),g.useEffect(()=>{r(_4(y?.preferences).openPondCommandAccessMode)},[y?.preferences.openPondCommandAccessMode,r]),g.useEffect(()=>{if(!h||!y)return;const Z=b5(y.preferences),me=JSON.stringify(Z);if(me==="{}"){ae.current=null;return}ae.current!==me&&(ae.current=me,J.savePreferences(h,Z).then(M).catch(_e=>{ae.current=null,s(_e instanceof Error?_e.message:String(_e))}))},[M,y,y?.preferences.codexPermissionMode,y?.preferences.codexReasoningEffort,h,s]),g.useEffect(()=>{if(!h||!y)return;const Z=w4(y.preferences),me=JSON.stringify(Z);if(me==="{}"){he.current=null;return}he.current!==me&&(he.current=me,J.savePreferences(h,Z).then(M).catch(_e=>{he.current=null,s(_e instanceof Error?_e.message:String(_e))}))},[M,y,y?.preferences.openPondCommandAccessMode,h,s]),g.useEffect(()=>{if(!h||!y){ve.current=null;return}if(y.account.state!=="signed_in"){ve.current=null,Ue();return}const Z=Xm(y.account);if(!Z){ve.current=null,Ue();return}Ue(),Qe("team");const me=y.preferences.defaultTeamId?.trim()??"",_e=Db(Z,me,y.accountMeta.asOf??"initial");if(ve.current===_e)return;ve.current=_e;let He=!1;const qe=Xe=>Nf({teamId:Xe,accountKey:Z,fetchAgents:async at=>(await J.listSandboxAgents(h,{teamId:at})).agents}).catch(()=>{!He&&ve.current===_e&&(ve.current=null)});return Yg({accountKey:Z,force:!0,fetchOrganizations:()=>$b(h)}).then(async Xe=>{if(He)return;if(Xe.length===0){Ue();return}if(!!me&&Xe.some(oe=>oe.teamId===me)){await qe(me),Ue();return}const Pe=NB(Xe)?.teamId;if(!Pe){Ue();return}const Ve=Ze.current;if(Ve&&Ve!==me){Ue();return}const u=qe(Pe);ve.current=Db(Z,Pe,y.accountMeta.asOf??"initial");const j=await J.savePreferences(h,{defaultTeamId:Pe});await u;const q=Ze.current;if(He){q&&q!==Pe&&J.savePreferences(h,{defaultTeamId:q}).then(M).catch(oe=>{s(oe instanceof Error?oe.message:String(oe))});return}if(q&&q!==Pe){M(await J.savePreferences(h,{defaultTeamId:q})),Ue();return}He||(M(j),Ue())}).catch(Xe=>{He||(ve.current=null,s(Xe instanceof Error?Xe.message:String(Xe)),Ue())}),()=>{He=!0}},[ze,M,y?.account,y?.accountMeta.asOf,y?.preferences.defaultTeamId,Ue,h,Qe,s]),g.useEffect(()=>{if(!h||!Ie)return;let Z=!1;const me=()=>{Z||(Z=!0,Yg({accountKey:Ie,force:!0,fetchOrganizations:()=>$b(h)}).catch(()=>{}).finally(()=>{Z=!1}))},_e=()=>{document.visibilityState==="visible"&&me()},He=window.setInterval(me,h6);return window.addEventListener("focus",me),document.addEventListener("visibilitychange",_e),()=>{window.clearInterval(He),window.removeEventListener("focus",me),document.removeEventListener("visibilitychange",_e)}},[h,Ie]);const H=g.useCallback(async()=>{Qe("connecting"),x(null);const Z=await RL();S(_e=>H4(_e,Z)?_e:Z),Qe("account");const me=await J.bootstrap(Z);ze(me),Ue(),s(_e=>_e&&(ek(_e)||_e==="Event stream disconnected")?null:_e)},[ze,Ue,Qe,s]);g.useEffect(()=>{let Z=!1,me=null;const _e=async He=>{try{await H()}catch(qe){if(Z)return;s(qe instanceof Error?qe.message:String(qe));const Xe=Math.min(5e3,750+He*750);me=window.setTimeout(()=>{_e(He+1)},Xe)}};return _e(0),()=>{Z=!0,me!==null&&window.clearTimeout(me)}},[H,s]);const X=g.useCallback(()=>{H().catch(()=>{})},[H]);O4({afterSequence:D?.afterSequence??null,appendEvents:O,connection:h,setApprovals:U,setSessions:ut,setError:s,onDisconnected:X}),g.useEffect(()=>{if(!h||!y){Le.current=null;return}const Z=D4(A);!Z||Le.current===Z||(Le.current=Z,J.profileCurrent(h).then(me=>{w(_e=>_e&&{..._e,profile:me})}).catch(me=>{Le.current=null,s(me instanceof Error?me.message:String(me))}))},[y,h,A,s]);const pe=g.useCallback(()=>{h&&J.refreshOpenPondAccount(h).then(({account:Z,accountMeta:me})=>{w(_e=>_e&&{..._e,account:Z,accountMeta:me})}).catch(Z=>s(Z instanceof Error?Z.message:String(Z)))},[h,s]);return{appPreferences:$,applyBootstrapPayload:ze,approvals:z,bootstrap:y,codexHistorySessions:E,connection:h,events:A,runtimeEventStore:R,refreshOpenPondAccount:pe,sessions:I,startup:m6(re),setAppPreferences:it,setBootstrap:w,setCodexHistorySessions:Fe,setEvents:N,setSessions:ut}}async function $b(e){return(await J.organizations(e)).organizations.map(Wc).filter(n=>!!n).filter(n=>n.status==="active")}function b6(e){return e>=f6?0:Math.max(0,p6-e)}function Db(e,t,n){return`${e}::${t||"none"}::${n}`}function v6({appDispatch:e,error:t,setErrorState:n}){const a=g.useRef(null),i=g.useRef(null),r=g.useRef(null),s=g.useRef(0),d=g.useCallback((h,S="info",y={})=>{const w=Date.now()+ ++s.current;return e({type:"showToast",toast:{id:w,message:h,tone:S,...y}}),w},[e]),p=g.useCallback(()=>{e({type:"patch",patch:{settingsSection:"diagnostics",sidebarOpen:!0,view:"settings"}})},[e]),m=g.useCallback(h=>{const S=i.current,y=typeof h=="function"?h(S):h;if(Object.is(S,y))return;if(i.current=y,n(y),!y){r.current!==null&&(e({type:"clearToast",toastId:r.current}),r.current=null);return}r.current=d(y6(y),"error",{actionLabel:"Open diagnostics settings",actionIcon:"settings",onAction:p,dismissible:!0});const w=a.current;w&&J.recordClientDiagnostic(w,{message:y,surface:"app",context:{href:window.location.href}}).catch(R=>{console.warn("Unable to record client diagnostic.",R)})},[e,p,n,d]);return g.useEffect(()=>{i.current=t,!(t||r.current===null)&&(e({type:"clearToast",toastId:r.current}),r.current=null)},[e,t]),{connectionRef:a,setError:m,showToast:d}}function y6(e){return Qx(e)}const S6={query:"",searchOpen:!1,archivedChatsOpen:!1,sectionMenuOpen:null,projectsExpanded:!1,cloudProjectsExpanded:!1,chatRowsVisibleCount:xn,sidebarOpen:!0,view:"chat",selectedAppId:null,selectedProjectId:null,selectedSessionId:null,prompt:"",promptDrafts:{},draftProvider:oi,draftModel:Ps,draftExperience:"chat",codexPermissionMode:_c,codexReasoningEffort:wc,openPondCommandAccessMode:qs,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 Df(e){return e.selectedSessionId?`session:${e.selectedSessionId}`:e.selectedProjectId?`project:${e.selectedProjectId}`:e.selectedAppId?`app:${e.selectedAppId}`:`new-${e.draftExperience}`}function fc(e,t,n){if(!n){if(!(t in e))return e;const{[t]:a,...i}=e;return i}return e[t]===n?e:{...e,[t]:n}}function x6(e){return fc(e.promptDrafts,Df(e),e.prompt)}function fs(e,t,n={}){const a={...e,...t},i=Df(a),r=x6(e),s=n.clearSelectedDraft?fc(r,i,""):n.preserveCurrentPrompt?fc(r,i,e.prompt):r;return{...e,...t,promptDrafts:s,prompt:n.clearSelectedDraft?"":n.preserveCurrentPrompt?e.prompt:s[i]??""}}function k6(e){return e==="draftExperience"||e==="selectedAppId"||e==="selectedProjectId"||e==="selectedSessionId"}function _6(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 i=String(a);return{...e,prompt:i,promptDrafts:fc(e.promptDrafts,Df(e),i)}}return k6(t.key)?fs(e,{[t.key]:a}):{...e,[t.key]:a}}case"patch":return{...e,...t.patch};case"selectApp":return fs(e,{selectedAppId:t.appId,selectedProjectId:null,selectedSessionId:null,view:"chat"});case"selectProject":return fs(e,{selectedAppId:null,selectedProjectId:t.projectId,selectedSessionId:null,view:"chat"},{preserveCurrentPrompt:!0});case"selectSession":{const n=t.projectId??null;return fs(e,{selectedSessionId:t.sessionId,selectedAppId:n?null:t.appId??null,selectedProjectId:n,view:"chat"})}case"beginNewChat":return fs(e,{selectedSessionId:null,selectedAppId:t.appId,selectedProjectId:null,error:null,view:"chat"});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 gt(e,t){return n=>e({type:"field",key:t,value:n})}function w6(e){return{setQuery:gt(e,"query"),setSearchOpen:gt(e,"searchOpen"),setArchivedChatsOpen:gt(e,"archivedChatsOpen"),setSectionMenuOpen:gt(e,"sectionMenuOpen"),setProjectsExpanded:gt(e,"projectsExpanded"),setCloudProjectsExpanded:gt(e,"cloudProjectsExpanded"),setChatRowsVisibleCount:gt(e,"chatRowsVisibleCount"),setSidebarOpen:gt(e,"sidebarOpen"),setView:gt(e,"view"),setSelectedAppId:gt(e,"selectedAppId"),setSelectedProjectId:gt(e,"selectedProjectId"),setSelectedSessionId:gt(e,"selectedSessionId"),setPrompt:gt(e,"prompt"),setDraftProvider:gt(e,"draftProvider"),setDraftModel:gt(e,"draftModel"),setDraftExperience:gt(e,"draftExperience"),setCodexPermissionMode:gt(e,"codexPermissionMode"),setCodexReasoningEffort:gt(e,"codexReasoningEffort"),setOpenPondCommandAccessMode:gt(e,"openPondCommandAccessMode"),setBusy:gt(e,"busy"),setDiffPanelOpen:gt(e,"diffPanelOpen"),setDiffPanelExpanded:gt(e,"diffPanelExpanded"),setRightPanelMode:gt(e,"rightPanelMode"),setRightChatPanels:gt(e,"rightChatPanels"),setTerminalOpen:gt(e,"terminalOpen"),setSyncingWorkspaceAppId:gt(e,"syncingWorkspaceAppId"),setSettingsSection:gt(e,"settingsSection"),setNewProjectDialogOpen:gt(e,"newProjectDialogOpen"),setNewProjectMode:gt(e,"newProjectMode"),setNewProjectName:gt(e,"newProjectName"),setNewProjectPath:gt(e,"newProjectPath"),setNewProjectBusy:gt(e,"newProjectBusy"),setCommitDialogOpen:gt(e,"commitDialogOpen"),setCommitMessage:gt(e,"commitMessage"),setCommitIncludeUnstaged:gt(e,"commitIncludeUnstaged"),setCommitNextStep:gt(e,"commitNextStep"),setCommitDraft:gt(e,"commitDraft"),setBranchDialogOpen:gt(e,"branchDialogOpen"),setBranchDialogName:gt(e,"branchDialogName"),setToast:gt(e,"toast"),setError:gt(e,"error")}}function hs(e){return e.selectedSessionId?`session:${e.selectedSessionId}`:e.selectedProjectId?`project:${e.selectedProjectId}`:e.selectedAppId?`app:${e.selectedAppId}`:"new-chat"}function I6(e={selectedAppId:null,selectedProjectId:null,selectedSessionId:null}){let t=e,n="";const a=new Map,i=new Set,r=m=>{if(!Object.is(n,m)){n=m;for(const h of i)h()}},s=()=>{const m=hs(t);n?a.set(m,n):a.delete(m)},d=(m,h={})=>{const S=n;s(),t={...t,...m};const y=hs(t);if(h.clear&&a.delete(y),h.preserveCurrentDraft){S?a.set(y,S):a.delete(y),r(S);return}r(h.clear?"":a.get(y)??"")},p={getScopeKey:()=>hs(t),getSnapshot:()=>n,subscribe(m){return i.add(m),()=>i.delete(m)},set:m=>p.setForScope(hs(t),m),setForScope(m,h){const S=hs(t),y=m===S?n:a.get(m)??"",w=typeof h=="function"?h(y):h;Object.is(y,w)||(w?a.set(m,w):a.delete(m),m===S&&r(w))},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 h=t[m.key],S=typeof m.value=="function"?m.value(h):m.value;Object.is(h,S)||d({[m.key]:S})}return}if(m.type==="patch"){const h={};"selectedAppId"in m.patch&&(h.selectedAppId=m.patch.selectedAppId),"selectedProjectId"in m.patch&&(h.selectedProjectId=m.patch.selectedProjectId),"selectedSessionId"in m.patch&&(h.selectedSessionId=m.patch.selectedSessionId),Object.keys(h).length>0&&d(h),"prompt"in m.patch&&typeof m.patch.prompt=="string"&&p.set(m.patch.prompt);return}if(m.type==="selectApp"){d({selectedAppId:m.appId,selectedProjectId:null,selectedSessionId:null});return}if(m.type==="selectProject"){d({selectedAppId:null,selectedProjectId:m.projectId,selectedSessionId:null},{preserveCurrentDraft:!0});return}if(m.type==="selectSession"){const h=m.projectId??null;d({selectedSessionId:m.sessionId,selectedAppId:h?null:m.appId??null,selectedProjectId:h});return}m.type==="beginNewChat"&&d({selectedSessionId:null,selectedAppId:m.appId,selectedProjectId:null})}};return p}function eK(e){return g.useSyncExternalStore(e.subscribe,e.getSnapshot,e.getSnapshot)}function C6(e){return{...e,draftExperience:_k()}}function R6(){const[e,t]=g.useReducer(_6,S6,C6),[n]=g.useState(()=>I6()),a=g.useCallback(r=>{n.applyAppAction(r),t(r)},[n]),i=g.useMemo(()=>({...w6(a),setPrompt:n.set}),[n,a]);return{composerDraftStore:n,dispatch:a,setters:i,state:e}}function A6(e){return!!(e&&e.includes("Git is required for OpenPond app workspaces")&&e.includes("Command Line Tools"))}function P6(e){const{connection:t,events:n,showToast:a}=e,i=g.useRef(new Set),r=g.useCallback(async()=>{if(t)try{const d=await J.installMacOSCommandLineTools(t);a(d.message,"info")}catch(d){a(d instanceof Error?d.message:String(d),"error")}},[t,a]),s=g.useCallback((d="OpenPond needs Git to create and sync local projects.")=>{a(d,"error",{actionLabel:"Install Tools",onAction:()=>{r()},persistent:!0})},[a,r]);g.useEffect(()=>{if(!t)return;let d=!1;return J.gitAvailability(t).then(p=>{d||p.ok||p.installAction!=="macos_command_line_tools"||s("OpenPond needs Git before it can create local projects.")}).catch(()=>{}),()=>{d=!0}},[t,s]),g.useEffect(()=>{for(const d of n){if(i.current.has(d.id))continue;const p=d.error??d.output??null;d.name==="workspace_action_result"&&d.status==="failed"&&A6(p)&&(i.current.add(d.id),s("OpenPond needs Git before it can update this project."))}},[n,s])}function T6({connection:e,preferences:t,sidebarOpen:n,diffPanelExpanded:a,setBootstrap:i,setError:r}){const[s,d]=g.useState(()=>ta().sidebarSectionsCollapsed),p=g.useRef(s),m=g.useRef({}),h=g.useRef(null),S=g.useRef(null),[y,w]=g.useState(L4),[R,A]=g.useState(!1),[N,O]=g.useState(z4),[D,x]=g.useState(!1),{pinned:I,projects:P,cloudProjects:E,chats:T,savedForLater:z}=s;g.useEffect(()=>{if(R)return;const ae=am(ta(t).sidebarWidth),he=Tb(ae,h.current);h.current=he.localChange,w(he.value)},[t,R]),g.useEffect(()=>{if(D)return;const ae=om(ta(t).diffPanelWidth),he=Tb(ae,S.current);S.current=he.localChange,O(he.value)},[D,t]),g.useEffect(()=>{const ae=ta(t).sidebarSectionsCollapsed;d(he=>{const ve=Z4(he,ae,m.current);return p.current=ve,ve})},[t]);const U=g.useCallback(ae=>{i(he=>he&&{...he,preferences:ae.preferences})},[i]),$=g.useCallback(async ae=>{if(e&&am(ta(t).sidebarWidth)!==ae)try{U(await J.savePreferences(e,{sidebarWidth:ae}))}catch(he){r(he instanceof Error?he.message:String(he))}},[e,t,r,U]),V=g.useCallback(async ae=>{if(e&&om(ta(t).diffPanelWidth)!==ae)try{U(await J.savePreferences(e,{diffPanelWidth:ae}))}catch(he){r(he instanceof Error?he.message:String(he))}},[e,t,r,U]),re=g.useCallback(async ae=>{if(!e)return;const he=ta(t).sidebarSectionsCollapsed;if(!E6(he,ae))try{U(await J.savePreferences(e,{sidebarSectionsCollapsed:ae}))}catch(ve){r(ve instanceof Error?ve.message:String(ve))}},[e,t,r,U]),Q=g.useCallback(ae=>{const he=p.current;G4(m.current,he,ae),p.current=ae,d(ae),re(ae)},[re]),Ie=g.useCallback(()=>{const ae=p.current;Q({...ae,pinned:!ae.pinned})},[Q]),Se=g.useCallback(()=>{const ae=p.current;Q({...ae,projects:!ae.projects})},[Q]),G=g.useCallback(()=>{const ae=p.current;Q({...ae,cloudProjects:!ae.cloudProjects})},[Q]),Ee=g.useCallback(()=>{const ae=p.current;Q({...ae,chats:!ae.chats})},[Q]),xe=g.useCallback(()=>{const ae=p.current;Q({...ae,savedForLater:!ae.savedForLater})},[Q]),le=g.useCallback(ae=>{if(!n)return;ae.preventDefault();const he=ae.clientX,ve=y;let Ze=ve;A(!0);function Re(Ce){Ze=am(ve+Ce.clientX-he),w(Ze)}function se(){window.removeEventListener("pointermove",Re),window.removeEventListener("pointerup",se);const Ce=Pb(ve,Ze);Ce&&(h.current=Ce),A(!1),$(Ze)}window.addEventListener("pointermove",Re),window.addEventListener("pointerup",se,{once:!0})},[$,n,y]),ke=g.useCallback(ae=>{if(a)return;ae.preventDefault();const he=ae.clientX,ve=N;let Ze=ve;x(!0);function Re(Ce){Ze=om(ve-(Ce.clientX-he)),O(Ze)}function se(){window.removeEventListener("pointermove",Re),window.removeEventListener("pointerup",se);const Ce=Pb(ve,Ze);Ce&&(S.current=Ce),x(!1),V(Ze)}window.addEventListener("pointermove",Re),window.addEventListener("pointerup",se,{once:!0})},[a,N,V]);return{pinnedCollapsed:I,projectsCollapsed:P,cloudProjectsCollapsed:E,chatsCollapsed:T,savedForLaterCollapsed:z,sidebarWidth:y,sidebarResizing:R,diffPanelWidth:N,diffPanelResizing:D,togglePinnedCollapsed:Ie,toggleProjectsCollapsed:Se,toggleCloudProjectsCollapsed:G,toggleChatsCollapsed:Ee,toggleSavedForLaterCollapsed:xe,startSidebarResize:le,startDiffPanelResize:ke}}function E6(e,t){return e.pinned===t.pinned&&e.projects===t.projects&&e.cloudProjects===t.cloudProjects&&e.chats===t.chats&&e.savedForLater===t.savedForLater}function M6(e){const[t,n]=g.useState({id:0,kind:null}),[a,i]=g.useState(null),r=g.useCallback((m=null)=>{n(h=>({id:h.id+1,kind:m}))},[]),s=g.useCallback(m=>{i(m)},[]),d=null,p=g.useMemo(()=>{if(e)return j6(a,r)},[e,a,r]);return{backAction:d,breadcrumbs:p,closeDetailKind:t.kind,closeDetailRequestId:t.id,onDetailOpenChange:s}}function j6(e,t){return e?[{label:"Models",onSelect:()=>t(null)},{label:e.kindLabel,onSelect:e.kindOnSelect??(()=>t(e.kind))},...e.workproductLabel?[{label:e.workproductLabel,onSelect:e.workproductOnSelect}]:[],...e.segments]:[{label:"Models"}]}const Lb=1e4,zb=3e4;function O6(e){const{connection:t,profileId:n}=e,[a,i]=g.useState(null),[r,s]=g.useState(!1),[d,p]=g.useState(null),[m,h]=g.useState(null),S=g.useRef(null),y=g.useRef(null),w=g.useCallback(()=>{if(!t)return Promise.resolve(null);if(S.current)return S.current;s(!0);const x=J.trainingState(t,n).then(I=>{const P=r2.parse(I);return y.current=P.activityRevision??null,i(P),h(null),P}).catch(I=>(h(oo(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,w()),[w]),A=g.useCallback(async(x,I,P,E="POST",T={})=>{if(!t)return null;T.silent||p(x);try{const z=await J.trainingRequest(t,I,P,E);return await R(),T.silent||h(null),z}catch(z){return T.silent||h(oo(z)),null}finally{T.silent||p(null)}},[t,R]);g.useEffect(()=>{if(y.current=null,!t){i(null);return}w()},[t,n,w]);const N=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=N?Lb:zb,E=async()=>{let T=P;try{const z=await J.trainingActivity(t,n);T=z.active?Lb:zb,(y.current===null||y.current!==z.revision)&&await w()}catch(z){h(oo(z))}x&&(I=window.setTimeout(()=>{E()},T))};return I=window.setTimeout(()=>{E()},P),()=>{x=!1,I!==null&&window.clearTimeout(I)}},[t,N,n,w]);const O=g.useMemo(()=>({saveComparisonSeries:x=>A("save-comparison-series","/comparison-series",{series:x}),saveContinualBenchIssueReview:x=>A("save-continual-support-issue-review","/continual-support/issue-reviews",{review:x},"PUT"),importContinualLearningDailyBatch:(x,I="json_upload")=>A("import-continual-learning-daily-batch","/continual-learning/daily-batches/import",{manifest:x,source:I}),saveContinualLearningDailyBatch:x=>A("save-continual-learning-daily-batch","/continual-learning/daily-batches",{batch:x},"PUT"),generateContinualLearningResponses:x=>A("generate-continual-learning-responses","/continual-learning/responses",x),sealComparisonSeries:(x,I)=>A("seal-comparison-series",`/comparison-series/${encodeURIComponent(x)}/seal`,{expectedRevision:I}),archiveComparisonSeries:(x,I)=>A("archive-comparison-series",`/comparison-series/${encodeURIComponent(x)}/archive`,{expectedRevision:I}),queueComparisonRelease:x=>A("queue-comparison-release",`/comparison-series/${encodeURIComponent(x.seriesId)}/releases`,x),startComparisonEvaluation:x=>A("start-comparison-evaluation",`/comparison-series-entries/${encodeURIComponent(x.entryId)}/evaluations`,x),loadComparisonAttemptEvidence:x=>t?J.trainingRequest(t,`/model-runs/${encodeURIComponent(x.runId)}/attempts/${encodeURIComponent(x.attemptId)}/evidence?kind=${x.kind}`,{},"GET"):Promise.resolve(null),linkComparisonRun:x=>A("link-comparison-run",`/comparison-series-entries/${encodeURIComponent(x.entryId)}/run`,x,"PATCH"),decideComparisonEntry:x=>A("decide-comparison-entry",`/comparison-series-entries/${encodeURIComponent(x.entryId)}/decision`,x),recordComparisonPromotion:x=>A("record-comparison-promotion",`/comparison-series-entries/${encodeURIComponent(x.entryId)}/promotion`,x),saveModelProject:x=>A("save-model-project","/models",x,"PUT"),listHostedModelProjects:async(x={})=>{if(!t)return null;x.silent||p("list-hosted-model-projects");try{const I=await J.trainingRequest(t,`/hosted-model-projects?profileId=${encodeURIComponent(n)}&refresh=${x.refresh===!0}`,{},"GET");return x.silent||h(null),I}catch(I){return x.silent||h(oo(I)),null}finally{x.silent||p(I=>I==="list-hosted-model-projects"?null:I)}},pullHostedModelProject:x=>A(`pull-hosted-model-project:${x}`,`/hosted-model-projects/${encodeURIComponent(x)}/pull`,{profileId:n}),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`,{}),createScorer:(x,I,P)=>A("create-scorer","/scorers",{grader:x,tasksetId:I,modelProjectId:P??null}),createTasksetDraft:(x="")=>A("create-taskset-draft","/taskset-drafts",{profileId:n,name:x}),importTasksetDraftPackage:x=>A("import-taskset-draft-package","/taskset-drafts/import",{packagePath:x,profileId:n}),tasksetGraderDetails:async x=>{if(!t)return null;try{return await J.trainingRequest(t,`/tasksets/${encodeURIComponent(x)}/graders`,{},"GET")}catch(I){return h(oo(I)),null}},saveTasksetDraft:x=>A("save-taskset-draft",`/taskset-drafts/${encodeURIComponent(x.id)}`,x,"PUT"),tasksetDraftWorkspace:async x=>{if(!t)return null;try{return await J.trainingRequest(t,`/taskset-drafts/${encodeURIComponent(x)}/workspace`,{},"GET")}catch(I){return h(oo(I)),null}},publishTasksetDraft:(x,I)=>A("publish-taskset-draft",`/taskset-drafts/${encodeURIComponent(x)}/publish`,{modelId:I??null}),deleteTasksetDraft:x=>A("delete-taskset-draft",`/taskset-drafts/${encodeURIComponent(x)}`,{},"DELETE"),inspectHuggingFaceDataset:x=>A("inspect-huggingface-dataset","/dataset-imports/huggingface/inspect",{profileId:n,url:x}),materializeDatasetImport:(x,I)=>A("materialize-dataset-import",`/dataset-imports/${encodeURIComponent(x)}/materialize`,I),cancelDatasetImport:x=>A("cancel-dataset-import",`/dataset-imports/${encodeURIComponent(x)}/cancel`,{}),datasetRows:(x,I={})=>{if(!t)return Promise.resolve(null);const P=new URLSearchParams;I.split&&P.set("split",I.split),I.cursor&&P.set("cursor",I.cursor),P.set("limit",String(I.limit??25));for(const E of I.columns??[])P.append("column",E);return J.trainingRequest(t,`/tasksets/${encodeURIComponent(x)}/rows?${P}`,{},"GET")},addSource:(x,I)=>A("add-source","/sources",{profileId:n,sessionId:x,turnIds:I}),addSources:x=>A("add-sources","/sources/batch",{profileId:n,sessionIds:x}),estimateSources:x=>t?J.trainingRequest(t,"/sources/estimate",{sessionIds:x}):Promise.resolve([]),searchChats:(x,I,P=0,E=20)=>t?J.trainingRequest(t,"/sources/search",{query:x,candidates:I,offset:P,limit:E}):Promise.resolve({schemaVersion:"openpond.trainingChatSearchResult.v1",query:x,offset:P,limit:E,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,E)=>A(`run-benchmark-${I}`,`/tasksets/${encodeURIComponent(x)}/benchmark-runs`,{phase:I,model:P,reasoningEffort:E,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,E=null)=>A("accept-harness-review","/harness-reviews/accept",{profileId:n,workspaceId:x,reviewRef:I,analysisModel:P,analysisReasoningEffort:E}),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 w();return h(null),x}catch(x){return h(oo(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,E)=>A("create-candidate",`/candidates/${encodeURIComponent(x)}/create`,{mode:I,analysisModel:P??null,analysisReasoningEffort:E??null}),auditGraders:x=>A("audit-graders","/audit-graders",{tasksetId:x}),executeTasksetAttempt:(x,I,P)=>A("execute-taskset-attempt",`/tasksets/${encodeURIComponent(x)}/attempts`,{taskId:I,model:P,seed:17,attempt:0,sampling:{maxOutputTokens:4096,temperature:0,topP:1}}),materializeSyntheticPreferenceCollection:x=>A("materialize-synthetic-preference-collection",`/tasksets/${encodeURIComponent(x.tasksetId)}/synthetic-preference-collection`,x),tasksetOperationalState:x=>t?J.trainingRequest(t,`/tasksets/${encodeURIComponent(x)}/operations`,{},"GET"):Promise.resolve(null),calibrateJudges:x=>A("calibrate-judges","/calibrate-judges",{tasksetId:x}),nextPreferenceComparison:(x,I)=>A("next-preference-comparison",`/tasksets/${encodeURIComponent(x)}/preference-comparisons/next`,{reviewerKey:I}),submitPreferenceComparison:x=>A("submit-preference-comparison",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/${encodeURIComponent(x.assignmentId)}/submit`,x),submitSyntheticFixturePreference:x=>A("submit-synthetic-fixture-preference",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/${encodeURIComponent(x.assignmentId)}/fixture-submit`,{...x,id:crypto.randomUUID()}),listPreferenceDatasets:x=>t?J.trainingRequest(t,`/tasksets/${encodeURIComponent(x)}/preference-datasets`,{},"GET"):Promise.resolve(null),materializePreferenceDataset:x=>A("materialize-preference-dataset",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-datasets`,{...x,id:`preference-dataset-${crypto.randomUUID()}`,revision:1}),launchRewardModelRun:x=>A("launch-reward-model-run",`/tasksets/${encodeURIComponent(x.tasksetId)}/reward-model-runs`,{...x,id:`reward-model-run-${crypto.randomUUID()}`}),learnedPreferenceRewardBinding:x=>A("learned-preference-reward-binding",`/tasksets/${encodeURIComponent(x.tasksetId)}/learned-preference-reward-binding`,x),retryRewardModelQualification:x=>A("retry-reward-model-qualification",`/reward-model-runs/${encodeURIComponent(x.runId)}/retry-qualification`,x),cancelRewardModelRun:x=>A("cancel-reward-model-run",`/reward-model-runs/${encodeURIComponent(x)}/cancel`,{}),markPreferenceComparisonUnreviewable:x=>A("mark-preference-comparison-unreviewable",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/${encodeURIComponent(x.assignmentId)}/unreviewable`,x),preferenceCalibrationStatus:(x,I,P)=>{if(!t)return Promise.resolve(null);const E=new URLSearchParams({reviewerKey:I});return P&&E.set("comparisonReleaseId",P),J.trainingRequest(t,`/tasksets/${encodeURIComponent(x)}/preference-comparisons/calibration/status?${E}`,{},"GET")},startPreferenceCalibrationBatch:x=>A("start-preference-calibration-batch",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/calibration/batches`,{...x,id:crypto.randomUUID()}),syncPreferenceCalibrationBatch:x=>A("sync-preference-calibration-batch",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/calibration/batches/${encodeURIComponent(x.jobId)}/sync`,x),reviewPreferenceComparisonWithModel:x=>A("review-preference-comparison-with-model",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/${encodeURIComponent(x.assignmentId)}/model-review`,{...x,id:crypto.randomUUID()}),runNextPreferenceCalibrationReview:x=>A("run-next-preference-calibration-review",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/calibration/model-reviews/next`,{...x,id:crypto.randomUUID()}),savePreferenceCalibration:x=>A("save-preference-calibration",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/calibration/report`,{...x,id:crypto.randomUUID()}),preferenceArtifactUrl:async x=>{if(!t)return null;const I=await fetch(`${t.serverUrl}/v1/training/artifacts/${encodeURIComponent(x)}/download`,{headers:{Authorization:`Bearer ${t.token}`}});if(!I.ok)throw new Error(await I.text());return URL.createObjectURL(await I.blob())},readiness:x=>A("readiness","/readiness",{tasksetId:x}),previewExpertBootstrap:x=>A("preview-expert-bootstrap",`/tasksets/${encodeURIComponent(x)}/expert-bootstrap/preview`,{}),approveExpertBootstrap:(x,I)=>A("approve-expert-bootstrap",`/tasksets/${encodeURIComponent(x)}/expert-bootstrap/approve`,{previewHash:I}),createPlan:x=>A("create-plan","/plans",{...x,tasksetId:x.tasksetId}),buildBundle:x=>A("build-bundle","/bundles",{planId:x}),approveTraining:(x,I)=>A("approve-training","/approvals",{planId:x,bundleId:I}),launch:(x,I)=>A("launch","/launch",{planId:x,approvalId:I}),prepareTraining:x=>A("prepare-training","/prepare",x),prepareModelRun:(x,I)=>A("prepare-model-run",`/model-projects/${encodeURIComponent(x)}/training/prepare`,I),startModelRun:(x,I)=>A("start-model-run",`/model-projects/${encodeURIComponent(x)}/training/start`,I),startPreparedTraining:x=>A("start-prepared-training","/start/prepared",x),startTraining:x=>A("start-training","/start",x),cancelJob:x=>A("cancel-job",`/jobs/${encodeURIComponent(x)}/cancel`,{}),cancelModelRun:x=>A("cancel-model-run",`/model-runs/${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")??"",E=/filename="([^"]+)"/.exec(P)?.[1]??"openpond-model-artifact",T=URL.createObjectURL(await I.blob()),z=document.createElement("a");return z.href=T,z.download=E,z.click(),URL.revokeObjectURL(T),!0}catch(I){return h(oo(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,w]);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 E=P.headers.get("content-disposition")??"",T=/filename="([^"]+)"/.exec(E)?.[1]??I,z=URL.createObjectURL(await P.blob()),U=document.createElement("a");return U.href=z,U.download=T,U.click(),URL.revokeObjectURL(z),!0}catch(P){return h(oo(P)),!1}finally{p(null)}}return{connection:t,payload:a,loading:r,busyAction:d,error:m,refresh:w,actions:O}}function oo(e){return e instanceof Error?e.message:String(e)}function tK({modelId:e,taskset:t}){const n=t.metadata.toolContractHash===Js?"cross_system":t.environment.kind==="stateful_harness"&&t.environment.actionBindings?.length?"harness":null,a=n?L6(t,n):[];return{model:{providerId:"openpond",modelId:e},tasksetId:t.id,tasksetName:t.name,taskRuntime:n,sourceProjectId:z6(t),tasks:a,selectedTaskIndex:0,sessionId:null}}function Wi(e){return e?.tasks.length?e.tasks[b_(e,e.selectedTaskIndex)]??null:null}function h_(e,t){return{...e,selectedTaskIndex:b_(e,t)}}function N6(e){return h_(e,e.selectedTaskIndex+1)}function $6(e,t,n){if(!e||g_(e,n))return null;const a=Wi(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 g_(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 D6({model:e,connection:t,loadBootstrap:n,applyBootstrap:a}){e.providerId!=="openpond"||!t||a(await n(t))}function L6(e,t){const n=new Set;return e.tasks.flatMap(a=>{const i=t==="cross_system"?a.metadata.taskId:a.metadata.caseId,r=typeof i=="string"?i.trim():"",s=typeof a.input.prompt=="string"?a.input.prompt.trim():"";return!r||!s||n.has(r)?[]:(n.add(r),[{authoredTaskId:a.id,generatedTaskId:r,prompt:s,split:a.split}])})}function z6(e){const t=new Set(e.sourceRefs.filter(ZM).flatMap(n=>{const a=n.workspaceId?.trim();return a?[a]:[]}));return t.size===1?t.values().next().value??null:null}function b_(e,t){return e.tasks.length?Math.max(0,Math.min(Math.trunc(t),e.tasks.length-1)):0}function U6({activeModel:e,activeProvider:t,applyBootstrapPayload:n,beginNewChat:a,composerDraftStore:i,connection:r,requestComposerFocus:s,selectedLocalProjectId:d,selectedSessionId:p,selectLocalProject:m,setDraftModel:h,setDraftProvider:S,setError:y,view:w}){const[R,A]=g.useState(null),N=g.useCallback(T=>{T.sourceProjectId?m(T.sourceProjectId):a(null)},[a,m]),O=g.useCallback(T=>{if(!R)return;const z={...h_(R,T),sessionId:R.sessionId?null:R.sessionId},U=Wi(z);A(z),U&&(R.sessionId&&N(z),i.set(U.prompt),s())},[N,i,R,s]),D=g.useCallback(()=>{const T=Wi(R);T&&i.getSnapshot().trim()===T.prompt.trim()&&i.set(""),A(null)},[i,R]),x=g.useCallback(T=>{const z=T.model;D6({model:z,connection:r,loadBootstrap:J.bootstrap,applyBootstrap:n}).then(()=>{const U={...T,selectedTaskIndex:0,sessionId:null};S(z.providerId),h(z.modelId),A(U.tasks.length?U:null),N(U);const $=Wi(U);$&&i.set($.prompt)}).catch(y)},[n,N,i,r,h,S,y]),I=g.useCallback(T=>{const z=!!(R&&R.model.providerId===t&&R.model.modelId===e);return{active:z,error:z?g_(R,d):null,metadata:z?$6(R,T,d):null}},[e,t,R,d]),P=g.useCallback(T=>{A(z=>z&&{...z,sessionId:T})},[]),E=g.useCallback(()=>{if(!R)return;const T={...N6(R),sessionId:null},z=Wi(T);A(T),z&&(N(T),i.set(z.prompt),s())},[N,i,R,s]);return g.useEffect(()=>{const T=Wi(R);!T||w!=="chat"||p||i.set(z=>z.trim()?z:T.prompt)},[i,R,d,p,w]),g.useEffect(()=>{R&&p&&R.sessionId!==p&&A(null)},[R?.sessionId,p]),{advanceAfterTurn:E,begin:x,bindSession:P,dismiss:D,handoff:R,prepareTurn:I,selectTask:O}}const gs=[],im=500;function H6(e){const{approvals:t,codexHistoryEvents:n,connection:a,latestServerSequence:i,runtimeIndexes:r,runtimeEventStore:s,selectedSessionId:d,serverId:p,setCodexHistoryEvents:m,setCodexHistorySessions:h,setError:S}=e,[y,w]=g.useState({}),[R,A]=g.useState({}),N=g.useRef(new Set);g.useEffect(()=>{w({}),A({}),N.current.clear()},[p]);const O=g.useCallback(async()=>{if(!a||!d||N.current.has(d))return!1;const E=R[d];if(E?.hasMore===!1)return!1;if(Nt(d)){const U=Math.max(E?.totalMatchingEvents??0,n.length,Uk),$=Math.min(lb,Math.max(w5,U*2));N.current.add(d),A(V=>({...V,[d]:{cursorSequence:null,hasMore:!0,loading:!0,totalMatchingEvents:V[d]?.totalMatchingEvents??n.length}}));try{const V=await Hk(a,d,{force:!0,limit:$,tail:!1});return m(V.events),h(re=>Kc(re,V.session)),A(re=>({...re,[d]:{cursorSequence:null,hasMore:V.events.length>=$&&$<lb,loading:!1,totalMatchingEvents:$}})),V.events.length>n.length}catch(V){return S(V instanceof Error?V.message:String(V)),A(re=>({...re,[d]:{cursorSequence:null,hasMore:re[d]?.hasMore??!0,loading:!1,totalMatchingEvents:re[d]?.totalMatchingEvents??n.length}})),!1}finally{N.current.delete(d)}}const T=so(y[d]??gs,s.getSessionEvents(d)),z=E?.cursorSequence??q6(T);if(!z)return!1;N.current.add(d),A(U=>({...U,[d]:{cursorSequence:U[d]?.cursorSequence??z,hasMore:U[d]?.hasMore??!0,loading:!0,totalMatchingEvents:U[d]?.totalMatchingEvents??null}}));try{const U=await J.runtimeEventsPage(a,{sessionId:d,beforeSequence:z,limit:im}),$=U.events.map(V=>V.event);return w(V=>({...V,[d]:so($,V[d]??gs)})),A(V=>({...V,[d]:{cursorSequence:U.previousSequence,hasMore:U.hasMore,loading:!1,totalMatchingEvents:U.totalMatchingEvents}})),$.length>0}catch(U){return S(U instanceof Error?U.message:String(U)),A($=>({...$,[d]:{cursorSequence:$[d]?.cursorSequence??z,hasMore:$[d]?.hasMore??!0,loading:!1,totalMatchingEvents:$[d]?.totalMatchingEvents??null}})),!1}finally{N.current.delete(d)}},[R,n.length,a,y,s,d,m,h,S]),D=d?y[d]??gs:gs,x=g.useMemo(()=>s.getSessionEvents(d).length,[s,d]),I=g.useRef(null);g.useEffect(()=>{if(!a||!d||Nt(d)||N.current.has(d)||D.length>0||x>0)return;const E=i;if(!E)return;const T=d,z=E+1;N.current.add(T),A(U=>({...U,[T]:{cursorSequence:U[T]?.cursorSequence??z,hasMore:U[T]?.hasMore??!0,loading:!0,totalMatchingEvents:U[T]?.totalMatchingEvents??null}})),J.runtimeEventsPage(a,{sessionId:T,beforeSequence:z,limit:im}).then(U=>{const $=U.events.map(V=>V.event);w(V=>({...V,[T]:so($,V[T]??gs)})),A(V=>({...V,[T]:{cursorSequence:U.previousSequence,hasMore:U.hasMore,loading:!1,totalMatchingEvents:U.totalMatchingEvents}}))}).catch(U=>{S(U instanceof Error?U.message:String(U)),A($=>({...$,[T]:{cursorSequence:$[T]?.cursorSequence??z,hasMore:$[T]?.hasMore??!0,loading:!1,totalMatchingEvents:$[T]?.totalMatchingEvents??null}}))}).finally(()=>{N.current.delete(T)})},[i,a,D.length,x,d,S]),g.useEffect(()=>{if(!a||!d||Nt(d)||N.current.has(d)||!i)return;const E=so(D,s.getSessionEvents(d)),T=uc(E);if(!T||T>=i)return;const z=`${d}:${T}:${i}`;if(I.current===z)return;I.current=z;let U=!1;return J.runtimeEventsPage(a,{sessionId:d,afterSequence:T,limit:im}).then($=>{if(U)return;const V=$.events.map(re=>re.event);V.length!==0&&w(re=>Tq(re,d,V))}).catch($=>{U||(I.current=null,S($ instanceof Error?$.message:String($)))}),()=>{U=!0}},[i,a,s,D,d,S]);const P=g.useMemo(()=>Nt(d)?Ym(n,[]):!d||D.length===0?r:Ym(so(D,s.getSessionEvents(d)),t),[t,n,r,D,d]);return{chatHistoryLoadStates:R,loadMoreSelectedChatHistory:O,selectedPagedSessionEvents:D,selectedRuntimeIndexes:P}}function q6(e){let t=null;for(const n of e)n.sequence!==void 0&&(t===null||n.sequence<t)&&(t=n.sequence);return t}function B6(e,t){const n=g.useRef(null);return g.useMemo(()=>{const a=bk(e,t,n.current);return n.current={events:e,indexes:a},a},[t,e])}function Qi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function rm(e){return Array.isArray(e)?e.filter(t=>!!Qi(t)):[]}function Jo(e){return typeof e=="string"&&e.trim()?e.trim():null}function Ub(e){return Jo(e)??Qi(e)}function F6(e){if(!e)return[];const t=Qi(e.sandboxActionRegistry),n=Qi(e.sandboxManifest),a=new Map;for(const i of[...rm(n?.actionCatalog),...rm(t?.actions),...rm(n?.actions)]){const r=Jo(i.id)??Jo(i.name);if(!r)continue;const s=a.get(r);a.set(r,{id:r,name:Jo(i.name)??s?.name??r,label:Jo(i.label)??s?.label??V6(r),description:Jo(i.description)??s?.description??null,visibility:Jo(i.visibility)??s?.visibility??"default",inputSchema:Ub(i.inputSchema)??s?.inputSchema??null,outputSchema:Ub(i.outputSchema)??s?.outputSchema??null,implementation:Qi(i.implementation)??s?.implementation??null,mcp:Qi(i.mcp)??s?.mcp??null,invokesModel:typeof i.invokesModel=="boolean"?i.invokesModel:s?.invokesModel})}return Array.from(a.values()).filter(i=>i.visibility!=="internal"&&i.visibility!=="debug")}function V6(e){const t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e}function v_(e){if(e.selectedCloudProject)return{id:e.selectedCloudProject.id,teamId:e.selectedCloudProject.teamId,name:e.selectedCloudProject.name,selectionKey:vt("cloud",e.selectedCloudProject.id),localProjectId:null};const t=e.selectedProject?.linkedSandboxProject??null;if(!t?.projectId||!t.teamId)return null;const n=e.cloudProjects?ma(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:vt("cloud",n?.id??t.projectId),localProjectId:e.selectedProject?.id??null}}const y_="openpond-agent",S_="openpond-profile-action";function Yc(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function lo(e){return typeof e=="string"&&e.trim()?e.trim():null}function Lf(e){return e.displayPrompt&&/(?:^|\s)@[A-Za-z0-9_-]+/.test(e.displayPrompt)?"mention":"slash"}function W6(e){const t=Yc(e),n=lo(t?.scope);return n!=="entire_manifest"&&n!=="start"&&n!=="action"&&n!=="service"&&n!=="schedule"?null:{scope:n,name:lo(t?.name)}}function K6(e){const t=lo(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 G6(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:y_,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 Z6(e){const t=Yc(e.implementation);if(t?.type!==y_)return null;const n=lo(t.agentId),a=lo(t.teamId),i=lo(t.projectId),r=W6(t.selectedEntrypoint),s=K6(t.workflowMode);return!n||!a||!i||!r||!s?null:{agentId:n,agentName:lo(t.agentName)??e.label??e.name??e.id,teamId:a,projectId:i,projectName:lo(t.projectName),selectedEntrypoint:r,workflowMode:s}}function J6(e,t={}){const n=t.agentName?.trim()||null;return{...e,implementation:{...Yc(e.implementation)??{},type:S_,actionId:e.id,...n?{agentName:n}:{}},invokesModel:e.invokesModel??!0}}function Y6(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=>J6(n,{agentName:n.agentId?t.get(n.agentId):null}))}function nK(e){return!!(e&&zf(e))}function aK(e){return!!(e&&zf(e)&&e.sourceActionId==="chat")}function zf(e){const t=Yc(e.implementation);if(t?.type!==S_)return null;const n=lo(t.actionId)??e.id;return n?{actionId:n,actionLabel:e.label??e.name??n}:null}function X6({action:e,attachments:t=[],displayPrompt:n,prompt:a,sessionId:i}){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:Lf({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{},...i?{sessionId:i}:{}}}}function Q6({action:e,attachments:t=[],displayPrompt:n,prompt:a,teamId:i}){return{teamId:i,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:Lf({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{}}}}function e3({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:Lf({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{}},workflowMode:e.workflowMode}}const er=new Map;function Uf(e,t){const n=e?.trim();return n?`${t?.trim()||"global"}|${n}`:null}function t3(e,t){const n=Uf(e,t);if(!n)return null;const a=er.get(n);return a?.updatedAt?a.projects:null}function n3(e,t,n){const a=Uf(e,n);a&&er.set(a,{projects:t,promise:null,updatedAt:Date.now()})}function a3(e){const t=e.teamId?.trim();if(!t)return Promise.resolve([]);const n=Uf(t,e.accountKey);if(!n)return Promise.resolve([]);const a=er.get(n);if(!e.force){if(a?.updatedAt)return Promise.resolve(a.projects);if(a?.promise)return a.promise}const i=e.fetchProjects(t).then(r=>(n3(t,r,e.accountKey),r)).catch(r=>{const s=er.get(n);throw s?.promise===i&&er.set(n,{projects:s.projects,promise:null,updatedAt:s.updatedAt}),r});return er.set(n,{projects:a?.projects??[],promise:i,updatedAt:a?.updatedAt??0}),i}function sm(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 o3({cloudProjectById:e,cloudProjects:t,connection:n,defaultTeamId:a,accountScopeKey:i,localProjects:r,profile:s,selectedCloudProject:d,selectedProject:p,reportError:m}){const[h,S]=g.useState(null),[y,w]=g.useState([]),[R,A]=g.useState([]),N=g.useMemo(()=>{const T=new Set;a&&T.add(a);for(const z of t)T.add(z.teamId);for(const z of r){const U=t.find($=>$.id===z.linkedSandboxProject?.projectId&&$.teamId===z.linkedSandboxProject?.teamId);U?.teamId&&T.add(U.teamId)}return[...T].sort()},[t,a,r]),O=N.join("\0"),D=g.useMemo(()=>v_({cloudProjects:t,selectedCloudProject:d,selectedProject:p}),[t,d,p]);g.useEffect(()=>{if(!n||N.length===0){A([]);return}let T=!1;const z=N.flatMap(U=>p_(U,i)??[]);return A(sm(z)),Promise.all(N.map(U=>Nf({teamId:U,accountKey:i,fetchAgents:async $=>(await J.listSandboxAgents(n,{teamId:$})).agents}))).then(U=>{T||A(sm(U.flat()))}).catch(()=>{T||A(sm(z))}),()=>{T=!0}},[i,n,O]),g.useEffect(()=>{if(!n||!D){S(null);return}const T=t3(D.teamId,i);T&&S(T.find(U=>U.id===D.id)??null);let z=!1;return a3({teamId:D.teamId,accountKey:i,fetchProjects:async U=>(await J.listSandboxProjects(n,{teamId:U})).projects}).then(U=>{z||S(U.find($=>$.id===D.id)??null)}).catch(()=>{z||S(null)}),()=>{z=!0}},[i,n,D?.id,D?.teamId]),g.useEffect(()=>{if(!n||!p){w([]);return}let T=!1;return J.localProjectActions(n,p.id).then(z=>{T||w(z.actions)}).catch(z=>{T||(w([]),m?.(`Could not load Project Actions for ${p.name}: ${z instanceof Error?z.message:String(z)}`))}),()=>{T=!0}},[n,m,p?.id,p?.name,p?.updatedAt]);const x=g.useMemo(()=>{const T=new Map;for(const z of F6(h))T.set(z.id,z);for(const z of y)T.set(z.id,z);return[...T.values()]},[y,h]),I=g.useMemo(()=>Y6(s),[s]),P=g.useMemo(()=>[...R.map(T=>G6(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 i3({selectedProjectId:e}){const[t,n]=g.useState(()=>new Set),a=g.useCallback(r=>{n(s=>{if(s.has(r))return s;const d=new Set(s);return d.add(r),d})},[]),i=g.useCallback(r=>{n(s=>{const d=new Set(s);return d.has(r)?d.delete(r):d.add(r),d})},[]);return g.useEffect(()=>{e&&a(e)},[a,e]),{expandedProjectIds:t,expandProject:a,toggleProjectExpanded:i,setExpandedProjectIds:n}}function r3(){const e=new Map;function t(i,r){const s=e.get(i);if(s)return s.consumers+=1,n(i,s,!0);const d=new AbortController,p={controller:d,consumers:1,settled:!1,promise:Promise.resolve().then(()=>r(d.signal)).finally(()=>{p.settled=!0,e.get(i)===p&&e.delete(i)})};return e.set(i,p),n(i,p,!1)}function n(i,r,s){let d=!1;return{key:i,promise:r.promise,shared:s,release:()=>{d||(d=!0,r.consumers=Math.max(0,r.consumers-1),r.consumers===0&&!r.settled&&r.controller.abort())}}}function a(){for(const i of e.values())i.consumers=0,i.settled||i.controller.abort()}return{request:t,cancelAll:a,inFlightCount:()=>e.size}}function lm(e,t,n){return`workspace-status:${e.serverUrl}:${t}:${n?"ensure":"read"}`}function s3(e,t){return`workspace-diff:${e.serverUrl}:${t}`}function cm(e){return e instanceof Error&&e.name==="AbortError"}function l3({connection:e,activeWorkspaceAppId:t,view:n,shouldLoadWorkspaceDiff:a,sidebarWorkspaceAppIds:i,setError:r}){const[s,d]=g.useState(null),[p,m]=g.useState({}),[h,S]=g.useState(null),[y,w]=g.useState(!1),[R,A]=g.useState(!1),N=g.useRef(new Set),O=g.useRef(new Set),D=g.useRef(r3()),x=t?p[t]??(s?.appId===t?s:null):null,I=h?.appId===t?h:null,P=n==="chat"||n==="labs",E=g.useCallback(U=>{N.current.add(U.appId),d(U),m($=>({...$,[U.appId]:U}))},[]),T=g.useCallback(async(U,$=!1)=>{if(!e||!U)return d(null),null;w(!0);const V=D.current.request(lm(e,U,$),re=>J.workspaceStatus(e,U,$,{signal:re}));try{const re=await V.promise;return E(re),$&&re.error?r(`Workspace sync failed: ${re.error}`):$&&r(null),re}catch(re){return cm(re)||(d(null),r(re instanceof Error?re.message:String(re))),null}finally{V.release(),w(!1)}},[e,E,r]),z=g.useCallback(async(U=t,$={})=>{if(!e||!U)return S(null),null;$.silent||A(!0);const V=D.current.request(s3(e,U),re=>J.workspaceDiff(e,U,{signal:re}));try{const re=await V.promise;return S(re),re}catch(re){return cm(re)||(S(null),r(re instanceof Error?re.message:String(re))),null}finally{V.release(),$.silent||A(!1)}},[t,e,r]);return g.useEffect(()=>{if(!e||!t||!P){d(null),S(null),w(!1);return}let U=!1;const $=D.current.request(lm(e,t,!1),V=>J.workspaceStatus(e,t,!1,{signal:V}));return w(!0),$.promise.then(V=>{U||(E(V),V.initialized||S(re=>re?.appId===V.appId?null:re))}).catch(V=>{cm(V)||U||(d(null),r(V instanceof Error?V.message:String(V)))}).finally(()=>{$.release(),U||w(!1)}),()=>{U=!0,$.release()}},[t,e,E,r,P]),g.useEffect(()=>{if(!e||!t||!P){S(null);return}if(!x?.initialized){x&&!x.initialized&&S(U=>U?.appId===t?null:U);return}a&&z(t)},[t,e,z,a,P,x?.dirty,x?.initialized]),g.useEffect(()=>{if(!e||i.length===0)return;const U=i.filter(re=>!N.current.has(re)&&!O.current.has(re));if(U.length===0)return;U.forEach(re=>O.current.add(re));let $=!1;const V=U.map(re=>({appId:re,request:D.current.request(lm(e,re,!1),Q=>J.workspaceStatus(e,re,!1,{signal:Q}))}));return Promise.all(V.map(({appId:re,request:Q})=>Q.promise.then(Ie=>({appId:re,state:Ie})).catch(()=>({appId:re,state:null})).finally(()=>{Q.release(),O.current.delete(re)}))).then(re=>{if(!$)for(const Q of re)Q.state&&E(Q.state)}),()=>{$=!0,V.forEach(({appId:re,request:Q})=>{Q.release(),O.current.delete(re)})}},[e,E,i]),g.useEffect(()=>()=>D.current.cancelAll(),[]),{workspaceState:s,workspaceStates:p,workspaceDiff:h,workspaceBusy:y,diffBusy:R,visibleWorkspaceState:x,visibleWorkspaceDiff:I,rememberWorkspaceState:E,refreshWorkspace:T,refreshWorkspaceDiff:z,setWorkspaceBusy:w}}const c3=1,d3=15e3,u3=15e3,x_=5*6e4,m3=5e3,p3=1e4;function k_(e,t=(a,i)=>new WebSocket(a,i),n={}){const a=new f3(e,t,n.reconnectDelayMs??h3);return a.open(),{close:()=>a.close()}}class f3{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=x_;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===c3)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-${g3(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."))},d3))},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 r=JSON.parse(n.data);if(!r||typeof r!="object"||Array.isArray(r))return;a=r}catch{this.reportError(new Error("Team chat realtime returned an invalid frame."));return}const i=typeof a.type=="string"?a.type:"";if(i==="connection_ack"){this.connectionAckTimer&&clearTimeout(this.connectionAckTimer),this.connectionAckTimer=null,this.keepAliveTimeoutMs=v3(a.connectionTimeoutMs),this.lastKeepAliveAt=Date.now(),this.startKeepAliveMonitor(),this.subscribe(t);return}if(i==="ka"){this.lastKeepAliveAt=Date.now();return}if(i==="subscribe_success"){const r=typeof a.id=="string"?a.id:"";if(!this.subscriptionChannels.has(r))return;this.acknowledgedSubscriptions.add(r),this.markReadyWhenSubscribed();return}if(i==="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(i==="connection_error"||i==="subscribe_error"){const r=y3(a);if(this.reportError(r),i==="connection_error")this.failConnection(r,!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 i=b3();this.subscriptionChannels.set(i,a),t.send(JSON.stringify({type:"subscribe",id:i,channel:a,authorization:n}))}this.subscriptionAckTimer=setTimeout(()=>{this.failConnection(new Error("Team chat realtime subscription acknowledgement timed out."))},u3)}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."))},m3)}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 h3(e){const t=Math.min(p3,500*2**Math.min(e,5));return Math.max(100,Math.floor(Math.random()*t))}function g3(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 b3(){return globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random().toString(36).slice(2)}`}function v3(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:x_}function y3(e){const n=(Array.isArray(e.errors)?e.errors:[])[0];if(n&&typeof n=="object"){const a=n,i=typeof a.errorType=="string"?a.errorType:"RealtimeError",r=typeof a.message=="string"?a.message:"Request failed";return new Error(`${i}: ${r}`)}return new Error("Team chat realtime request failed.")}function S3(e,t,n){const a=[`/team-chat/users/${e.session.userId}/${e.session.teamId}`,...Array.from(new Set(e.threadIds)).map(i=>`/team-chat/threads/${i}`)];return k_({realtimeUrl:e.session.realtimeUrl,httpUrl:e.session.httpUrl,authorizationToken:e.session.token,channels:a,onEvent:i=>{const r=sy.safeParse(i);r.success&&e.onEvent(r.data)},onReady:e.onReady,onError:e.onError},t,n)}function x3(e){return e.refs.find(t=>t.refType==="message_reply")??null}function k3(e){return{id:e.id,authorType:e.authorType,authorUserId:e.authorUserId,authorAgentId:e.authorAgentId,body:e.body,deleted:!!e.deletedAt}}function oK(e,t){const n=x3(e);if(!n)return null;const a=t.get(n.refId);return a?k3(a):w3(n)}function _3(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 iK(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 rK(e){return e.deleted?"Message deleted":e.body.replace(/\s+/g," ").trim()||"Attachment"}function w3(e){const t=e.preview;return{id:e.refId,authorType:I3(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 I3(e){return e==="agent"||e==="system"?e:"user"}function Hb(e,t,n){return n===t.conversationId?{...e,aiThread:t}:e}function C3(e,t){return!e||e.thread.id!==t.thread.id?t:{...t,messages:ol([...e.messages,...t.messages]),hasMoreBefore:e.messages.length>t.messages.length?e.hasMoreBefore:t.hasMoreBefore}}function dm(e,t){const n=Array.from(t.values()).filter(i=>i.threadId===e.thread.id);if(n.length===0)return e;let a=e.thread;for(const i of n)a=hr(a,i,"message.created",!0,i.authorUserId);return{...e,thread:a,messages:ol([...e.messages,...n])}}function R3(e,t){const n=new Set(e.map(i=>i.lastMessage?.clientRequestId).filter(i=>!!i)),a=new Map;for(const i of t.values()){if(i.clientRequestId&&n.has(i.clientRequestId))continue;const r=a.get(i.threadId)??[];r.push(i),a.set(i.threadId,r)}return e.map(i=>{let r=i;for(const s of a.get(i.id)??[])r=hr(r,s,"message.created",!0,s.authorUserId);return r}).sort((i,r)=>r.lastMessageAt.localeCompare(i.lastMessageAt))}function um(e,t,n){for(const a of e)!a.clientRequestId||a.id.startsWith("pending:")||(t.delete(a.clientRequestId),n.delete(a.clientRequestId))}function mm(e,t,n){const a=e.get(t);a&&e.set(t,{...a,metadata:{...a.metadata,deliveryStatus:n}})}function qb(e,t,n){const a=e.get(t);a&&e.set(t,{...a,metadata:{...a.metadata,uploadProgress:n}})}function ol(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,i)=>a.sequence!==i.sequence?a.sequence-i.sequence:a.createdAt.localeCompare(i.createdAt))}function __(e){return e.type!=="message.created"&&e.type!=="message.updated"&&e.type!=="message.deleted"?null:zp.safeParse(e.payload.message).data??null}function w_(e,t,n){const a=__(t);if(a){const i=e.selectedThreadId===a.threadId,r=e.detail?.thread.id===a.threadId?{...e.detail,thread:hr(e.detail.thread,a,t.type,i,n),messages:ol([...e.detail.messages,a])}:e.detail,d=e.threads.some(p=>p.id===a.threadId)?e.threads.map(p=>p.id===a.threadId?hr(p,a,t.type,i,n):p).sort((p,m)=>m.lastMessageAt.localeCompare(p.lastMessageAt)):e.threads;return{...e,detail:r,threads:d,error:null}}if(t.type==="read.updated"){const i=typeof t.payload.userId=="string"?t.payload.userId:null,r=Number(t.payload.sequence);if(!i||!Number.isSafeInteger(r)||r<0)return e;const s=d=>({...d,participants:d.participants.map(p=>p.userId===i?{...p,lastReadSequence:Math.max(p.lastReadSequence,r)}:p)});return{...e,threads:e.threads.map(d=>d.id===t.threadId?s(d):d),detail:e.detail?.thread.id===t.threadId?{...e.detail,thread:s(e.detail.thread)}:e.detail}}return e}function hr(e,t,n,a,i){const r=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===i?0:r?e.unreadCount+1:e.unreadCount}}function A3(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:_3(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 P3(e,t){const n=e.detail?.thread.id===t.threadId?{...e.detail,thread:hr(e.detail.thread,t,"message.created",!0,t.authorUserId),messages:ol([...e.detail.messages,t])}:e.detail;return{...e,detail:n,threads:e.threads.map(a=>a.id===t.threadId?hr(a,t,"message.created",!0,t.authorUserId):a).sort((a,i)=>i.lastMessageAt.localeCompare(a.lastMessageAt)),error:null}}function Bb(e,t,n){return w_(e,{teamId:t.teamId,threadId:t.threadId,type:"message.created",payload:{message:t},createdAt:t.createdAt},n)}function T3(e,t){return lp(e,t,"failed")}function lp(e,t,n){const a=i=>i.clientRequestId===t&&i.id.startsWith("pending:")?{...i,metadata:{...i.metadata,deliveryStatus:n}}:i;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(i=>({...i,lastMessage:i.lastMessage?a(i.lastMessage):null}))}}function Fb(e,t,n){const a=i=>i.clientRequestId===t&&i.id.startsWith("pending:")?{...i,metadata:{...i.metadata,uploadProgress:n}}:i;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(i=>({...i,lastMessage:i.lastMessage?a(i.lastMessage):null}))}}function E3(e,t){const n=e.detail?.messages.filter(r=>r.id!==t)??[],a=n.at(-1)??null,i=e.detail?{...e.detail,thread:e.detail.thread.lastMessageId===t?Vb(e.detail.thread,a):e.detail.thread,messages:n}:null;return{...e,detail:i,threads:e.threads.map(r=>r.lastMessageId===t?Vb(r,a):r)}}function M3(e){if(e.length>Xo.maxAttachments)return null;const t=[];for(const n of e){if(n.kind!=="image"||!j3(n.mediaType)||!n.contentsBase64||n.sizeBytes<=0||n.sizeBytes>Xo.maxAttachmentBytes)return null;t.push({...n,kind:"image",mediaType:n.mediaType,contentsBase64:n.contentsBase64})}return t}function Vb(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 j3(e){return e==="image/png"||e==="image/jpeg"||e==="image/webp"||e==="image/gif"}const O3={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 N3(e){const t=e instanceof Error?e.message:String(e),n=t.trim().toLowerCase();for(const[a,i]of Object.entries(O3))if(n.includes(a))return i;return n.includes("event stream ended")?"Team chat realtime disconnected. Messages will continue to refresh automatically.":a_(t)}const I_="openpond.team-chat.notification-mode";function C_(){try{return typeof window>"u"?null:window.localStorage}catch{return null}}function $3(e=C_()){const t=e?.getItem(I_);return t==="direct_mentions"||t==="none"?t:"all"}function D3(e,t=C_()){try{t?.setItem(I_,e)}catch{}}function L3(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 z3(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}`,r=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:r.length>160?`${r.slice(0,157)}…`:r}}const Wb={members:[],agents:[],threads:[],selectedThreadId:null,detail:null,aiThread:null,agentConversation:null,loading:!1,busy:!1,error:null};function Ol(e,t){return e.map(n=>n.id===t&&n.unreadCount!==0?{...n,unreadCount:0}:n)}function Nl(e){return!e||e.thread.unreadCount===0?e:{...e,thread:{...e.thread,unreadCount:0}}}function U3(e){return{teamId:e.teamId,body:e.body.trim(),clientRequestId:e.clientRequestId,selectedAgentId:e.conversation.agent.id,conversationId:e.conversation.conversationId}}function H3(e){return{teamId:e.teamId,body:e.body.trim(),clientRequestId:e.clientRequestId,selectedActionKey:e.selectedActionKey,approvalId:e.approvalId??null}}async function Kb(e,t=J.markTeamChatRead){return e.lastMessageSequence<=0?!1:t(e.connection,e.threadId,e.teamId,e.lastMessageSequence).then(()=>!0,()=>!1)}function q3(e){const[t,n]=g.useState(Wb),a=g.useRef(t);a.current=t;const[i,r]=g.useState($3),[s,d]=g.useState(null),p=g.useRef(null),m=g.useRef(null),h=g.useRef(0),S=g.useRef(new Map),y=g.useRef(new Map),w=g.useRef(0),R=g.useRef(null),A=g.useRef(0),N=g.useRef(new Set),O=g.useRef(0),D=g.useRef(!1),x=g.useRef(new Map),I=g.useRef(new Map),[P,E]=g.useState(null),[T,z]=g.useState(null),U=g.useCallback(M=>{r(M),D3(M)},[]),$=g.useCallback(M=>{d(H=>H?.eventId===M?null:H)},[]),V=g.useCallback(async()=>{if(!e.connection||!e.teamId)return[];const M=await J.teamChatThreads(e.connection,e.teamId),H=R3(M.threads,x.current);return n(X=>({...X,threads:H})),H},[e.connection,e.teamId]),re=g.useCallback(async()=>{if(!e.connection||!e.teamId)return{members:[],agents:[]};const[M,H]=await Promise.all([J.teamChatMembers(e.connection,e.teamId),J.teamChatAgents(e.connection,e.teamId)]);return n(X=>({...X,members:M.members,agents:H.agents})),{members:M.members,agents:H.agents}},[e.connection,e.teamId]),Q=g.useCallback(async M=>{const H=M??p.current;if(!e.connection||!e.teamId||!H)return null;const X=(y.current.get(H)??0)+1;y.current.set(H,X);const pe=await J.teamChatThread(e.connection,e.teamId,H);um(pe.messages,x.current,I.current);const Z=dm(pe,x.current);return y.current.get(H)!==X||(n(me=>me.selectedThreadId===H?{...me,threads:Ol(me.threads,H),detail:Nl(C3(me.detail,Z))}:me),p.current===H&&Z.thread.lastMessageSequence>0&&await J.markTeamChatRead(e.connection,H,e.teamId,Z.thread.lastMessageSequence).catch(()=>{})),Z},[e.connection,e.teamId]),Ie=g.useCallback(async M=>{const H=M??m.current;if(!e.connection||!e.teamId||!H)return null;const X=(S.current.get(H)??0)+1;S.current.set(H,X);const pe=await J.teamChatAiThread(e.connection,e.teamId,H);return S.current.get(H)===X&&m.current===H&&n(Z=>Hb(Z,pe,m.current)),pe},[e.connection,e.teamId]),Se=g.useCallback(async M=>{const H=M??R.current;if(!e.connection||!e.teamId||!H)return null;const X=await J.teamChatAgentConversation(e.connection,e.teamId,H);return n(pe=>pe.agentConversation?.run.id===H?{...pe,agentConversation:X}:pe),X},[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 M=t.agentConversation?.run.status;if(!M||!["pending","queued","running"].includes(M))return;const H=window.setInterval(()=>{Se().catch(X=>{n(pe=>({...pe,error:cn(X)}))})},2500);return()=>window.clearInterval(H)},[Se,t.agentConversation?.run.status]),g.useEffect(()=>{if(!e.connection||!e.teamId||!e.currentUserId){n(Wb),E(null),z(null),I.current.clear(),x.current.clear(),y.current.clear(),S.current.clear(),w.current+=1,d(null),N.current.clear(),O.current=0,A.current=0;return}let M=!1;return m.current=null,h.current+=1,w.current+=1,E(null),z(null),I.current.clear(),x.current.clear(),N.current.clear(),O.current=0,n(H=>({...H,aiThread:null,agentConversation:null,loading:!0,error:null})),(async()=>{try{const H=await J.teamChatEvents(e.connection,e.teamId);if(M)return;A.current=H.cursor;const X=J.teamChatMembers(e.connection,e.teamId),pe=J.teamChatAgents(e.connection,e.teamId),Z=await J.teamChatGeneral(e.connection,e.teamId),[me,_e,He]=await Promise.all([X,pe,J.teamChatThreads(e.connection,e.teamId)]);if(M)return;const qe=p.current&&He.threads.some(Pe=>Pe.id===p.current)?p.current:Z.thread.id,Xe=qe===Z.thread.id?Z:await J.teamChatThread(e.connection,e.teamId,qe);if(M)return;const at=Nl(Xe);n(Pe=>({...Pe,members:me.members,agents:_e.agents,threads:Ol(He.threads,qe),selectedThreadId:qe,detail:at,loading:!1,error:null})),Kb({connection:e.connection,teamId:e.teamId,threadId:qe,lastMessageSequence:at?.thread.lastMessageSequence??0}),z(e.teamId)}catch(H){if(M)return;n(X=>({...X,loading:!1,error:cn(H)}))}})(),()=>{M=!0}},[e.connection,e.currentUserId,e.refreshToken,e.teamId]);const G=g.useCallback(M=>{if(N.current.has(M.id))return;if(N.current.add(M.id),N.current.size>2e3){const X=N.current.values().next().value;typeof X=="number"&&N.current.delete(X)}const H=__(M);if(H&&M.type==="message.created"){const X=a.current,pe=X.threads.find(me=>me.id===H.threadId)??(X.detail?.thread.id===H.threadId?X.detail.thread:null),Z=me=>{M.id<=O.current||L3({mode:i,currentUserId:e.currentUserId,message:H,thread:me})&&(O.current=M.id,d(z3({eventId:M.id,message:H,thread:me,members:X.members})))};pe?Z(pe):V().then(me=>{const _e=me.find(He=>He.id===H.threadId);_e&&Z(_e)}).catch(()=>{})}H?.clientRequestId&&!H.id.startsWith("pending:")&&(x.current.delete(H.clientRequestId),I.current.delete(H.clientRequestId)),n(X=>w_(X,M,e.currentUserId)),M.type==="thread.created"&&V().catch(X=>{n(pe=>({...pe,error:cn(X)}))}),(M.type==="ai_thread.created"||M.type==="ai_turn.updated")&&(Q(M.threadId).catch(X=>{n(pe=>({...pe,error:cn(X)}))}),M.conversationId===m.current&&Ie(M.conversationId).catch(X=>{n(pe=>({...pe,error:cn(X)}))})),H&&M.type==="message.created"&&p.current===H.threadId&&H.authorUserId!==e.currentUserId&&e.connection&&e.teamId&&J.markTeamChatRead(e.connection,H.threadId,e.teamId,H.sequence).catch(()=>{})},[e.connection,e.currentUserId,e.teamId,i,Ie,Q,V]),Ee=g.useCallback(async()=>{if(!(!e.connection||!e.teamId||D.current)){D.current=!0;try{let M=!0;for(;M;){const H=await J.teamChatEvents(e.connection,e.teamId,{after:A.current,limit:250});for(const X of H.events)G(X);A.current=H.cursor,M=H.hasMore}}finally{D.current=!1}}},[G,e.connection,e.teamId]);g.useEffect(()=>{if(!e.connection||!e.teamId||T!==e.teamId)return;let M=!1,H=null;const X=async()=>{try{const pe=await J.teamChatRealtimeSession(e.connection,e.teamId);if(M||(await Ee(),M))return;E(pe);const Z=Math.max(3e4,new Date(pe.expiresAt).getTime()-Date.now()-3e4);H=window.setTimeout(()=>{X()},Z)}catch{M||(Ee().catch(()=>{}),H=window.setTimeout(()=>{X()},1e4))}};return X(),()=>{M=!0,H!==null&&window.clearTimeout(H),E(null)}},[Ee,e.connection,e.teamId,T]);const xe=t.threads.map(M=>M.id).sort().join(",");g.useEffect(()=>{if(!P)return;const M=S3({session:P,threadIds:xe?xe.split(","):[],onEvent:G,onReady:()=>{Ee().catch(H=>{n(X=>({...X,error:cn(H)}))})},onError:()=>{Ee().catch(()=>{})}});return()=>{M.close()}},[G,Ee,P,xe]),g.useEffect(()=>{if(!e.connection||!e.teamId||T!==e.teamId)return;const M=window.setInterval(()=>{Ee().catch(()=>{})},15e3);return()=>window.clearInterval(M)},[Ee,e.connection,e.teamId,T]);const le=g.useCallback(async M=>{if(!e.connection||!e.teamId)return;const H=w.current+1;w.current=H;const X=p.current!==M;p.current=M,X&&(h.current+=1,m.current=null),n(pe=>({...pe,threads:Ol(pe.threads,M),selectedThreadId:M,detail:pe.detail?.thread.id===M?Nl(pe.detail):null,aiThread:X?null:pe.aiThread,agentConversation:X?null:pe.agentConversation,loading:!0,error:null}));try{const pe=await J.teamChatThread(e.connection,e.teamId,M);if(w.current!==H||p.current!==M)return;um(pe.messages,x.current,I.current);const Z=dm(pe,x.current);n(me=>({...me,threads:Ol(me.threads,M),detail:Nl(Z),loading:!1})),await J.markTeamChatRead(e.connection,M,e.teamId,Z.thread.lastMessageSequence).catch(()=>{})}catch(pe){if(w.current!==H)return;n(Z=>({...Z,loading:!1,error:cn(pe)}))}},[e.connection,e.teamId]),ke=g.useCallback(async M=>{if(!e.connection||!e.teamId)return null;const H=w.current+1;w.current=H,n(X=>({...X,busy:!0,error:null}));try{const X=await J.teamChatDm(e.connection,e.teamId,M);if(w.current!==H)return null;um(X.messages,x.current,I.current);const pe=dm(X,x.current),Z=p.current!==pe.thread.id;return p.current=pe.thread.id,Z&&(h.current+=1,m.current=null),n(me=>({...me,selectedThreadId:pe.thread.id,detail:pe,aiThread:Z?null:me.aiThread,agentConversation:Z?null:me.agentConversation,busy:!1})),await Kb({connection:e.connection,teamId:e.teamId,threadId:pe.thread.id,lastMessageSequence:pe.thread.lastMessageSequence}),await V(),pe}catch(X){return w.current!==H||n(pe=>({...pe,busy:!1,error:cn(X)})),null}},[e.connection,e.teamId,V]),ae=g.useCallback(async()=>{const M=t.detail,H=M?.messages[0]?.sequence;if(!e.connection||!e.teamId||!M||!M.hasMoreBefore||H==null)return!1;n(X=>({...X,loading:!0,error:null}));try{const X=await J.teamChatThread(e.connection,e.teamId,M.thread.id,{beforeSequence:H,limit:50});return n(pe=>{if(pe.detail?.thread.id!==M.thread.id)return pe;const Z=[...X.messages,...pe.detail.messages];return{...pe,loading:!1,detail:{...pe.detail,messages:ol(Z),hasMoreBefore:X.hasMoreBefore}}}),!0}catch(X){return n(pe=>({...pe,loading:!1,error:cn(X)})),!1}},[e.connection,e.teamId,t.detail]),he=g.useCallback(async M=>{const H=p.current,X=M3(M.attachments??[]);if(!X)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||!H||!M.body.trim()&&X.length===0)return!1;if(M.replyToMessage&&(M.replyToMessage.threadId!==H||M.replyToMessage.teamId!==e.teamId||M.replyToMessage.id.startsWith("pending:")||M.replyToMessage.deletedAt))return n(me=>({...me,error:"That message is no longer available to reply to."})),!1;if(M.useModel){if(X.length>0)return n(_e=>({..._e,error:"Images can be sent to the team thread with Use model turned off."})),!1;const me=h.current;n(_e=>({..._e,busy:!0,error:null}));try{const _e=await J.createTeamChatAiThread(e.connection,H,{teamId:e.teamId,body:M.body.trim(),clientRequestId:crypto.randomUUID(),providerId:M.providerId,modelId:M.modelId}),He=h.current===me&&p.current===H;return He&&(h.current+=1,m.current=_e.conversationId),n(qe=>({...qe,aiThread:He?_e:qe.aiThread})),_e.activeTurn&&await J.executeTeamChatAiTurn(e.connection,_e.activeTurn.id,e.teamId),await Promise.all([Q(H),V()]),n(qe=>({...qe,busy:!1})),!0}catch(_e){return n(He=>({...He,busy:!1,error:cn(_e)})),!1}}const pe=crypto.randomUUID();if(M.selectedActionKey){if(X.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 J.createTeamChatAgentRun(e.connection,H,H3({teamId:e.teamId,body:M.body,clientRequestId:pe,selectedActionKey:M.selectedActionKey,approvalId:M.approvalId})),await Promise.all([Q(H),V()]),n(me=>({...me,busy:!1})),!0}catch(me){return n(_e=>({..._e,busy:!1,error:cn(me)})),!1}}I.current.set(pe,{inputs:X,uploaded:null});const Z=A3({clientRequestId:pe,threadId:H,teamId:e.teamId,userId:e.currentUserId,body:M.body.trim(),mentionUserIds:M.mentionUserIds??[],attachments:X,replyToMessage:M.replyToMessage,sequence:(t.detail?.thread.lastMessageSequence??0)+1});x.current.set(pe,Z),n(me=>P3(me,Z));try{const me=[];for(const[qe,Xe]of X.entries())me.push(await J.uploadTeamChatAttachment(e.connection,H,{teamId:e.teamId,attachment:Xe})),qb(x.current,pe,`${qe+1} of ${X.length}`),n(at=>Fb(at,pe,`${qe+1} of ${X.length}`));const _e=I.current.get(pe);_e&&(_e.uploaded=me);const He=await J.sendTeamChatMessage(e.connection,H,{teamId:e.teamId,body:M.body.trim(),clientRequestId:pe,mentionUserIds:M.mentionUserIds,attachmentIds:me.map(qe=>qe.id),replyToMessageId:M.replyToMessage?.id??null});return I.current.delete(pe),x.current.delete(pe),n(qe=>Bb(qe,He,e.currentUserId)),!0}catch(me){return mm(x.current,pe,"failed"),n(_e=>({...T3(_e,pe),error:cn(me)})),!1}},[e.connection,e.currentUserId,e.teamId,Q,V,t.detail?.thread.lastMessageSequence]),ve=g.useCallback(async M=>{if(!(!e.connection||!e.teamId)){h.current+=1,m.current=M,n(H=>({...H,aiThread:H.aiThread?.conversationId===M?H.aiThread:null,busy:!0,error:null}));try{const H=await J.teamChatAiThread(e.connection,e.teamId,M);if(m.current!==M)return;n(X=>({...X,aiThread:H,busy:!1}))}catch(H){if(m.current!==M)return;n(X=>({...X,busy:!1,error:cn(H)}))}}},[e.connection,e.teamId]),Ze=g.useCallback(async M=>{if(!(!e.connection||!e.teamId)){R.current=M,n(H=>({...H,busy:!0,error:null}));try{const H=await J.teamChatAgentConversation(e.connection,e.teamId,M);n(X=>({...X,agentConversation:H,busy:!1}))}catch(H){n(X=>({...X,busy:!1,error:cn(H)}))}}},[e.connection,e.teamId]),Re=g.useCallback(()=>{R.current=null,n(M=>({...M,agentConversation:null}))},[]),se=g.useCallback(async M=>{const H=p.current,X=t.agentConversation;if(!e.connection||!e.teamId||!H||!X||!M.body.trim())return!1;n(pe=>({...pe,busy:!0,error:null}));try{const pe=await J.createTeamChatAgentRun(e.connection,H,U3({teamId:e.teamId,body:M.body,clientRequestId:M.clientRequestId,conversation:X}));R.current=pe.run.id;const[Z]=await Promise.all([J.teamChatAgentConversation(e.connection,e.teamId,pe.run.id),Q(H),V()]);return n(me=>({...me,agentConversation:Z,busy:!1})),!0}catch(pe){return n(Z=>({...Z,busy:!1,error:cn(pe)})),!1}},[e.connection,e.teamId,Q,V,t.agentConversation]),Ce=g.useCallback(()=>{h.current+=1,m.current=null,n(M=>({...M,aiThread:null}))},[]),Le=g.useCallback(async M=>{const H=m.current;if(!e.connection||!e.teamId||!H||!M.body.trim())return!1;n(X=>({...X,busy:!0,error:null}));try{const X=await J.sendTeamChatAiTurn(e.connection,H,{teamId:e.teamId,body:M.body.trim(),clientRequestId:crypto.randomUUID(),providerId:M.providerId,modelId:M.modelId});return n(pe=>({...Hb(pe,X,m.current),busy:!1})),X.activeTurn&&await J.executeTeamChatAiTurn(e.connection,X.activeTurn.id,e.teamId),!0}catch(X){return n(pe=>({...pe,busy:!1,error:cn(X)})),!1}},[e.connection,e.teamId]),Qe=g.useCallback(async()=>{const M=t.aiThread?.activeTurn?.id;return!e.connection||!e.teamId||!M?!1:(await J.cancelTeamChatAiTurnExecution(e.connection,M,e.teamId)).cancelled},[e.connection,e.teamId,t.aiThread?.activeTurn?.id]),it=g.useCallback(async(M,H)=>{if(!e.connection||!e.teamId)return!1;try{return await J.editTeamChatMessage(e.connection,M.threadId,M.id,{teamId:e.teamId,body:H}),await Q(M.threadId),!0}catch(X){return n(pe=>({...pe,error:cn(X)})),!1}},[e.connection,e.teamId,Q]),ut=g.useCallback(async M=>{if(!e.connection||!e.teamId)return!1;try{return await J.deleteTeamChatMessage(e.connection,M.threadId,M.id,e.teamId),await Q(M.threadId),!0}catch(H){return n(X=>({...X,error:cn(H)})),!1}},[e.connection,e.teamId,Q]),Fe=g.useCallback(async M=>{if(!e.connection||!e.teamId||!M.clientRequestId||!M.id.startsWith("pending:"))return!1;const H=Array.isArray(M.metadata.mentionUserIds)?M.metadata.mentionUserIds.filter(Z=>typeof Z=="string"):[],X=I.current.get(M.clientRequestId),pe=M.refs.find(Z=>Z.refType==="message_reply");mm(x.current,M.clientRequestId,"sending"),n(Z=>lp(Z,M.clientRequestId,"sending"));try{let Z=X?.uploaded??[];if(X&&!X.uploaded){Z=[];for(const[_e,He]of X.inputs.entries())Z.push(await J.uploadTeamChatAttachment(e.connection,M.threadId,{teamId:e.teamId,attachment:He})),qb(x.current,M.clientRequestId,`${_e+1} of ${X.inputs.length}`),n(qe=>Fb(qe,M.clientRequestId,`${_e+1} of ${X.inputs.length}`));X.uploaded=Z}const me=await J.sendTeamChatMessage(e.connection,M.threadId,{teamId:e.teamId,body:M.body,clientRequestId:M.clientRequestId,mentionUserIds:H,attachmentIds:Z.map(_e=>_e.id),replyToMessageId:pe?.refId??null});return I.current.delete(M.clientRequestId),x.current.delete(M.clientRequestId),n(_e=>Bb(_e,me,e.currentUserId)),!0}catch(Z){return mm(x.current,M.clientRequestId,"failed"),n(me=>({...lp(me,M.clientRequestId,"failed"),error:cn(Z)})),!1}},[e.connection,e.currentUserId,e.teamId]),Ue=g.useCallback(M=>{M.id.startsWith("pending:")&&(M.clientRequestId&&I.current.delete(M.clientRequestId),M.clientRequestId&&x.current.delete(M.clientRequestId),n(H=>E3(H,M.id)))},[]),ze=g.useCallback(async(M,H)=>{if(!e.connection||!e.teamId)return!1;try{const X=await J.setTeamChatThreadMuted(e.connection,M,e.teamId,H),pe=Z=>Z.id===X.threadId?{...Z,mutedAt:X.mutedAt}:Z;return n(Z=>({...Z,threads:Z.threads.map(pe),detail:Z.detail?.thread.id===X.threadId?{...Z.detail,thread:pe(Z.detail.thread)}:Z.detail,error:null})),!0}catch(X){return n(pe=>({...pe,error:cn(X)})),!1}},[e.connection,e.teamId]);return{...t,currentUserId:e.currentUserId,notificationMode:i,incomingNotification:s,setNotificationMode:U,dismissIncomingNotification:$,setThreadMuted:ze,selectThread:le,openDm:ke,loadMoreMessages:ae,sendMessage:he,openAiThread:ve,openAgentConversation:Ze,closeAgentConversation:Re,sendAgentTurn:se,closeAiThread:Ce,sendAiTurn:Le,stopAiTurn:Qe,editMessage:it,deleteMessage:ut,retryMessage:Fe,dismissFailedMessage:Ue,refreshDirectory:re,refresh:async()=>{await Promise.all([re(),V(),Q(),Ie(),Se()])}}}function cn(e){return N3(e)}const R_="local-profile-agent";function sK(e){const t=e.profile;if(!t||t.mode!=="local")return e.hostedActions;const n=new Set(e.hostedActions.flatMap(s=>{const d=s.implementation;return d?.type!=="openpond-agent"||d.profileName!==t.activeProfile?[]:[Yo(d.agentName),Yo(s.name),Yo(s.label)].filter(Boolean)})),a=t.hosted?.teamId===e.teamId?t.hosted.hostedSourceMaterialization:null,i=new Set(e.hostedActions.map(s=>s.implementation?.agentId).filter(s=>typeof s=="string")),r=t.agents.flatMap(s=>s.enabled?a?.agentId===s.id&&!!(a.runtimeAgentId&&i.has(a.runtimeAgentId))||n.has(Yo(s.name))||n.has(Yo(s.id))?[]:[V3(t,s)]:[]);return[...e.hostedActions,...r]}function lK(e){return e?.implementation?.type===R_}function cK(e){const t=e.implementation?.profileAgentId;return typeof t=="string"&&t.trim()?t.trim():null}function B3(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 F3(e,t){const n=t.runtimeAgentId?.trim()??"",a=t.profileName?.trim()??"",i=Yo(t.agentName);return e.find(r=>{const s=r.implementation;return s?.type!=="openpond-agent"?!1:n&&typeof s.agentId=="string"&&s.agentId===n?!0:!!(a&&s.profileName===a&&i&&[s.agentName,r.name,r.label].some(d=>Yo(d)===i))})??null}function V3(e,t){return{id:`local-profile:${e.activeProfile??"default"}:${t.id}:chat`,name:t.name,label:t.name,description:W3(e),approvalPolicy:{required:!1,risk:"write"},setupRequirements:e.setupGate.blockingRequirements,invokesModel:!0,implementation:{type:R_,profileAgentId:t.id,profileName:e.activeProfile??"default"}}}function W3(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 Yo(e){return typeof e=="string"?e.trim().toLowerCase().replace(/[^a-z0-9]+/g,""):""}const Gb=5;function K3(e){return g.useCallback(async t=>{if(!e.connection||!e.teamId)throw new Error("Connect OpenPond to a Team before publishing an agent.");const n=await J.profileCheck(e.connection,{kind:"all"}),a=B3(n,t);if(a)throw new Error(a);const i=n?.agents.find(m=>m.id===t);if(!i)throw new Error(`Profile agent not found: ${t}`);const s=(await J.profilePush(e.connection,{teamId:e.teamId,ensureHosted:!0,hostedSourceAgentId:t,message:null})).localProfile?.hosted?.hostedSourceMaterialization,d=s?.agentId===t?s.runtimeAgentId:null;e.applyBootstrapPayload(await J.bootstrap(e.connection));let p=null;for(let m=0;m<Gb;m+=1){const h=await e.refreshDirectory();if(p=F3(h.agents,{runtimeAgentId:d,profileName:n.activeProfile,agentName:i.name}),p)break;m<Gb-1&&await G3(200*(m+1))}if(!p)throw new Error(`${i.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 G3(e){return new Promise(t=>{setTimeout(t,e)})}function Z3(e){g.useEffect(()=>{if(!e.notification)return;const{eventId:t,threadId:n,title:a,body:i}=e.notification;e.showToast(`${a}: ${i}`,"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 J3(e){const{connection:t,refreshToken:n=null}=e,[a,i]=g.useState([]),[r,s]=g.useState(null),[d,p]=g.useState(null),[m,h]=g.useState(null),[S,y]=g.useState(!1),[w,R]=g.useState(!1),[A,N]=g.useState(!1),[O,D]=g.useState(null),[x,I]=g.useState(null),[P,E]=g.useState(null),[T,z]=g.useState(0),U=g.useRef(0),$=g.useMemo(()=>a.find(ae=>ae.id===d)??null,[a,d]),V=g.useCallback(async()=>{if(!t)return!1;y(!0),D(null);try{const ae=await J.communities(t);return i(ae.items),s(ae.nextCursor),p(he=>he&&ae.items.some(ve=>ve.id===he)?he:null),!0}catch(ae){return D(Jl(ae)),!1}finally{y(!1)}},[t]),re=g.useCallback(async()=>{if(!t||!r||S)return!1;y(!0),D(null);try{const ae=await J.communities(t,r);return i(he=>Y3(he,ae.items)),s(ae.nextCursor),!0}catch(ae){return D(Jl(ae)),!1}finally{y(!1)}},[t,S,r]),Q=g.useCallback(async ae=>{if(!t)return null;const he=++U.current;R(!0),I(null);try{const ve=await J.communityPreview(t,ae.slug);return U.current===he&&h(ve),ve}catch(ve){return U.current===he&&I(Jl(ve)),null}finally{U.current===he&&R(!1)}},[t]),Ie=g.useCallback(ae=>{const he=a.find(ve=>ve.id===ae);he&&(p(he.id),h(ve=>ve?.id===he.id?ve:null),E(null),Q(he))},[a,Q]),Se=g.useCallback(()=>{U.current+=1,p(null),h(null),I(null),E(null)},[]);g.useEffect(()=>{if(!t){i([]),h(null),p(null);return}V()},[t,V,n]),g.useEffect(()=>{!$||m?.id===$.id||w||Q($)},[Q,m?.id,w,$]);const G=g.useCallback(async()=>{const ae=$;await V(),ae&&await Q(ae)},[Q,V,$]),Ee=g.useCallback(async()=>{if(!t||!m?.currentRules||A)return!1;N(!0),E(null);try{return await J.joinCommunity(t,m.id,m.currentRules.id),z(ae=>ae+1),await G(),!0}catch(ae){const he=$l(ae);return E(he),he.kind==="rules_stale"&&await G(),!1}finally{N(!1)}},[t,A,m,G]),xe=g.useCallback(async()=>{if(!t||!m?.currentRules||A)return!1;N(!0),E(null);try{return await J.acceptCommunityRules(t,m.id,m.currentRules.id),z(ae=>ae+1),await G(),!0}catch(ae){const he=$l(ae);return E(he),he.kind==="rules_stale"&&await G(),!1}finally{N(!1)}},[t,A,m,G]),le=g.useCallback(async()=>{if(!t||!m||A)return!1;N(!0),E(null);try{return await J.leaveCommunity(t,m.id),z(ae=>ae+1),await G(),!0}catch(ae){return E($l(ae)),!1}finally{N(!1)}},[t,A,m,G]),ke=g.useCallback(async ae=>{if(!t||!m||A)return!1;N(!0),E(null);try{return await J.updateCommunityNotifications(t,m.id,ae),i(he=>he.map(ve=>ve.id===m.id&&ve.membership?{...ve,membership:{...ve.membership,notificationMode:ae}}:ve)),h(he=>he?.id===m.id&&he.membership?{...he,membership:{...he.membership,notificationMode:ae}}:he),!0}catch(he){return E($l(he)),!1}finally{N(!1)}},[t,A,m]);return{items:a,nextCursor:r,selectedCommunityId:d,selectedSummary:$,preview:m,discoveryLoading:S,previewLoading:w,membershipBusy:A,discoveryError:O,previewError:x,membershipError:P,membershipVersion:T,refresh:V,loadMore:re,showDiscovery:Se,selectCommunity:Ie,join:Ee,acceptRules:xe,leave:le,updateNotifications:ke,clearMembershipError:()=>E(null)}}function Y3(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 Jl(e){return e instanceof Error?e.message:String(e)}function $l(e){const t=Jl(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 X3(e,t,n){return k_({realtimeUrl:e.session.realtimeUrl,httpUrl:e.session.httpUrl,authorizationToken:e.session.token,channels:[e.session.channel],onEvent:a=>{const i=gy.safeParse(a);i.success&&e.onEvent(i.data)},onReady:e.onReady,onError:e.onError},t,n)}function Q3(e){const{connection:t,preview:n,currentUserId:a,membershipVersion:i}=e,r=n?.id??null,s=n?.membership?.status==="active",d=!n?.capabilities.requiresRulesAcceptance,[p,m]=g.useState([]),[h,S]=g.useState(null),[y,w]=g.useState({}),[R,A]=g.useState([]),[N,O]=g.useState(!1),[D,x]=g.useState(!1),[I,P]=g.useState(!1),[E,T]=g.useState(!1),[z,U]=g.useState(null),[$,V]=g.useState(null),[re,Q]=g.useState(null),[Ie,Se]=g.useState(null),[G,Ee]=g.useState(!1),[xe,le]=g.useState(null),[ke,ae]=g.useState(null),he=g.useRef(null),ve=g.useRef([]),Ze=g.useRef("mentions"),Re=g.useRef(0),se=g.useRef({}),Ce=g.useRef(new Set),Le=g.useMemo(()=>p.find(Pe=>Pe.id===h)??null,[p,h]),Qe=h?y[h]??null:null;g.useEffect(()=>{he.current=h},[h]),g.useEffect(()=>{ve.current=p},[p]),g.useEffect(()=>{Ze.current=n?.membership?.notificationMode??"mentions"},[n?.membership?.notificationMode]);const it=g.useCallback(async()=>{if(!t||!r)return!1;O(!0),U(null);try{const Pe=await J.communityChannels(t,r);return m(Pe.channels),S(Ve=>Ve&&Pe.channels.some(u=>u.id===Ve)?Ve:Pe.channels.find(u=>u.isDefault)?.id??Pe.channels[0]?.id??null),Ee(!1),!0}catch(Pe){const Ve=ea(Pe);return U(Ve),bs(Ve)&&Ee(!0),!1}finally{O(!1)}},[r,t]),ut=g.useCallback(async Pe=>{if(!t||!r)return!1;const Ve=++Re.current;x(!0),V(null);try{const u=await J.communityMessages(t,r,Pe,{limit:50});return Ve!==Re.current?!1:(w(j=>({...j,[Pe]:{items:u.messages,hasMoreBefore:u.hasMoreBefore,preview:u.preview}})),Ee(!1),!0)}catch(u){if(Ve!==Re.current)return!1;const j=ea(u);return V(j),bs(j)&&Ee(!0),!1}finally{Ve===Re.current&&x(!1)}},[r,t]);g.useEffect(()=>{m(n?.channels??[]),w({}),S(n?.channels.find(Pe=>Pe.isDefault)?.id??n?.channels[0]?.id??null),U(null),V(null),Q(null),Ee(!1),Ce.current.clear(),r&&it()},[r,it,i]),g.useEffect(()=>{h&&ut(h)},[ut,h]);const Fe=g.useCallback(async(Pe,Ve)=>{if(!t||!r||!s||!d||Ve<=0)return!1;if((se.current[Pe]??0)>=Ve)return!0;se.current[Pe]=Ve;try{const u=await J.markCommunityRead(t,r,Pe,Ve);return m(j=>j.map(q=>q.id===Pe?{...q,unreadCount:0,readState:q.readState?{...q.readState,lastReadSequence:u.sequence,lastReadAt:new Date().toISOString()}:{lastReadSequence:u.sequence,lastReadAt:new Date().toISOString(),mutedAt:null,pinnedAt:null}}:q)),!0}catch(u){const j=ea(u);return bs(j)&&Ee(!0),!1}},[r,t,s,d]);g.useEffect(()=>{const Pe=Qe?.items.at(-1)?.sequence??0;h&&Pe>0&&Fe(h,Pe)},[Fe,h,Qe?.items]);const Ue=g.useCallback(Pe=>{if(Pe.communityId!==r||Ce.current.has(Pe.id))return;Ce.current.add(Pe.id);const Ve=hy.safeParse(Pe.payload.message);if(Ve.success&&Pe.type!=="read.updated"){const u=Ve.data;if(w(j=>{const q=j[Pe.channelId];if(!q)return j;const ne=q.items.some(F=>F.id===u.id)?q.items.map(F=>F.id===u.id?u:F):[...q.items,u].sort((F,_)=>F.sequence-_.sequence);return{...j,[Pe.channelId]:{...q,items:ne}}}),m(j=>j.map(q=>q.id===Pe.channelId?{...q,lastMessageSequence:Math.max(q.lastMessageSequence,u.sequence),unreadCount:he.current===Pe.channelId||u.authorUserId===a?0:Math.max(q.unreadCount+(Pe.type==="message.created"?1:0),0)}:q)),Pe.type==="message.created"&&u.authorUserId!==a){const j=ve.current.find(ne=>ne.id===Pe.channelId),q=eV(u).includes(a??""),oe=Ze.current;!j?.readState?.mutedAt&&(oe==="all"||oe==="mentions"&&q)&&ae({communityId:Pe.communityId,channelId:Pe.channelId,message:u})}he.current===Pe.channelId&&Fe(Pe.channelId,u.sequence);return}Pe.type==="read.updated"&&Pe.payload.userId===a&&it()},[r,a,it,Fe]);g.useEffect(()=>{if(!t||!r||!s||!d)return;let Pe=!1,Ve=null;return Q(null),Promise.all([J.communityRealtimeSession(t,r),J.communityEvents(t,r)]).then(async([u,j])=>{if(Pe)return;const q=async()=>{let ne=j.cursor;for(;;){const F=await J.communityEvents(t,r,{after:ne,limit:200});if(Pe)return;for(const _ of F.events)Ue(_);if(ne=F.cursor,!F.hasMore)return}},oe=X3({session:u,onEvent:Ue,onReady:()=>{Q(null),q().catch(ne=>Q(ea(ne)))},onError:ne=>Q(ea(ne))});Ve=()=>oe.close(),await q()}).catch(u=>{if(!Pe){const j=ea(u);Q(j),bs(j)&&Ee(!0)}}),()=>{Pe=!0,Ve?.()}},[Ue,r,t,s,i,d]);const ze=g.useCallback(async()=>{if(!t||!r||!h||I)return!1;const Pe=y[h],Ve=Pe?.items[0]?.sequence;if(!Pe?.hasMoreBefore||Ve==null)return!1;P(!0),V(null);try{const u=await J.communityMessages(t,r,h,{beforeSequence:Ve,limit:50});return w(j=>{const q=j[h]??Pe,oe=new Set(q.items.map(ne=>ne.id));return{...j,[h]:{...q,items:[...u.messages.filter(ne=>!oe.has(ne.id)),...q.items],hasMoreBefore:u.hasMoreBefore}}}),!0}catch(u){return V(ea(u)),!1}finally{P(!1)}},[r,t,y,I,h]),M=g.useCallback(async Pe=>{if(!t||!r||!h||E)return!1;T(!0),Se(null),le(null);try{const Ve=await Promise.all(Pe.attachments.map(j=>J.uploadCommunityAttachment(t,r,h,j))),u=await J.sendCommunityMessage(t,r,h,{body:Pe.body,clientRequestId:Pe.clientRequestId,mentionUserIds:Pe.mentionUserIds,attachmentIds:Ve.map(j=>j.id),replyToMessageId:Pe.replyToMessageId});return w(j=>{const q=j[h]??{items:[],hasMoreBefore:!1,preview:!1};return q.items.some(oe=>oe.id===u.id)?j:{...j,[h]:{...q,items:[...q.items,u]}}}),await Fe(h,u.sequence),!0}catch(Ve){const u=ea(Ve);return Se(u),le({...Pe,message:u}),bs(u)&&Ee(!0),!1}finally{T(!1)}},[r,t,Fe,h,E]),H=g.useCallback(Pe=>M({body:Pe.body,clientRequestId:crypto.randomUUID(),mentionUserIds:Pe.mentionUserIds??[],attachments:Pe.attachments??[],replyToMessageId:Pe.replyToMessageId??null}),[M]),X=g.useCallback(async(Pe,Ve)=>{if(!t||!r||!h)return!1;Se(null);try{const u=await J.editCommunityMessage(t,r,h,Pe,Ve);return Zb(w,h,u),!0}catch(u){return Se(ea(u)),!1}},[r,t,h]),pe=g.useCallback(async Pe=>{if(!t||!r||!h)return!1;Se(null);try{const Ve=await J.deleteCommunityMessage(t,r,h,Pe);return Zb(w,h,Ve),!0}catch(Ve){return Se(ea(Ve)),!1}},[r,t,h]),Z=g.useCallback(async(Pe,Ve)=>{if(!t||!r)return!1;Se(null);try{const u=await J.setCommunityChannelMuted(t,r,Pe,Ve);return m(j=>j.map(q=>q.id===Pe&&q.readState?{...q,readState:{...q.readState,mutedAt:u.mutedAt}}:q)),!0}catch(u){return Se(ea(u)),!1}},[r,t]),me=g.useCallback(async(Pe="")=>{if(!t||!r||!s)return[];try{const Ve=await J.searchCommunityMembers(t,r,{query:Pe,limit:50});return A(u=>tV(u,Ve.items)),Ve.items}catch(Ve){return Se(ea(Ve)),[]}},[r,t,s]);g.useEffect(()=>{s&&d?me():A([])},[s,d,me]);const _e=g.useCallback(async Pe=>{if(!t||!r||!h)return!1;try{const Ve=await J.communityAttachmentDownload(t,r,h,Pe);return window.open(Ve.url,"_blank","noopener,noreferrer"),!0}catch(Ve){return Se(ea(Ve)),!1}},[r,t,h]),He=g.useCallback(()=>h?ut(h):Promise.resolve(!1),[ut,h]),qe=g.useCallback(()=>xe?M(xe):Promise.resolve(!1),[xe,M]),Xe=g.useCallback(()=>le(null),[]),at=g.useCallback(()=>ae(null),[]);return{channels:p,selectedChannelId:h,selectedChannel:Le,messages:Qe?.items??[],hasMoreBefore:Qe?.hasMoreBefore??!1,previewMode:Qe?.preview??!s,members:R,channelsLoading:N,messagesLoading:D,olderMessagesLoading:I,sending:E,channelsError:z,messagesError:$,realtimeError:re,actionError:Ie,lostMembership:G,failedSend:xe,incomingNotification:ke,selectChannel:S,loadChannels:it,loadMessages:He,loadOlder:ze,sendMessage:H,retrySend:qe,dismissFailedSend:Xe,editMessage:X,deleteMessage:pe,setMuted:Z,searchMembers:me,downloadAttachment:_e,dismissIncomingNotification:at}}function Zb(e,t,n){e(a=>{const i=a[t];return i?{...a,[t]:{...i,items:i.items.map(r=>r.id===n.id?n:r)}}:a})}function eV(e){const t=e.metadata.mentionUserIds;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function tV(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 bs(e){return e.includes("community_membership_required")||e.includes("community_rules")}function ea(e){return e instanceof Error?e.message:String(e)}function nV(e){const t=J3({connection:e.connection,refreshToken:e.refreshToken}),n=Q3({connection:e.connection,preview:t.preview,currentUserId:e.currentUserId,membershipVersion:t.membershipVersion}),a=n.incomingNotification,i=t.items,r=n.channels,s=t.selectCommunity,d=n.selectChannel,p=n.dismissIncomingNotification,{setView:m,showToast:h}=e,S=g.useCallback(()=>{t.showDiscovery(),m("community")},[t.showDiscovery,m]),y=g.useCallback(R=>{t.selectCommunity(R),m("community")},[t.selectCommunity,m]),w=g.useCallback(R=>{n.selectChannel(R),m("community")},[n.selectChannel,m]);return g.useEffect(()=>{if(!a)return;const R=i.find(N=>N.id===a.communityId),A=r.find(N=>N.id===a.channelId);h(`${R?.displayName??"Community"} · #${A?.displayName??"channel"}: ${a.message.body.slice(0,120)||"New message"}`,"info",{actionLabel:"View",onAction:()=>{s(a.communityId),d(a.channelId),m("community")},placement:"top-right"}),p()},[r,i,p,a,d,s,m,h]),{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:w},view:{communities:t,chat:n,currentUserId:e.currentUserId}}}const aV=[];function oV(e){const t=g.useCallback(a=>TB(e,a),[e]),n=g.useCallback(()=>AB(e)??aV,[e]);return g.useSyncExternalStore(t,n,n)}function iV(e){const[t,n]=g.useState(()=>ju());return g.useEffect(()=>{let a=!0;return e?(J.connectedAppStatus(e,{status:"all"}).then(i=>{a&&n(i.apps)}).catch(i=>{console.warn("Unable to load connected app mention status.",i),a&&n(ju())}),()=>{a=!1}):(n(ju()),()=>{a=!1})},[e]),t}function rV(){const{composerDraftStore:e,dispatch:t,setters:n,state:a}=R6(),[i,r]=g.useState(null),[s,d]=g.useState([]),[p,m]=g.useState(null),[h,S]=g.useState(null),[y,w]=g.useState([]),[R,A]=g.useState(null),[N,O]=g.useState(null),[D,x]=g.useState(Ak),[I,P]=g.useState({}),[E,T]=g.useState(()=>new Set),z=g.useCallback((rt,Bt)=>{T(Lt=>{if(Lt.has(rt)===Bt)return Lt;const zt=new Set(Lt);return Bt?zt.add(rt):zt.delete(rt),zt})},[]),[U,$]=g.useState(0),[V,re]=g.useState(null),Q=g.useRef(null),{confirmProjectAction:Ie,projectConfirmDialog:Se,resolveProjectConfirmDialog:G}=yq(),{query:Ee,searchOpen:xe,archivedChatsOpen:le,sectionMenuOpen:ke,projectsExpanded:ae,cloudProjectsExpanded:he,chatRowsVisibleCount:ve,sidebarOpen:Ze,view:Re,selectedAppId:se,selectedProjectId:Ce,selectedSessionId:Le,draftProvider:Qe,draftModel:it,draftExperience:ut,codexPermissionMode:Fe,codexReasoningEffort:Ue,openPondCommandAccessMode:ze,busy:M,diffPanelOpen:H,diffPanelExpanded:X,rightPanelMode:pe,rightChatPanels:Z,terminalOpen:me,settingsSection:_e,newProjectDialogOpen:He,newProjectMode:qe,newProjectName:Xe,newProjectPath:at,newProjectBusy:Pe,commitDialogOpen:Ve,commitMessage:u,commitIncludeUnstaged:j,commitNextStep:q,commitDraft:oe,branchDialogOpen:ne,branchDialogName:F,toast:_,error:W}=a,Y=M6(Re==="labs"),{setQuery:ee,setSearchOpen:K,setArchivedChatsOpen:ce,setSectionMenuOpen:ue,setProjectsExpanded:Ne,setCloudProjectsExpanded:je,setChatRowsVisibleCount:$e,setSidebarOpen:Ge,setView:We,setSelectedAppId:mt,setSelectedProjectId:qt,setSelectedSessionId:jt,setPrompt:_n,setDraftProvider:bn,setDraftModel:Xt,setDraftExperience:yt,setCodexPermissionMode:tn,setCodexReasoningEffort:Et,setOpenPondCommandAccessMode:St,setDiffPanelOpen:on,setDiffPanelExpanded:Ot,setRightPanelMode:rn,setRightChatPanels:Tn,setTerminalOpen:pn,setSyncingWorkspaceAppId:Ca,setSettingsSection:Ra,setNewProjectDialogOpen:$t,setNewProjectMode:zn,setNewProjectName:st,setNewProjectPath:vn,setNewProjectBusy:Aa,setCommitDialogOpen:Pa,setCommitMessage:aa,setCommitIncludeUnstaged:Ta,setCommitNextStep:te,setCommitDraft:De,setBranchDialogOpen:Ke,setBranchDialogName:et,setError:Rt}=n,{connectionRef:bt,setError:lt,showToast:wt}=v6({appDispatch:t,error:W,setErrorState:Rt}),{appPreferences:oa,applyBootstrapPayload:Un,bootstrap:tt,codexHistorySessions:Sn,connection:xt,events:yn,runtimeEventStore:En,approvals:wn,sessions:Ea,startup:ha,setAppPreferences:Ka,setBootstrap:Ma,setCodexHistorySessions:Yn,setEvents:kt,setSessions:ja}=g6({setDraftModel:Xt,setDraftProvider:bn,setCodexPermissionMode:tn,setCodexReasoningEffort:Et,setOpenPondCommandAccessMode:St,setError:lt,setSelectedAppId:mt,setSelectedProjectId:qt,setSelectedSessionId:jt});bt.current=xt,g.useEffect(()=>{tt&&w(tt.sidebarFileBookmarks??[])},[tt?.sidebarFileBookmarks]);const ia=g.useMemo(()=>[...yn].reverse().find(rt=>rt.name==="tool.completed"&&rt.action==="manage_sidebar_file")??null,[yn]),fi=g.useRef(null);g.useEffect(()=>{!xt||!ia||fi.current===ia.id||(fi.current=ia.id,J.sidebarFiles(xt).then(rt=>w(rt.items)).catch(rt=>lt(rt instanceof Error?rt.message:String(rt))))},[xt,ia,lt]);const zo=g.useCallback(async(rt,Bt)=>{if(!xt)return;const Lt=y;w(zt=>Bt==="none"?zt.filter(va=>va.id!==rt.id):zt.some(va=>va.id===rt.id)?zt.map(va=>va.id===rt.id?{...va,status:Bt}:va):[...zt,{...rt,status:Bt}]);try{const zt=await J.patchSidebarFile(xt,{workspaceKind:rt.workspaceKind,workspaceId:rt.workspaceId,workspaceName:rt.workspaceName,path:rt.path,status:Bt,sourceSessionId:rt.sourceSessionId});w(zt.items)}catch(zt){w(Lt),lt(zt instanceof Error?zt.message:String(zt))}},[xt,lt,y]),Uo=iV(xt),Ga=O6({connection:xt,profileId:tt?.profile?.activeProfile??"default"}),{pinnedCollapsed:hi,projectsCollapsed:gi,cloudProjectsCollapsed:bi,chatsCollapsed:vi,savedForLaterCollapsed:Cr,sidebarWidth:Rr,sidebarResizing:Oa,diffPanelWidth:Ar,diffPanelResizing:yi,togglePinnedCollapsed:Si,toggleProjectsCollapsed:xi,toggleCloudProjectsCollapsed:Pr,toggleChatsCollapsed:Xn,toggleSavedForLaterCollapsed:Tr,startSidebarResize:Er,startDiffPanelResize:Mr}=T6({connection:xt,preferences:tt?.preferences,sidebarOpen:Ze,diffPanelExpanded:X,setBootstrap:Ma,setError:lt}),{cloudProjectById:ki,linkedProjectByAppId:_i,localProjectById:wi,mentionableSandboxApps:jr,selectedApp:Na,selectedCloudProject:Za,selectedProject:Hn,selectedProjectLinkedApp:Or,selectedProjectLinkedOpenPondApp:Nr,selectedSession:fn,selectedSessionLinkedProject:Ii,sidebarSessions:qn}=KB({bootstrap:tt,codexHistorySessions:Sn,selectedAppId:se,selectedProjectId:Ce,selectedSessionId:Le,sessions:Ea}),ga=fn?.experience??ut;g.useEffect(()=>{SB(ga)},[ga]);const Ja=g.useMemo(()=>xU(qn,ga),[ga,qn]),$a=B6(yn,wn),{chatMentionApps:$r,connectedAppMentions:Dr,pendingApproval:Ya}=m5({bootstrap:tt,connectedAppRows:Uo,mentionableSandboxApps:jr,runtimeIndexes:$a,selectedApp:Na,selectedCloudProject:Za,selectedProject:Hn,selectedSession:fn,selectedSessionId:Le}),{codexHistoryEvents:Ho,setCodexHistoryEvents:Ci}=$5({connection:xt,selectedSessionId:Le,selectedSessionLocallyActive:!!(Le&&E.has(Le)),selectedSessionStatus:fn?.status,setCodexHistorySessions:Yn,setError:lt}),{account:qo,accountPending:Ri,accountSignedOut:Bo,activeModel:Ai,activeProvider:ra,activeWorkspaceAppId:vo,activeWorkspaceId:Fo,activeWorkspaceKind:Xa,activeWorkspaceLocation:Pi,appDefaults:Da,cloudLinked:Ti,selectedCodexHistoryPending:Lr,selectedSessionProjectId:Vo,startMessage:Ei,workspaceName:Mi}=qB({bootstrap:tt,draftModel:it,draftProvider:Qe,selectedApp:Na,selectedAppId:se,selectedCloudProject:Za,selectedProject:Hn,selectedSession:fn,selectedSessionId:Le,selectedSessionLinkedProject:Ii}),ji=g.useMemo(()=>jB(tt?.account??null),[tt?.account]),zr=g.useMemo(()=>Xm(tt?.account??null),[tt?.account]),Wo=oV(zr),Oi=g.useMemo(()=>$B(Wo,Da.defaultTeamId),[Da.defaultTeamId,Wo]),yo=Oi?.teamId??null,La=q3({connection:xt,teamId:yo,currentUserId:qo?.profile?.id??null,refreshToken:tt?.accountMeta.asOf??null}),Ur=K3({connection:xt,teamId:yo,applyBootstrapPayload:Un,refreshDirectory:La.refreshDirectory});Z3({notification:La.incomingNotification,dismiss:La.dismissIncomingNotification,selectThread:La.selectThread,setView:We,showToast:wt});const{communities:Hr,sidebar:qr,view:Br}=nV({connection:xt,currentUserId:qo?.profile?.id??null,refreshToken:tt?.accountMeta.asOf??null,setView:We,showToast:wt}),ba=La.aiThread?.conversationId??null,Ni=Re==="team"&&!!ba&&H&&pe==="chat";g.useEffect(()=>{if(Re==="team"){if(ba){rn("chat"),on(!0);return}pe==="chat"&&on(!1)}},[pe,on,rn,ba,Re]);const Ko=g.useCallback(()=>{if(ba){if(Ni){on(!1);return}rn("chat"),on(!0)}},[on,rn,Ni,ba]),Fr=g.useMemo(()=>ma(Hn,tt?.cloudProjects??[]),[tt?.cloudProjects,Hn]),Qa=fn?.provider==="codex"?ze:fn?.openPondCommandAccessMode??ze,Mn=vo,Vr=Fo,Wr=Xa,Kr=Mi,{openPondActionCatalog:Gr,selectedActionCatalog:ft}=o3({cloudProjectById:ki,cloudProjects:tt?.cloudProjects??[],connection:xt,defaultTeamId:Da.defaultTeamId,accountScopeKey:ji,localProjects:tt?.localProjects??[],profile:tt?.profile,selectedCloudProject:Za,selectedProject:Hn,reportError:lt}),{expandedProjectIds:Dt,expandProject:Bn,toggleProjectExpanded:sn,setExpandedProjectIds:Qn}=i3({selectedProjectId:Ce});e5({activeWorkspaceId:Fo,activeWorkspaceKind:Xa,appDispatch:t,connection:xt,expandProject:Bn,linkedProjectByAppId:_i,providerSettings:tt?.providers??null,selectedAppId:se,selectedSession:fn,selectedSessionId:Le,selectedSessionProjectId:Vo,setDiffPanelExpanded:Ot,setDraftModel:Xt,setDraftProvider:bn,setError:lt,setSelectedAppId:mt,setSelectedProjectId:qt,setSessions:ja,setTerminalOpen:pn,toast:_});const{changeCodexPermissionMode:In,changeCodexReasoningEffort:ed}=v5({connection:xt,setBootstrap:Ma,setCodexPermissionMode:tn,setCodexReasoningEffort:Et,setError:lt}),{changeOpenPondCommandAccessMode:td}=I4({connection:xt,selectedSession:fn,setBootstrap:Ma,setError:lt,setOpenPondCommandAccessMode:St,setSessions:ja}),nd=t5({connection:xt,setError:lt}),Zr=g.useCallback(()=>{$(rt=>rt+1)},[]),il=a5({appDispatch:t,expandProject:Bn,linkedProjectByAppId:_i,requestComposerFocus:Zr,onBeginNewChat:()=>{an({kind:"chat",sessionId:null}),re(null),yt(rt=>rt==="development"?"work":rt)},setMentionedAppId:S}),ad=g.useCallback(rt=>{const Bt=vt("local",rt);t({type:"selectProject",projectId:Bt}),Bn(Bt)},[t,Bn]),{advanceAfterTurn:od,begin:id,bindSession:rd,dismiss:sd,handoff:ld,prepareTurn:cd,selectTask:dd}=U6({activeModel:Ai,activeProvider:ra,applyBootstrapPayload:Un,beginNewChat:il,composerDraftStore:e,connection:xt,requestComposerFocus:Zr,selectedLocalProjectId:Hn?.id??null,selectedSessionId:Le,selectLocalProject:ad,setDraftModel:Xt,setDraftProvider:bn,setError:lt,view:Re});P6({connection:xt,events:yn,showToast:wt}),j4({searchOpen:xe,sectionMenuOpen:ke,setSectionMenuOpen:ue,setSearchOpen:K,setQuery:ee}),g.useEffect(()=>{P({})},[tt?.server.id]);const{chatHistoryLoadStates:ud,loadMoreSelectedChatHistory:rl,selectedPagedSessionEvents:md,selectedRuntimeIndexes:sl}=H6({approvals:wn,codexHistoryEvents:Ho,connection:xt,latestServerSequence:tt?.eventWindow?.latestSequence,runtimeIndexes:$a,runtimeEventStore:En,selectedSessionId:Le,serverId:tt?.server.id,setCodexHistoryEvents:Ci,setCodexHistorySessions:Yn,setError:lt}),{activeSessions:pd,archivedSessions:fd,pinnedProjects:hd,pinnedSessions:ll,savedForLaterSessions:Jr,pinnedFiles:gd,savedForLaterFiles:bd,pinnedItems:cl,projectRows:dl,localProjectRows:ul,visibleProjectRows:Yr,cloudProjectRows:vd,projectSessionRowsByProjectId:ml,childSessionRowsByParentId:yd,sidebarProjectIdBySessionId:Xr,chatRows:Sd,visibleChatRows:pl,sessionEvents:xd,chatMessages:fl,contextUsage:kd,goalRuntime:_d,subagentRuntime:hl}=C4({localProjects:tt?.localProjects??[],cloudProjects:tt?.cloudProjects??[],sessions:Ja,runtimeIndexes:sl,appPreferences:oa,selectedSessionId:Le,selectedProjectId:Ce,archivedChatsOpen:le,projectsExpanded:ae,chatRowsVisibleCount:ve,sidebarFileBookmarks:y}),wd=g.useCallback(rt=>{yt(rt);const Bt=[...Ja].filter(Lt=>rt==="work"?Lt.experience==="work"||Lt.experience==="development":Lt.experience===rt).sort((Lt,zt)=>zt.updatedAt.localeCompare(Lt.updatedAt))[0]??[...qn].filter(Lt=>Lt.experience===rt).sort((Lt,zt)=>zt.updatedAt.localeCompare(Lt.updatedAt))[0]??null;if(Bt)t({type:"selectSession",sessionId:Bt.id,appId:rt!=="chat"?Bt.appId:null,projectId:rt!=="chat"?Xr[Bt.id]??null:null});else if(t({type:"beginNewChat",appId:null}),rt==="chat"&&ra==="codex"){const Lt=Wm(tt?.providers,{enabledOnly:!0}).find(zt=>zt.value!=="codex")?.value??oi;bn(Lt),Xt(lc(Lt,tt?.providers)??Ps)}rt==="chat"&&(pn(!1),Ot(!1),rn("home")),We("chat")},[t,ra,tt?.providers,Ja,Ot,yt,Xt,bn,rn,pn,We,Xr,qn]),Id=g.useCallback(rt=>{const Bt=e.getSnapshot();if(yt(rt),(Le||se||Ce)&&(t({type:"beginNewChat",appId:null}),Bt&&e.set(Bt)),rt==="chat"&&ra==="codex"){const Lt=Wm(tt?.providers,{enabledOnly:!0}).find(zt=>zt.value!=="codex")?.value??oi;bn(Lt),Xt(lc(Lt,tt?.providers)??Ps)}rt==="chat"&&(pn(!1),Ot(!1),rn("home")),We("chat")},[ra,t,tt?.providers,e,se,Ce,Le,Ot,yt,Xt,bn,rn,pn,We]),{pendingChatUserMessages:Qr,recordPendingChatUserMessage:Cd,visibleChatMessages:Rd}=S4({chatMessages:fl,runtimeIndexes:sl,selectedSessionId:Le}),So=g.useMemo(()=>NU({selectedAppId:se,selectedProjectId:Ce,selectedSessionId:Le}),[se,Ce,Le]),gl=g.useRef(null);g.useEffect(()=>{const rt=gl.current;gl.current=So,!(!rt||rt.kind!=="draft"||So.kind!=="session")&&(Ds(rt,So)||d(Bt=>{const Lt=$U({tabs:Bt,previousScope:rt,activeScope:So});return Lt.some((va,tu)=>va!==Bt[tu])?Lt:Bt}))},[So]);const Ad=g.useMemo(()=>DU(s),[s]),{goalRuntime:Pd,runningSessionIds:Td,selectedSessionRunning:Ed,sidebarGoalRuntimeBySessionId:Md,sidebarSubagentRuntimeBySessionId:jd}=M4({codexHistoryEvents:Ho,codexHistorySessions:Sn,connection:xt,expandedProjectIds:Dt,goalRuntime:_d,locallyActiveCodexHistorySessionIds:E,pinnedSessions:ll,savedForLaterSessions:Jr,projectSessionRowsByProjectId:ml,rightChatHistoryEvents:I,runtimeIndexes:$a,selectedSession:fn,selectedSessionId:Le,serverId:tt?.server.id,setCodexHistorySessions:Yn,sidebarSessions:qn,subagentRuntime:hl,visibleChatRows:pl,visibleProjectRows:Yr}),{dragItem:Od,pinnedPreviewKeys:bl,startPinnedDrag:Nd,clearSidebarDrag:$i,previewPinnedDrop:$d,commitPinnedDrop:Dd,commitPinnedPreviewDrop:Ld}=D5({connection:xt,appPreferences:oa,sessions:qn,pinnedItems:cl,setAppPreferences:Ka,setCodexHistorySessions:Yn,setSessions:ja,sidebarFileBookmarks:y,setSidebarFileBookmarks:w,setError:lt}),{clearTaskDrag:es,commitTaskDrop:zd,commitTaskPreviewDrop:Ud,previewTaskDrop:ts,startTaskDrag:ns,taskDragSessionId:as,taskPreviewSessionIds:os}=L5({connection:xt,sessions:qn,setCodexHistorySessions:Yn,setError:lt,setSessions:ja}),{commandProjectRows:Hd,contextWindowStatus:is,pinnedRows:rs,sidebarWorkspaceAppIds:ss}=n5({activeProvider:ra,contextCompaction:Da.contextCompaction,contextUsage:kd,pinnedItems:cl,pinnedPreviewKeys:bl??[],pinnedProjects:hd,projectRows:dl,visibleProjectRows:Yr}),za=!!(Mn&&(Re==="chat"||Re==="labs")&&(Ve||H&&(pe==="changes"||pe==="goal"))),{workspaceStates:ls,workspaceBusy:yl,diffBusy:qd,visibleWorkspaceState:cs,visibleWorkspaceDiff:Bd,rememberWorkspaceState:Sl,refreshWorkspace:Fd,refreshWorkspaceDiff:Go,setWorkspaceBusy:Vd}=l3({connection:xt,activeWorkspaceAppId:Mn,view:Re,shouldLoadWorkspaceDiff:za,sidebarWorkspaceAppIds:ss,setError:lt});Q.current=Sl;const Wd=g.useCallback((rt=Mn)=>!rt||rt!==Mn||!za?Promise.resolve(null):Go(rt),[Go,za,Mn]),Kd=g.useCallback(async(rt={})=>{!Mn||!za||await Go(Mn,rt)},[Go,za,Mn]),Gd=!1,Zd=!!(fn?.provider==="codex"&&fn.cwd&&!Va(fn.workspaceKind)),Jd=!!(cs&&!cs.initialized&&Xa!=="local_project"&&ra!=="codex"&&!Zd&&!Lr),ds=Xa==="local_project"&&!!Hn?.sandboxTemplate?.detected&&!Hn?.linkedOpenPondApp?.appId,[xl,us]=g.useState(null),[Yd,Xd]=g.useState(null),{projectTarget:Qd,workspaceTarget:eu}=BB({accountPending:Ri,accountSignedOut:Bo,activeWorkspaceLocation:Pi,bootstrap:tt,busy:M,cloudLinked:Ti,selectedCloudProject:Za,selectedProject:Hn,selectedSession:fn,pendingWorkspaceTarget:xl,workspaceStates:ls,workspaceBusy:yl});return g.useEffect(()=>{us(null)},[fn?.id]),{composerDraftStore:e,appDispatch:t,pendingTerminalCommand:i,setPendingTerminalCommand:r,terminalTabs:s,setTerminalTabs:d,trainingDetailTasksetId:p,setTrainingDetailTasksetId:m,mentionedAppId:h,setMentionedAppId:S,cloudSetupDialog:R,setCloudSetupDialog:A,rightPanelTabRequest:N,setRightPanelTabRequest:O,workspaceDiffPanelViewState:D,setWorkspaceDiffPanelViewState:x,rightChatHistoryEvents:I,setRightChatHistoryEvents:P,locallyActiveCodexHistorySessionIds:E,setCodexHistoryTurnLocallyActive:z,mainComposerFocusRequestId:U,requestMainComposerFocus:Zr,draftSubagentDelegationMode:V,setDraftSubagentDelegationMode:re,confirmProjectAction:Ie,projectConfirmDialog:Se,resolveProjectConfirmDialog:G,query:Ee,searchOpen:xe,archivedChatsOpen:le,sectionMenuOpen:ke,projectsExpanded:ae,cloudProjectsExpanded:he,sidebarOpen:Ze,view:Re,selectedAppId:se,selectedProjectId:Ce,selectedSessionId:Le,draftProvider:Qe,draftModel:it,draftExperience:ut,activeExperience:ga,changeExperience:wd,changeNewExperience:Id,codexPermissionMode:Fe,codexReasoningEffort:Ue,openPondCommandAccessMode:ze,busy:M,diffPanelOpen:H,diffPanelExpanded:X,rightPanelMode:pe,rightChatPanels:Z,terminalOpen:me,settingsSection:_e,newProjectDialogOpen:He,newProjectMode:qe,newProjectName:Xe,newProjectPath:at,newProjectBusy:Pe,commitDialogOpen:Ve,commitMessage:u,commitIncludeUnstaged:j,commitNextStep:q,commitDraft:oe,branchDialogOpen:ne,branchDialogName:F,toast:_,error:W,labDetailNavigation:Y,setQuery:ee,setSearchOpen:K,setArchivedChatsOpen:ce,setSectionMenuOpen:ue,setProjectsExpanded:Ne,setCloudProjectsExpanded:je,setChatRowsVisibleCount:$e,setSidebarOpen:Ge,setView:We,setSelectedAppId:mt,setSelectedProjectId:qt,setSelectedSessionId:jt,setPrompt:_n,setDraftProvider:bn,setDraftModel:Xt,setDraftExperience:yt,setDiffPanelOpen:on,setDiffPanelExpanded:Ot,setRightPanelMode:rn,setRightChatPanels:Tn,setTerminalOpen:pn,setSyncingWorkspaceAppId:Ca,setSettingsSection:Ra,setNewProjectDialogOpen:$t,setNewProjectMode:zn,setNewProjectName:st,setNewProjectPath:vn,setNewProjectBusy:Aa,setCommitDialogOpen:Pa,setCommitMessage:aa,setCommitIncludeUnstaged:Ta,setCommitNextStep:te,setCommitDraft:De,setBranchDialogOpen:Ke,setBranchDialogName:et,setError:lt,showToast:wt,appPreferences:oa,applyBootstrapPayload:Un,approvals:wn,bootstrap:tt,connection:xt,events:yn,runtimeEventStore:En,sessions:Ea,startup:ha,setAppPreferences:Ka,setCodexHistorySessions:Yn,setEvents:kt,setSessions:ja,training:Ga,pinnedCollapsed:hi,projectsCollapsed:gi,cloudProjectsCollapsed:bi,chatsCollapsed:vi,savedForLaterCollapsed:Cr,sidebarWidth:Rr,sidebarResizing:Oa,diffPanelWidth:Ar,diffPanelResizing:yi,togglePinnedCollapsed:Si,toggleProjectsCollapsed:xi,toggleCloudProjectsCollapsed:Pr,toggleChatsCollapsed:Xn,toggleSavedForLaterCollapsed:Tr,startSidebarResize:Er,startDiffPanelResize:Mr,cloudProjectById:ki,localProjectById:wi,selectedApp:Na,selectedCloudProject:Za,selectedProject:Hn,selectedProjectLinkedApp:Or,selectedProjectLinkedOpenPondApp:Nr,selectedSession:fn,sidebarSessions:qn,runtimeIndexes:$a,chatMentionApps:$r,connectedAppMentions:Dr,pendingApproval:Ya,codexHistoryEvents:Ho,setCodexHistoryEvents:Ci,account:qo,accountPending:Ri,accountSignedOut:Bo,activeModel:Ai,activeProvider:ra,activeWorkspaceAppId:vo,activeWorkspaceId:Fo,activeWorkspaceKind:Xa,activeWorkspaceLocation:Pi,appDefaults:Da,selectedSessionProjectId:Vo,startMessage:Ei,workspaceName:Mi,accountScopeKey:ji,organizations:Wo,teamChatOrganization:Oi,teamChatTeamId:yo,teamChat:La,publishTeamProfileAgent:Ur,communities:Hr,communitySidebar:qr,communityView:Br,teamAiThreadId:ba,toggleTeamAiSidebar:Ko,selectedProjectConfirmedCloudProject:Fr,activeOpenPondCommandAccessMode:Qa,viewWorkspaceAppId:Mn,viewWorkspaceId:Vr,viewWorkspaceKind:Wr,viewWorkspaceName:Kr,openPondActionCatalog:Gr,selectedActionCatalog:ft,expandedProjectIds:Dt,expandProject:Bn,toggleProjectExpanded:sn,setExpandedProjectIds:Qn,changeCodexPermissionMode:In,changeCodexReasoningEffort:ed,changeOpenPondCommandAccessMode:td,resolveApproval:nd,beginNewChat:il,advanceTrainingModelChatAfterTurn:od,beginNewChatWithTrainingModel:id,bindTrainingModelChatSession:rd,dismissTrainingChatHandoff:sd,trainingChatHandoff:ld,prepareTrainingModelChatTurn:cd,selectTrainingChatTaskForComposer:dd,chatHistoryLoadStates:ud,loadMoreSelectedChatHistory:rl,selectedPagedSessionEvents:md,activeSessions:pd,archivedSessions:fd,pinnedSessions:ll,savedForLaterSessions:Jr,pinnedFiles:gd,savedForLaterFiles:bd,sidebarFileBookmarks:y,setSidebarFileStatus:zo,projectRows:dl,localProjectRows:ul,visibleProjectRows:Yr,cloudProjectRows:vd,projectSessionRowsByProjectId:ml,childSessionRowsByParentId:yd,sidebarProjectIdBySessionId:Xr,chatRows:Sd,visibleChatRows:pl,chatRowsVisibleCount:ve,sessionEvents:xd,chatMessages:fl,goalRuntime:Pd,subagentRuntime:hl,pendingChatUserMessages:Qr,recordPendingChatUserMessage:Cd,visibleChatMessages:Rd,activeTerminalScope:So,terminalSummaries:Ad,runningSessionIds:Td,selectedSessionRunning:Ed,sidebarGoalRuntimeBySessionId:Md,sidebarSubagentRuntimeBySessionId:jd,taskDragSessionId:as,taskPreviewSessionIds:os,startTaskDrag:ns,clearTaskDrag:es,previewTaskDrop:ts,commitTaskDrop:zd,commitTaskPreviewDrop:Ud,dragItem:Od,startPinnedDrag:Nd,clearSidebarDrag:$i,previewPinnedDrop:$d,commitPinnedDrop:Dd,commitPinnedPreviewDrop:Ld,commandProjectRows:Hd,contextWindowStatus:is,pinnedRows:rs,workspaceStates:ls,workspaceBusy:yl,diffBusy:qd,visibleWorkspaceState:cs,visibleWorkspaceDiff:Bd,rememberWorkspaceState:Sl,refreshWorkspace:Fd,refreshWorkspaceDiff:Go,setWorkspaceBusy:Vd,refreshWorkspaceDiffWhenNeeded:Wd,refreshVisibleWorkspaceDiff:Kd,managedWorkspace:Gd,canSyncActiveWorkspace:Jd,canPublishOpenPondProject:ds,pendingWorkspaceTarget:xl,setPendingWorkspaceTarget:us,pendingSidebarWorkspaceTarget:Yd,setPendingSidebarWorkspaceTarget:Xd,projectTarget:Qd,workspaceTarget:eu}}const sV=/^(localhost|\[::1\]|127(?:\.\d{1,3}){3})(?::\d+)?(?:[/?#].*)?$/i,lV=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+(?:[:/?#].*)?$/i;function cV(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:sV.test(n)?Dl(`http://${n}`,new Set(["http:"])):lV.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 dV(e){const t=cV(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 uV="openpond-coding-core-v1",mV="feature";function cp(e){const t=new URL("/sandboxes",Hf(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",mV),t.searchParams.set("runtimeProfileId",uV),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 dK(e){const t=e.organizationSlug?.trim(),n=t?`/sandboxes/${encodeURIComponent(t)}/billing`:"/sandboxes/billing",a=new URL(n,Hf(e.accountBaseUrl));return!t&&e.teamId?.trim()&&a.searchParams.set("teamId",e.teamId.trim()),a.toString()}function Jb(e){const t=e.organizationSlug?.trim(),n=e.projectSlug?.trim();return!t||!n?null:new URL(`/${encodeURIComponent(t)}/${encodeURIComponent(n)}`,Hf(e.accountBaseUrl)).toString()}function Hf(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 pV({account:e,browserConversationId:t,cloudProjectById:n,cloudProjects:a,diffPanelOpen:i,rightPanelMode:r,selectedProjectId:s,setDiffPanelOpen:d,setNewProjectDialogOpen:p,setNewProjectMode:m,setNewProjectName:h,setRightPanelMode:S}){const y=g.useCallback(()=>{S("changes"),d(!0)},[d,S]),w=g.useCallback(()=>{if(i&&r==="changes"){d(!1);return}y()},[i,r,d,y]),R=g.useCallback(()=>{S("browser"),d(!0)},[d,S]),A=g.useCallback(()=>{S("goal"),d(!0)},[d,S]),N=g.useCallback((I,P)=>{dV({conversationId:t,href:I,explicitFile:P?.explicitFile,newTab:P?.newTab}).then(E=>{E&&R()})},[t,R]),O=g.useCallback(()=>{m("cloud"),h(""),p(!0)},[p,m,h]),D=g.useCallback(I=>{const P=n.get(I);P&&N(cp({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,N]);return{createCloudEnvironmentFromSidebar:g.useCallback(()=>{const I=s?.startsWith("cloud:")?s.slice(6):a[0]?.id??null;if(I){D(I);return}O()},[a,O,s,D]),openCloudProjectDialog:O,openUrlInBrowserPanel:N,showBrowserPanel:R,showChangesPanel:y,showGoalSidebarTab:A,toggleChangesPanel:w}}function fV(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 hV({browserConversationId:e,sessionIds:t,onOpenSession:n,onShowBrowserPanel:a}){g.useEffect(()=>window.openpond?.browser?.onRevealRequest?.(r=>{const s=fV({currentConversationId:e,requestConversationId:r.conversationId,sessionIds:t});s.reveal&&(s.sessionIdToOpen&&n(s.sessionIdToOpen),a())}),[e,n,a,t])}const gV="chat",bV=["help me","please","can you","could you","make","create","build"],vV=new Set(["a","an","and","for","from","i","me","my","of","our","please","produce","summary","the","to","with"]);function Yb(e){const t=pm(e.label);if(t&&!dp(t))return Xb(t);const n=pm(e.name);if(n&&!dp(n))return Xb(n);const a=pm(e.actionId)?.replace(/\.chat$/i,"")??"";return yV(a||t||"Profile Agent")}function dp(e){return e.trim().toLowerCase()===gV}function yV(e){const t=SV(e.replace(/\.chat$/i,"").replace(/[._-]+/g," ").replace(/\s+/g," ").trim()),a=t.toLowerCase().split(/\s+/).map(i=>i.replace(/[^a-z0-9]/g,"")).filter(i=>i&&!vV.has(i)).slice(0,3);return A_(a.length?a.join(" "):t||e)}function Xb(e){return A_(e).split(/\s+/).slice(0,4).join(" ")}function SV(e){let t=e.trim();for(const n of bV)if(t.toLowerCase().startsWith(`${n} `)){t=t.slice(n.length).trim();break}return t}function pm(e){return typeof e=="string"&&e.trim()?e.trim():null}function A_(e){return e.replace(/[._-]+/g," ").replace(/\s+/g," ").trim().replace(/\b[a-z0-9]/gi,t=>t.toUpperCase())}const xV="openpond-profile-action";function kV(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Ll(e){return typeof e=="string"&&e.trim()?e.trim():null}function _V(e){const t=kV(e.implementation);if(t?.type!==xV)return null;const n=Ll(t.actionId)??e.id;if(e.sourceActionId!=="chat"&&n!=="chat"&&!n.endsWith(".chat"))return null;const a=Ll(e.label);if(a&&!dp(a))return Yb({label:a,description:e.description});const i=Ll(t.agentName)??Ll(e.name);return Yb({actionId:n,description:e.description,name:i})}function wV(e){const t=_V(e);return t||e.label?.trim()||e.name?.trim()||e.id}function P_(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 IV=new Set(["action","agent","chat","customer","default","filter","items","open","openpond","profile","run","summarize","track","workflow"]);function T_(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function gr(e){return typeof e=="string"&&e.trim()?e.trim():null}function tr(e,t,n={}){const a=gr(t)?An(String(t)):"";a&&(!n.generic&&IV.has(a)||e.add(a))}function zl(e,t){const n=gr(t);if(n)for(const a of n.split(/[.:/\\\s]+/g))tr(e,a)}function CV(e,t){const n=gr(t);if(n)for(const a of n.split(/[^A-Za-z0-9_-]+/g))a.length<4||tr(e,a)}function E_(e){const t=new Set,n=T_(e.implementation),a=gr(n?.actionId);return tr(t,e.id,{generic:!0}),zl(t,e.id),tr(t,a,{generic:!0}),zl(t,a),tr(t,e.name,{generic:!0}),zl(t,e.name),tr(t,e.label,{generic:!0}),zl(t,e.label),CV(t,e.description),t}function RV(e){const t=T_(e.implementation);return[e.id,e.name??"",e.label??"",e.description??"",gr(t?.actionId)??"",gr(t?.agentName)??"",P_(e),...Array.from(E_(e))].join(" ").toLowerCase()}function uK(e,t,n=8){const a=An(t);return e.length===0?[]:e.filter(i=>a?RV(i).includes(a):!0).slice(0,n)}function AV(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>An(t[1]??"")).filter(Boolean)}function PV(e,t){const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return e.replace(new RegExp(`(^|\\s)@${n}(?=\\s|$)`,"g"),"$1").replace(/\s+/g," ").trim()}function TV(e,t){const n=AV(e);if(n.length===0||t.length===0)return null;const a=new Map;for(const r of n)for(const s of t)E_(s).has(r)&&a.set(s.id,{action:s,mention:r});if(a.size!==1)return null;const i=Array.from(a.values())[0];return{action:i.action,mention:i.mention,prompt:PV(e,i.mention)}}function mK(e){return wV(e)}function pK(e){return e.description||P_(e)}const qf=[{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:"workflow",command:"/workflow",label:"Schedule workflow",description:"Create a recurring prompt that posts each run back into this chat."},{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 EV(e){return qf.filter(t=>t.id!=="goal"||e==="codex")}function M_(e,t){return t==="work"?e.id==="submit-issue"||e.id==="workflow":t==="development"?e.id!=="workflow":t==="chat"?e.id!=="sync-cloud":!0}function fK(e,t){return EV(e).filter(n=>M_(n,t))}const MV=new Set(qf.map(e=>e.id));function hK(e){return e.subcommands?.length?e.subcommands.join(", "):e.description}function jV(e){return[e.id,e.command,e.label,e.description].join(" ")}function OV(e){return(e.subcommands??[]).flatMap(t=>[t,`${e.id} ${t}`,`${e.command} ${t}`]).join(" ")}function NV(e){const t=/^\/([a-z][a-z0-9_-]*)(?:\s+([\s\S]*))?$/.exec(e.trim());if(!t)return null;const n=t[1];return MV.has(n)?{command:n,args:t[2]?.trim()??""}:null}function $V(e){const t=e.trim();if(!t.startsWith("!"))return null;const n=t.slice(1).trim();return n?{command:n}:null}function gK({commands:e=qf,prompt:t,limit:n=10}){if(!t.startsWith("/"))return[];const a=t.slice(1).trim().toLowerCase();if(!a)return e.slice(0,n);const i=e.filter(d=>d.id.startsWith(a));if(i.length>0)return i.slice(0,n);const r=e.filter(d=>jV(d).toLowerCase().includes(a));return(r.length>0?r:e.filter(d=>OV(d).toLowerCase().includes(a))).slice(0,n)}function bK(e){return e==="owner"?"Owner":e==="admin"?"Admin":"Member"}function Xc(e){return e?.role==="owner"||e?.role==="admin"}function vK(e){const t=Qc(e.organizations,e.defaultTeamId),n=Xc(t),a=e.localProject??null;if(!a)return DV("Open a local project to set up an Agent.");const i=LV(a,e.projects),r=zV(a,i,e.agents),s=!!a.sandboxTemplate?.detected,d=t&&!n?"Ask an owner or admin to connect this project.":null;return s?i?UV(a,i)?Ul({state:"needs_sync",actionLabel:"Sync Project",project:i,agent:r,canManage:n,actionBlockedReason:d}):r?{state:"ready",actionLabel:"Run Agent",canAct:!0,reason:null,project:i,agent:r}:Ul({state:"needs_agent",actionLabel:"Create Agent",project:i,agent:null,canManage:n,actionBlockedReason:d}):Ul({state:"needs_project",actionLabel:"Connect Project",project:null,agent:null,canManage:n,actionBlockedReason:d}):Ul({state:"missing_config",actionLabel:"Add Agent config",project:i,agent:r,canManage:n,actionBlockedReason:d})}function Ul(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 DV(e){return{state:"blocked",actionLabel:"Ask admin",canAct:!1,reason:e,project:null,agent:null}}function Qc(e,t){if(e.length===0)return null;const n=t?.trim()??"";if(n){const a=e.find(i=>i.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 LV(e,t){const n=e.linkedSandboxProject;return n?.projectId?t.find(a=>a.id===n.projectId)??null:null}function zV(e,t,n){if(!t)return null;const a=e.preferredSandboxAgentId;if(a){const i=n.find(r=>r.id===a&&r.projectId===t.id);if(i)return i}return n.find(i=>i.projectId===t.id)??null}function UV(e,t){if(t.sandboxManifestError||!t.sandboxManifestSyncedAt||!t.sandboxManifestHash)return!0;if(e.sandboxTemplate?.manifestHash&&t.sandboxManifestHash)return e.sandboxTemplate.manifestHash!==t.sandboxManifestHash;if(e.linkedSandboxProject?.manifestHash&&t.sandboxManifestHash)return e.linkedSandboxProject.manifestHash!==t.sandboxManifestHash;const n=e.sandboxTemplate?.manifestPath;return n&&t.sandboxManifestPath?!n.endsWith(t.sandboxManifestPath):!1}const Zo=e=>e.slice(0,2e4);function HV({model:e,provider:t,providerSettings:n}){return{model:_f(t,e,n),modelRef:Sa(t,e,n)}}function qV(e,t){return e.some(n=>n.id===t.id)?e:[...e,t]}function BV(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 FV(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 Qb({action:e,prompt:t,runPayload:n,sessionId:a}){const i=new Date().toISOString(),r=`openpond_action_${n.run.id}`,s=n.run.status==="failed"?"failed":n.run.status==="succeeded"?"completed":"started";return[{id:`${r}_user`,sessionId:a,turnId:r,name:"turn.started",timestamp:i,source:"chat_action",args:{prompt:t}},{id:`${r}_result`,sessionId:a,turnId:r,name:"workspace_action_result",timestamp:n.run.updatedAt??i,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 VV({applyBootstrapPayload:e,connection:t,codexPermissionMode:n,codexReasoningEffort:a,openPondCommandAccessMode:i,draftModel:r,draftProvider:s,experience:d,expandProject:p,ensureCloudSessionReady:m,getPrompt:h,bootstrap:S,chatMessages:y,apps:w,connectedAppMentions:R,mentionedAppId:A,refreshWorkspace:N,refreshWorkspaceDiff:O,selectedApp:D,selectedActionCatalog:x,openPondActionCatalog:I,cloudProjects:P,accountScopeKey:E,selectedCloudProject:T,selectedProject:z,selectedProjectLinkedOpenPondApp:U,selectedSession:$,workspaceTarget:V,subagentDelegationMode:re,setDraftModel:Q,setDraftProvider:Ie,setError:Se,setPrompt:G,setMentionedAppId:Ee,setCodexHistoryEvents:xe,setCodexHistorySessions:le,onCodexHistoryTurnActivityChange:ke,onCodexHistoryTurnPayload:ae,onPendingUserMessage:he,setEvents:ve,setSelectedAppId:Ze,setSelectedProjectId:Re,setSelectedSessionId:se,setSessions:Ce,setView:Le,setWorkspaceBusy:Qe}){function it(F){J.bootstrap(F).then(e).catch(_=>{console.warn("[chat] Message was accepted, but the post-send bootstrap refresh failed.",_);const W=_ instanceof Error?_.message:String(_);Se(`Message sent, but the chat list could not refresh: ${W}`)})}const ut=g.useRef(new Set),Fe=S?.providers??null;function Ue(F,_){return F==="codex"?void 0:_}function ze(F){return!!(F&&F.provider!=="codex"&&(F.workspaceKind==="local_project"&&F.cwd?.trim()||(F.workspaceKind==="sandbox"||F.workspaceKind==="sandbox_template"||F.workspaceKind==="sandbox_app")&&F.workspaceId))}function M(F){Ie(F),Q(_=>Do(F,_,Fe)),Le("chat")}async function H(F,_){return(p_(_,E)??await Nf({teamId:_,accountKey:E,fetchAgents:async ee=>(await J.listSandboxAgents(t,{teamId:ee})).agents})).find(ee=>ee.projectId===F)??null}async function X(){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 F=await J.organizations(t),_=Qc(F.organizations.map(Wc).filter(W=>!!W).filter(W=>W.status==="active"),S?.preferences.defaultTeamId??null);if(!_)throw new Error("Add an OpenPond account before syncing a Project to Cloud.");if(!Xc(_))throw new Error(`You need owner or admin access to create projects in ${_.displayName}.`);return _}async function pe(F){if(!t)return!1;const _=z;if(!_)throw new Error("Select a local Project before using /sync-cloud.");const W=await X(),Y=_.linkedSandboxProject?.defaultBranch?.trim()||"main",ee=vt("local",_.id),K=ma(_,P),ce=await J.createSession(t,{provider:"openpond",modelRef:Sa("openpond",rr,Fe),openPondCommandAccessMode:Ue("openpond",i),appId:null,appName:null,workspaceKind:"local_project",workspaceId:_.id,workspaceName:_.name,localProjectId:_.id,cloudProjectId:K?.id??null,cloudTeamId:K?.teamId??null,cwd:_.workspacePath,title:`Sync ${_.name} to Cloud`});Ce(ue=>[ce,...ue]),F.onSessionCreated?.(ce),F.selectSession&&(se(ce.id),Re(ee),Ze(null),Le("chat"),p(ee)),F.clearPromptForTurn(),Qe(!0);try{const ue=await J.uploadLocalProjectCloudSource(t,_.id,{teamId:W.teamId,projectName:_.name,branch:Y,chatSessionId:ce.id,displayPrompt:F.displayPrompt});return e(ue.bootstrap),p(ee),p(vt("cloud",ue.project.id)),!0}catch(ue){const Ne=await J.bootstrap(t).catch(()=>null);throw Ne&&e(Ne),ue}finally{Qe(!1)}}async function Z(F){if(!t||F.providerForTurn==="codex"||F.selectedSessionForTurn?.provider==="codex")return!1;let _=ze(F.selectedSessionForTurn)?F.selectedSessionForTurn:null;if(!_&&F.selectedSessionForTurn)throw new Error("Select a project to use this.");if(!_)if(T){const Y=vt("cloud",T.id),ee=F.providerForTurn;_=await J.createSession(t,{provider:ee,modelRef:Sa(ee,F.modelForTurnValue,Fe),openPondCommandAccessMode:Ue(ee,F.openPondCommandAccessModeForTurn),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:T.id,workspaceName:T.name,localProjectId:null,cloudProjectId:T.id,cloudTeamId:T.teamId,cwd:null,autoTitlePrompt:Zo(F.command)}),Ce(K=>[_,...K]),F.onSessionCreated?.(_),F.selectSession&&(se(_.id),Re(Y),Ze(null),Le("chat"),p(Y))}else{const Y=z;if(!Y)throw new Error("Select a project to use this.");const ee=ma(Y,P),K=vt("local",Y.id),ce=F.providerForTurn;_=await J.createSession(t,{provider:ce,modelRef:Sa(ce,F.modelForTurnValue,Fe),openPondCommandAccessMode:Ue(ce,F.openPondCommandAccessModeForTurn),appId:null,appName:null,workspaceKind:"local_project",workspaceId:Y.id,workspaceName:Y.name,localProjectId:Y.id,cloudProjectId:ee?.id??null,cloudTeamId:ee?.teamId??null,cwd:Y.workspacePath,autoTitlePrompt:Zo(F.command)}),Ce(ue=>[_,...ue]),F.onSessionCreated?.(_),F.selectSession&&(se(_.id),Re(K),Ze(null),Le("chat"),p(K))}if(!_)throw new Error("Select a project to use this.");F.clearPromptForTurn();const W=await J.runSessionCommand(t,_.id,{command:F.command,cwd:_.cwd});return Ce(Y=>Ss(Y,W.session)),ve(Y=>ro(Y,W.events)),!0}async function me(F=[],_=null,W,Y={}){const ee=W??h();let K=ee.trim()||(F.length>0?"Please review the attached files.":"");if(!t||!K)return!1;const ce=Y.displayPrompt?.trim()||K,ue=Y.provider??s,Ne=Y.model??r,je=Y.openPondCommandAccessMode??i,$e=Y.session!==void 0,Ge=$e?Y.session??null:$,We=Y.experience??Ge?.experience??d,mt=We==="development"||We==="work"&&(Ge?.workspaceKind==="local_project"||!!Ge?.localProjectId||!!Ge?.cloudProjectId||!$e&&!!(z||T||D||V==="hybrid"||V==="local")),qt=$e||!mt?null:D,jt=$e||!mt?null:z,_n=$e||!mt?null:T,bn=$e||!mt?null:U,Xt=!$e&&mt&&V==="hybrid",yt=Y.selectSession??!0,tn=Y.chatMessages??y,Et=Y.session!==void 0?null:A,St=Y.clearPrompt===void 0?()=>{G(""),Ee(null)}:Y.clearPrompt,on=_?null:TV(K,x),Ot=_??on?.action??null,rn=on?.prompt||K,Tn=mt&&!Ot?$V(K):null,pn=Ot||Tn?null:NV(K),Ca=pn&&!M_({id:pn.command},We)?pn:null,Ra=Y.usageAttribution??(pn?{surface:"chat",workflowKind:"slash_command",commandName:`/${pn.command}`,commandSource:"prompt_parse"}:void 0);Se(null);let $t=null,zn=null;try{if(!mt&&ue==="codex")throw new Error("The Codex provider requires repository-aware Work.");if(Ca)throw new Error(`/${Ca.command} isn't available in ${We}.`);if(Tn&&ue!=="codex"&&Ge?.provider!=="codex"){if(F.length>0)throw new Error("Direct commands do not accept attachments.");return await Z({command:Tn.command,clearPromptForTurn:St,modelForTurnValue:Ne,onSessionCreated:Y.onSessionCreated,openPondCommandAccessModeForTurn:je,providerForTurn:ue,selectedSessionForTurn:Ge,selectSession:yt})}if(!$e&&pn?.command==="sync-cloud")return await pe({clearPromptForTurn:St,displayPrompt:ce,onSessionCreated:Y.onSessionCreated,selectSession:yt});if(Ot){const et=Z6(Ot);if(et){let tt=Ge;if(!tt||tt.cloudProjectId!==et.projectId){tt=await J.createSession(t,{provider:"openpond",modelRef:Sa("openpond",Ne,Fe),openPondCommandAccessMode:Ue("openpond",je),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:et.projectId,workspaceName:et.projectName??et.agentName,localProjectId:null,cloudProjectId:et.projectId,cloudTeamId:et.teamId,cwd:null,autoTitlePrompt:Zo(ce)}),Ce(En=>[tt,...En]),Y.onSessionCreated?.(tt),yt&&se(tt.id);const yn=vt("cloud",et.projectId);yt&&Re(yn),yt&&p(yn)}const Sn=await J.runSandboxAgent(t,et.agentId,e3({agent:et,attachments:F,displayPrompt:ce,prompt:rn})),xt=await J.bootstrap(t);return e(xt),St(),ve(yn=>ro(yn,Qb({action:Ot,prompt:ce,runPayload:Sn,sessionId:tt.id}))),!0}const Rt=zf(Ot);if(Rt){let tt=Ge;(!tt||tt.provider!=="openpond")&&(tt=await J.createSession(t,{provider:"openpond",modelRef:Sa("openpond",Ne,Fe),openPondCommandAccessMode:Ue("openpond",je),appId:null,appName:null,workspaceId:null,workspaceName:"OpenPond profile",localProjectId:null,cloudProjectId:null,cloudTeamId:null,cwd:null,autoTitlePrompt:Zo(ce)}),Ce(xt=>[tt,...xt]),Y.onSessionCreated?.(tt),yt&&se(tt.id)),await J.runProfileAction(t,X6({action:Rt,attachments:F,displayPrompt:ce,prompt:rn,sessionId:tt.id}));const Sn=await J.bootstrap(t);return e(Sn),St(),!0}const bt=v_({cloudProjects:P,selectedCloudProject:T,selectedProject:z});if(!bt)throw new Error("Select a Project linked to an OpenPond Cloud Project before running an action.");let lt=Ge;(!lt||lt.cloudProjectId!==bt.id)&&(lt=await J.createSession(t,{provider:"openpond",modelRef:Sa("openpond",Ne,Fe),openPondCommandAccessMode:Ue("openpond",je),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:bt.id,workspaceName:bt.name,localProjectId:bt.localProjectId,cloudProjectId:bt.id,cloudTeamId:bt.teamId,cwd:null,autoTitlePrompt:Zo(ce)}),Ce(tt=>[lt,...tt]),Y.onSessionCreated?.(lt),yt&&(se(lt.id),Re(bt.selectionKey),p(bt.selectionKey)));const wt=await H(bt.id,bt.teamId);if(!wt)throw new Error("No OpenPond Agent is available for this Project.");St();const oa=await J.runSandboxAgent(t,wt.id,Q6({action:Ot,attachments:F,displayPrompt:ce,prompt:rn,teamId:bt.teamId})),Un=await J.bootstrap(t);return e(Un),ve(tt=>ro(tt,Qb({action:Ot,prompt:ce,runPayload:oa,sessionId:lt.id}))),!0}let st=Ge;if(st&&Nt(st.id)){zn=ub({afterMessageId:tn.at(-1)?.id??null,attachments:F,content:K,sessionId:st.id}),St(),$t=st.id,ut.current.add($t),he?.(zn),ke?.($t,!0);const et=BV(st.id,K),Rt=lt=>{(!$e||$?.id===st.id)&&xe(wt=>qV(wt,lt)),Y.onCodexHistoryOptimisticEvent?.(lt)};Rt(et),le(lt=>lt.map(wt=>wt.id===st.id?{...wt,status:"active"}:wt));const bt=await J.sendCodexHistoryTurn(t,st.id,{prompt:K,attachments:F.length>0?F:void 0,model:_f("codex",Ne,Fe),modelRef:Sa("codex",Ne,Fe),...Ag(n),codexPermissionMode:n,codexReasoningEffort:a}).catch(lt=>{throw Rt(FV(et,lt)),lt});return(!$e||$?.id===st.id)&&xe(lt=>ro(lt,bt.events)),le(lt=>Ss(lt,bt.session)),ae?.(bt),it(t),!0}const Aa=(Et?w.find(et=>et.id===Et&&FB(ee,et)&&et.sandbox)??null:null)??VB(ee,Mk(w)),Pa=We==="chat"?[]:r5(ee,R).map(et=>et.ref);if(!st){const et=bn?.appId??qt?.id??null,Rt=bn?.appName??qt?.name??null,bt=_n,lt=$e?null:ma(jt,P),wt=Xt?Ck({cloudProjects:P,selectedCloudProject:bt,selectedProject:jt}):null;if(wt?.kind==="missing_cloud_project")throw new Error(wt.message);const oa=wt?.kind==="ready",Un=oa?ue:bt?"openpond":ue,tt=Sa(Un,Ne,Fe),Sn=Ue(Un,je),xt=oa?Rk({modelRef:tt,provider:Un,target:wt,title:K.slice(0,64)}):null;st=await J.createSession(t,xt?{...xt,subagentDelegationMode:re,metadata:{...xt.metadata,...Y.sessionMetadata??{}},...Sn?{openPondCommandAccessMode:Sn}:{},autoTitlePrompt:Zo(K)}:{experience:We,provider:Un,modelRef:tt,subagentDelegationMode:re,...Sn?{openPondCommandAccessMode:Sn}:{},appId:et,appName:Rt,workspaceKind:bt?"sandbox":jt?"local_project":qt?"sandbox_app":void 0,workspaceId:jt?.id??(qt?et:void 0),workspaceName:bt?.name??jt?.name??Rt,localProjectId:jt?.id??null,cloudProjectId:bt?.id??lt?.id??null,cloudTeamId:bt?.teamId??lt?.teamId??null,...!bt&&!jt&&!qt&&V==="local"?{metadata:{..._B(),...Y.sessionMetadata??{}}}:{cwd:jt?jt.workspacePath:null,...Y.sessionMetadata?{metadata:Y.sessionMetadata}:{}},autoTitlePrompt:Zo(K)}),Ce(yn=>[st,...yn]),Y.onSessionCreated?.(st),yt&&(se(st.id),bt&&Re(vt("cloud",bt.id)),st.workspaceKind==="local_project"&&st.workspaceId&&p(vt("local",st.workspaceId)),bt&&p(vt("cloud",bt.id)))}if(ev(st)&&Va(st.workspaceKind)&&st.provider!=="openpond"&&!Wa(st))throw new Error("Cloud workspaces use OpenPond Chat. Switch to Local to use local providers.");if(ev(st)&&Va(st.workspaceKind)&&m)try{st=await m(st)}catch(et){const Rt=et instanceof Error?et.message:String(et);throw await J.recordPreflightTurnFailure(t,st.id,{prompt:K,error:Rt,target:Wa(st)?"hybrid_sandbox":"cloud_workspace"}).then(e).catch(()=>{}),et}zn=ub({afterMessageId:tn.at(-1)?.id??null,attachments:F,content:K,sessionId:st.id}),St(),$t=st.id,ut.current.add($t),he?.(zn),Ce(et=>et.map(Rt=>Rt.id===$t?{...Rt,status:"active"}:Rt));const aa=ue,Ta=HV({provider:aa,model:Ne,providerSettings:Fe}),te=SU(aa,Ta.model??Ne,Fe),De=aa==="codex"?Ag(n):{approvalPolicy:"on-request",sandbox:"workspace-write"};await J.sendTurn(t,st.id,{prompt:K,metadata:Y.turnMetadata,attachments:F.length>0?F:void 0,mentionedAppIds:Aa?[Aa.id]:void 0,mentionedConnectedApps:Pa.length>0?Pa:void 0,openPondActionCatalog:I.length>0?I:void 0,usageAttribution:Ra,...Ta,...De,codexPermissionMode:aa==="codex"?n:"default",codexReasoningEffort:te?a:void 0}),it(t);const Ke=st.workspaceId??st.appId;return Ke&&st.workspaceKind!=="sandbox"&&st.workspaceKind!=="sandbox_template"&&N(Ke,!1).then(et=>{et?.initialized&&O(Ke)}),!0}catch(st){return Se(st instanceof Error?st.message:String(st)),!1}finally{$t&&ut.current.delete($t),$t&&Nt($t)&&ke?.($t,!1),$t&&(Nt($t)?le(st=>st.map(vn=>vn.id===$t&&vn.status==="active"?{...vn,status:"idle"}:vn)):Ce(st=>st.map(vn=>vn.id===$t&&vn.status==="active"?{...vn,status:"idle"}:vn)))}}async function _e(F,_){const W=ut.current.values().next().value??null,Y=F??$?.id??W;if(!t||!Y)return!1;if(Se(null),Nt(Y))try{const ee=await J.interruptCodexHistoryTurn(t,Y);if(!ee.interrupted){if(ee.reason==="no_active_openpond_turn"){const ce=await J.codexHistoryThread(t,Y,{tail:!0}),ue={...ce.session,status:"idle"};return $?.id===Y&&xe(Ne=>ro(Ne,ce.events)),le(Ne=>Ss(Ne,ue)),Se("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 Se("This Codex history turn is still starting. Try stopping it again in a moment."),!1}const K=await J.codexHistoryThread(t,Y,{tail:!0});return $?.id===Y&&xe(ce=>ro(ce,K.events)),le(ce=>Ss(ce,K.session)),!0}catch(ee){const K=ee instanceof Error?ee.message:String(ee);return Se(K==="Not found"?"OpenPond could not find this Codex history session, so it cannot interrupt it here.":K),!1}try{await J.interruptTurn(t,Y,_);const ee=await J.bootstrap(t);return e(ee),!0}catch(ee){return Se(ee instanceof Error?ee.message:String(ee)),!1}}async function He(F,_){if(!t){Se("OpenPond App server is not connected.");return}Se(null),await J.applyCreateImproveAction(t,F.id,{..._,runId:F.id,expectedRevision:F.revision,actionId:`web:${_.type}:${crypto.randomUUID()}`});const W=await J.bootstrap(t);e(W)}async function qe(F){await He(F.run,{type:"approve_plan"})}async function Xe(F){await He(F.run,{type:"cancel",reason:null})}async function at(F,_){await He(F.run,{type:"revise_plan",revision:_})}async function Pe(F,_,W){await He(F.run,{type:"answer_question",questionId:_,value:W})}async function Ve(F){await He(F.run,{type:"pause"})}async function u(F){await He(F.run,{type:"resume"})}async function j(F,_){await He(F.run,{type:"open_pull_request",candidateId:_})}async function q(F,_){await He(F.run,{type:"apply_candidate",candidateId:_})}async function oe(F,_){await He(F.run,{type:"reject_candidate",candidateId:_,reason:null})}async function ne(F,_){await He(F.run,{type:"reconcile_pull_request",candidateId:_})}return{answerCreateImproveQuestion:Pe,approveCreateImproveRun:qe,applyCreateImproveCandidate:q,cancelCreateImproveRun:Xe,changeDraftProvider:M,openCreateImprovePullRequest:j,pauseCreateImproveRun:Ve,reconcileCreateImprovePullRequest:ne,rejectCreateImproveCandidate:oe,resumeCreateImproveRun:u,reviseCreateImproveRun:at,sendPrompt:me,stopTurn:_e}}function ev(e){return e.experience==="development"||e.experience==="work"&&(e.workspaceKind==="local_project"||!!e.localProjectId||!!e.cloudProjectId||e.metadata?.workspaceTarget==="local")}async function WV({branch:e,connection:t,session:n}){if(!Va(n.workspaceKind))return{sandbox:null,session:n,status:"already_running"};const a=await J.ensureCloudWorkspaceReady(t,n.id,{branch:e,surface:"desktop"});return{bootstrap:await J.bootstrap(t),output:a.output,sandbox:null,session:a.session,status:a.status}}function KV(e){return Wa(e)?"Preparing Hybrid sandbox...":"Starting Cloud workspace..."}function GV(e,t){if(e==="already_running")return null;const n=Wa(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 ZV(e,t){return!e.cloudProjectId||!e.cloudTeamId?!0:t.some(n=>n.id===e.cloudProjectId&&n.teamId===e.cloudTeamId)}function JV({applyBootstrapPayload:e,cloudProjects:t,connection:n,localProjectById:a,selectedCloudProject:i,selectedProject:r,setWorkspaceBusy:s,showToast:d,visibleWorkspaceState:p}){return g.useCallback(async m=>{if(!n)throw new Error("OpenPond App server is not connected.");const h=r??(m.localProjectId?a.get(m.localProjectId)??null:null);if(m.cloudProjectId&&m.cloudTeamId&&!ZV(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||d(KV(m),"info"),s(!0);try{const S=await WV({branch:r?.linkedSandboxProject?.defaultBranch??i?.defaultBranch??p?.currentBranch??null,connection:n,localProject:h,session:m,source:Wa(m)?"openpond-app-hybrid-chat-preflight":"openpond-app-cloud-chat-preflight"});S.bootstrap&&e(S.bootstrap);const y=GV(S.status,m);return y&&d(y,"success"),S.session}finally{s(!1)}},[e,t,n,a,i,r,s,d,p?.currentBranch])}function YV(){return{diffPanelOpen:!1,diffPanelExpanded:!1,rightPanelMode:"changes",rightChatPanels:[]}}function XV(e){return{diffPanelOpen:e.diffPanelOpen,diffPanelExpanded:e.diffPanelExpanded,rightPanelMode:e.rightPanelMode,rightChatPanels:e.rightChatPanels}}function tv(e){return{...e,rightChatPanels:e.rightChatPanels.map(t=>({...t}))}}function QV(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 i=t.rightChatPanels[a];return!!(i&&n.id===i.id&&n.activationVersion===i.activationVersion&&n.sessionId===i.sessionId&&n.prompt===i.prompt&&n.provider===i.provider&&n.model===i.model&&n.scrollTop===i.scrollTop&&n.stickyToBottom===i.stickyToBottom)})}function e9(e){return`${e.conversationId}\0${e.workspaceSourceKey||"none"}`}function t9(e){const{appDispatch:t,diffPanelExpanded:n,diffPanelOpen:a,rightChatPanels:i,rightPanelMode:r,selectedAppId:s,selectedCloudProject:d,selectedProjectId:p,selectedSession:m,selectedSessionId:h,setWorkspaceDiffPanelViewState:S,view:y,viewWorkspaceAppId:w,viewWorkspaceId:R,viewWorkspaceKind:A,workspaceDiffPanelViewState:N}=e,O=g.useRef(new Map),D=g.useRef(new Map),x=g.useRef(null),I=g.useRef(null),P=h??`draft:${p??s??d?.id??"general"}`,E=g.useMemo(()=>R?`${A??"workspace"}:${R}`:w?`app:${w}`:m?.cwd&&!Va(m.workspaceKind)?`cwd:${m.cwd}`:"none",[m?.cwd,m?.workspaceKind,y,w,R,A]),T=e9({conversationId:P,workspaceSourceKey:E}),z=g.useMemo(()=>XV({diffPanelExpanded:n,diffPanelOpen:a,rightChatPanels:i,rightPanelMode:r}),[n,a,i,r]);g.useEffect(()=>{const $=x.current;$&&O.current.set($,tv(z))},[P,z]),g.useEffect(()=>{if(x.current===P)return;x.current=P;const V=O.current.get(P)??YV();QV(z,V)||t({type:"patch",patch:tv(V)})},[P,z]),g.useEffect(()=>{const $=I.current;$&&D.current.set($,Ju(N))},[T,N]),g.useEffect(()=>{if(I.current===T)return;I.current=T;const V=D.current.get(T)??Ak();S(re=>Xg(re,V)?re:Ju(V))},[T]);const U=g.useCallback($=>{S(V=>Xg(V,$)?V:Ju($))},[]);return{browserConversationId:P,handleWorkspaceDiffPanelViewStateChange:U}}function n9({account:e,accountPending:t,accountSignedOut:n,activeWorkspaceKind:a,activeWorkspaceLocation:i,appDispatch:r,applyBootstrapPayload:s,busy:d,cloudSetupDialog:p,cloudProjects:m,connection:h,defaultTeamId:S,expandProject:y,localProjectById:w,selectedCloudProject:R,selectedProject:A,selectedSession:N,selectedSessionProjectId:O,setCloudSetupDialog:D,setDiffPanelOpen:x,setError:I,setSessions:P,setWorkspaceBusy:E,showToast:T,visibleWorkspaceState:z,workspaceBusy:U}){const $=e?.baseUrl??e?.activeProfile?.baseUrl??null,V=g.useCallback(async(G,Ee)=>{if(h)try{const xe=await J.previewLocalProjectCloudSource(h,G.id,{branch:Ee});D(le=>!le||le.status!=="confirm"||le.localProjectId!==G.id||le.branch!==Ee?le:{...le,branch:xe.preview.branch,cloudProjectId:xe.preview.targetProjectId,preview:xe.preview,previewLoading:!1,previewError:null})}catch(xe){const le=xe instanceof Error?xe.message:String(xe);D(ke=>!ke||ke.status!=="confirm"||ke.localProjectId!==G.id||ke.branch!==Ee?ke:{...ke,preview:null,previewLoading:!1,previewError:le})}},[h,D]),re=g.useCallback(async()=>{const G=p;if(!G||G.status==="uploading")return;if(G.projectKind==="cloud"){D(ke=>ke&&{...ke,status:"ready",error:null});return}if(!h){D(ke=>ke&&{...ke,status:"error",error:"OpenPond App server is not connected."});return}const Ee=G.localProjectId??"",xe=w.get(Ee);if(!xe){D(ke=>ke&&{...ke,status:"error",error:"Project is no longer available."});return}E(!0);const le=ma(xe,m);D(ke=>ke&&{...ke,status:"uploading",error:null,previewLoading:!1});try{const ke=await J.organizations(h),ae=Qc(ke.organizations.map(Wc).filter(Le=>!!Le).filter(Le=>Le.status==="active"),S);if(!ae)throw new Error("Add an OpenPond account before creating a Cloud environment.");if(!Xc(ae))throw new Error(`You need owner or admin access to create projects in ${ae.displayName}.`);const he=G.branch||xe.linkedSandboxProject?.defaultBranch||"main",ve=vt("local",xe.id),Ze=await J.createSession(h,{provider:"openpond",appId:null,appName:null,workspaceKind:"local_project",workspaceId:xe.id,workspaceName:xe.name,localProjectId:xe.id,cloudProjectId:le?.id??null,cloudTeamId:le?.teamId??null,cwd:xe.workspacePath,title:`Sync ${xe.name} to Cloud`});P(Le=>[Ze,...Le]),r({type:"selectSession",sessionId:Ze.id,projectId:ve}),y(ve);const Re=await J.uploadLocalProjectCloudSource(h,xe.id,{teamId:ae.teamId,projectName:xe.name,branch:he,chatSessionId:Ze.id,displayPrompt:`/sync-cloud ${xe.name}`});s(Re.bootstrap),y(ve),y(vt("cloud",Re.project.id));const se=cp({accountBaseUrl:$,teamId:Re.project.teamId,projectId:Re.project.id,projectName:Re.project.name,baseBranch:Re.upload.branch,localProjectId:xe.id,source:"openpond-app"}),Ce=Jb({accountBaseUrl:$,organizationSlug:Re.project.organizationSlug,projectSlug:Re.project.slug});D({status:"ready",localProjectId:xe.id,cloudProjectId:Re.project.id,teamId:Re.project.teamId,projectName:Re.project.name,projectKind:"local",projectUrl:Ce,setupUrl:se,branch:Re.upload.branch,preview:G.preview??null,previewLoading:!1,previewError:null,upload:{branch:Re.upload.branch,headCommit:Re.upload.headCommit,fileCount:Re.upload.fileCount,byteCount:Re.upload.byteCount,skippedCount:Re.upload.skippedCount,initializedEmptyProject:Re.upload.initializedEmptyProject},error:null}),T("Source uploaded to OpenPond Git. Cloud setup link is ready.","success")}catch(ke){const ae=ke instanceof Error?ke.message:String(ke),he=h?await J.bootstrap(h).catch(()=>null):null;he&&s(he),I(ae),D(ve=>ve&&{...ve,status:"error",error:ae})}finally{E(!1)}},[$,r,s,p,m,h,S,y,w,D,I,P,E,T]),Q=g.useCallback((G,Ee)=>{if(!h){T("OpenPond App server is not connected.","error");return}if(t){T("Checking OpenPond account. Try again in a moment.","info");return}if(n){T("Add an OpenPond account before using Cloud.","error");return}const xe=Ee||G.linkedSandboxProject?.defaultBranch||"main";D({status:"confirm",localProjectId:G.id,projectName:G.name,projectKind:"local",projectUrl:null,setupUrl:null,branch:xe,preview:null,previewLoading:!0,previewError:null,upload:null,error:null}),V(G,xe)},[t,n,h,V,D,T]),Ie=g.useCallback(async G=>{if(G===i||U||d)return;if(I(null),G==="upload_cloud"){if(!A){T("Select a local Project before uploading source.","error");return}Q(A,z?.currentBranch??null);return}if(G==="local"){const le=N?.localProjectId??A?.id??O??null,ke=le?w.get(le)??null:null;if(!ke){T("No linked local workspace for this Cloud chat.","error");return}if(Va(a)&&!window.confirm("Switch to Local? Cloud changes will stay in the hosted workspace until you preserve or export them."))return;const ae=vt("local",ke.id);r({type:"selectProject",projectId:ae}),y(ae),x(!1),T(`Switched to Local: ${ke.name}`,"info");return}if(!h){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:Jb({accountBaseUrl:$,organizationSlug:R.organizationSlug,projectSlug:R.slug}),setupUrl:cp({accountBaseUrl:$,teamId:R.teamId,projectId:R.id,projectName:R.name,baseBranch:R.defaultBranch,source:"openpond-app"}),branch:R.defaultBranch??"main",preview:null,previewLoading:!1,previewError:null,upload:null,error:null});return}const Ee=A;if(!Ee){T("Select a Project before Cloud coding.","error");return}const xe=z?.currentBranch||Ee.linkedSandboxProject?.defaultBranch||"main";Q(Ee,xe)},[$,t,n,a,i,r,d,h,m,y,w,Q,R,A,N,O,D,x,I,T,z?.currentBranch,U]),Se=g.useCallback(G=>{xf(G)&&Q(G.project)},[Q]);return{changeWorkspaceTarget:Ie,moveProjectToCloud:Se,openCloudSetupForLocalProject:Q,startCloudSetupUpload:re}}function a9({advanceTrainingTurn:e,bindTrainingSession:t,composerDraftStore:n,onSessionCreated:a,onSubmitted:i,prepareTrainingTurn:r,sendPrompt:s,setMentionedAppId:d,showToast:p}){return g.useCallback(async(m=[],h=null,S,y={})=>{const w=S??n.getSnapshot(),R=r(w);if(R.active&&w.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,h,S,{clearPrompt:y.preservePrompt?()=>{}:void 0,displayPrompt:y.displayPrompt,onSessionCreated:N=>{a(N),R.metadata&&t(N.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 i?.(),A&&R.metadata&&e(),A},[e,t,n,a,i,r,s,d,p])}function o9({appDispatch:e,connection:t,sessions:n,setDiffPanelOpen:a,setRightPanelMode:i,setSessions:r,setView:s}){return g.useCallback(async d=>{if(!t)return;const p=n.find(S=>!S.archived&&S.workspaceKind==="sandbox"&&S.workspaceId===d.sandboxId);if(p){e({type:"selectSession",sessionId:p.id,appId:null,projectId:null}),i("changes"),a(!0),s("chat");return}const m=d.name??`Sandbox ${d.sandboxId.slice(0,8)}`,h=await J.createSession(t,{provider:"openpond",appId:null,appName:null,workspaceKind:"sandbox",workspaceId:d.sandboxId,workspaceName:m,cwd:null,title:m});r(S=>[h,...S]),e({type:"selectSession",sessionId:h.id,appId:null,projectId:null}),i("changes"),a(!0),s("chat")},[e,t,n,a,i,r,s])}function i9({connection:e,defaultTeamId:t,sessions:n,selectedProjectId:a,confirmProjectAction:i,openExistingProjectDialog:r,applyBootstrapPayload:s,expandProject:d,setExpandedProjectIds:p,setSelectedAppId:m,setSelectedProjectId:h,setSelectedSessionId:S,setError:y,setView:w,showToast:R}){function A(P){const E=vt("local",P.id);m(null),h(E),S(null),w("chat"),d(E)}async function N(P){if(!e)return!1;y(null);const E=P.trim();if(!E)return!1;try{const T=await J.createLocalProject(e,{path:E});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 O(){if(e){if(y(null),window.openpond?.selectFolder){const P=await window.openpond.selectFolder();if(P.canceled||!P.path)return;await N(P.path);return}r()}}async function D(P){if(!e)return!1;const E=P.trim();if(!E)return!1;y(null);try{const T=await J.createLocalProject(e,{createNew:!0,name:E});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 E=P.trim();if(!E)return!1;y(null);try{const T=await J.organizations(e),z=Qc(T.organizations.map(Wc).filter(Q=>!!Q).filter(Q=>Q.status==="active"),t);if(!z)throw new Error("Add an OpenPond account before creating a Cloud Project.");if(!Xc(z))throw new Error(`You need owner or admin access to create projects in ${z.displayName}.`);const U=`${Pk(E)}-${Date.now().toString(36)}`;let $=(await J.upsertSandboxProject(e,{teamId:z.teamId,name:E,sourceType:"internal_repo",normalizedSourceIdentity:U,internalRepoPath:U,defaultBranch:"main",sourceConfig:{sourceType:"internal_repo",sourceValue:U},metadata:{source:"openpond-app-new-cloud-project"}})).project;$=(await J.uploadSandboxProjectSource(e,$.id,{teamId:z.teamId,branch:"main",commitMessage:"Initialize cloud project",entries:[{path:"README.md",type:"file",contentsBase64:OB(`# ${E}
158
-
159
- Created in OpenPond Cloud.
160
- `)}]})).project;const V=await J.bootstrap(e);s(V);const re=vt("cloud",$.id);return m(null),h(re),S(null),w("chat"),d(re),R(`Created Cloud Project: ${$.name}`,"success"),!0}catch(T){const z=T instanceof Error?T.message:String(T);return y(z),R(z,"error"),!1}}async function I(P){if(!e)return;if(hU(P)){const U=`Archive ${P.project.name} in OpenPond Cloud?`;if(!(i?await i({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(U)))return;y(null);try{await J.archiveSandboxProject(e,P.project.id,{teamId:P.project.teamId}),s(await J.bootstrap(e)),p(V=>{const re=new Set(V);return re.delete(P.id),re}),a===P.id&&(h(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(!xf(P))return;const E=P.project,T=`Remove ${E.name} from Projects? The folder will not be deleted.`;if(i?await i({title:"Remove Project",body:`${E.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 U=await J.deleteLocalProject(e,E.id);s(U),p($=>{const V=new Set($);return V.delete(P.id),V}),a===P.id&&(h(null),S($=>{const V=n.find(re=>re.id===$);return V?.workspaceKind==="local_project"&&V.workspaceId===E.id?null:$})),R(`Removed ${E.name}`,"success")}catch(U){y(U instanceof Error?U.message:String(U)),R("Project could not be removed","error")}}}return{addProjectFolder:O,addProjectFolderPath:N,createCloudProjectFromScratch:x,createProjectFromScratch:D,removeProject:I}}function r9({addProjectFolder:e,addProjectFolderPath:t,appDispatch:n,busy:a,cloudProjectById:i,createCloudProjectFromScratch:r,createProjectFromScratch:s,expandProject:d,localProjectById:p,onCreateCloudEnvironment:m,onNewCloudProject:h,onNewLocalProject:S,onUseExistingFolderPath:y,newProjectBusy:w,newProjectMode:R,newProjectName:A,newProjectPath:N,projectTargetValue:O,setDiffPanelOpen:D,setDraftModel:x,setDraftProvider:I,setError:P,setNewProjectBusy:E,setNewProjectDialogOpen:T,setNewProjectName:z,setNewProjectPath:U,showToast:$,workspaceBusy:V}){const re=g.useCallback(Ie=>{if(Ie===O||a||V)return;if(P(null),Ie==="action:new-local-project"){S();return}if(Ie==="action:add-local-project"){e();return}if(Ie==="action:add-local-project-path"){y();return}if(Ie==="action:new-cloud-project"){h();return}if(Ie==="action:create-cloud-environment"){m();return}if(Ie==="none"){n({type:"selectProject",projectId:null}),D(!1),$("Started a chat without project files.","info");return}const Se=Ie.indexOf(":"),G=Se>=0?Ie.slice(0,Se):"",Ee=Se>=0?Ie.slice(Se+1):"";if(G==="local"){const xe=p.get(Ee);if(!xe){$("Project is no longer available.","error");return}const le=vt("local",xe.id);n({type:"selectProject",projectId:le}),d(le),D(!1);return}if(G==="cloud"){const xe=i.get(Ee);if(!xe){$("Cloud Project is no longer available.","error");return}const le=vt("cloud",xe.id);n({type:"selectProject",projectId:le}),d(le),I("openpond"),x(ke=>Do("openpond",ke)),D(!1)}},[e,n,a,i,d,p,m,h,S,y,O,D,x,I,P,$,V]),Q=g.useCallback(async()=>{const Ie=A.trim(),Se=N.trim();if(!w&&!(R==="existing-local"?!Se:!Ie)){E(!0);try{(R==="cloud"?await r(Ie):R==="existing-local"?await t(Se):await s(Ie))&&(T(!1),z(""),U(""))}finally{E(!1)}}},[t,r,s,w,R,A,N,E,T,z,U]);return{changeProjectTarget:re,submitNewProjectDialog:Q}}function s9(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 yK(e){return e.reduce((t,n)=>!t||n.activationVersion>=t.activationVersion?n:t,null)}function l9(e,t){const n=Math.max(0,...e.map(r=>r.activationVersion))+1;let a=!1;const i=e.map(r=>r.id!==t?r:(a=!0,{...r,activationVersion:n}));return a?i:[...e]}function c9(e,t){const n=Math.max(0,...e.map(r=>r.activationVersion))+1;let a=!1;const i=e.map(r=>r.sessionId!==t.sessionId?r:(a=!0,{...r,activationVersion:n,prompt:t.prompt??r.prompt}));return a?i:[...e]}function j_(e){return!!(e.parentSessionId&&e.subagentRunId)}function d9(e){const t=e.sessions.filter(j_);return{knownSessionIds:new Set(t.map(n=>n.id)),newSessions:t.filter(n=>!e.knownSessionIds.has(n.id))}}function u9(e,t){const n=new Set(e.map(i=>i.sessionId).filter(Boolean)),a=t.filter(j_).filter(i=>!n.has(i.id)).map(i=>({id:`right-subagent-${i.id}`,activationVersion:1,sessionId:i.id,prompt:"",provider:i.provider,model:i.modelRef?.modelId??"",scrollTop:0,stickyToBottom:!0}));return a.length>0?[...e,...a]:e}const nv="openpond/openpond",m9="github.issue.write";function p9(e){return e.some(t=>t.provider==="github"&&(t.ref.capabilities??[]).includes(m9))}function SK(e){return[`Title: ${e.title.trim()}`,"","Description:",e.description.trim()].join(`
161
- `)}function f9(e){const t=e.trim();return[`@github Submit this request as a new GitHub issue in ${nv}.`,`Use the GitHub connected app write operation github.issue.create with input.repo set to ${nv}, 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 h9(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"workflow":return{kind:"send_prompt",prompt:["Create a scheduled workflow attached to this chat.","Use the schedule_work tool after resolving the exact cadence, local date/time, and timezone from my request. Ask a concise clarification only if a required scheduling detail is genuinely missing.",`Workflow request: ${n}`].join(`
164
-
165
- `),requiresInstructions:!0};case"train":return{kind:"open_training",objective:n||null};case"submit-issue":return{kind:"send_prompt",prompt:f9(n),requiresInstructions:!0};case"sync-cloud":return{kind:"send_prompt",prompt:`/sync-cloud ${n}`,requiresInstructions:!1}}}const av=[];function g9(e){const{approvals:t,codexHistoryEvents:n,contextCompaction:a,pendingChatUserMessages:i,rightChatHistoryEvents:r,rightChatPanels:s,runningSessionIds:d,selectedSessionId:p,sidebarSessions:m}=e;return g.useMemo(()=>{const h=new Map(m.map(y=>[y.id,y])),S=b9(t);return s.map(y=>{const w=y.sessionId?h.get(y.sessionId)??null:null,R=Nt(y.sessionId),A=R?(y.sessionId?r[y.sessionId]:void 0)??(y.sessionId===p?n:av):av,N=Ym(A,[]),O=y.sessionId?S.get(y.sessionId)??null:null,D=!!(w&&d.has(w.id)),x=R?qq({events:A}):null,I=w?.cwd??null,P=w?.appId??w?.localProjectId??(w?.workspaceKind==="local_project"?w.workspaceId??null:null)??(w?.cwd&&!Va(w.workspaceKind)?y0(w.cwd):null),E=y.sessionId?i[y.sessionId]??null:null;return{...y,session:w,title:Bq(x,w?.title??"New task"),messages:R?Fk(Zc(A),E):[],createImproveRun:x,contextWindowStatus:ok({provider:y.provider,snapshot:Sk(N,y.sessionId),preferences:a}),goalRuntime:xk(N,y.sessionId),pendingApproval:O,running:D,workspaceRootPath:I,activeWorkspaceAppId:P,pendingUserMessage:E,runtimeSource:R?"history":"live"}})},[t,n,a,i,r,s,d,p,m])}function b9(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 v9(e){const{applyPayload:t,connection:n,locallyActiveSessionIds:a,panels:i,sessions:r,setError:s}=e,d=g.useMemo(()=>{const h=new Set,S=[];for(const y of i)!Nt(y.sessionId)||!y.sessionId||h.has(y.sessionId)||(h.add(y.sessionId),S.push(y.sessionId));return S.join(`
166
- `)},[i]),p=g.useMemo(()=>{if(!d)return"";const h=new Set(d.split(`
167
- `).filter(Boolean));return r.filter(S=>h.has(S.id)&&S.status==="active").map(S=>S.id).join(`
168
- `)},[d,r]),m=g.useMemo(()=>d?d.split(`
169
- `).filter(h=>a.has(h)).join(`
170
- `):"",[a,d]);g.useEffect(()=>{if(!n||!d)return;const h=d.split(`
171
- `).filter(Boolean),S=new Set(p.split(`
172
- `).filter(Boolean)),y=new Set(m.split(`
173
- `).filter(Boolean)),w=h.map(R=>Mf({connection:n,locallyActive:y.has(R),onError:A=>s(A instanceof Error?A.message:String(A)),onPayload:A=>t(Ef(A,y.has(R))),reportedActive:S.has(R),sessionId:R,surface:"thread"}));return()=>w.forEach(R=>R())},[p,t,n,m,d,s])}const ov=[];function y9(e){const{activeModel:t,activeProvider:n,approvals:a,applyRightCodexHistoryPayload:i,codexHistoryEvents:r,connectedAppMentions:s,connection:d,contextCompaction:p,openLabTraining:m,locallyActiveCodexHistorySessionIds:h,openPondCommandAccessMode:S,pendingChatUserMessages:y,providerSettings:w,rightChatHistoryEvents:R,rightChatPanels:A,rightPanelMode:N,runtimeIndexes:O,runtimeEventStore:D,runningSessionIds:x,selectedSession:I,selectedSessionId:P,sendPrompt:E,setDiffPanelOpen:T,setError:z,setRightChatHistoryEvents:U,setRightChatPanels:$,setRightPanelMode:V,setRightPanelTabRequest:re,setView:Q,showChangesPanel:Ie,showToast:Se,sidebarSessions:G,startupReady:Ee}=e,xe=g.useRef(null),le=g.useRef(new Map),ke=g.useRef(new Set);g.useEffect(()=>{if(!d)return;const Fe=A.flatMap(Ue=>Ue.sessionId&&!Nt(Ue.sessionId)?[Ue.sessionId]:[]);for(const Ue of Fe)Object.hasOwn(R,Ue)||ke.current.has(Ue)||(ke.current.add(Ue),J.runtimeEventsPage(d,{sessionId:Ue,beforeSequence:Number.MAX_SAFE_INTEGER,limit:500}).then(ze=>{const M=ze.events.map(H=>H.event);U(H=>({...H,[Ue]:so(H[Ue]??ov,M)}))}).catch(ze=>{z(ze instanceof Error?ze.message:String(ze))}).finally(()=>{ke.current.delete(Ue)}))},[d,R,A,z,U]);const ae=g.useCallback(Fe=>{re(Ue=>({id:(Ue?.id??0)+1,tab:Fe})),Ie()},[Ie]),he=g.useCallback((Fe=null,Ue={})=>{const ze=Fe?.id?A.find(H=>H.sessionId===Fe.id)??null:null;if(ze)return $(H=>c9(H,{sessionId:Fe.id,prompt:Ue.prompt})),T(!0),V("chat"),Ue.preserveView||Q("chat"),ze.id;const M=s9({sessionId:Fe?.id??null,provider:Fe?.provider??n,model:Fe?.modelRef?.modelId??t,prompt:Ue.prompt});return $(H=>[...H,M]),T(!0),V("chat"),Ue.preserveView||Q("chat"),M.id},[t,n,A,T,$,V,Q]);g.useEffect(()=>{if(!Ee)return;const Fe=xe.current;if(!Fe){xe.current=new Set(G.filter(H=>!!(H.parentSessionId&&H.subagentRunId)).map(H=>H.id));return}const Ue=d9({sessions:G,knownSessionIds:Fe});xe.current=Ue.knownSessionIds;for(const H of Ue.newSessions)le.current.set(H.id,H);const ze=I?.parentSessionId??I?.id??null;if(!ze)return;const M=[...le.current.values()].filter(H=>H.parentSessionId===ze);if(M.length!==0){for(const H of M)le.current.delete(H.id);$(H=>u9(H,M)),T(!0),V("chat")}},[I?.id,I?.parentSessionId,T,$,V,G,Ee]);const ve=g.useCallback(()=>{if(A.length===0){he(null);return}T(!0),V("chat"),Q("chat")},[he,A.length,T,V,Q]),Ze=g.useCallback(Fe=>{const Ue=A.length<=1&&A.some(M=>M.id===Fe),ze=()=>{$(M=>M.filter(H=>H.id!==Fe))};if(Ue&&N==="chat"){if(ae("files"),typeof window>"u"){ze();return}window.requestAnimationFrame(ze);return}ze()},[A,N,$,ae]),Re=g.useCallback((Fe,Ue)=>{$(ze=>ze.map(M=>M.id===Fe?{...M,prompt:Ue}:M))},[$]),se=g.useCallback(Fe=>{$(Ue=>l9(Ue,Fe))},[$]),Ce=g.useCallback((Fe,Ue)=>{$(ze=>ze.map(M=>M.id===Fe?{...M,...Ue}:M))},[$]),Le=g.useCallback((Fe,Ue)=>{$(ze=>ze.map(M=>M.id===Fe?{...M,model:Ue}:M))},[$]),Qe=g.useCallback((Fe,Ue)=>{$(ze=>ze.map(M=>M.id===Fe?{...M,provider:Ue,model:Do(Ue,M.model,w)}:M))},[w,$]);v9({applyPayload:i,connection:d,locallyActiveSessionIds:h,panels:A,sessions:G,setError:z});const it=g9({approvals:a,codexHistoryEvents:r,contextCompaction:p,pendingChatUserMessages:y,rightChatHistoryEvents:R,rightChatPanels:A,runningSessionIds:x,selectedSessionId:P,sidebarSessions:G}),ut=g.useCallback(async(Fe,Ue=[],ze=null,M=null,H={})=>{const X=A.find(at=>at.id===Fe);if(!X)return!1;const pe=H.promptOverride??X.prompt,Z=M?h9(M,pe):null;if(Z?.kind==="open_training")return Ue.length>0?(Se("/train uses this chat; add other chats from Models.","error"),!1):(m({objective:Z.objective,sessionId:X.sessionId}),H.preservePrompt||Re(Fe,""),!0);if(M&&Z?.kind==="send_prompt"&&Z.requiresInstructions&&!pe.trim())return Se(`Add instructions after ${M.command}.`,"info"),!1;if(M&&Ue.length>0)return Se(`${M.command} tasks do not accept attachments yet. Add file context in the task thread.`,"error"),!1;if(M?.id==="submit-issue"&&!p9(s))return Se("Connect the GitHub app before using /submit-issue.","error"),!1;const me=X.sessionId?G.find(at=>at.id===X.sessionId)??null:null,_e=X.provider==="codex"?S:me?.openPondCommandAccessMode??S,He=Z?.kind==="send_prompt"?Z.prompt:pe,qe=Nt(X.sessionId)?(X.sessionId?R[X.sessionId]:void 0)??(X.sessionId===P?r:ov):D.getSessionEvents(X.sessionId),Xe=Nt(X.sessionId)&&X.sessionId?at=>{const Pe=X.sessionId;U(Ve=>({...Ve,[Pe]:so(Ve[Pe]??qe,[at])}))}:void 0;return E(Ue,ze,He,{session:me,selectSession:!1,provider:X.provider,model:X.model,openPondCommandAccessMode:_e,chatMessages:Zc(qe),displayPrompt:H.displayPrompt,turnMetadata:H.turnMetadata,usageAttribution:M?.id==="submit-issue"?{surface:"chat",workflowKind:"slash_command",commandName:M.command,commandSource:"composer_selection"}:void 0,onCodexHistoryOptimisticEvent:Xe,clearPrompt:H.preservePrompt?()=>{}:()=>Re(Fe,""),onSessionCreated:at=>{$(Pe=>Pe.map(Ve=>Ve.id===Fe?{...Ve,sessionId:at.id,provider:at.provider,model:at.modelRef?.modelId??Ve.model}:Ve))}})},[r,s,R,A,O,D,P,m,S,E,$,Q,G,Se,Re]);return{activateRightChatPanel:se,closeRightChatPanel:Ze,openRightChatPanel:he,rightChatPanelViews:it,showRightChatPanel:ve,showRightPanelDiffTab:ae,submitRightChatPrompt:ut,updateRightChatModel:Le,updateRightChatPrompt:Re,updateRightChatProvider:Qe,updateRightChatScrollState:Ce}}function S9(e){const{appPreferences:t,connection:n,selectedSessionId:a,setAppPreferences:i,setCodexHistorySessions:r,setError:s,setSelectedSessionId:d,setSessions:p}=e;async function m(O,D){if(!n)return;const x=t[O]??{},I={...x,...D,archived:D.pinned?!1:D.archived??x.archived};i(P=>({...P,[O]:I}));try{const P=await J.patchSidebarAppPreference(n,O,D);i(E=>({...E,[O]:P}))}catch(P){s(P instanceof Error?P.message:String(P)),i(E=>({...E,[O]:x}))}}function h(O){m(O.id,{pinned:!O.pinned,archived:!1})}async function S(O,D){if(!n)return;const x=Nt(O.id)?r:p,I={...O,...D};x(P=>P.some(E=>E.id===O.id)?P.map(E=>E.id===O.id?I:E):[I,...P]);try{const P=await J.patchSession(n,O.id,D);x(E=>E.some(T=>T.id===P.id)?E.map(T=>T.id===P.id?P:T):[P,...E])}catch(P){s(P instanceof Error?P.message:String(P)),x(E=>E.map(T=>T.id===O.id?O:T))}}function y(O){S(O,{pinned:!1,savedForLater:!O.savedForLater,archived:!1})}function w(O){S(O,{pinned:!O.pinned,savedForLater:!1,archived:!1})}function R(O){S(O,{pinned:!1,savedForLater:!1,archived:!0}),a===O.id&&d(null)}function A(O){S(O,{archived:!1})}function N(O,D){const x=D.trim();!x||x===O.title||S(O,{title:x})}return{archiveSession:R,renameSession:N,restoreSession:A,toggleProjectPinned:h,toggleSessionPinned:w,toggleSessionSavedForLater:y}}function x9(e){return e.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,72)||"new-branch"}function k9({connection:e,activeWorkspaceAppId:t,appDefaults:n,bootstrap:a,branchDialogName:i,commitIncludeUnstaged:r,commitMessage:s,commitNextStep:d,draftModel:p,draftProvider:m,cloudProjects:h,selectedApp:S,selectedProject:y,selectedProjectLinkedOpenPondApp:w,selectedSession:R,sessions:A,title:N,visibleWorkspaceDiff:O,visibleWorkspaceState:D,workspaceBusy:x,workspaceName:I,appDispatch:P,applyBootstrapPayload:E,expandProject:T,refreshWorkspace:z,refreshWorkspaceDiff:U,rememberWorkspaceState:$,setBranchDialogOpen:V,setCommitDialogOpen:re,setError:Q,setSessions:Ie,setSettingsSection:Se,setSyncingWorkspaceAppId:G,setView:Ee,setWorkspaceBusy:xe,showToast:le}){function ke(){return`${Dx(n.defaultBranchPrefix)}${x9(I??N??"new-branch")}`}function ae(){return I?`Update ${I}`:(O?.filesChanged??D?.changedFilesCount??0)===1?"Update workspace file":"Update workspace files"}function he(ze="commit"){P({type:"openCommitDialog",nextStep:ze})}function ve(){P({type:"openBranchDialog",branchName:ke()})}function Ze(){x||V(!1),Se("defaults"),Ee("settings"),an({kind:"settings",section:"defaults"})}async function Re(ze){if(!(!e||!t)){xe(!0),Q(null);try{const M=await J.checkoutWorkspaceBranch(e,t,{branch:ze});$(M),M.initialized&&U(t)}catch(M){Q(M instanceof Error?M.message:String(M))}finally{xe(!1)}}}async function se(){if(!e||!t)return;const ze=i.trim();if(ze){xe(!0),Q(null);try{const M=await J.createWorkspaceBranch(e,t,{branch:ze});$(M),M.initialized&&U(t),V(!1),le(`Checked out ${ze}`,"success")}catch(M){Q(M instanceof Error?M.message:String(M))}finally{xe(!1)}}}async function Ce(ze){G(ze);const M=a?.apps.find(H=>H.id===ze)?.name??a?.localProjects.find(H=>H.id===ze)?.name??"Workspace";try{const H=await z(ze,!0);H?.initialized&&ze===t&&U(ze),H?.initialized&&!H.error?le(`${M} synced locally`,"success"):H?.error&&le("Workspace sync failed","error")}finally{G(H=>H===ze?null:H)}}async function Le(){t&&await Ce(t)}async function Qe(ze,M,H={}){if(!e)return null;const X=R&&!Nt(R.id)?R:null;if(C9(M,X,H)||X&&_9(X,y,S))return X;const pe=X?await it(X):null;if(pe)return pe;const Z=w9(A,y,S);if(Z){const qe=Z.workspaceKind==="local_project"&&Z.workspaceId?vt("local",Z.workspaceId):null;return P({type:"selectSession",sessionId:Z.id,appId:Z.appId,projectId:qe}),Z.workspaceKind==="local_project"&&Z.workspaceId&&T(vt("local",Z.workspaceId)),Z}const me=ma(y,h),_e=await J.createSession(e,{provider:m,modelRef:Sa(m,p,a?.providers??null),appId:w?.appId??S?.id??null,appName:w?.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:ze});Ie(qe=>[_e,...qe]);const He=_e.workspaceKind==="local_project"&&_e.workspaceId?vt("local",_e.workspaceId):null;return P({type:"selectSession",sessionId:_e.id,appId:_e.appId,projectId:He}),_e.workspaceKind==="local_project"&&_e.workspaceId&&T(vt("local",_e.workspaceId)),_e}async function it(ze){if(!e||!y||!w?.appId||Nt(ze.id)||ze.workspaceKind==="local_project"||ze.appId!==w.appId)return null;const M=ma(y,h),H=await J.patchSession(e,ze.id,{appId:w.appId,appName:w.appName,workspaceKind:"local_project",workspaceId:y.id,workspaceName:y.name,localProjectId:y.id,cloudProjectId:M?.id??null,cloudTeamId:M?.teamId??null,cwd:y.workspacePath});return Ie(X=>X.map(pe=>pe.id===H.id?H:pe)),P({type:"selectSession",sessionId:H.id,appId:H.appId,projectId:vt("local",y.id)}),T(vt("local",y.id)),H}async function ut(ze,M={}){if(!e)return null;const H=await Qe(I?`${I} workspace`:"Workspace action",ze,M);if(!H)return null;const X=await J.workspaceTool(e,H.id,{action:ze,args:M,source:"ui_button"});le(X.output,X.ok?"success":"error"),E(await J.bootstrap(e));const pe=X.appId??I9(H);return pe&&(await z(pe,!1))?.initialized&&await U(pe),X}async function Fe(ze,M={}){if(ze==="git_commit"&&typeof M.message!="string")return he("commit"),null;xe(!0),Q(null);try{return await ut(ze,M)}catch(H){return Q(H instanceof Error?H.message:String(H)),null}finally{xe(!1)}}async function Ue(){const ze=s.trim()||ae(),M=d==="commit_publish",H=M&&!!D?.remoteUrl;if(!(H&&!window.confirm("Replace the current origin remote with the new OpenPond repo after committing?"))){xe(!0),Q(null);try{if(!(await ut("git_commit",{message:ze,includeUnstaged:r}))?.ok||d==="commit_push"&&!(await ut("git_push",{runChecks:!1}))?.ok||M&&!(await ut("publish_openpond_repo",{replaceOrigin:H}))?.ok)return;re(!1)}catch(X){Q(X instanceof Error?X.message:String(X))}finally{xe(!1)}}}return{changeWorkspaceBranch:Re,openCommitDialog:he,openCreateWorkspaceBranchDialog:ve,openDefaultsSettingsFromBranchDialog:Ze,runWorkspaceTool:Fe,submitCommitDialog:Ue,submitCreateWorkspaceBranch:se,syncWorkspaceLocally:Le,syncWorkspaceLocallyForApp:Ce}}function _9(e,t,n){return!t&&!n?!0:O_(e,t,n)}function w9(e,t,n){if(!t&&!n)return null;let a=null,i=Number.NEGATIVE_INFINITY;for(const r of e){if(r.archived||!O_(r,t,n))continue;const s=Date.parse(r.updatedAt),d=Number.isFinite(s)?s:0;(!a||d>i)&&(a=r,i=d)}return a}function O_(e,t,n){return t?e.workspaceKind==="local_project"&&e.workspaceId===t.id:n?e.appId===n.id||e.workspaceId===n.id:!1}function I9(e){return e.workspaceKind==="sandbox"?e.localProjectId??null:e.workspaceId??e.appId??null}function C9(e,t,n={}){return(R9(e)||P9(e,n))&&A9(t)}function R9(e){return e.startsWith("sandbox_")?e!=="sandbox_create"&&e!=="sandbox_templates"&&e!=="sandbox_template_launch":!1}function A9(e){return e?.workspaceKind==="sandbox"||e?.workspaceKind==="sandbox_template"}function P9(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 T9(e,t){return e.kind==="general"?"# general":e.title?e.title:e.participants.find(a=>a.userId!==t)?.name??"Direct message"}const E9=[];function M9(e){const{composerDraftStore:t,appDispatch:n,mentionedAppId:a,setMentionedAppId:i,cloudSetupDialog:r,setCloudSetupDialog:s,setRightPanelTabRequest:d,workspaceDiffPanelViewState:p,setWorkspaceDiffPanelViewState:m,rightChatHistoryEvents:h,setRightChatHistoryEvents:S,locallyActiveCodexHistorySessionIds:y,setCodexHistoryTurnLocallyActive:w,draftSubagentDelegationMode:R,setDraftSubagentDelegationMode:A,confirmProjectAction:N,view:O,selectedAppId:D,selectedProjectId:x,selectedSessionId:I,draftProvider:P,draftModel:E,activeExperience:T,codexPermissionMode:z,codexReasoningEffort:U,openPondCommandAccessMode:$,busy:V,diffPanelOpen:re,diffPanelExpanded:Q,rightPanelMode:Ie,rightChatPanels:Se,newProjectMode:G,newProjectName:Ee,newProjectPath:xe,newProjectBusy:le,commitMessage:ke,commitIncludeUnstaged:ae,commitNextStep:he,branchDialogName:ve,setSectionMenuOpen:Ze,setView:Re,setSelectedAppId:se,setSelectedProjectId:Ce,setSelectedSessionId:Le,setPrompt:Qe,setDraftProvider:it,setDraftModel:ut,setDiffPanelOpen:Fe,setRightPanelMode:Ue,setRightChatPanels:ze,setSyncingWorkspaceAppId:M,setSettingsSection:H,setNewProjectDialogOpen:X,setNewProjectMode:pe,setNewProjectName:Z,setNewProjectPath:me,setNewProjectBusy:_e,setCommitDialogOpen:He,setBranchDialogOpen:qe,setError:Xe,showToast:at,appPreferences:Pe,applyBootstrapPayload:Ve,approvals:u,bootstrap:j,connection:q,events:oe,runtimeEventStore:ne,sessions:F,startup:_,setAppPreferences:W,setCodexHistorySessions:Y,setEvents:ee,setSessions:K,cloudProjectById:ce,localProjectById:ue,selectedApp:Ne,selectedCloudProject:je,selectedProject:$e,selectedProjectLinkedOpenPondApp:Ge,selectedSession:We,sidebarSessions:mt,runtimeIndexes:qt,connectedAppMentions:jt,codexHistoryEvents:_n,setCodexHistoryEvents:bn,account:Xt,accountPending:yt,accountSignedOut:tn,activeModel:Et,activeProvider:St,activeWorkspaceAppId:on,activeWorkspaceKind:Ot,activeWorkspaceLocation:rn,appDefaults:Tn,selectedSessionProjectId:pn,workspaceName:Ca,accountScopeKey:Ra,teamChat:$t,communities:zn,selectedProjectConfirmedCloudProject:st,activeOpenPondCommandAccessMode:vn,viewWorkspaceAppId:Aa,viewWorkspaceId:Pa,viewWorkspaceKind:aa,openPondActionCatalog:Ta,selectedActionCatalog:te,expandProject:De,setExpandedProjectIds:Ke,advanceTrainingModelChatAfterTurn:et,bindTrainingModelChatSession:Rt,prepareTrainingModelChatTurn:bt,chatMessages:lt,pendingChatUserMessages:wt,recordPendingChatUserMessage:oa,runningSessionIds:Un,workspaceBusy:tt,visibleWorkspaceState:Sn,visibleWorkspaceDiff:xt,rememberWorkspaceState:yn,refreshWorkspace:En,setWorkspaceBusy:wn,refreshWorkspaceDiffWhenNeeded:Ea,setPendingWorkspaceTarget:ha,pendingSidebarWorkspaceTarget:Ka,setPendingSidebarWorkspaceTarget:Ma,projectTarget:Yn,workspaceTarget:kt}=e,ja=O==="apps"?"Apps":O==="get-started"?"Walkthroughs":O==="labs"?"Models":O==="scheduled"?"Workflows":O==="outputs"?"Outputs":O==="projects"?"Projects":O==="team"?$t.detail?T9($t.detail.thread,$t.currentUserId):"Team Chat":O==="community"?zn.preview?.displayName??"Communities":We?.title??Cx(T),{browserConversationId:ia,handleWorkspaceDiffPanelViewStateChange:fi}=t9({appDispatch:n,diffPanelExpanded:Q,diffPanelOpen:re,rightChatPanels:Se,rightPanelMode:Ie,selectedAppId:D,selectedCloudProject:je,selectedProjectId:x,selectedSession:We,selectedSessionId:I,setWorkspaceDiffPanelViewState:m,view:O,viewWorkspaceAppId:Aa,viewWorkspaceId:Pa,viewWorkspaceKind:aa,workspaceDiffPanelViewState:p}),zo=g.useCallback(ft=>{an({kind:"chat",sessionId:ft}),Le(ft),se(null),Ce(null),Re("chat")},[se,Ce,Le,Re]),Uo=g.useCallback(()=>{pe("existing-local"),Z(""),me(""),X(!0)},[X,pe,Z,me]),Ga=g.useCallback(()=>{pe("local"),Z(""),me(""),X(!0)},[X,pe,Z,me]),{addProjectFolder:hi,addProjectFolderPath:gi,createCloudProjectFromScratch:bi,createProjectFromScratch:vi,removeProject:Cr}=i9({connection:q,defaultTeamId:Tn.defaultTeamId,sessions:F,selectedProjectId:x,confirmProjectAction:N,openExistingProjectDialog:Uo,applyBootstrapPayload:Ve,expandProject:De,setExpandedProjectIds:Ke,setSelectedAppId:se,setSelectedProjectId:Ce,setSelectedSessionId:Le,setError:Xe,setView:Re,showToast:at}),{changeWorkspaceBranch:Rr,openCommitDialog:Oa,openCreateWorkspaceBranchDialog:Ar,openDefaultsSettingsFromBranchDialog:yi,runWorkspaceTool:Si,submitCommitDialog:xi,submitCreateWorkspaceBranch:Pr,syncWorkspaceLocally:Xn}=k9({connection:q,activeWorkspaceAppId:on,appDefaults:Tn,bootstrap:j,branchDialogName:ve,commitIncludeUnstaged:ae,commitMessage:ke,commitNextStep:he,draftModel:E,draftProvider:P,cloudProjects:j?.cloudProjects??[],selectedApp:Ne,selectedProject:$e,selectedProjectLinkedOpenPondApp:Ge,selectedSession:We,sessions:F,title:ja,visibleWorkspaceDiff:xt,visibleWorkspaceState:Sn,workspaceBusy:tt,workspaceName:Ca,appDispatch:n,applyBootstrapPayload:Ve,expandProject:De,refreshWorkspace:En,refreshWorkspaceDiff:Ea,rememberWorkspaceState:yn,setBranchDialogOpen:qe,setCommitDialogOpen:He,setError:Xe,setSessions:K,setSettingsSection:H,setSyncingWorkspaceAppId:M,setView:Re,setWorkspaceBusy:wn,showToast:at}),Tr=JV({applyBootstrapPayload:Ve,cloudProjects:j?.cloudProjects??[],connection:q,localProjectById:ue,selectedCloudProject:je,selectedProject:$e,setWorkspaceBusy:wn,showToast:at,visibleWorkspaceState:Sn}),Er=j?.preferences.subagents.delegationMode??"manual",Mr=We?.subagentDelegationMode??R,ki=!!(T==="development"&&j?.preferences.subagents.enabled&&St!=="codex"&&!Nt(I)&&!We?.subagentRunId),_i=g.useCallback(ft=>{if(!We){A(ft);return}if(!q||Nt(We.id)||We.subagentRunId)return;const Dt=We.id,Bn=We.subagentDelegationMode??null;K(sn=>sn.map(Qn=>Qn.id===Dt?{...Qn,subagentDelegationMode:ft}:Qn)),J.patchSession(q,Dt,{subagentDelegationMode:ft}).then(sn=>{K(Qn=>Qn.map(In=>In.id===sn.id?sn:In))}).catch(sn=>{K(Qn=>Qn.map(In=>In.id===Dt?{...In,subagentDelegationMode:Bn}:In)),Xe(sn instanceof Error?sn.message:String(sn))})},[q,We,Xe,K]),wi=g.useCallback(ft=>{S(Dt=>Dt[ft.session.id]===ft.events?Dt:{...Dt,[ft.session.id]:ft.events}),Y(Dt=>Kc(Dt,ft.session))},[Y]),{answerCreateImproveQuestion:jr,applyCreateImproveCandidate:Na,approveCreateImproveRun:Za,cancelCreateImproveRun:Hn,changeDraftProvider:Or,openCreateImprovePullRequest:Nr,reconcileCreateImprovePullRequest:fn,rejectCreateImproveCandidate:Ii,pauseCreateImproveRun:qn,resumeCreateImproveRun:ga,reviseCreateImproveRun:Ja,sendPrompt:$a,stopTurn:$r}=VV({applyBootstrapPayload:Ve,bootstrap:j,chatMessages:lt,connection:q,codexPermissionMode:z,codexReasoningEffort:U,openPondCommandAccessMode:vn,draftModel:E,draftProvider:P,experience:T,expandProject:De,getPrompt:t.getSnapshot,apps:j?.apps??[],connectedAppMentions:jt,mentionedAppId:a,ensureCloudSessionReady:Tr,refreshWorkspace:En,refreshWorkspaceDiff:Ea,selectedApp:Ne,selectedActionCatalog:te,openPondActionCatalog:Ta,cloudProjects:j?.cloudProjects??[],accountScopeKey:Ra,selectedCloudProject:je,selectedProject:$e,selectedProjectLinkedOpenPondApp:Ge,selectedSession:We,sessions:F,workspaceTarget:kt.value,subagentDelegationMode:We?.subagentDelegationMode??R,setDraftModel:ut,setDraftProvider:it,setError:Xe,setPrompt:Qe,setMentionedAppId:i,setCodexHistoryEvents:bn,setCodexHistorySessions:Y,onCodexHistoryTurnActivityChange:w,onCodexHistoryTurnPayload:wi,onPendingUserMessage:oa,setEvents:ee,setSelectedAppId:se,setSelectedProjectId:Ce,setSelectedSessionId:Le,setSessions:K,setView:Re,setWorkspaceBusy:wn}),{archiveSession:Dr,restoreSession:Ya,renameSession:Ho,toggleProjectPinned:Ci,toggleSessionPinned:qo,toggleSessionSavedForLater:Ri}=S9({appPreferences:Pe,connection:q,selectedSessionId:I,setAppPreferences:W,setCodexHistorySessions:Y,setError:Xe,setSelectedSessionId:Le,setSessions:K}),{changeWorkspaceTarget:Bo,moveProjectToCloud:Ai,startCloudSetupUpload:ra}=n9({account:Xt,accountPending:yt,accountSignedOut:tn,activeWorkspaceKind:Ot,activeWorkspaceLocation:rn,appDispatch:n,applyBootstrapPayload:Ve,busy:V,cloudSetupDialog:r,cloudProjects:j?.cloudProjects??[],connection:q,defaultTeamId:Tn.defaultTeamId,expandProject:De,localProjectById:ue,selectedCloudProject:je,selectedProject:$e,selectedSession:We,selectedSessionProjectId:pn,setCloudSetupDialog:s,setDiffPanelOpen:Fe,setError:Xe,setSessions:K,setWorkspaceBusy:wn,showToast:at,visibleWorkspaceState:Sn,workspaceBusy:tt}),vo=g.useCallback(async ft=>{if(T==="work"&&!We){if(ft==="local"){ha("local"),at($e?`Next task will use the local ${$e.name} checkout.`:"Next task will use an app-managed local workspace.","info");return}if(ft==="cloud"&&!$e&&!je){if(yt){at("Checking OpenPond account. Try again in a moment.","info");return}if(tn){at("Add an OpenPond account before using Hosted.","error");return}ha("cloud"),at("Next task will use Hosted without a Project.","info");return}}if(ft==="hybrid"){const Dt=je?.id??st?.id??We?.cloudProjectId??null,Bn=je?.teamId??st?.teamId??We?.cloudTeamId??null;if(yt){at("Checking OpenPond account. Try again in a moment.","info");return}if(tn){at("Add an OpenPond account before using Hybrid.","error");return}if(!Dt||!Bn){ha(null),at("Upload/sync this Project to Cloud before using Hybrid.","error");return}if(We&&!Nt(We.id)){if(Wa(We))return;if(!q){at("OpenPond App server is not connected.","error");return}const sn=await J.patchSession(q,We.id,{provider:P,modelRef:Sa(P,E,j?.providers??null),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:null,workspaceName:je?.name??st?.name??$e?.name??We.workspaceName??"Hybrid workspace",localProjectId:$e?.id??We.localProjectId??null,cloudProjectId:Dt,cloudTeamId:Bn,metadata:Ik(We.metadata),cwd:$e?.workspacePath??We.cwd??null});K(Qn=>Qn.map(In=>In.id===sn.id?sn:In)),ha(null),at("Hybrid will use your selected model with hosted sandbox edits.","info");return}ha("hybrid"),at("Next message will use Hybrid with a hosted sandbox.","info");return}ha(null),await Bo(ft)},[yt,tn,T,j?.providers,Bo,q,E,P,je?.id,je?.name,je?.teamId,$e?.id,st?.id,st?.name,st?.teamId,$e?.name,$e?.workspacePath,We,ha,K,at]),Fo=g.useCallback((ft,Dt)=>{se(null),Ce(ft),Le(null),Re("chat"),De(ft),Ma({projectId:ft,target:Dt})},[De,se,Ce,Le,Re]);g.useEffect(()=>{if(!Ka||O!=="chat"||x!==Ka.projectId||I!==null)return;const ft=Ka.target;Ma(null),vo(ft)},[vo,Ka,x,I,O]);const Xa=a9({advanceTrainingTurn:et,bindTrainingSession:Rt,composerDraftStore:t,onSessionCreated:ft=>{Le(ft.id),Re("chat"),an({kind:"chat",sessionId:ft.id}),A(null)},onSubmitted:async()=>{const ft=We;if(!(!q||!ft||!$s(ft)))try{const Dt=await J.patchSession(q,ft.id,{metadata:wU(ft.metadata)});K(Bn=>Bn.map(sn=>sn.id===Dt.id?Dt:sn))}catch(Dt){at(Dt instanceof Error?`Task started, but its Draft label could not be cleared: ${Dt.message}`:"Task started, but its Draft label could not be cleared.","error")}},prepareTrainingTurn:bt,sendPrompt:$a,setMentionedAppId:i,showToast:at}),Pi=o9({appDispatch:n,connection:q,sessions:F,setDiffPanelOpen:Fe,setRightPanelMode:Ue,setSessions:K,setView:Re}),{createCloudEnvironmentFromSidebar:Da,openCloudProjectDialog:Ti,openUrlInBrowserPanel:Lr,showBrowserPanel:Vo,showChangesPanel:Ei,showGoalSidebarTab:Mi}=pV({account:Xt,browserConversationId:ia,cloudProjectById:ce,cloudProjects:j?.cloudProjects??[],diffPanelOpen:re,rightPanelMode:Ie,selectedProjectId:x,setDiffPanelOpen:Fe,setNewProjectDialogOpen:X,setNewProjectMode:pe,setNewProjectName:Z,setRightPanelMode:Ue}),{changeProjectTarget:ji,submitNewProjectDialog:zr}=r9({addProjectFolder:hi,addProjectFolderPath:gi,appDispatch:n,busy:V,cloudProjectById:ce,createCloudProjectFromScratch:bi,createProjectFromScratch:vi,expandProject:De,localProjectById:ue,newProjectBusy:le,newProjectMode:G,newProjectName:Ee,newProjectPath:xe,onCreateCloudEnvironment:Da,onNewCloudProject:Ti,onNewLocalProject:Ga,onUseExistingFolderPath:Uo,projectTargetValue:Yn.value,setDiffPanelOpen:Fe,setDraftModel:ut,setDraftProvider:it,setError:Xe,setNewProjectBusy:_e,setNewProjectDialogOpen:X,setNewProjectName:Z,setNewProjectPath:me,showToast:at,workspaceBusy:tt}),Wo=g.useMemo(()=>F.map(ft=>ft.id),[F]);hV({browserConversationId:ia,sessionIds:Wo,onOpenSession:zo,onShowBrowserPanel:Vo});const[Oi,yo]=g.useState(null),La=g.useCallback(ft=>{yo({id:Date.now(),objective:ft.objective,initialSessionIds:ft.sessionId?[ft.sessionId]:[]}),Ro({kind:"index"}),Re("labs")},[Re]),{activateRightChatPanel:Ur,closeRightChatPanel:Hr,openRightChatPanel:qr,rightChatPanelViews:Br,showRightChatPanel:ba,showRightPanelDiffTab:Ni,submitRightChatPrompt:Ko,updateRightChatModel:Fr,updateRightChatPrompt:Qa,updateRightChatProvider:Mn,updateRightChatScrollState:Vr}=y9({activeModel:Et,activeProvider:St,approvals:u,applyRightCodexHistoryPayload:wi,codexHistoryEvents:_n,connectedAppMentions:jt,connection:q,contextCompaction:Tn.contextCompaction,openLabTraining:La,locallyActiveCodexHistorySessionIds:y,openPondCommandAccessMode:$,pendingChatUserMessages:wt,providerSettings:j?.providers??null,rightChatHistoryEvents:h,rightChatPanels:Se,rightPanelMode:Ie,runtimeIndexes:qt,runtimeEventStore:ne,runningSessionIds:Un,selectedSession:We,selectedSessionId:I,sendPrompt:$a,setDiffPanelOpen:Fe,setError:Xe,setRightChatHistoryEvents:S,setRightChatPanels:ze,setRightPanelMode:Ue,setRightPanelTabRequest:d,setView:Re,showChangesPanel:Ei,showToast:at,sidebarSessions:mt,startupReady:_.ready}),Wr=g.useCallback(()=>{Ze(null),H("profile"),Re("settings"),an({kind:"settings",section:"profile"})},[Ze,H,Re]),Kr=g.useMemo(()=>ro(j?.diagnostics??E9,oe.filter(ft=>ft.name==="diagnostic")),[j?.diagnostics,oe]),Gr=g.useCallback(()=>{if(re){Fe(!1);return}if(O==="labs"){Ue("changes"),d({id:Date.now(),tab:"summary"}),Fe(!0);return}Ue("home"),Fe(!0)},[re,Fe,Ue,d,O]);return{title:ja,browserConversationId:ia,handleWorkspaceDiffPanelViewStateChange:fi,openSessionInChat:zo,openExistingProjectPathDialog:Uo,addProjectFolder:hi,removeProject:Cr,changeProjectTarget:ji,submitNewProjectDialog:zr,changeWorkspaceBranch:Rr,openCommitDialog:Oa,openCreateWorkspaceBranchDialog:Ar,openDefaultsSettingsFromBranchDialog:yi,runWorkspaceTool:Si,submitCommitDialog:xi,submitCreateWorkspaceBranch:Pr,syncWorkspaceLocally:Xn,subagentDelegationDefaultMode:Er,subagentDelegationMode:Mr,subagentDelegationAvailable:ki,changeSubagentDelegationMode:_i,answerCreateImproveQuestion:jr,applyCreateImproveCandidate:Na,approveCreateImproveRun:Za,cancelCreateImproveRun:Hn,changeDraftProvider:Or,openCreateImprovePullRequest:Nr,reconcileCreateImprovePullRequest:fn,rejectCreateImproveCandidate:Ii,pauseCreateImproveRun:qn,resumeCreateImproveRun:ga,reviseCreateImproveRun:Ja,sendPrompt:$a,stopTurn:$r,archiveSession:Dr,restoreSession:Ya,renameSession:Ho,toggleProjectPinned:Ci,toggleSessionPinned:qo,toggleSessionSavedForLater:Ri,moveProjectToCloud:Ai,startCloudSetupUpload:ra,changeWorkspaceTarget:vo,switchProjectWorkspaceTarget:Fo,sendPromptFromMainComposer:Xa,openSandboxWorkspace:Pi,createCloudEnvironmentFromSidebar:Da,openCloudProjectDialog:Ti,openUrlInBrowserPanel:Lr,showBrowserPanel:Vo,showChangesPanel:Ei,showGoalSidebarTab:Mi,rightChatTrainingLaunchRequest:Oi,setRightChatTrainingLaunchRequest:yo,closeRightChatPanel:Hr,openRightChatPanel:qr,rightChatPanelViews:Br,showRightChatPanel:ba,showRightPanelDiffTab:Ni,submitRightChatPrompt:Ko,activateRightChatPanel:Ur,updateRightChatModel:Fr,updateRightChatPrompt:Qa,updateRightChatProvider:Mn,updateRightChatScrollState:Vr,openProfileSettings:Wr,diagnosticEvents:Kr,toggleRightSidebar:Gr}}function j9(){const e=rV(),t=M9(e);return v.jsx(RB,{primary:e,secondary:t})}const xK=Object.freeze(Object.defineProperty({__proto__:null,App:j9},Symbol.toStringTag,{value:"Module"}));export{Wi as $,LL as A,kg as B,Mo as C,Tk as D,KW as E,lz as F,pz as G,gK as H,Do as I,fK as J,Wm as K,kW as L,VW as M,FB as N,DH as O,SK as P,nF as Q,NV as R,$z as S,FW as T,WW as U,aK as V,eK as W,Ir as X,kq as Y,Sa as Z,qq as _,ii as a,uz as a$,Nt as a0,so as a1,Fk as a2,OW as a3,hB as a4,Y6 as a5,jW as a6,dB as a7,nK as a8,J6 as a9,Nf as aA,Dx as aB,YL as aC,nz as aD,yW as aE,SW as aF,NR as aG,fB as aH,pB as aI,Lm as aJ,kx as aK,Sz as aL,vp as aM,xW as aN,_W as aO,Dm as aP,Tz as aQ,$m as aR,Y9 as aS,Ap as aT,pq as aU,hW as aV,Fc as aW,Sf as aX,an as aY,zm as aZ,Hz as a_,ta as aa,Va as ab,M_ as ac,p9 as ad,f9 as ae,dV as af,NW as ag,Mz as ah,yf as ai,hU as aj,gf as ak,Sx as al,Bc as am,JW as an,xf as ao,Bg as ap,vf as aq,bq as ar,Xm as as,NB as at,bK as au,AB as av,Yg as aw,Wc as ax,Uu as ay,vq as az,p4 as b,FL as b$,J9 as b0,xp as b1,kp as b2,_g as b3,Z9 as b4,OL as b5,vK as b6,Qc as b7,kz as b8,eW as b9,PW as bA,TW as bB,EW as bC,CW as bD,RW as bE,nW as bF,rW as bG,iW as bH,oW as bI,aW as bJ,Ty as bK,ZM as bL,_t as bM,QO as bN,tK as bO,Js as bP,sW as bQ,dW as bR,cW as bS,lW as bT,lU as bU,oU as bV,Ro as bW,fW as bX,tU as bY,Fm as bZ,dU as b_,kc as ba,bf as bb,xx as bc,hf as bd,DW as be,qW as bf,BW as bg,Qg as bh,zW as bi,Ju as bj,HW as bk,UW as bl,Wk as bm,LW as bn,Xg as bo,$W as bp,At as bq,gP as br,Q9 as bs,Ak as bt,tW as bu,pW as bv,ju as bw,X9 as bx,Wn as by,AW as bz,pt as c,vz as c0,Jb as c1,cV as c2,Ym as c3,xk as c4,ok as c5,Sk as c6,yK as c7,Nb as c8,QW as c9,Yb as ca,dp as cb,ZW as cc,Kk as cd,YW as ce,XW as cf,dK as cg,ez as ch,gz as ci,rK as cj,oK as ck,iK as cl,k3 as cm,T9 as cn,sK as co,lK as cp,cK as cq,Um as cr,Fx as cs,wW as ct,Ds as cu,uW as cv,mW as cw,IW as cx,xK as cy,io as d,qc as e,bW as f,GW as g,MW as h,ff as i,wV as j,mK as k,hK as l,P_ as m,pK as n,J as o,SU as p,gW as q,vW as r,Ix as s,Ns as t,lc as u,nv as v,Xo as w,qf as x,An as y,uK as z};