openpond 0.2.43 → 0.2.45
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.
- package/dist/app-server.d.ts +18127 -5586
- package/dist/app-server.js +1 -1
- package/dist/chunks/actions-command-CRDLSPFA.js +2 -0
- package/dist/chunks/{app-layer-OV7RVSQW.js → app-layer-MDJFV3HZ.js} +1 -1
- package/dist/chunks/app-server-runtime-PJONTCCO.js +2 -0
- package/dist/chunks/apps-MD2DKEDW.js +2 -0
- package/dist/chunks/{chunk-T5QA4W2H.js → chunk-25GCTLAZ.js} +5 -5
- package/dist/chunks/chunk-3BJ4P5LI.js +520 -0
- package/dist/chunks/chunk-3SRIPOJQ.js +2 -0
- package/dist/chunks/{chunk-7EDOA6KD.js → chunk-4EGDKOYP.js} +3 -3
- package/dist/chunks/{chunk-QUNRWDVO.js → chunk-5ZFEQLRI.js} +3 -3
- package/dist/chunks/chunk-6BL2ZIAP.js +184 -0
- package/dist/chunks/chunk-6QUICEQA.js +5 -0
- package/dist/chunks/chunk-7D2WMUWK.js +3 -0
- package/dist/chunks/chunk-7KIBRK3A.js +4 -0
- package/dist/chunks/{chunk-O277DPTX.js → chunk-B6LYKEMU.js} +1 -1
- package/dist/chunks/{chunk-ZG7QX66E.js → chunk-CR6CDOKS.js} +8 -8
- package/dist/chunks/chunk-CXS3WXL3.js +2 -0
- package/dist/chunks/chunk-DWGB536R.js +19 -0
- package/dist/chunks/{chunk-6UPCR6EL.js → chunk-EG55BFQ4.js} +1 -1
- package/dist/chunks/chunk-ELNJUG64.js +17 -0
- package/dist/chunks/{chunk-HI7W3IVO.js → chunk-FXIUKYUR.js} +12 -12
- package/dist/chunks/chunk-GEDEVI4Y.js +2 -0
- package/dist/chunks/chunk-H3C4ZYEA.js +16 -0
- package/dist/chunks/chunk-HUBI3RUK.js +2 -0
- package/dist/chunks/{chunk-IE2WZ3I3.js → chunk-IYRHG54Q.js} +1 -1
- package/dist/chunks/chunk-J65BMG5Q.js +2 -0
- package/dist/chunks/chunk-KOR2AZVB.js +24 -0
- package/dist/chunks/{chunk-LLNCHGE4.js → chunk-LL4QP2IM.js} +1 -1
- package/dist/chunks/chunk-M2YXYBSP.js +2 -0
- package/dist/chunks/chunk-NPOHW5OU.js +2 -0
- package/dist/chunks/{chunk-KRC2S5QF.js → chunk-NXUCGKY2.js} +3 -3
- package/dist/chunks/chunk-PDIT2QS7.js +8 -0
- package/dist/chunks/{chunk-T7MJBBHE.js → chunk-PGKEDR3S.js} +1 -1
- package/dist/chunks/chunk-QVRNOGAU.js +21 -0
- package/dist/chunks/chunk-TNXILYI6.js +2 -0
- package/dist/chunks/chunk-TVQE3JMI.js +2 -0
- package/dist/chunks/chunk-U6SFIFDM.js +2409 -0
- package/dist/chunks/chunk-V6WBSW5Q.js +3 -0
- package/dist/chunks/chunk-VESOG2SS.js +2 -0
- package/dist/chunks/chunk-VFTUP5NQ.js +2 -0
- package/dist/chunks/{chunk-G2WJC6DE.js → chunk-VVV5I22A.js} +2 -2
- package/dist/chunks/chunk-XPB6NY7L.js +42 -0
- package/dist/chunks/{chunk-VG7XO6PR.js → chunk-XWLI7WJH.js} +2 -24
- package/dist/chunks/{chunk-KIGN4FI6.js → chunk-YWX7FKLM.js} +1 -1
- package/dist/chunks/cli-BKBH6FZY.js +2 -0
- package/dist/chunks/{configuration-command-ANYM5UYG.js → configuration-command-75ZCMZ6X.js} +1 -1
- package/dist/chunks/connected-evidence-UPUVVQ6P.js +2 -0
- package/dist/chunks/{continual-MHMPLLUZ.js → continual-WWPXK2LO.js} +1 -1
- package/dist/chunks/core-commands-SS2GV7WU.js +2 -0
- package/dist/chunks/datasets-TCLXV34N.js +2 -0
- package/dist/chunks/desktop-test-7ZHZHUB6.js +3 -0
- package/dist/chunks/{dist-GC7DXKTI.js → dist-VDN6E54A.js} +1 -1
- package/dist/chunks/evaluation-coordination-ZX5GLMRC.js +2 -0
- package/dist/chunks/experiment-improvements-O6DCQXCX.js +2 -0
- package/dist/chunks/experiments-JOQOBQXY.js +2 -0
- package/dist/chunks/{extension-5LQRULQP.js → extension-3M2CSWZB.js} +1 -1
- package/dist/chunks/{help-NTSTG6RR.js → help-RLRU33WN.js} +1 -1
- package/dist/chunks/hosted-experiment-improvement-IKO677PI.js +3 -0
- package/dist/chunks/hosted-harness-runtime-H2Q2SNZT.js +2 -0
- package/dist/chunks/hosted-profile-candidate-FHHSLJNO.js +3 -0
- package/dist/chunks/hosted-profile-compiler-5B256VV3.js +2 -0
- package/dist/chunks/hosted-profile-evaluation-control-Z25TZOW4.js +2 -0
- package/dist/chunks/hosted-profile-evaluation-inspection-MFYPLTZQ.js +3 -0
- package/dist/chunks/hosted-profile-evaluation-preparation-MAB2PSCC.js +3 -0
- package/dist/chunks/human-review-6H3BW7OZ.js +2 -0
- package/dist/chunks/learning-Y6WNDVQW.js +2 -0
- package/dist/chunks/{opchat-77PRAQ5W.js → opchat-3E4FH3DC.js} +1 -1
- package/dist/chunks/{organizations-2KWTYIPU.js → organizations-PRVCUPMN.js} +1 -1
- package/dist/chunks/{profile-HVLH672B.js → profile-DC4UEVVG.js} +1 -1
- package/dist/chunks/project-agent-ZX3CELKI.js +2 -0
- package/dist/chunks/sandbox-command-HHQMZK3G.js +2 -0
- package/dist/chunks/{sandbox-template-QMB6DSTS.js → sandbox-template-DFHWHCIQ.js} +1 -1
- package/dist/chunks/{src-N447LUPO.js → src-CREVQF7M.js} +1 -1
- package/dist/chunks/src-MAZ7OBVY.js +327 -0
- package/dist/chunks/taskset-TB2ICAZU.js +2 -0
- package/dist/chunks/{teams-bot-RNHQMPQA.js → teams-bot-BNBL57S5.js} +1 -1
- package/dist/chunks/training-FW5FOGR3.js +2 -0
- package/dist/chunks/{workspaces-V5YTXJLV.js → workspaces-WTPFRJMS.js} +1 -1
- package/dist/cli.js +1 -1
- package/dist/index.js +1 -1
- package/dist/profile/local-profile.d.ts +2 -0
- package/dist/web/assets/App-BgeSqoRS.css +1 -0
- package/dist/web/assets/App-C6EWFrLP.js +227 -0
- package/dist/web/assets/{AppDialog-v-BfV1lA.js → AppDialog-Cgn_fTGR.js} +1 -1
- package/dist/web/assets/AppTerminalPanel-cNYkSvM2.js +2 -0
- package/dist/web/assets/{AppsView-Dl-37F0w.js → AppsView-9zpKBSLv.js} +1 -1
- package/dist/web/assets/{BrowserSidebar-DltF217k.js → BrowserSidebar-Xo21N1ej.js} +1 -1
- package/dist/web/assets/{CartesianChart-gK-Ll3kX.js → CartesianChart-Bg3Lm5mZ.js} +1 -1
- package/dist/web/assets/{CollaborationTabs-BuWquQYn.js → CollaborationTabs-BIfgIy5X.js} +1 -1
- package/dist/web/assets/{CommandMenu-Cs5S8t-Q.js → CommandMenu-D9BimyPx.js} +1 -1
- package/dist/web/assets/{CommunityView-BJBkQEMV.js → CommunityView-BoW-yLju.js} +1 -1
- package/dist/web/assets/{ComposerCreateImproveStrip-C36fKc-v.js → ComposerCreateImproveStrip-BIKVEgr1.js} +1 -1
- package/dist/web/assets/{GetStartedView-9A49MgYA.js → GetStartedView-B99v4-hh.js} +1 -1
- package/dist/web/assets/HostedModelLearningReview-DEScpX2Z.js +1 -0
- package/dist/web/assets/HostedModelLearningSettings-4HT5eEiL.js +1 -0
- package/dist/web/assets/LabModelVersionDetailPage-DkYdI7gr.js +1 -0
- package/dist/web/assets/{LabSkillSidebar-BAKym5GY.js → LabSkillSidebar-Bp5XYipm.js} +1 -1
- package/dist/web/assets/LabsRoute-ACN76d2j.css +1 -0
- package/dist/web/assets/LabsRoute-VopO7n34.js +105 -0
- package/dist/web/assets/MainChatThread-3Gg0oDZT.js +2 -0
- package/dist/web/assets/{MainPane-gPkr0OWu.js → MainPane-CUqMVG9-.js} +11 -11
- package/dist/web/assets/{MarkdownText-B-au2zEv.js → MarkdownText-De0WzrEw.js} +1 -1
- package/dist/web/assets/{NativeSkillSidebar-DHFKZ7P1.js → NativeSkillSidebar-B4jtf5RO.js} +1 -1
- package/dist/web/assets/{NewExperienceSwitcher-Dhbf5KJT.js → NewExperienceSwitcher-Bg1DVr96.js} +1 -1
- package/dist/web/assets/{NewProjectDialog-hlAzFK2Y.js → NewProjectDialog-i_wvIBw-.js} +1 -1
- package/dist/web/assets/{OutputsPage-C0N2rOxE.js → OutputsPage-CZiPxLyN.js} +1 -1
- package/dist/web/assets/{ProjectsPage-CkHBgLPx.js → ProjectsPage-BD0eml0M.js} +1 -1
- package/dist/web/assets/{RightChatPanelStack-BiW6ZzPN.js → RightChatPanelStack-CEBFPHKP.js} +1 -1
- package/dist/web/assets/{RightSidebarHomePanel-BS9YSdYB.js → RightSidebarHomePanel-BTpU5wGh.js} +1 -1
- package/dist/web/assets/{ScheduledWorkPage-819sQcDR.js → ScheduledWorkPage-Y6XGoh-X.js} +1 -1
- package/dist/web/assets/{SettingsView-BZrOUPZb.js → SettingsView-Kh14f463.js} +3 -3
- package/dist/web/assets/{TeamChatView-CUNcbSa7.js → TeamChatView-5LjuRNd6.js} +1 -1
- package/dist/web/assets/{TerminalOverlay-MIlGPpXe.js → TerminalOverlay-BCWBSotQ.js} +1 -1
- package/dist/web/assets/{TrainingCreationPanel-BNcyNoa8.js → TrainingCreationPanel-hvOHRVJx.js} +1 -1
- package/dist/web/assets/{TrainingDraftPanel-CKV16LNC.js → TrainingDraftPanel-CGEHGljE.js} +1 -1
- package/dist/web/assets/{UsageSettingsSection-SVgUHnUL.js → UsageSettingsSection-B8nbqhag.js} +1 -1
- package/dist/web/assets/{WorkSidebarPanel-CfkaaFHA.js → WorkSidebarPanel-B6hlPEIs.js} +1 -1
- package/dist/web/assets/{WorkspaceDiffPanel-CQhqlqg5.js → WorkspaceDiffPanel-q8A15-0x.js} +9 -9
- package/dist/web/assets/{WorkspaceEnvironmentMenu-CJB-z2tS.js → WorkspaceEnvironmentMenu-BiFTPWtC.js} +1 -1
- package/dist/web/assets/{WorkspaceGitDialogs-B3xtasTt.js → WorkspaceGitDialogs-Dyx4Rbiy.js} +1 -1
- package/dist/web/assets/{WorkspaceMonacoEditor-DVfyICNZ.js → WorkspaceMonacoEditor-B1dKexHo.js} +60 -60
- package/dist/web/assets/{arrow-up-right-CYG4Vm07.js → arrow-up-right-CCj7SOGp.js} +1 -1
- package/dist/web/assets/chunk-DJWHN7NU-1eQoMoKO.js +1 -0
- package/dist/web/assets/{clipboard-DGSnfljX.js → clipboard-BY6ELc9Z.js} +1 -1
- package/dist/web/assets/{cloud-upload-Bw_zrS2y.js → cloud-upload-BOka5EKK.js} +1 -1
- package/dist/web/assets/cssMode-C34j8ti5.js +1 -0
- package/dist/web/assets/{folder-open-CcGOldH7.js → folder-open-CX2jidFj.js} +1 -1
- package/dist/web/assets/{folder-plus-DEIDaX2B.js → folder-plus-Dh2Q9LP3.js} +1 -1
- package/dist/web/assets/{git-commit-horizontal-B-Ao6y--.js → git-commit-horizontal-CfevriuT.js} +1 -1
- package/dist/web/assets/htmlMode-BORwVkZg.js +1 -0
- package/dist/web/assets/index-B9VSiz_z.css +1 -0
- package/dist/web/assets/{index-C8_8-lW7.js → index-BBjRfC--.js} +6 -6
- package/dist/web/assets/{info-DwOXHkN_.js → info-Bv3dbs3G.js} +1 -1
- package/dist/web/assets/{jsonMode-txmGM7K6.js → jsonMode-BYWtZ6AK.js} +4 -4
- package/dist/web/assets/{lspLanguageFeatures-D59Drc_9.js → lspLanguageFeatures-CEAdFSpU.js} +1 -1
- package/dist/web/assets/{minimize-2-C5UCV16_.js → minimize-2-MhorZwY5.js} +1 -1
- package/dist/web/assets/{monaco.contribution-BOmcYK8k.js → monaco.contribution-CDhPpbIo.js} +2 -2
- package/dist/web/assets/{monaco.contribution-CbK7796k.js → monaco.contribution-CN7AWJNd.js} +2 -2
- package/dist/web/assets/monaco.contribution-DHA7FuJX.js +2 -0
- package/dist/web/assets/{monaco.contribution-5HcktwaM.js → monaco.contribution-ZUUVx_3M.js} +2 -2
- package/dist/web/assets/{monitor-D4hpNTai.js → monitor-DLcrkfM5.js} +1 -1
- package/dist/web/assets/{python-Cie4Ghu8.js → python-CXwvPmc4.js} +1 -1
- package/dist/web/assets/{refresh-cw-CIOzrJnj.js → refresh-cw-BTfIxHb3.js} +1 -1
- package/dist/web/assets/{save-D7EtdMHG.js → save-DaN65kMq.js} +1 -1
- package/dist/web/assets/{square-JpDfrqp_.js → square-zRgIUdSv.js} +1 -1
- package/dist/web/assets/toggleHighContrast-BgpFWRpS.css +1 -0
- package/dist/web/assets/{toggleHighContrast-DdGkc-Be.js → toggleHighContrast-DWeRZFzr.js} +1 -1
- package/dist/web/assets/{tsMode-DwgEL7oI.js → tsMode-nLBhKngY.js} +1 -1
- package/dist/web/assets/{upload-BkwOzqS-.js → upload-BfUu4Eu1.js} +1 -1
- package/dist/web/assets/{useLocalAgentSchedules-bO0Qycih.js → useLocalAgentSchedules-BCITWhg2.js} +1 -1
- package/dist/web/assets/{useSessionTurnCache-DxUh5scW.js → useSessionTurnCache-BQMWfV8u.js} +1 -1
- package/dist/web/assets/{wifi-off-D6Keejtn.js → wifi-off-bdka5es5.js} +1 -1
- package/dist/web/assets/{workers-BgG66q0n.js → workers-z7XHFFNs.js} +1 -1
- package/dist/web/assets/{yaml-COMRGPWg.js → yaml-BTr4i4DD.js} +1 -1
- package/dist/web/index.html +5 -5
- package/docs/command-reference.md +85 -1
- package/package.json +6 -2
- package/dist/chunks/actions-command-DWQ3VGGP.js +0 -2
- package/dist/chunks/app-server-runtime-JVLXE5LF.js +0 -2
- package/dist/chunks/apps-5DQAYDNI.js +0 -2
- package/dist/chunks/chunk-3D4QN4NM.js +0 -19
- package/dist/chunks/chunk-45UOD2DA.js +0 -2
- package/dist/chunks/chunk-5IN3HQJU.js +0 -2
- package/dist/chunks/chunk-6KKQXETR.js +0 -5
- package/dist/chunks/chunk-6XF4GI35.js +0 -2
- package/dist/chunks/chunk-7KC5LWCU.js +0 -2
- package/dist/chunks/chunk-7R7O2XXP.js +0 -2
- package/dist/chunks/chunk-DGD52VZC.js +0 -13
- package/dist/chunks/chunk-E6WT4HWF.js +0 -3
- package/dist/chunks/chunk-EWQZASG4.js +0 -2400
- package/dist/chunks/chunk-IFI24VF6.js +0 -5
- package/dist/chunks/chunk-KDOS6YMH.js +0 -2
- package/dist/chunks/chunk-MDE3HHLH.js +0 -2
- package/dist/chunks/chunk-P45OSKQL.js +0 -4
- package/dist/chunks/chunk-ROJX6IYW.js +0 -578
- package/dist/chunks/chunk-SXN3QOW4.js +0 -3
- package/dist/chunks/chunk-V44RF57H.js +0 -2
- package/dist/chunks/chunk-VJJ3UXOI.js +0 -42
- package/dist/chunks/chunk-W3NG7YLC.js +0 -8
- package/dist/chunks/chunk-XMKAMR7M.js +0 -2
- package/dist/chunks/cli-7D7CYCIY.js +0 -2
- package/dist/chunks/core-commands-TYWE3TNW.js +0 -2
- package/dist/chunks/datasets-FM3UBK4R.js +0 -13
- package/dist/chunks/desktop-test-Z5IKJU3P.js +0 -3
- package/dist/chunks/experiments-IWBRIDQE.js +0 -2
- package/dist/chunks/hosted-harness-runtime-S75BLD57.js +0 -2
- package/dist/chunks/hosted-profile-compiler-JNNYWLC7.js +0 -2
- package/dist/chunks/hosted-profile-evaluation-control-IK4Y2EQZ.js +0 -2
- package/dist/chunks/hosted-profile-evaluation-inspection-YWKUB7RT.js +0 -3
- package/dist/chunks/hosted-profile-evaluation-preparation-JXOF73BB.js +0 -3
- package/dist/chunks/project-agent-7NLKJMAM.js +0 -2
- package/dist/chunks/sandbox-command-FNS4JBVC.js +0 -2
- package/dist/chunks/src-TZBL6NA7.js +0 -325
- package/dist/chunks/taskset-BZYQT65N.js +0 -2
- package/dist/chunks/training-7PST5HZU.js +0 -2
- package/dist/web/assets/App-7h_oHCFd.css +0 -1
- package/dist/web/assets/App-BEQmrTGQ.js +0 -226
- package/dist/web/assets/AppTerminalPanel-CnKcllS2.js +0 -2
- package/dist/web/assets/HostedModelLearningReview-JgxDUDio.js +0 -1
- package/dist/web/assets/HostedModelLearningSettings-CH7CsAhw.js +0 -1
- package/dist/web/assets/LabModelVersionDetailPage-N2qcy1Yv.js +0 -1
- package/dist/web/assets/LabsRoute-DooCmsN8.css +0 -1
- package/dist/web/assets/LabsRoute-Y992kQoQ.js +0 -52
- package/dist/web/assets/MainChatThread-CPhREQso.js +0 -2
- package/dist/web/assets/cssMode-CSpYOKj-.js +0 -1
- package/dist/web/assets/htmlMode-DstkgJXG.js +0 -1
- package/dist/web/assets/index-DUIWDN8o.css +0 -1
- package/dist/web/assets/monaco.contribution-BomZ1gys.js +0 -2
- package/dist/web/assets/toggleHighContrast-B7NOMXDY.css +0 -1
|
@@ -1,226 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CommandMenu-Cs5S8t-Q.js","./index-C8_8-lW7.js","./index-DUIWDN8o.css","./CommandMenu-Cb3vNGJr.css","./SettingsView-BZrOUPZb.js","./refresh-cw-CIOzrJnj.js","./save-D7EtdMHG.js","./MarkdownText-B-au2zEv.js","./folder-open-CcGOldH7.js","./wifi-off-D6Keejtn.js","./useLocalAgentSchedules-bO0Qycih.js","./cloud-upload-Bw_zrS2y.js","./git-commit-horizontal-B-Ao6y--.js","./folder-plus-DEIDaX2B.js","./AppDialog-v-BfV1lA.js","./WorkspaceDiffPanel-CQhqlqg5.js","./training-model-data-CKOkpBBL.js","./info-DwOXHkN_.js","./minimize-2-C5UCV16_.js","./clipboard-DGSnfljX.js","./SettingsView-C7av3zwv.css","./git-dialogs-C-F47S10.css","./NewProjectDialog-hlAzFK2Y.js","./monitor-D4hpNTai.js","./WorkspaceGitDialogs-B3xtasTt.js","./upload-BkwOzqS-.js","./WorkspaceEnvironmentMenu-CJB-z2tS.js","./square-JpDfrqp_.js","./WorkspaceEnvironmentMenu-DGIFdG3o.css","./MainPane-gPkr0OWu.js","./arrow-up-right-CYG4Vm07.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{r as v,j as k,a as bR,_ as ni}from"./index-C8_8-lW7.js";const $S=v.createContext(void 0),NS=e=>{const t=v.useContext($S);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},yR=({client:e,children:t})=>(v.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),k.jsx($S.Provider,{value:e,children:t})),SR={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)};var xR=class{#e=SR;#t=!1;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};const qr=new xR;function kR(e){setTimeout(e,0)}const wR=typeof window>"u"||"Deno"in globalThis;function Gn(){}function IR(e,t){return typeof e=="function"?e(t):e}function DS(e){return typeof e=="number"&&e>=0&&e!==1/0}function LS(e,t){return Math.max(e+(t||0)-Date.now(),0)}function nn(e,t){return typeof e=="function"?e(t):e}function Vv(e,t){const{type:n="all",exact:a,fetchStatus:o,predicate:i,queryKey:s,stale:l}=e;if(s){if(a){if(t.queryHash!==Th(s,t.options))return!1}else if(!ls(t.queryKey,s))return!1}if(n!=="all"){const m=t.isActive();if(n==="active"&&!m||n==="inactive"&&m)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||o&&o!==t.state.fetchStatus||i&&!i(t))}function Kv(e,t){const{exact:n,status:a,predicate:o,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(wl(t.options.mutationKey)!==wl(i))return!1}else if(!ls(t.options.mutationKey,i))return!1}return!(a&&t.state.status!==a||o&&!o(t))}function Th(e,t){return(t?.queryKeyHashFn||wl)(e)}function wl(e){return JSON.stringify(e,(t,n)=>kf(n)?Object.keys(n).sort().reduce((a,o)=>(a[o]=n[o],a),{}):n)}function ls(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(Array.isArray(e)&&Array.isArray(t)){for(let a=0;a<t.length;a++)if(!ls(e[a],t[a]))return!1;return!0}const n=Object.keys(t);for(const a of n)if(!ls(e[a],t[a]))return!1;return!0}return!1}const _R=Object.prototype.hasOwnProperty;function US(e,t,n=0){if(e===t)return e;if(n>500)return t;const a=Wv(e)&&Wv(t);if(!a&&!(kf(e)&&kf(t)))return t;const o=(a?e:Object.keys(e)).length,i=a?t:Object.keys(t),s=i.length,l=a?new Array(s):{};let m=0;for(let d=0;d<s;d++){const h=a?d:i[d],g=e[h],y=t[h];if(g===y){l[h]=g,(a?d<o:_R.call(e,h))&&m++;continue}if(g===null||y===null||typeof g!="object"||typeof y!="object"){l[h]=y;continue}const w=US(g,y,n+1);l[h]=w,w===g&&m++}return o===s&&m===o?e:l}function rp(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function Wv(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function kf(e){if(!Gv(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!Gv(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Gv(e){return Object.prototype.toString.call(e)==="[object Object]"}function CR(e){return new Promise(t=>{qr.setTimeout(t,e)})}function wf(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?US(e,t):t}function RR(e,t,n=0){const a=[...e,t];return n&&a.length>n?a.slice(1):a}function PR(e,t,n=0){const a=[t,...e];return n&&a.length>n?a.slice(0,-1):a}const Eh=Symbol();function HS(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Eh?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function zS(e,t){return typeof e=="function"?e(...t):!!e}function AR(e,t,n){let a=!1,o;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(o??=t(),a||(a=!0,o.aborted?n():o.addEventListener("abort",n,{once:!0})),o)}),e}let TR=()=>wR;const Mh=()=>TR();var Kl=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},ER=class extends Kl{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}};const jh=new ER,MR=kR;function jR(){let e=[],t=0,n=l=>{l()},a=l=>{l()},o=MR;const i=l=>{t?e.push(l):o(()=>{n(l)})},s=()=>{const l=e;e=[],l.length&&o(()=>{a(()=>{l.forEach(m=>{n(m)})})})};return{batch:l=>{let m;t++;try{m=l()}finally{t--,t||s()}return m},batchCalls:l=>(...m)=>{i(()=>{l(...m)})},schedule:i,setNotifyFunction:l=>{n=l},setBatchNotifyFunction:l=>{a=l},setScheduler:l=>{o=l}}}const An=jR();var OR=class extends Kl{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};const Cd=new OR;function $R(e){return Math.min(1e3*2**e,3e4)}function qS(e){return(e??"online")==="online"?Cd.isOnline():!0}var If=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function BS(e){let t=!1,n=0,a,o="pending",i,s;const l=new Promise((N,$)=>{i=N,s=$});l.catch(Gn);const m=()=>o!=="pending",d=N=>{if(!m()){const $=new If(N);P($),e.onCancel?.($)}},h=()=>{t=!0},g=()=>{t=!1},y=()=>jh.isFocused()&&(e.networkMode==="always"||Cd.isOnline())&&e.canRun(),w=()=>qS(e.networkMode)&&e.canRun(),_=N=>{m()||(a?.(),o="resolved",i(N))},P=N=>{m()||(a?.(),o="rejected",s(N))},M=()=>new Promise(N=>{a=$=>{(m()||y())&&N($)},e.onPause?.()}).then(()=>{a=void 0,m()||e.onContinue?.()}),C=()=>{if(m())return;let N;const $=n===0?e.initialPromise:void 0;try{N=$??e.fn()}catch(j){N=Promise.reject(j)}Promise.resolve(N).then(_).catch(j=>{if(m())return;const x=e.retry??(Mh()?0:3),R=e.retryDelay??$R,E=typeof R=="function"?R(n,j):R,U=x===!0||typeof x=="number"&&n<x||typeof x=="function"&&x(n,j);if(t||!U){P(j);return}n++,e.onFail?.(n,j),CR(E).then(()=>y()?void 0:M()).then(()=>{t?P(j):C()})})};return{promise:l,status:()=>o,cancel:d,continue:()=>(a?.(),l),cancelRetry:h,continueRetry:g,canStart:w,start:()=>(w()?C():M().then(C),l)}}var FS=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),DS(this.gcTime)&&(this.#e=qr.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Mh()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(qr.clearTimeout(this.#e),this.#e=void 0)}};function NR(e){return{onFetch:(t,n)=>{const a=t.options,o=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],s=t.state.data?.pageParams||[];let l={pages:[],pageParams:[]},m=0;const d=async()=>{let h=!1;const g=_=>{AR(_,()=>t.signal,()=>h=!0)},y=HS(t.options,t.fetchOptions),w=async(_,P,M)=>{if(h)return Promise.reject(t.signal.reason);if(P==null&&_.pages.length)return Promise.resolve(_);const N=(()=>{const R={client:t.client,queryKey:t.queryKey,pageParam:P,direction:M?"backward":"forward",meta:t.options.meta};return g(R),R})(),$=await y(N),{maxPages:j}=t.options,x=M?PR:RR;return{pages:x(_.pages,$,j),pageParams:x(_.pageParams,P,j)}};if(o&&i.length){const _=o==="backward",P=_?VS:_f,M={pages:i,pageParams:s};l=await w(M,P(a,M),_)}else{const _=e??i.length;do{const P=m===0?s[0]??a.initialPageParam:_f(a,l);if(m>0&&P==null)break;l=await w(l,P),m++}while(m<_)}return l};t.options.persister?t.fetchFn=()=>t.options.persister?.(d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=d}}}function _f(e,{pages:t,pageParams:n}){const a=t.length-1;return t.length>0?e.getNextPageParam(t[a],t,n[a],n):void 0}function VS(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function EY(e,t){return t?_f(e,t)!=null:!1}function MY(e,t){return!t||!e.getPreviousPageParam?!1:VS(e,t)!=null}var DR=class extends FS{#e;#t;#n;#a;#r;#o;#i;#l;constructor(e){super(),this.#l=!1,this.#i=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#r=e.client,this.#a=this.#r.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=Jv(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#o?.promise}setOptions(e){if(this.options={...this.#i,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=Jv(this.options);t.data!==void 0&&(this.setState(Zv(t.data,t.dataUpdatedAt)),this.#t=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#a.remove(this)}setData(e,t){const n=wf(this.state.data,e,this.options);return this.#s({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#s({type:"setState",state:e})}cancel(e){const t=this.#o?.promise;return this.#o?.cancel(e),t?t.then(Gn).catch(Gn):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>nn(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Eh||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>nn(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!LS(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#o?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#o?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#a.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){const t=this.observers.indexOf(e);t!==-1&&(this.observers.splice(t,1),this.observers.length||(this.#o&&(this.#l||this.state.fetchStatus==="paused"&&this.state.status==="pending"?this.#o.cancel({revert:!0}):this.#o.cancelRetry()),this.scheduleGc()),this.#a.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#s({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#o?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#o)return this.#o.continueRetry(),this.#o.promise}if(e&&this.setOptions(e),!this.options.queryFn){const m=this.observers.find(d=>d.options.queryFn);m&&this.setOptions(m.options)}const n=new AbortController,a=m=>{Object.defineProperty(m,"signal",{enumerable:!0,get:()=>(this.#l=!0,n.signal)})},o=()=>{const m=HS(this.options,t),h=(()=>{const g={client:this.#r,queryKey:this.queryKey,meta:this.meta};return a(g),g})();return this.#l=!1,this.options.persister?this.options.persister(m,h,this):m(h)},s=(()=>{const m={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#r,state:this.state,fetchFn:o};return a(m),m})();(this.#e==="infinite"?NR(this.options.pages):this.options.behavior)?.onFetch(s,this),this.#n=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==s.fetchOptions?.meta)&&this.#s({type:"fetch",meta:s.fetchOptions?.meta});const l=this.#o=BS({initialPromise:t?.initialPromise,fn:s.fetchFn,onCancel:m=>{m instanceof If&&m.revert&&this.setState({...this.#n,fetchStatus:"idle"}),n.abort()},onFail:(m,d)=>{this.#s({type:"failed",failureCount:m,error:d})},onPause:()=>{this.#s({type:"pause"})},onContinue:()=>{this.#s({type:"continue"})},retry:s.options.retry,retryDelay:s.options.retryDelay,networkMode:s.options.networkMode,canRun:()=>!0});try{const m=await l.start();if(m===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(m),this.#a.config.onSuccess?.(m,this),this.#a.config.onSettled?.(m,this.state.error,this),m}catch(m){if(m instanceof If){if(m.silent)return this.#o.promise;if(m.revert){if(this.state.data===void 0)throw m;return this.state.data}}throw this.#s({type:"error",error:m}),this.#a.config.onError?.(m,this),this.#a.config.onSettled?.(this.state.data,m,this),m}finally{this.#o===l&&(this.#o=void 0),this.scheduleGc()}}#s(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...KS(n.data,this.options),fetchMeta:e.meta??null};case"success":const a={...n,...Zv(e.data,e.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?a:void 0,a;case"error":const o=e.error;return{...n,error:o,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:o,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),An.batch(()=>{this.observers.slice().forEach(n=>{n.onQueryUpdate()}),this.#a.notify({query:this,type:"updated",action:e})})}};function KS(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:qS(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Zv(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Jv(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,a=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?a??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var LR=class extends Kl{#e;#t=void 0;#n=void 0;#a=void 0;#r;#o;#i;#l;#s;#p;#d;#u;#c;#f=new Set;constructor(e,t){super(),this.options=t,this.#e=e,this.#i=null,this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Yv(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Cf(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Cf(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#S(),this.#x(),this.#t.removeObserver(this)}setOptions(e){const t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof nn(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#k(),this.#t.setOptions(this.options),t._defaulted&&!rp(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const a=this.hasListeners();a&&Qv(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),a&&(this.#t!==n||nn(this.options.enabled,this.#t)!==nn(t.enabled,this.#t)||nn(this.options.staleTime,this.#t)!==nn(t.staleTime,this.#t))&&this.#g();const o=this.#v();a&&(this.#t!==n||nn(this.options.enabled,this.#t)!==nn(t.enabled,this.#t)||o!==this.#c)&&this.#b(o)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return rp(this.getCurrentResult(),n)||(this.#a=n,this.#o=this.options,this.#r=this.#t.state),n}getCurrentResult(){return this.#a}trackResult(e,t){return new Proxy(e,{get:(n,a)=>(this.trackProp(a),t?.(a),Reflect.get(n,a))})}trackProp(e){this.#f.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);let a=()=>{},o;const i=new Promise(s=>{o=s,a=this.#e.getQueryCache().subscribe(l=>{l.type==="updated"&&l.query.queryHash===n.queryHash&&n.state.data!==void 0&&(a(),s(this.createResult(n,t)))})});return Promise.race([n.fetch().then(()=>{const s=this.createResult(n,t);return o?.(s),s}).finally(()=>{a()}),i])}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#a))}#m(e){this.#k();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Gn)),t}#h(e){return!Mh()&&nn(this.options.enabled,this.#t)!==!1&&DS(e)}#g(){this.#S();const e=nn(this.options.staleTime,this.#t);if(this.#a.isStale||!this.#h(e))return;const t=LS(this.#a.dataUpdatedAt,e)+1;this.#d=qr.setTimeout(()=>{this.#a.isStale||this.updateResult()},t)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#b(e){this.#x(),this.#c=e,!(this.#c===0||!this.#h(this.#c))&&(this.#u=qr.setInterval(()=>{(this.options.refetchIntervalInBackground||jh.isFocused())&&this.#m()},this.#c))}#y(){this.#g(),this.#b(this.#v())}#S(){this.#d!==void 0&&(qr.clearTimeout(this.#d),this.#d=void 0)}#x(){this.#u!==void 0&&(qr.clearInterval(this.#u),this.#u=void 0)}createResult(e,t){const n=this.#t,a=this.options,o=this.#a,i=this.#r,s=this.#o,l=e!==n?e.state:this.#n,{state:m}=e;let d={...m},h=!1,g;if(t._optimisticResults){const x=this.hasListeners(),R=!x&&Yv(e,t),E=x&&Qv(e,n,t,a);(R||E)&&(d={...d,...KS(m.data,e.options)}),t._optimisticResults==="isRestoring"&&(d.fetchStatus="idle")}let{error:y,errorUpdatedAt:w,status:_}=d;g=d.data;let P=!1;if(t.placeholderData!==void 0&&g===void 0&&_==="pending"){let x;o?.isPlaceholderData&&t.placeholderData===s?.placeholderData?(x=o.data,P=!0):x=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,x!==void 0&&(_="success",g=wf(o?.data,x,t),h=!0)}if(t.select&&g!==void 0&&!P)if(o&&g===i?.data&&t.select===this.#l)g=this.#s;else try{this.#l=t.select,g=t.select(g),g=wf(o?.data,g,t),this.#s=g,this.#i=null}catch(x){this.#i=x}else g===void 0&&(this.#i=null);this.#i&&(y=this.#i,g=this.#s,w=Date.now(),_="error",h=!1);const M=d.fetchStatus==="fetching",C=_==="pending",N=_==="error",$=C&&M,j=g!==void 0;return{status:_,fetchStatus:d.fetchStatus,isPending:C,isSuccess:_==="success",isError:N,isInitialLoading:$,isLoading:$,data:g,dataUpdatedAt:d.dataUpdatedAt,error:y,errorUpdatedAt:w,failureCount:d.fetchFailureCount,failureReason:d.fetchFailureReason,errorUpdateCount:d.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:d.dataUpdateCount>l.dataUpdateCount||d.errorUpdateCount>l.errorUpdateCount,isFetching:M,isRefetching:M&&!C,isLoadingError:N&&!j,isPaused:d.fetchStatus==="paused",isPlaceholderData:h,isRefetchError:N&&j,isStale:Oh(e,t),refetch:this.refetch,isEnabled:nn(t.enabled,e)!==!1}}updateResult(){const e=this.#a,t=this.createResult(this.#t,this.options);if(this.#r=this.#t.state,this.#o=this.options,this.#r.data!==void 0&&(this.#p=this.#t),rp(t,e))return;this.#a=t;const a=(()=>{if(!e)return!0;const{notifyOnChangeProps:o}=this.options,i=typeof o=="function"?o():o;if(i==="all"||!i&&!this.#f.size)return!0;const s=new Set(i??this.#f);return this.options.throwOnError&&s.add("error"),Object.keys(this.#a).some(l=>{const m=l;return this.#a[m]!==e[m]&&s.has(m)})})();An.batch(()=>{a&&this.listeners.forEach(o=>{o(this.#a)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}#k(){const e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;const t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}};function UR(e,t){return nn(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&nn(t.retryOnMount,e)===!1)}function Yv(e,t){return UR(e,t)||e.state.data!==void 0&&Cf(e,t,t.refetchOnMount)}function Cf(e,t,n){if(nn(t.enabled,e)!==!1&&nn(t.staleTime,e)!=="static"){const a=typeof n=="function"?n(e):n;return a==="always"||a!==!1&&Oh(e,t)}return!1}function Qv(e,t,n,a){return(e!==t||nn(a.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Oh(e,n)}function Oh(e,t){return nn(t.enabled,e)!==!1&&e.isStaleByTime(nn(t.staleTime,e))}var HR=class extends FS{#e;#t;#n;#a;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||zR(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#n.remove(this))}continue(){return this.#a?.continue()??(this.state.status==="pending"?this.execute(this.state.variables):Promise.resolve())}async execute(e){const t=()=>{this.#r({type:"continue"})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey},a=this.#a=BS({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(new Error("No mutationFn found")),onFail:(s,l)=>{this.#r({type:"failed",failureCount:s,error:l})},onPause:()=>{this.#r({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)}),o=this.state.status==="pending",i=!a.canStart();try{if(o)t();else{this.#r({type:"pending",variables:e,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);const l=await this.options.onMutate?.(e,n);l!==this.state.context&&this.#r({type:"pending",context:l,variables:e,isPaused:i})}const s=await a.start();return await this.#n.config.onSuccess?.(s,e,this.state.context,this,n),await this.options.onSuccess?.(s,e,this.state.context,n),await this.#n.config.onSettled?.(s,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(s,null,e,this.state.context,n),this.#r({type:"success",data:s}),s}catch(s){try{await this.#n.config.onError?.(s,e,this.state.context,this,n)}catch(l){Promise.reject(l)}try{await this.options.onError?.(s,e,this.state.context,n)}catch(l){Promise.reject(l)}try{await this.#n.config.onSettled?.(void 0,s,this.state.variables,this.state.context,this,n)}catch(l){Promise.reject(l)}try{await this.options.onSettled?.(void 0,s,e,this.state.context,n)}catch(l){Promise.reject(l)}throw this.#r({type:"error",error:s}),s}finally{this.#a===a&&(this.#a=void 0),this.#n.runNext(this)}}#r(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),An.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:"updated",action:e})})}};function zR(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var qR=class extends Kl{#e;#t;#n;constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}build(e,t,n){const a=new HR({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(a),a}add(e){this.#e.add(e);const t=Dc(e);if(typeof t=="string"){const n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#e.delete(e)){const t=Dc(e);if(typeof t=="string"){const n=this.#t.get(t);if(n)if(n.length>1){const a=n.indexOf(e);a!==-1&&n.splice(a,1)}else n[0]===e&&this.#t.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=Dc(e);if(typeof t=="string"){const n=this.#t.get(t)?.find(a=>a.state.status==="pending");return!n||n===e}else return!0}runNext(e){const t=Dc(e);return typeof t=="string"?this.#t.get(t)?.find(n=>n!==e&&n.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){An.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>Kv(t,n))}findAll(e={}){return this.getAll().filter(t=>Kv(e,t))}notify(e){An.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return An.batch(()=>Promise.all(e.map(t=>t.continue().catch(Gn))))}};function Dc(e){return e.options.scope?.id}var BR=class extends Kl{#e;constructor(e={}){super(),this.config=e,this.#e=new Map}build(e,t,n){const a=t.queryKey,o=t.queryHash??Th(a,t);let i=this.get(o);return i||(i=new DR({client:e,queryKey:a,queryHash:o,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(a)}),this.add(i)),i}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){An.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>Vv(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>Vv(e,n)):t}notify(e){An.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){An.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){An.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},FR=class{#e;#t;#n;#a;#r;#o;#i;#l;constructor(e={}){this.#e=e.queryCache||new BR,this.#t=e.mutationCache||new qR,this.#n=e.defaultOptions||{},this.#a=new Map,this.#r=new Map,this.#o=0}mount(){this.#o++,this.#o===1&&(this.#i=jh.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#l=Cd.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#o--,this.#o===0&&(this.#i?.(),this.#i=void 0,this.#l?.(),this.#l=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#e.build(this,t),a=n.state.data;return a===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(nn(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(a))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:n})=>[t,n.data])}setQueryData(e,t,n){const a=this.defaultQueryOptions({queryKey:e}),o=this.#e.get(a.queryHash)?.state.data,i=IR(t,o);if(i!==void 0)return this.#e.build(this,a).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return An.batch(()=>this.#e.findAll(e).map(({queryKey:a})=>[a,this.setQueryData(a,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;An.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return An.batch(()=>{const a=n.findAll(e),o=new Set(a);return a.forEach(i=>{i.reset()}),this.refetchQueries({type:"active",predicate:i=>o.has(i)},t)})}cancelQueries(e,t={}){const n={revert:!0,...t},a=An.batch(()=>this.#e.findAll(e).map(o=>o.cancel(n)));return Promise.all(a).then(Gn).catch(Gn)}invalidateQueries(e,t={}){return An.batch(()=>(this.#e.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},a=An.batch(()=>this.#e.findAll(e).filter(o=>!o.isDisabled()&&!o.isStatic()).map(o=>{let i=o.fetch(void 0,n);return n.throwOnError||(i=i.catch(Gn)),o.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(a).then(Gn)}async query(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t),a=n.isStaleByTime(nn(t.staleTime,n))?await n.fetch(t):n.state.data,o=t.select;return o?o(a):a}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t);return n.isStaleByTime(nn(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Gn).catch(Gn)}infiniteQuery(e){return e._type="infinite",this.query(e)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Gn).catch(Gn)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return Cd.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#a.set(wl(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#a.values()],n={};return t.forEach(a=>{ls(e,a.queryKey)&&Object.assign(n,a.defaultOptions)}),n}setMutationDefaults(e,t){this.#r.set(wl(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#r.values()],n={};return t.forEach(a=>{ls(e,a.mutationKey)&&Object.assign(n,a.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Th(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Eh&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}};const WS=v.createContext(!1),VR=()=>v.useContext(WS);WS.Provider;function KR(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}const WR=v.createContext(KR()),GR=()=>v.useContext(WR),ZR=(e,t,n)=>{const a=n?.state.error&&typeof e.throwOnError=="function"?zS(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||a)&&(t.isReset()||(e.retryOnMount=!1))},JR=e=>{v.useEffect(()=>{e.clearReset()},[e])},YR=({result:e,errorResetBoundary:t,throwOnError:n,query:a,suspense:o})=>e.isError&&!t.isReset()&&!e.isFetching&&a&&(o&&e.data===void 0||zS(n,[e.error,a])),QR=e=>{if(e.suspense){const n=o=>o==="static"?o:Math.max(o??1e3,1e3),a=e.staleTime;e.staleTime=typeof a=="function"?(...o)=>n(a(...o)):n(a),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},XR=(e,t)=>e?.suspense&&t.isPending,eP=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function tP(e,t,n){const a=VR(),o=GR(),i=NS(),s=i.defaultQueryOptions(e),l=i.getQueryCache().get(s.queryHash),m=e.subscribed!==!1;s._optimisticResults=a?"isRestoring":m?"optimistic":void 0,QR(s),ZR(s,o,l),JR(o);const[d]=v.useState(()=>new t(i,s)),h=d.getOptimisticResult(s),g=!a&&m;if(v.useSyncExternalStore(v.useCallback(y=>{const w=g?d.subscribe(An.batchCalls(y)):Gn;return d.updateResult(),w},[d,g]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),v.useEffect(()=>{d.setOptions(s)},[s,d]),XR(s,h))throw eP(s,d,o);if(YR({result:h,errorResetBoundary:o,throwOnError:s.throwOnError,query:l,suspense:s.suspense}))throw h.error;return s.notifyOnChangeProps?h:d.trackResult(h)}function nP(e,t){return tP(e,LR)}function aP(){return new FR({defaultOptions:{queries:{staleTime:6e4,gcTime:15*6e4,retry:1,refetchOnWindowFocus:!1}}})}var Xv;function ge(e,t,n){function a(l,m){if(l._zod||Object.defineProperty(l,"_zod",{value:{def:m,constr:s,traits:new Set},enumerable:!1}),l._zod.traits.has(e))return;l._zod.traits.add(e),t(l,m);const d=s.prototype,h=Object.keys(d);for(let g=0;g<h.length;g++){const y=h[g];y in l||(l[y]=d[y].bind(l))}}const o=n?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function s(l){var m;const d=n?.Parent?new i:this;a(d,l),(m=d._zod).deferred??(m.deferred=[]);for(const h of d._zod.deferred)h();return d}return Object.defineProperty(s,"init",{value:a}),Object.defineProperty(s,Symbol.hasInstance,{value:l=>n?.Parent&&l instanceof n.Parent?!0:l?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}class ns extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class GS extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(Xv=globalThis).__zod_globalConfig??(Xv.__zod_globalConfig={});const $h=globalThis.__zod_globalConfig;function Fo(e){return $h}function ZS(e){const t=Object.values(e).filter(a=>typeof a=="number");return Object.entries(e).filter(([a,o])=>t.indexOf(+a)===-1).map(([a,o])=>o)}function Rf(e,t){return typeof t=="bigint"?t.toString():t}function tu(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Nh(e){return e==null}function Dh(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function oP(e,t){const n=e/t,a=Math.round(n),o=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-a)<o?0:n-a}const eb=Symbol("evaluating");function _t(e,t,n){let a;Object.defineProperty(e,t,{get(){if(a!==eb)return a===void 0&&(a=eb,a=n()),a},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function ai(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Sr(...e){const t={};for(const n of e){const a=Object.getOwnPropertyDescriptors(n);Object.assign(t,a)}return Object.defineProperties({},t)}function tb(e){return JSON.stringify(e)}function rP(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const JS="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Il(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const iP=tu(()=>{if($h.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function cs(e){if(Il(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Il(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function YS(e){return cs(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const sP=new Set(["string","number","symbol"]);function ds(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function xr(e,t,n){const a=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(a._zod.parent=e),a}function et(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 lP(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const cP={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 dP(e,t){const n=e._zod.def,a=n.checks;if(a&&a.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const i=Sr(e._zod.def,{get shape(){const s={};for(const l in t){if(!(l in n.shape))throw new Error(`Unrecognized key: "${l}"`);t[l]&&(s[l]=n.shape[l])}return ai(this,"shape",s),s},checks:[]});return xr(e,i)}function uP(e,t){const n=e._zod.def,a=n.checks;if(a&&a.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const i=Sr(e._zod.def,{get shape(){const s={...e._zod.def.shape};for(const l in t){if(!(l in n.shape))throw new Error(`Unrecognized key: "${l}"`);t[l]&&delete s[l]}return ai(this,"shape",s),s},checks:[]});return xr(e,i)}function mP(e,t){if(!cs(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const i=e._zod.def.shape;for(const s in t)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const o=Sr(e._zod.def,{get shape(){const i={...e._zod.def.shape,...t};return ai(this,"shape",i),i}});return xr(e,o)}function pP(e,t){if(!cs(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Sr(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t};return ai(this,"shape",a),a}});return xr(e,n)}function fP(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=Sr(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t._zod.def.shape};return ai(this,"shape",a),a},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return xr(e,n)}function hP(e,t,n){const o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const s=Sr(t._zod.def,{get shape(){const l=t._zod.def.shape,m={...l};if(n)for(const d in n){if(!(d in l))throw new Error(`Unrecognized key: "${d}"`);n[d]&&(m[d]=e?new e({type:"optional",innerType:l[d]}):l[d])}else for(const d in l)m[d]=e?new e({type:"optional",innerType:l[d]}):l[d];return ai(this,"shape",m),m},checks:[]});return xr(t,s)}function gP(e,t,n){const a=Sr(t._zod.def,{get shape(){const o=t._zod.def.shape,i={...o};if(n)for(const s in n){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(i[s]=new e({type:"nonoptional",innerType:o[s]}))}else for(const s in o)i[s]=new e({type:"nonoptional",innerType:o[s]});return ai(this,"shape",i),i}});return xr(t,a)}function Bi(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 vP(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 Fi(e,t){return t.map(n=>{var a;return(a=n).path??(a.path=[]),n.path.unshift(e),n})}function Lc(e){return typeof e=="string"?e:e?.message}function Vo(e,t,n){const a=e.message?e.message:Lc(e.inst?._zod.def?.error?.(e))??Lc(t?.error?.(e))??Lc(n.customError?.(e))??Lc(n.localeError?.(e))??"Invalid input",{inst:o,continue:i,input:s,...l}=e;return l.path??(l.path=[]),l.message=a,t?.reportInput&&(l.input=s),l}function Lh(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function _l(...e){const[t,n,a]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:a}:{...t}}const QS=(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,Rf,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},XS=ge("$ZodError",QS),ex=ge("$ZodError",QS,{Parent:Error});function bP(e,t=n=>n.message){const n={},a=[];for(const o of e.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):a.push(t(o));return{formErrors:a,fieldErrors:n}}function yP(e,t=n=>n.message){const n={_errors:[]},a=(o,i=[])=>{for(const s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(l=>a({issues:l},[...i,...s.path]));else if(s.code==="invalid_key")a({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")a({issues:s.issues},[...i,...s.path]);else{const l=[...i,...s.path];if(l.length===0)n._errors.push(t(s));else{let m=n,d=0;for(;d<l.length;){const h=l[d];d===l.length-1?(m[h]=m[h]||{_errors:[]},m[h]._errors.push(t(s))):m[h]=m[h]||{_errors:[]},m=m[h],d++}}}};return a(e),n}const Uh=e=>(t,n,a,o)=>{const i=a?{...a,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw new ns;if(s.issues.length){const l=new(o?.Err??e)(s.issues.map(m=>Vo(m,i,Fo())));throw JS(l,o?.callee),l}return s.value},Hh=e=>async(t,n,a,o)=>{const i=a?{...a,async:!0}:{async:!0};let s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){const l=new(o?.Err??e)(s.issues.map(m=>Vo(m,i,Fo())));throw JS(l,o?.callee),l}return s.value},nu=e=>(t,n,a)=>{const o=a?{...a,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise)throw new ns;return i.issues.length?{success:!1,error:new(e??XS)(i.issues.map(s=>Vo(s,o,Fo())))}:{success:!0,data:i.value}},SP=nu(ex),au=e=>async(t,n,a)=>{const o=a?{...a,async:!0}:{async:!0};let i=t._zod.run({value:n,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(s=>Vo(s,o,Fo())))}:{success:!0,data:i.value}},xP=au(ex),kP=e=>(t,n,a)=>{const o=a?{...a,direction:"backward"}:{direction:"backward"};return Uh(e)(t,n,o)},wP=e=>(t,n,a)=>Uh(e)(t,n,a),IP=e=>async(t,n,a)=>{const o=a?{...a,direction:"backward"}:{direction:"backward"};return Hh(e)(t,n,o)},_P=e=>async(t,n,a)=>Hh(e)(t,n,a),CP=e=>(t,n,a)=>{const o=a?{...a,direction:"backward"}:{direction:"backward"};return nu(e)(t,n,o)},RP=e=>(t,n,a)=>nu(e)(t,n,a),PP=e=>async(t,n,a)=>{const o=a?{...a,direction:"backward"}:{direction:"backward"};return au(e)(t,n,o)},AP=e=>async(t,n,a)=>au(e)(t,n,a),TP=/^[cC][0-9a-z]{6,}$/,EP=/^[0-9a-z]+$/,MP=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,jP=/^[0-9a-vA-V]{20}$/,OP=/^[A-Za-z0-9]{27}$/,$P=/^[a-zA-Z0-9_-]{21}$/,NP=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,DP=/^([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})$/,nb=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)$/,LP=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,UP="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function HP(){return new RegExp(UP,"u")}const zP=/^(?:(?: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])$/,qP=/^(([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}|:))$/,BP=/^((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])$/,FP=/^(([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])$/,VP=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,tx=/^[A-Za-z0-9_-]*$/,KP=/^https?$/,WP=/^\+[1-9]\d{6,14}$/,nx="(?:(?:\\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])))",GP=new RegExp(`^${nx}$`);function ax(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 ZP(e){return new RegExp(`^${ax(e)}$`)}function JP(e){const t=ax({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(`^${nx}T(?:${a})$`)}const YP=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},QP=/^-?\d+$/,ox=/^-?\d+(?:\.\d+)?$/,XP=/^(?:true|false)$/i,eA=/^null$/i,tA=/^[^A-Z]*$/,nA=/^[^a-z]*$/,Xn=ge("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),rx={number:"number",bigint:"bigint",object:"date"},ix=ge("$ZodCheckLessThan",(e,t)=>{Xn.init(e,t);const n=rx[typeof t.value];e._zod.onattach.push(a=>{const o=a._zod.bag,i=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=a=>{(t.inclusive?a.value<=t.value:a.value<t.value)||a.issues.push({origin:n,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:a.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),sx=ge("$ZodCheckGreaterThan",(e,t)=>{Xn.init(e,t);const n=rx[typeof t.value];e._zod.onattach.push(a=>{const o=a._zod.bag,i=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=a=>{(t.inclusive?a.value>=t.value:a.value>t.value)||a.issues.push({origin:n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:a.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),aA=ge("$ZodCheckMultipleOf",(e,t)=>{Xn.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):oP(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})}}),oA=ge("$ZodCheckNumberFormat",(e,t)=>{Xn.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),a=n?"int":"number",[o,i]=cP[t.format];e._zod.onattach.push(s=>{const l=s._zod.bag;l.format=t.format,l.minimum=o,l.maximum=i,n&&(l.pattern=QP)}),e._zod.check=s=>{const l=s.value;if(n){if(!Number.isInteger(l)){s.issues.push({expected:a,format:t.format,code:"invalid_type",continue:!1,input:l,inst:e});return}if(!Number.isSafeInteger(l)){l>0?s.issues.push({input:l,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:a,inclusive:!0,continue:!t.abort}):s.issues.push({input:l,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:a,inclusive:!0,continue:!t.abort});return}}l<o&&s.issues.push({origin:"number",input:l,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),l>i&&s.issues.push({origin:"number",input:l,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),rA=ge("$ZodCheckMaxLength",(e,t)=>{var n;Xn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const o=a.value;return!Nh(o)&&o.length!==void 0}),e._zod.onattach.push(a=>{const o=a._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(a._zod.bag.maximum=t.maximum)}),e._zod.check=a=>{const o=a.value;if(o.length<=t.maximum)return;const s=Lh(o);a.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),iA=ge("$ZodCheckMinLength",(e,t)=>{var n;Xn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const o=a.value;return!Nh(o)&&o.length!==void 0}),e._zod.onattach.push(a=>{const o=a._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(a._zod.bag.minimum=t.minimum)}),e._zod.check=a=>{const o=a.value;if(o.length>=t.minimum)return;const s=Lh(o);a.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),sA=ge("$ZodCheckLengthEquals",(e,t)=>{var n;Xn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const o=a.value;return!Nh(o)&&o.length!==void 0}),e._zod.onattach.push(a=>{const o=a._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=a=>{const o=a.value,i=o.length;if(i===t.length)return;const s=Lh(o),l=i>t.length;a.issues.push({origin:s,...l?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:a.value,inst:e,continue:!t.abort})}}),ou=ge("$ZodCheckStringFormat",(e,t)=>{var n,a;Xn.init(e,t),e._zod.onattach.push(o=>{const i=o._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(a=e._zod).check??(a.check=()=>{})}),lA=ge("$ZodCheckRegex",(e,t)=>{ou.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})}}),cA=ge("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=tA),ou.init(e,t)}),dA=ge("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=nA),ou.init(e,t)}),uA=ge("$ZodCheckIncludes",(e,t)=>{Xn.init(e,t);const n=ds(t.includes),a=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=a,e._zod.onattach.push(o=>{const i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(a)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),mA=ge("$ZodCheckStartsWith",(e,t)=>{Xn.init(e,t);const n=new RegExp(`^${ds(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(a=>{const o=a._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=a=>{a.value.startsWith(t.prefix)||a.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:a.value,inst:e,continue:!t.abort})}}),pA=ge("$ZodCheckEndsWith",(e,t)=>{Xn.init(e,t);const n=new RegExp(`.*${ds(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(a=>{const o=a._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=a=>{a.value.endsWith(t.suffix)||a.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:a.value,inst:e,continue:!t.abort})}}),fA=ge("$ZodCheckOverwrite",(e,t)=>{Xn.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class hA{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const a=t.split(`
|
|
3
|
-
`).filter(s=>s),o=Math.min(...a.map(s=>s.length-s.trimStart().length)),i=a.map(s=>s.slice(o)).map(s=>" ".repeat(this.indent*2)+s);for(const s of i)this.content.push(s)}compile(){const t=Function,n=this?.args,o=[...(this?.content??[""]).map(i=>` ${i}`)];return new t(...n,o.join(`
|
|
4
|
-
`))}}const gA={major:4,minor:4,patch:3},Gt=ge("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=gA;const a=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&a.unshift(e);for(const o of a)for(const i of o._zod.onattach)i(e);if(a.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=(s,l,m)=>{let d=Bi(s),h;for(const g of l){if(g._zod.def.when){if(vP(s)||!g._zod.def.when(s))continue}else if(d)continue;const y=s.issues.length,w=g._zod.check(s);if(w instanceof Promise&&m?.async===!1)throw new ns;if(h||w instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await w,s.issues.length!==y&&(d||(d=Bi(s,y)))});else{if(s.issues.length===y)continue;d||(d=Bi(s,y))}}return h?h.then(()=>s):s},i=(s,l,m)=>{if(Bi(s))return s.aborted=!0,s;const d=o(l,a,m);if(d instanceof Promise){if(m.async===!1)throw new ns;return d.then(h=>e._zod.parse(h,m))}return e._zod.parse(d,m)};e._zod.run=(s,l)=>{if(l.skipChecks)return e._zod.parse(s,l);if(l.direction==="backward"){const d=e._zod.parse({value:s.value,issues:[]},{...l,skipChecks:!0});return d instanceof Promise?d.then(h=>i(h,s,l)):i(d,s,l)}const m=e._zod.parse(s,l);if(m instanceof Promise){if(l.async===!1)throw new ns;return m.then(d=>o(d,a,l))}return o(m,a,l)}}_t(e,"~standard",()=>({validate:o=>{try{const i=SP(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return xP(e,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),zh=ge("$ZodString",(e,t)=>{Gt.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??YP(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}}),Yt=ge("$ZodStringFormat",(e,t)=>{ou.init(e,t),zh.init(e,t)}),vA=ge("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=DP),Yt.init(e,t)}),bA=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=nb(a))}else t.pattern??(t.pattern=nb());Yt.init(e,t)}),yA=ge("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=LP),Yt.init(e,t)}),SA=ge("$ZodURL",(e,t)=>{Yt.init(e,t),e._zod.check=n=>{try{const a=n.value.trim();if(!t.normalize&&t.protocol?.source===KP.source&&!/^https?:\/\//i.test(a)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}const o=new URL(a);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=o.href:n.value=a;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),xA=ge("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=HP()),Yt.init(e,t)}),kA=ge("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=$P),Yt.init(e,t)}),wA=ge("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=TP),Yt.init(e,t)}),IA=ge("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=EP),Yt.init(e,t)}),_A=ge("$ZodULID",(e,t)=>{t.pattern??(t.pattern=MP),Yt.init(e,t)}),CA=ge("$ZodXID",(e,t)=>{t.pattern??(t.pattern=jP),Yt.init(e,t)}),RA=ge("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=OP),Yt.init(e,t)}),PA=ge("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=JP(t)),Yt.init(e,t)}),AA=ge("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=GP),Yt.init(e,t)}),TA=ge("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=ZP(t)),Yt.init(e,t)}),EA=ge("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=NP),Yt.init(e,t)}),MA=ge("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=zP),Yt.init(e,t),e._zod.bag.format="ipv4"}),jA=ge("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=qP),Yt.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})}}}),OA=ge("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=BP),Yt.init(e,t)}),$A=ge("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=FP),Yt.init(e,t),e._zod.check=n=>{const a=n.value.split("/");try{if(a.length!==2)throw new Error;const[o,i]=a;if(!i)throw new Error;const s=Number(i);if(`${s}`!==i)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${o}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function lx(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const NA=ge("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=VP),Yt.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{lx(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function DA(e){if(!tx.test(e))return!1;const t=e.replace(/[-_]/g,a=>a==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return lx(n)}const LA=ge("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=tx),Yt.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{DA(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),UA=ge("$ZodE164",(e,t)=>{t.pattern??(t.pattern=WP),Yt.init(e,t)});function HA(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[a]=n;if(!a)return!1;const o=JSON.parse(atob(a));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}const zA=ge("$ZodJWT",(e,t)=>{Yt.init(e,t),e._zod.check=n=>{HA(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),cx=ge("$ZodNumber",(e,t)=>{Gt.init(e,t),e._zod.pattern=e._zod.bag.pattern??ox,e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;const i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),n}}),qA=ge("$ZodNumberFormat",(e,t)=>{oA.init(e,t),cx.init(e,t)}),BA=ge("$ZodBoolean",(e,t)=>{Gt.init(e,t),e._zod.pattern=XP,e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=!!n.value}catch{}const o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}}),FA=ge("$ZodNull",(e,t)=>{Gt.init(e,t),e._zod.pattern=eA,e._zod.values=new Set([null]),e._zod.parse=(n,a)=>{const o=n.value;return o===null||n.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),n}}),VA=ge("$ZodUnknown",(e,t)=>{Gt.init(e,t),e._zod.parse=n=>n}),KA=ge("$ZodNever",(e,t)=>{Gt.init(e,t),e._zod.parse=(n,a)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function ab(e,t,n){e.issues.length&&t.issues.push(...Fi(n,e.issues)),t.value[n]=e.value}const WA=ge("$ZodArray",(e,t)=>{Gt.init(e,t),e._zod.parse=(n,a)=>{const o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);const i=[];for(let s=0;s<o.length;s++){const l=o[s],m=t.element._zod.run({value:l,issues:[]},a);m instanceof Promise?i.push(m.then(d=>ab(d,n,s))):ab(m,n,s)}return i.length?Promise.all(i).then(()=>n):n}});function Rd(e,t,n,a,o,i){const s=n in a;if(e.issues.length){if(o&&i&&!s)return;t.issues.push(...Fi(n,e.issues))}if(!s&&!o){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?s&&(t.value[n]=void 0):t.value[n]=e.value}function dx(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=lP(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function ux(e,t,n,a,o,i){const s=[],l=o.keySet,m=o.catchall._zod,d=m.def.type,h=m.optin==="optional",g=m.optout==="optional";for(const y in t){if(y==="__proto__"||l.has(y))continue;if(d==="never"){s.push(y);continue}const w=m.run({value:t[y],issues:[]},a);w instanceof Promise?e.push(w.then(_=>Rd(_,n,y,t,h,g))):Rd(w,n,y,t,h,g)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i}),e.length?Promise.all(e).then(()=>n):n}const GA=ge("$ZodObject",(e,t)=>{if(Gt.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const l=t.shape;Object.defineProperty(t,"shape",{get:()=>{const m={...l};return Object.defineProperty(t,"shape",{value:m}),m}})}const a=tu(()=>dx(t));_t(e._zod,"propValues",()=>{const l=t.shape,m={};for(const d in l){const h=l[d]._zod;if(h.values){m[d]??(m[d]=new Set);for(const g of h.values)m[d].add(g)}}return m});const o=Il,i=t.catchall;let s;e._zod.parse=(l,m)=>{s??(s=a.value);const d=l.value;if(!o(d))return l.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),l;l.value={};const h=[],g=s.shape;for(const y of s.keys){const w=g[y],_=w._zod.optin==="optional",P=w._zod.optout==="optional",M=w._zod.run({value:d[y],issues:[]},m);M instanceof Promise?h.push(M.then(C=>Rd(C,l,y,d,_,P))):Rd(M,l,y,d,_,P)}return i?ux(h,d,l,m,a.value,e):h.length?Promise.all(h).then(()=>l):l}}),ZA=ge("$ZodObjectJIT",(e,t)=>{GA.init(e,t);const n=e._zod.parse,a=tu(()=>dx(t)),o=y=>{const w=new hA(["shape","payload","ctx"]),_=a.value,P=$=>{const j=tb($);return`shape[${j}]._zod.run({ value: input[${j}], issues: [] }, ctx)`};w.write("const input = payload.value;");const M=Object.create(null);let C=0;for(const $ of _.keys)M[$]=`key_${C++}`;w.write("const newResult = {};");for(const $ of _.keys){const j=M[$],x=tb($),R=y[$],E=R?._zod?.optin==="optional",U=R?._zod?.optout==="optional";w.write(`const ${j} = ${P($)};`),E&&U?w.write(`
|
|
5
|
-
if (${j}.issues.length) {
|
|
6
|
-
if (${x} in input) {
|
|
7
|
-
payload.issues = payload.issues.concat(${j}.issues.map(iss => ({
|
|
8
|
-
...iss,
|
|
9
|
-
path: iss.path ? [${x}, ...iss.path] : [${x}]
|
|
10
|
-
})));
|
|
11
|
-
}
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
if (${j}.value === undefined) {
|
|
15
|
-
if (${x} in input) {
|
|
16
|
-
newResult[${x}] = undefined;
|
|
17
|
-
}
|
|
18
|
-
} else {
|
|
19
|
-
newResult[${x}] = ${j}.value;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
`):E?w.write(`
|
|
23
|
-
if (${j}.issues.length) {
|
|
24
|
-
payload.issues = payload.issues.concat(${j}.issues.map(iss => ({
|
|
25
|
-
...iss,
|
|
26
|
-
path: iss.path ? [${x}, ...iss.path] : [${x}]
|
|
27
|
-
})));
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
if (${j}.value === undefined) {
|
|
31
|
-
if (${x} in input) {
|
|
32
|
-
newResult[${x}] = undefined;
|
|
33
|
-
}
|
|
34
|
-
} else {
|
|
35
|
-
newResult[${x}] = ${j}.value;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
`):w.write(`
|
|
39
|
-
const ${j}_present = ${x} in input;
|
|
40
|
-
if (${j}.issues.length) {
|
|
41
|
-
payload.issues = payload.issues.concat(${j}.issues.map(iss => ({
|
|
42
|
-
...iss,
|
|
43
|
-
path: iss.path ? [${x}, ...iss.path] : [${x}]
|
|
44
|
-
})));
|
|
45
|
-
}
|
|
46
|
-
if (!${j}_present && !${j}.issues.length) {
|
|
47
|
-
payload.issues.push({
|
|
48
|
-
code: "invalid_type",
|
|
49
|
-
expected: "nonoptional",
|
|
50
|
-
input: undefined,
|
|
51
|
-
path: [${x}]
|
|
52
|
-
});
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
if (${j}_present) {
|
|
56
|
-
if (${j}.value === undefined) {
|
|
57
|
-
newResult[${x}] = undefined;
|
|
58
|
-
} else {
|
|
59
|
-
newResult[${x}] = ${j}.value;
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
`)}w.write("payload.value = newResult;"),w.write("return payload;");const N=w.compile();return($,j)=>N(y,$,j)};let i;const s=Il,l=!$h.jitless,d=l&&iP.value,h=t.catchall;let g;e._zod.parse=(y,w)=>{g??(g=a.value);const _=y.value;return s(_)?l&&d&&w?.async===!1&&w.jitless!==!0?(i||(i=o(t.shape)),y=i(y,w),h?ux([],_,y,w,g,e):y):n(y,w):(y.issues.push({expected:"object",code:"invalid_type",input:_,inst:e}),y)}});function ob(e,t,n,a){for(const i of e)if(i.issues.length===0)return t.value=i.value,t;const o=e.filter(i=>!Bi(i));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(i=>i.issues.map(s=>Vo(s,a,Fo())))}),t)}const mx=ge("$ZodUnion",(e,t)=>{Gt.init(e,t),_t(e._zod,"optin",()=>t.options.some(a=>a._zod.optin==="optional")?"optional":void 0),_t(e._zod,"optout",()=>t.options.some(a=>a._zod.optout==="optional")?"optional":void 0),_t(e._zod,"values",()=>{if(t.options.every(a=>a._zod.values))return new Set(t.options.flatMap(a=>Array.from(a._zod.values)))}),_t(e._zod,"pattern",()=>{if(t.options.every(a=>a._zod.pattern)){const a=t.options.map(o=>o._zod.pattern);return new RegExp(`^(${a.map(o=>Dh(o.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(a,o)=>{if(n)return n(a,o);let i=!1;const s=[];for(const l of t.options){const m=l._zod.run({value:a.value,issues:[]},o);if(m instanceof Promise)s.push(m),i=!0;else{if(m.issues.length===0)return m;s.push(m)}}return i?Promise.all(s).then(l=>ob(l,a,e,o)):ob(s,a,e,o)}}),JA=ge("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,mx.init(e,t);const n=e._zod.parse;_t(e._zod,"propValues",()=>{const o={};for(const i of t.options){const s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(const[l,m]of Object.entries(s)){o[l]||(o[l]=new Set);for(const d of m)o[l].add(d)}}return o});const a=tu(()=>{const o=t.options,i=new Map;for(const s of o){const l=s._zod.propValues?.[t.discriminator];if(!l||l.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const m of l){if(i.has(m))throw new Error(`Duplicate discriminator value "${String(m)}"`);i.set(m,s)}}return i});e._zod.parse=(o,i)=>{const s=o.value;if(!Il(s))return o.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),o;const l=a.value.get(s?.[t.discriminator]);return l?l._zod.run(o,i):t.unionFallback||i.direction==="backward"?n(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(a.value.keys()),input:s,path:[t.discriminator],inst:e}),o)}}),YA=ge("$ZodIntersection",(e,t)=>{Gt.init(e,t),e._zod.parse=(n,a)=>{const o=n.value,i=t.left._zod.run({value:o,issues:[]},a),s=t.right._zod.run({value:o,issues:[]},a);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([m,d])=>rb(n,m,d)):rb(n,i,s)}});function Pf(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(cs(e)&&cs(t)){const n=Object.keys(t),a=Object.keys(e).filter(i=>n.indexOf(i)!==-1),o={...e,...t};for(const i of a){const s=Pf(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};o[i]=s.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let a=0;a<e.length;a++){const o=e[a],i=t[a],s=Pf(o,i);if(!s.valid)return{valid:!1,mergeErrorPath:[a,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function rb(e,t,n){const a=new Map;let o;for(const l of t.issues)if(l.code==="unrecognized_keys"){o??(o=l);for(const m of l.keys)a.has(m)||a.set(m,{}),a.get(m).l=!0}else e.issues.push(l);for(const l of n.issues)if(l.code==="unrecognized_keys")for(const m of l.keys)a.has(m)||a.set(m,{}),a.get(m).r=!0;else e.issues.push(l);const i=[...a].filter(([,l])=>l.l&&l.r).map(([l])=>l);if(i.length&&o&&e.issues.push({...o,keys:i}),Bi(e))return e;const s=Pf(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 QA=ge("$ZodRecord",(e,t)=>{Gt.init(e,t),e._zod.parse=(n,a)=>{const o=n.value;if(!cs(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;const i=[],s=t.keyType._zod.values;if(s){n.value={};const l=new Set;for(const d of s)if(typeof d=="string"||typeof d=="number"||typeof d=="symbol"){l.add(typeof d=="number"?d.toString():d);const h=t.keyType._zod.run({value:d,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=>Vo(w,a,Fo())),input:d,path:[d],inst:e});continue}const g=h.value,y=t.valueType._zod.run({value:o[d],issues:[]},a);y instanceof Promise?i.push(y.then(w=>{w.issues.length&&n.issues.push(...Fi(d,w.issues)),n.value[g]=w.value})):(y.issues.length&&n.issues.push(...Fi(d,y.issues)),n.value[g]=y.value)}let m;for(const d in o)l.has(d)||(m=m??[],m.push(d));m&&m.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:m})}else{n.value={};for(const l of Reflect.ownKeys(o)){if(l==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,l))continue;let m=t.keyType._zod.run({value:l,issues:[]},a);if(m instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof l=="string"&&ox.test(l)&&m.issues.length){const g=t.keyType._zod.run({value:Number(l),issues:[]},a);if(g instanceof Promise)throw new Error("Async schemas not supported in object keys currently");g.issues.length===0&&(m=g)}if(m.issues.length){t.mode==="loose"?n.value[l]=o[l]:n.issues.push({code:"invalid_key",origin:"record",issues:m.issues.map(g=>Vo(g,a,Fo())),input:l,path:[l],inst:e});continue}const h=t.valueType._zod.run({value:o[l],issues:[]},a);h instanceof Promise?i.push(h.then(g=>{g.issues.length&&n.issues.push(...Fi(l,g.issues)),n.value[m.value]=g.value})):(h.issues.length&&n.issues.push(...Fi(l,h.issues)),n.value[m.value]=h.value)}}return i.length?Promise.all(i).then(()=>n):n}}),XA=ge("$ZodEnum",(e,t)=>{Gt.init(e,t);const n=ZS(t.entries),a=new Set(n);e._zod.values=a,e._zod.pattern=new RegExp(`^(${n.filter(o=>sP.has(typeof o)).map(o=>typeof o=="string"?ds(o):o.toString()).join("|")})$`),e._zod.parse=(o,i)=>{const s=o.value;return a.has(s)||o.issues.push({code:"invalid_value",values:n,input:s,inst:e}),o}}),eT=ge("$ZodLiteral",(e,t)=>{if(Gt.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"?ds(a):a?ds(a.toString()):String(a)).join("|")})$`),e._zod.parse=(a,o)=>{const i=a.value;return n.has(i)||a.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),a}}),tT=ge("$ZodTransform",(e,t)=>{Gt.init(e,t),e._zod.optin="optional",e._zod.parse=(n,a)=>{if(a.direction==="backward")throw new GS(e.constructor.name);const o=t.transform(n.value,n);if(a.async)return(o instanceof Promise?o:Promise.resolve(o)).then(s=>(n.value=s,n.fallback=!0,n));if(o instanceof Promise)throw new ns;return n.value=o,n.fallback=!0,n}});function ib(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const px=ge("$ZodOptional",(e,t)=>{Gt.init(e,t),e._zod.optin="optional",e._zod.optout="optional",_t(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),_t(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Dh(n.source)})?$`):void 0}),e._zod.parse=(n,a)=>{if(t.innerType._zod.optin==="optional"){const o=n.value,i=t.innerType._zod.run(n,a);return i instanceof Promise?i.then(s=>ib(s,o)):ib(i,o)}return n.value===void 0?n:t.innerType._zod.run(n,a)}}),nT=ge("$ZodExactOptional",(e,t)=>{px.init(e,t),_t(e._zod,"values",()=>t.innerType._zod.values),_t(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,a)=>t.innerType._zod.run(n,a)}),aT=ge("$ZodNullable",(e,t)=>{Gt.init(e,t),_t(e._zod,"optin",()=>t.innerType._zod.optin),_t(e._zod,"optout",()=>t.innerType._zod.optout),_t(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Dh(n.source)}|null)$`):void 0}),_t(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)}),oT=ge("$ZodDefault",(e,t)=>{Gt.init(e,t),e._zod.optin="optional",_t(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,a)=>{if(a.direction==="backward")return t.innerType._zod.run(n,a);if(n.value===void 0)return n.value=t.defaultValue,n;const o=t.innerType._zod.run(n,a);return o instanceof Promise?o.then(i=>sb(i,t)):sb(o,t)}});function sb(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const rT=ge("$ZodPrefault",(e,t)=>{Gt.init(e,t),e._zod.optin="optional",_t(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))}),iT=ge("$ZodNonOptional",(e,t)=>{Gt.init(e,t),_t(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(a=>a!==void 0)):void 0}),e._zod.parse=(n,a)=>{const o=t.innerType._zod.run(n,a);return o instanceof Promise?o.then(i=>lb(i,e)):lb(o,e)}});function lb(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 sT=ge("$ZodCatch",(e,t)=>{Gt.init(e,t),e._zod.optin="optional",_t(e._zod,"optout",()=>t.innerType._zod.optout),_t(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,a)=>{if(a.direction==="backward")return t.innerType._zod.run(n,a);const o=t.innerType._zod.run(n,a);return o instanceof Promise?o.then(i=>(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(s=>Vo(s,a,Fo()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=o.value,o.issues.length&&(n.value=t.catchValue({...n,error:{issues:o.issues.map(i=>Vo(i,a,Fo()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),fx=ge("$ZodPipe",(e,t)=>{Gt.init(e,t),_t(e._zod,"values",()=>t.in._zod.values),_t(e._zod,"optin",()=>t.in._zod.optin),_t(e._zod,"optout",()=>t.out._zod.optout),_t(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,a)=>{if(a.direction==="backward"){const i=t.out._zod.run(n,a);return i instanceof Promise?i.then(s=>Uc(s,t.in,a)):Uc(i,t.in,a)}const o=t.in._zod.run(n,a);return o instanceof Promise?o.then(i=>Uc(i,t.out,a)):Uc(o,t.out,a)}});function Uc(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 lT=ge("$ZodPreprocess",(e,t)=>{fx.init(e,t)}),cT=ge("$ZodReadonly",(e,t)=>{Gt.init(e,t),_t(e._zod,"propValues",()=>t.innerType._zod.propValues),_t(e._zod,"values",()=>t.innerType._zod.values),_t(e._zod,"optin",()=>t.innerType?._zod?.optin),_t(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,a)=>{if(a.direction==="backward")return t.innerType._zod.run(n,a);const o=t.innerType._zod.run(n,a);return o instanceof Promise?o.then(cb):cb(o)}});function cb(e){return e.value=Object.freeze(e.value),e}const dT=ge("$ZodLazy",(e,t)=>{Gt.init(e,t),_t(e._zod,"innerType",()=>{const n=t;return n._cachedInner||(n._cachedInner=t.getter()),n._cachedInner}),_t(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),_t(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),_t(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),_t(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(n,a)=>e._zod.innerType._zod.run(n,a)}),uT=ge("$ZodCustom",(e,t)=>{Xn.init(e,t),Gt.init(e,t),e._zod.parse=(n,a)=>n,e._zod.check=n=>{const a=n.value,o=t.fn(a);if(o instanceof Promise)return o.then(i=>db(i,n,a,e));db(o,n,a,e)}});function db(e,t,n,a){if(!e){const o={code:"custom",input:n,inst:a,path:[...a._zod.def.path??[]],continue:!a._zod.def.abort};a._zod.def.params&&(o.params=a._zod.def.params),t.issues.push(_l(o))}}var ub;class mT{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const a=n[0];return this._map.set(t,a),a&&typeof a=="object"&&"id"in a&&this._idmap.set(a.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const a={...this.get(n)??{}};delete a.id;const o={...a,...this._map.get(t)};return Object.keys(o).length?o:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function pT(){return new mT}(ub=globalThis).__zod_globalRegistry??(ub.__zod_globalRegistry=pT());const cl=globalThis.__zod_globalRegistry;function fT(e,t){return new e({type:"string",...et(t)})}function hT(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...et(t)})}function mb(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...et(t)})}function gT(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...et(t)})}function vT(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...et(t)})}function bT(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...et(t)})}function yT(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...et(t)})}function ST(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...et(t)})}function xT(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...et(t)})}function kT(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...et(t)})}function wT(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...et(t)})}function IT(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...et(t)})}function _T(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...et(t)})}function CT(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...et(t)})}function RT(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...et(t)})}function PT(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...et(t)})}function AT(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...et(t)})}function TT(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...et(t)})}function ET(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...et(t)})}function MT(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...et(t)})}function jT(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...et(t)})}function OT(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...et(t)})}function $T(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...et(t)})}function NT(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...et(t)})}function DT(e,t){return new e({type:"string",format:"date",check:"string_format",...et(t)})}function LT(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...et(t)})}function UT(e,t){return new e({type:"string",format:"duration",check:"string_format",...et(t)})}function HT(e,t){return new e({type:"number",checks:[],...et(t)})}function jY(e,t){return new e({type:"number",coerce:!0,checks:[],...et(t)})}function zT(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...et(t)})}function qT(e,t){return new e({type:"boolean",...et(t)})}function BT(e,t){return new e({type:"null",...et(t)})}function FT(e){return new e({type:"unknown"})}function VT(e,t){return new e({type:"never",...et(t)})}function pb(e,t){return new ix({check:"less_than",...et(t),value:e,inclusive:!1})}function ip(e,t){return new ix({check:"less_than",...et(t),value:e,inclusive:!0})}function fb(e,t){return new sx({check:"greater_than",...et(t),value:e,inclusive:!1})}function sp(e,t){return new sx({check:"greater_than",...et(t),value:e,inclusive:!0})}function hb(e,t){return new aA({check:"multiple_of",...et(t),value:e})}function hx(e,t){return new rA({check:"max_length",...et(t),maximum:e})}function Pd(e,t){return new iA({check:"min_length",...et(t),minimum:e})}function gx(e,t){return new sA({check:"length_equals",...et(t),length:e})}function KT(e,t){return new lA({check:"string_format",format:"regex",...et(t),pattern:e})}function WT(e){return new cA({check:"string_format",format:"lowercase",...et(e)})}function GT(e){return new dA({check:"string_format",format:"uppercase",...et(e)})}function ZT(e,t){return new uA({check:"string_format",format:"includes",...et(t),includes:e})}function JT(e,t){return new mA({check:"string_format",format:"starts_with",...et(t),prefix:e})}function YT(e,t){return new pA({check:"string_format",format:"ends_with",...et(t),suffix:e})}function ks(e){return new fA({check:"overwrite",tx:e})}function QT(e){return ks(t=>t.normalize(e))}function XT(){return ks(e=>e.trim())}function eE(){return ks(e=>e.toLowerCase())}function tE(){return ks(e=>e.toUpperCase())}function nE(){return ks(e=>rP(e))}function aE(e,t,n){return new e({type:"array",element:t,...et(n)})}function oE(e,t,n){const a=et(n);return a.abort??(a.abort=!0),new e({type:"custom",check:"custom",fn:t,...a})}function rE(e,t,n){return new e({type:"custom",check:"custom",fn:t,...et(n)})}function iE(e,t){const n=sE(a=>(a.addIssue=o=>{if(typeof o=="string")a.issues.push(_l(o,a.value,n._zod.def));else{const i=o;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=a.value),i.inst??(i.inst=n),i.continue??(i.continue=!n._zod.def.abort),a.issues.push(_l(i))}},e(a.value,a)),t);return n}function sE(e,t){const n=new Xn({check:"custom",...et(t)});return n._zod.check=e,n}function vx(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??cl,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 ln(e,t,n={path:[],schemaPath:[]}){var a;const o=e._zod.def,i=t.seen.get(e);if(i)return i.count++,n.schemaPath.includes(e)&&(i.cycle=n.path),i.schema;const s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s);const l=e._zod.toJSONSchema?.();if(l)s.schema=l;else{const 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[o.type];if(!w)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);w(e,t,y,h)}const g=e._zod.parent;g&&(s.ref||(s.ref=g),ln(g,t,h),t.seen.get(g).isParent=!0)}const m=t.metadataRegistry.get(e);return m&&Object.assign(s.schema,m),t.io==="input"&&Un(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 bx(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const a=new Map;for(const s of e.seen.entries()){const l=e.metadataRegistry.get(s[0])?.id;if(l){const m=a.get(l);if(m&&m!==s[0])throw new Error(`Duplicate schema id "${l}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);a.set(l,s[0])}}const o=s=>{const l=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const g=e.external.registry.get(s[0])?.id,y=e.external.uri??(_=>_);if(g)return{ref:y(g)};const w=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=w,{defId:w,ref:`${y("__shared")}#/${l}/${w}`}}if(s[1]===n)return{ref:"#"};const d=`#/${l}/`,h=s[1].schema.id??`__schema${e.counter++}`;return{defId:h,ref:d+h}},i=s=>{if(s[1].schema.$ref)return;const l=s[1],{ref:m,defId:d}=o(s);l.def={...l.schema},d&&(l.defId=d);const h=l.schema;for(const g in h)delete h[g];h.$ref=m};if(e.cycles==="throw")for(const s of e.seen.entries()){const l=s[1];if(l.cycle)throw new Error(`Cycle detected: #/${l.cycle?.join("/")}/<root>
|
|
64
|
-
|
|
65
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const s of e.seen.entries()){const l=s[1];if(t===s[0]){i(s);continue}if(e.external){const d=e.external.registry.get(s[0])?.id;if(t!==s[0]&&d){i(s);continue}}if(e.metadataRegistry.get(s[0])?.id){i(s);continue}if(l.cycle){i(s);continue}if(l.count>1&&e.reused==="ref"){i(s);continue}}}function yx(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const a=l=>{const m=e.seen.get(l);if(m.ref===null)return;const d=m.def??m.schema,h={...d},g=m.ref;if(m.ref=null,g){a(g);const w=e.seen.get(g),_=w.schema;if(_.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(d.allOf=d.allOf??[],d.allOf.push(_)):Object.assign(d,_),Object.assign(d,h),l._zod.parent===g)for(const M in d)M==="$ref"||M==="allOf"||M in h||delete d[M];if(_.$ref&&w.def)for(const M in d)M==="$ref"||M==="allOf"||M in w.def&&JSON.stringify(d[M])===JSON.stringify(w.def[M])&&delete d[M]}const y=l._zod.parent;if(y&&y!==g){a(y);const w=e.seen.get(y);if(w?.schema.$ref&&(d.$ref=w.schema.$ref,w.def))for(const _ in d)_==="$ref"||_==="allOf"||_ in w.def&&JSON.stringify(d[_])===JSON.stringify(w.def[_])&&delete d[_]}e.override({zodSchema:l,jsonSchema:d,path:m.path??[]})};for(const l of[...e.seen.entries()].reverse())a(l[0]);const o={};if(e.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const l=e.external.registry.get(t)?.id;if(!l)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(l)}Object.assign(o,n.def??n.schema);const i=e.metadataRegistry.get(t)?.id;i!==void 0&&o.id===i&&delete o.id;const s=e.external?.defs??{};for(const l of e.seen.entries()){const m=l[1];m.def&&m.defId&&(m.def.id===m.defId&&delete m.def.id,s[m.defId]=m.def)}e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?o.$defs=s:o.definitions=s);try{const l=JSON.parse(JSON.stringify(o));return Object.defineProperty(l,"~standard",{value:{...t["~standard"],jsonSchema:{input:Ad(t,"input",e.processors),output:Ad(t,"output",e.processors)}},enumerable:!1,writable:!1}),l}catch{throw new Error("Error converting schema to JSON.")}}function Un(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 Un(a.element,n);if(a.type==="set")return Un(a.valueType,n);if(a.type==="lazy")return Un(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 Un(a.innerType,n);if(a.type==="intersection")return Un(a.left,n)||Un(a.right,n);if(a.type==="record"||a.type==="map")return Un(a.keyType,n)||Un(a.valueType,n);if(a.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:Un(a.in,n)||Un(a.out,n);if(a.type==="object"){for(const o in a.shape)if(Un(a.shape[o],n))return!0;return!1}if(a.type==="union"){for(const o of a.options)if(Un(o,n))return!0;return!1}if(a.type==="tuple"){for(const o of a.items)if(Un(o,n))return!0;return!!(a.rest&&Un(a.rest,n))}return!1}const lE=(e,t={})=>n=>{const a=vx({...n,processors:t});return ln(e,a),bx(a,e),yx(a,e)},Ad=(e,t,n={})=>a=>{const{libraryOptions:o,target:i}=a??{},s=vx({...o??{},target:i,io:t,processors:n});return ln(e,s),bx(s,e),yx(s,e)},cE={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},dE=(e,t,n,a)=>{const o=n;o.type="string";const{minimum:i,maximum:s,format:l,patterns:m,contentEncoding:d}=e._zod.bag;if(typeof i=="number"&&(o.minLength=i),typeof s=="number"&&(o.maxLength=s),l&&(o.format=cE[l]??l,o.format===""&&delete o.format,l==="time"&&delete o.format),d&&(o.contentEncoding=d),m&&m.size>0){const h=[...m];h.length===1?o.pattern=h[0].source:h.length>1&&(o.allOf=[...h.map(g=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:g.source}))])}},uE=(e,t,n,a)=>{const o=n,{minimum:i,maximum:s,format:l,multipleOf:m,exclusiveMaximum:d,exclusiveMinimum:h}=e._zod.bag;typeof l=="string"&&l.includes("int")?o.type="integer":o.type="number";const g=typeof h=="number"&&h>=(i??Number.NEGATIVE_INFINITY),y=typeof d=="number"&&d<=(s??Number.POSITIVE_INFINITY),w=t.target==="draft-04"||t.target==="openapi-3.0";g?w?(o.minimum=h,o.exclusiveMinimum=!0):o.exclusiveMinimum=h:typeof i=="number"&&(o.minimum=i),y?w?(o.maximum=d,o.exclusiveMaximum=!0):o.exclusiveMaximum=d:typeof s=="number"&&(o.maximum=s),typeof m=="number"&&(o.multipleOf=m)},mE=(e,t,n,a)=>{n.type="boolean"},pE=(e,t,n,a)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},fE=(e,t,n,a)=>{n.not={}},hE=(e,t,n,a)=>{},gE=(e,t,n,a)=>{const o=e._zod.def,i=ZS(o.entries);i.every(s=>typeof s=="number")&&(n.type="number"),i.every(s=>typeof s=="string")&&(n.type="string"),n.enum=i},vE=(e,t,n,a)=>{const o=e._zod.def,i=[];for(const s of o.values)if(s===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(s))}else i.push(s);if(i.length!==0)if(i.length===1){const s=i[0];n.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[s]:n.const=s}else i.every(s=>typeof s=="number")&&(n.type="number"),i.every(s=>typeof s=="string")&&(n.type="string"),i.every(s=>typeof s=="boolean")&&(n.type="boolean"),i.every(s=>s===null)&&(n.type="null"),n.enum=i},bE=(e,t,n,a)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},yE=(e,t,n,a)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},SE=(e,t,n,a)=>{const o=n,i=e._zod.def,{minimum:s,maximum:l}=e._zod.bag;typeof s=="number"&&(o.minItems=s),typeof l=="number"&&(o.maxItems=l),o.type="array",o.items=ln(i.element,t,{...a,path:[...a.path,"items"]})},xE=(e,t,n,a)=>{const o=n,i=e._zod.def;o.type="object",o.properties={};const s=i.shape;for(const d in s)o.properties[d]=ln(s[d],t,{...a,path:[...a.path,"properties",d]});const l=new Set(Object.keys(s)),m=new Set([...l].filter(d=>{const h=i.shape[d]._zod;return t.io==="input"?h.optin===void 0:h.optout===void 0}));m.size>0&&(o.required=Array.from(m)),i.catchall?._zod.def.type==="never"?o.additionalProperties=!1:i.catchall?i.catchall&&(o.additionalProperties=ln(i.catchall,t,{...a,path:[...a.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},kE=(e,t,n,a)=>{const o=e._zod.def,i=o.inclusive===!1,s=o.options.map((l,m)=>ln(l,t,{...a,path:[...a.path,i?"oneOf":"anyOf",m]}));i?n.oneOf=s:n.anyOf=s},wE=(e,t,n,a)=>{const o=e._zod.def,i=ln(o.left,t,{...a,path:[...a.path,"allOf",0]}),s=ln(o.right,t,{...a,path:[...a.path,"allOf",1]}),l=d=>"allOf"in d&&Object.keys(d).length===1,m=[...l(i)?i.allOf:[i],...l(s)?s.allOf:[s]];n.allOf=m},IE=(e,t,n,a)=>{const o=n,i=e._zod.def;o.type="object";const s=i.keyType,m=s._zod.bag?.patterns;if(i.mode==="loose"&&m&&m.size>0){const h=ln(i.valueType,t,{...a,path:[...a.path,"patternProperties","*"]});o.patternProperties={};for(const g of m)o.patternProperties[g.source]=h}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(o.propertyNames=ln(i.keyType,t,{...a,path:[...a.path,"propertyNames"]})),o.additionalProperties=ln(i.valueType,t,{...a,path:[...a.path,"additionalProperties"]});const d=s._zod.values;if(d){const h=[...d].filter(g=>typeof g=="string"||typeof g=="number");h.length>0&&(o.required=h)}},_E=(e,t,n,a)=>{const o=e._zod.def,i=ln(o.innerType,t,a),s=t.seen.get(e);t.target==="openapi-3.0"?(s.ref=o.innerType,n.nullable=!0):n.anyOf=[i,{type:"null"}]},CE=(e,t,n,a)=>{const o=e._zod.def;ln(o.innerType,t,a);const i=t.seen.get(e);i.ref=o.innerType},RE=(e,t,n,a)=>{const o=e._zod.def;ln(o.innerType,t,a);const i=t.seen.get(e);i.ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))},PE=(e,t,n,a)=>{const o=e._zod.def;ln(o.innerType,t,a);const i=t.seen.get(e);i.ref=o.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},AE=(e,t,n,a)=>{const o=e._zod.def;ln(o.innerType,t,a);const i=t.seen.get(e);i.ref=o.innerType;let s;try{s=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=s},TE=(e,t,n,a)=>{const o=e._zod.def,i=o.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?i?o.out:o.in:o.out;ln(s,t,a);const l=t.seen.get(e);l.ref=s},EE=(e,t,n,a)=>{const o=e._zod.def;ln(o.innerType,t,a);const i=t.seen.get(e);i.ref=o.innerType,n.readOnly=!0},Sx=(e,t,n,a)=>{const o=e._zod.def;ln(o.innerType,t,a);const i=t.seen.get(e);i.ref=o.innerType},ME=(e,t,n,a)=>{const o=e._zod.innerType;ln(o,t,a);const i=t.seen.get(e);i.ref=o},jE=ge("ZodISODateTime",(e,t)=>{PA.init(e,t),en.init(e,t)});function xx(e){return NT(jE,e)}const OE=ge("ZodISODate",(e,t)=>{AA.init(e,t),en.init(e,t)});function $E(e){return DT(OE,e)}const NE=ge("ZodISOTime",(e,t)=>{TA.init(e,t),en.init(e,t)});function DE(e){return LT(NE,e)}const LE=ge("ZodISODuration",(e,t)=>{EA.init(e,t),en.init(e,t)});function UE(e){return UT(LE,e)}const kx=(e,t)=>{XS.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>yP(e,n)},flatten:{value:n=>bP(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,Rf,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,Rf,2)}},isEmpty:{get(){return e.issues.length===0}}})},HE=ge("ZodError",kx),Ra=ge("ZodError",kx,{Parent:Error}),zE=Uh(Ra),qE=Hh(Ra),BE=nu(Ra),FE=au(Ra),VE=kP(Ra),KE=wP(Ra),WE=IP(Ra),GE=_P(Ra),ZE=CP(Ra),JE=RP(Ra),YE=PP(Ra),QE=AP(Ra),gb=new WeakMap;function Wl(e,t,n){const a=Object.getPrototypeOf(e);let o=gb.get(a);if(o||(o=new Set,gb.set(a,o)),!o.has(t)){o.add(t);for(const i in n){const s=n[i];Object.defineProperty(a,i,{configurable:!0,enumerable:!1,get(){const l=s.bind(this);return Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:l}),l},set(l){Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:l})}})}}}const Zt=ge("ZodType",(e,t)=>(Gt.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Ad(e,"input"),output:Ad(e,"output")}}),e.toJSONSchema=lE(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,a)=>zE(e,n,a,{callee:e.parse}),e.safeParse=(n,a)=>BE(e,n,a),e.parseAsync=async(n,a)=>qE(e,n,a,{callee:e.parseAsync}),e.safeParseAsync=async(n,a)=>FE(e,n,a),e.spa=e.safeParseAsync,e.encode=(n,a)=>VE(e,n,a),e.decode=(n,a)=>KE(e,n,a),e.encodeAsync=async(n,a)=>WE(e,n,a),e.decodeAsync=async(n,a)=>GE(e,n,a),e.safeEncode=(n,a)=>ZE(e,n,a),e.safeDecode=(n,a)=>JE(e,n,a),e.safeEncodeAsync=async(n,a)=>YE(e,n,a),e.safeDecodeAsync=async(n,a)=>QE(e,n,a),Wl(e,"ZodType",{check(...n){const a=this.def;return this.clone(Sr(a,{checks:[...a.checks??[],...n.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,a){return xr(this,n,a)},brand(){return this},register(n,a){return n.add(this,a),this},refine(n,a){return this.check(qM(n,a))},superRefine(n,a){return this.check(BM(n,a))},overwrite(n){return this.check(ks(n))},optional(){return Sb(this)},exactOptional(){return AM(this)},nullable(){return xb(this)},nullish(){return Sb(xb(this))},nonoptional(n){return $M(this,n)},array(){return p(this)},or(n){return Dt([this,n])},and(n){return _M(this,n)},transform(n){return kb(this,Px(n))},default(n){return MM(this,n)},prefault(n){return OM(this,n)},catch(n){return DM(this,n)},pipe(n){return kb(this,n)},readonly(){return HM(this)},describe(n){const a=this.clone();return cl.add(a,{description:n}),a},meta(...n){if(n.length===0)return cl.get(this);const a=this.clone();return cl.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 cl.get(e)?.description},configurable:!0}),e)),wx=ge("_ZodString",(e,t)=>{zh.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(a,o,i)=>dE(e,a,o);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Wl(e,"_ZodString",{regex(...a){return this.check(KT(...a))},includes(...a){return this.check(ZT(...a))},startsWith(...a){return this.check(JT(...a))},endsWith(...a){return this.check(YT(...a))},min(...a){return this.check(Pd(...a))},max(...a){return this.check(hx(...a))},length(...a){return this.check(gx(...a))},nonempty(...a){return this.check(Pd(1,...a))},lowercase(a){return this.check(WT(a))},uppercase(a){return this.check(GT(a))},trim(){return this.check(XT())},normalize(...a){return this.check(QT(...a))},toLowerCase(){return this.check(eE())},toUpperCase(){return this.check(tE())},slugify(){return this.check(nE())}})}),XE=ge("ZodString",(e,t)=>{zh.init(e,t),wx.init(e,t),e.email=n=>e.check(hT(eM,n)),e.url=n=>e.check(ST(tM,n)),e.jwt=n=>e.check($T(gM,n)),e.emoji=n=>e.check(xT(nM,n)),e.guid=n=>e.check(mb(vb,n)),e.uuid=n=>e.check(gT(Hc,n)),e.uuidv4=n=>e.check(vT(Hc,n)),e.uuidv6=n=>e.check(bT(Hc,n)),e.uuidv7=n=>e.check(yT(Hc,n)),e.nanoid=n=>e.check(kT(aM,n)),e.guid=n=>e.check(mb(vb,n)),e.cuid=n=>e.check(wT(oM,n)),e.cuid2=n=>e.check(IT(rM,n)),e.ulid=n=>e.check(_T(iM,n)),e.base64=n=>e.check(MT(pM,n)),e.base64url=n=>e.check(jT(fM,n)),e.xid=n=>e.check(CT(sM,n)),e.ksuid=n=>e.check(RT(lM,n)),e.ipv4=n=>e.check(PT(cM,n)),e.ipv6=n=>e.check(AT(dM,n)),e.cidrv4=n=>e.check(TT(uM,n)),e.cidrv6=n=>e.check(ET(mM,n)),e.e164=n=>e.check(OT(hM,n)),e.datetime=n=>e.check(xx(n)),e.date=n=>e.check($E(n)),e.time=n=>e.check(DE(n)),e.duration=n=>e.check(UE(n))});function r(e){return fT(XE,e)}const en=ge("ZodStringFormat",(e,t)=>{Yt.init(e,t),wx.init(e,t)}),eM=ge("ZodEmail",(e,t)=>{yA.init(e,t),en.init(e,t)}),vb=ge("ZodGUID",(e,t)=>{vA.init(e,t),en.init(e,t)}),Hc=ge("ZodUUID",(e,t)=>{bA.init(e,t),en.init(e,t)}),tM=ge("ZodURL",(e,t)=>{SA.init(e,t),en.init(e,t)}),nM=ge("ZodEmoji",(e,t)=>{xA.init(e,t),en.init(e,t)}),aM=ge("ZodNanoID",(e,t)=>{kA.init(e,t),en.init(e,t)}),oM=ge("ZodCUID",(e,t)=>{wA.init(e,t),en.init(e,t)}),rM=ge("ZodCUID2",(e,t)=>{IA.init(e,t),en.init(e,t)}),iM=ge("ZodULID",(e,t)=>{_A.init(e,t),en.init(e,t)}),sM=ge("ZodXID",(e,t)=>{CA.init(e,t),en.init(e,t)}),lM=ge("ZodKSUID",(e,t)=>{RA.init(e,t),en.init(e,t)}),cM=ge("ZodIPv4",(e,t)=>{MA.init(e,t),en.init(e,t)}),dM=ge("ZodIPv6",(e,t)=>{jA.init(e,t),en.init(e,t)}),uM=ge("ZodCIDRv4",(e,t)=>{OA.init(e,t),en.init(e,t)}),mM=ge("ZodCIDRv6",(e,t)=>{$A.init(e,t),en.init(e,t)}),pM=ge("ZodBase64",(e,t)=>{NA.init(e,t),en.init(e,t)}),fM=ge("ZodBase64URL",(e,t)=>{LA.init(e,t),en.init(e,t)}),hM=ge("ZodE164",(e,t)=>{UA.init(e,t),en.init(e,t)}),gM=ge("ZodJWT",(e,t)=>{zA.init(e,t),en.init(e,t)}),Ix=ge("ZodNumber",(e,t)=>{cx.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(a,o,i)=>uE(e,a,o),Wl(e,"ZodNumber",{gt(a,o){return this.check(fb(a,o))},gte(a,o){return this.check(sp(a,o))},min(a,o){return this.check(sp(a,o))},lt(a,o){return this.check(pb(a,o))},lte(a,o){return this.check(ip(a,o))},max(a,o){return this.check(ip(a,o))},int(a){return this.check(bb(a))},safe(a){return this.check(bb(a))},positive(a){return this.check(fb(0,a))},nonnegative(a){return this.check(sp(0,a))},negative(a){return this.check(pb(0,a))},nonpositive(a){return this.check(ip(0,a))},multipleOf(a,o){return this.check(hb(a,o))},step(a,o){return this.check(hb(a,o))},finite(){return this}});const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function u(e){return HT(Ix,e)}const vM=ge("ZodNumberFormat",(e,t)=>{qA.init(e,t),Ix.init(e,t)});function bb(e){return zT(vM,e)}const bM=ge("ZodBoolean",(e,t)=>{BA.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>mE(e,n,a)});function A(e){return qT(bM,e)}const yM=ge("ZodNull",(e,t)=>{FA.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>pE(e,n,a)});function ru(e){return BT(yM,e)}const SM=ge("ZodUnknown",(e,t)=>{VA.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>hE()});function ce(){return FT(SM)}const xM=ge("ZodNever",(e,t)=>{KA.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>fE(e,n,a)});function _x(e){return VT(xM,e)}const kM=ge("ZodArray",(e,t)=>{WA.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>SE(e,n,a,o),e.element=t.element,Wl(e,"ZodArray",{min(n,a){return this.check(Pd(n,a))},nonempty(n){return this.check(Pd(1,n))},max(n,a){return this.check(hx(n,a))},length(n,a){return this.check(gx(n,a))},unwrap(){return this.element}})});function p(e,t){return aE(kM,e,t)}const Cx=ge("ZodObject",(e,t)=>{ZA.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>xE(e,n,a,o),_t(e,"shape",()=>t.shape),Wl(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:ce()})},loose(){return this.clone({...this._zod.def,catchall:ce()})},strict(){return this.clone({...this._zod.def,catchall:_x()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return mP(this,n)},safeExtend(n){return pP(this,n)},merge(n){return fP(this,n)},pick(n){return dP(this,n)},omit(n){return uP(this,n)},partial(...n){return hP(Ax,this,n[0])},required(...n){return gP(Tx,this,n[0])}})});function c(e,t){const n={type:"object",shape:e??{},...et(t)};return new Cx(n)}function lp(e,t){return new Cx({type:"object",shape:e,catchall:_x(),...et(t)})}const Rx=ge("ZodUnion",(e,t)=>{mx.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>kE(e,n,a,o),e.options=t.options});function Dt(e,t){return new Rx({type:"union",options:e,...et(t)})}const wM=ge("ZodDiscriminatedUnion",(e,t)=>{Rx.init(e,t),JA.init(e,t)});function It(e,t,n){return new wM({type:"union",options:t,discriminator:e,...et(n)})}const IM=ge("ZodIntersection",(e,t)=>{YA.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>wE(e,n,a,o)});function _M(e,t){return new IM({type:"intersection",left:e,right:t})}const yb=ge("ZodRecord",(e,t)=>{QA.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>IE(e,n,a,o),e.keyType=t.keyType,e.valueType=t.valueType});function re(e,t,n){return!t||!t._zod?new yb({type:"record",keyType:r(),valueType:e,...et(t)}):new yb({type:"record",keyType:e,valueType:t,...et(n)})}const Af=ge("ZodEnum",(e,t)=>{XA.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(a,o,i)=>gE(e,a,o),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(a,o)=>{const i={};for(const s of a)if(n.has(s))i[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new Af({...t,checks:[],...et(o),entries:i})},e.exclude=(a,o)=>{const i={...t.entries};for(const s of a)if(n.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new Af({...t,checks:[],...et(o),entries:i})}});function b(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(a=>[a,a])):e;return new Af({type:"enum",entries:n,...et(t)})}const CM=ge("ZodLiteral",(e,t)=>{eT.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>vE(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 S(e,t){return new CM({type:"literal",values:Array.isArray(e)?e:[e],...et(t)})}const RM=ge("ZodTransform",(e,t)=>{tT.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>yE(e,n),e._zod.parse=(n,a)=>{if(a.direction==="backward")throw new GS(e.constructor.name);n.addIssue=i=>{if(typeof i=="string")n.issues.push(_l(i,n.value,t));else{const s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=e),n.issues.push(_l(s))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(i=>(n.value=i,n.fallback=!0,n)):(n.value=o,n.fallback=!0,n)}});function Px(e){return new RM({type:"transform",transform:e})}const Ax=ge("ZodOptional",(e,t)=>{px.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>Sx(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function Sb(e){return new Ax({type:"optional",innerType:e})}const PM=ge("ZodExactOptional",(e,t)=>{nT.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>Sx(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function AM(e){return new PM({type:"optional",innerType:e})}const TM=ge("ZodNullable",(e,t)=>{aT.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>_E(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function xb(e){return new TM({type:"nullable",innerType:e})}const EM=ge("ZodDefault",(e,t)=>{oT.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>RE(e,n,a,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function MM(e,t){return new EM({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():YS(t)}})}const jM=ge("ZodPrefault",(e,t)=>{rT.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>PE(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function OM(e,t){return new jM({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():YS(t)}})}const Tx=ge("ZodNonOptional",(e,t)=>{iT.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>CE(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function $M(e,t){return new Tx({type:"nonoptional",innerType:e,...et(t)})}const NM=ge("ZodCatch",(e,t)=>{sT.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>AE(e,n,a,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function DM(e,t){return new NM({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const Ex=ge("ZodPipe",(e,t)=>{fx.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>TE(e,n,a,o),e.in=t.in,e.out=t.out});function kb(e,t){return new Ex({type:"pipe",in:e,out:t})}const LM=ge("ZodPreprocess",(e,t)=>{Ex.init(e,t),lT.init(e,t)}),UM=ge("ZodReadonly",(e,t)=>{cT.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>EE(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function HM(e){return new UM({type:"readonly",innerType:e})}const zM=ge("ZodLazy",(e,t)=>{dT.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>ME(e,n,a,o),e.unwrap=()=>e._zod.def.getter()});function Mx(e){return new zM({type:"lazy",getter:e})}const jx=ge("ZodCustom",(e,t)=>{uT.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>bE(e,n)});function cp(e,t){return oE(jx,(()=>!0),t)}function qM(e,t={}){return rE(jx,e,t)}function BM(e,t){return iE(e,t)}function Yr(e){const t=Mx(()=>Dt([r(e),u(),A(),ru(),p(t),re(r(),t)]));return t}function FM(e,t){return new LM({type:"pipe",in:Px(e),out:t})}const zn={custom:"custom"},VM=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),KM=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 WM(e){const t=typeof e=="string"?new TextEncoder().encode(e):e,n=Math.ceil((t.byteLength+9)/64)*64,a=new Uint8Array(n);a.set(t),a[t.byteLength]=128;const o=t.byteLength*8,i=new DataView(a.buffer);i.setUint32(n-8,Math.floor(o/4294967296),!1),i.setUint32(n-4,o>>>0,!1);const s=new Uint32Array(VM),l=new Uint32Array(64);for(let m=0;m<n;m+=64){for(let C=0;C<16;C+=1)l[C]=i.getUint32(m+C*4,!1);for(let C=16;C<64;C+=1){const N=l[C-15],$=l[C-2],j=eo(N,7)^eo(N,18)^N>>>3,x=eo($,17)^eo($,19)^$>>>10;l[C]=l[C-16]+j+l[C-7]+x>>>0}let d=s[0],h=s[1],g=s[2],y=s[3],w=s[4],_=s[5],P=s[6],M=s[7];for(let C=0;C<64;C+=1){const N=w&_^~w&P,$=d&h^d&g^h&g,j=eo(d,2)^eo(d,13)^eo(d,22),x=eo(w,6)^eo(w,11)^eo(w,25),R=M+x+N+KM[C]+l[C]>>>0,E=j+$>>>0;M=P,P=_,_=w,w=y+R>>>0,y=g,g=h,h=d,d=R+E>>>0}s[0]=s[0]+d>>>0,s[1]=s[1]+h>>>0,s[2]=s[2]+g>>>0,s[3]=s[3]+y>>>0,s[4]=s[4]+w>>>0,s[5]=s[5]+_>>>0,s[6]=s[6]+P>>>0,s[7]=s[7]+M>>>0}return Array.from(s,m=>m.toString(16).padStart(8,"0")).join("")}function eo(e,t){return e>>>t|e<<32-t}const GM=2e3,Ox=25e7,T=r().trim().min(1).max(240),J=r().regex(/^[a-f0-9]{64}$/),Oe=r().datetime({offset:!0}),In=re(r(),ce()).default({}),Z=c({id:T,contentHash:J}).strict(),Vt=Z.extend({revision:u().int().positive()}).strict(),sn=c({id:T,path:r().trim().min(1).max(GM).refine(JM),contentHash:J,sizeBytes:u().int().nonnegative().max(Ox),mediaType:r().trim().min(1).max(200),visibility:b(["policy","verifier","host_private"])}).strict(),Fa=c({id:T,contentHash:J,mediaType:r().trim().min(1).max(200).nullable().default(null),sizeBytes:u().int().nonnegative().max(Ox).nullable().default(null)}).strict(),Gl=b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]);function ZM(e){return`${JSON.stringify(Tf(e),null,2)}
|
|
66
|
-
`}function qh(e){return WM(e)}function Xt(e){return qh(ZM(e))}function JM(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function Tf(e){return Array.isArray(e)?e.map(Tf):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,Tf(n)]))}const Bh=c({provider:T,model:T,revision:r().trim().min(1).max(500).nullable().default(null),artifactHash:J.nullable().default(null),tokenizerRevision:r().trim().min(1).max(500).nullable().default(null),chatTemplateHash:J.nullable().default(null)}).strict(),Fh=["openpond","codex","anthropic","openai","xai","google","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],oi=b(Fh),cn=c({providerId:oi,modelId:r().trim().min(1).max(300)}),iu=b(["active","preview","planned","deprecated"]),$x=b(["openpond-account","openpond-managed","codex-login","chatgpt-subscription","local-byok","hosted-byok","custom"]),YM=b(["none","local_secret","env","openpond_account","codex_login","chatgpt_subscription","hosted"]),wb=c({connected:A().default(!1),source:YM.default("none"),redacted:r().nullable().default(null),lastValidatedAt:r().nullable().default(null),lastError:r().nullable().default(null)}),Ef=c({hostedOpChat:A().default(!1),localRuntime:A().default(!0),localByok:A().default(!1),hostedByok:A().default(!1)}),QM=b(["hosted","provider","manual","none"]),Mf=c({chatCompletions:A().default(!0),streaming:A().default(!0),modelDiscovery:QM.default("none"),toolCalling:A().default(!1),reasoning:A().default(!1),imageInput:A().default(!1),structuredOutput:A().default(!1)}),XM=b(["hosted","provider","curated","manual","cache"]),jf=c({streaming:A().default(!0),toolCalling:A().default(!1),reasoning:A().default(!1),reasoningEfforts:p(b(["off","low","medium","high","xhigh","max"])).default([]),vision:A().default(!1),structuredOutput:A().default(!1)}),ej=c({id:r().trim().min(1).max(300),providerId:oi,displayName:r().trim().min(1).max(300),contextWindow:u().int().positive().nullable().default(null),outputLimit:u().int().positive().nullable().default(null),lifecycleStatus:iu.default("active"),source:XM,capabilities:jf.default(()=>jf.parse({})),raw:re(r(),ce()).optional()}),tj=c({providerId:oi,models:p(ej).default([]),fetchedAt:r().nullable().default(null),lastError:r().nullable().default(null),source:b(["none","hosted","provider","curated","manual"]).default("none")}),nj=c({enabled:A().default(!1),baseUrl:r().trim().min(1).max(2048).nullable().default(null),defaultModel:r().trim().min(1).max(300).nullable().default(null),modelOverrides:p(r().trim().min(1).max(300)).max(500).default([]),updatedAt:r().nullable().default(null)}),aj=c({enabled:A().optional(),baseUrl:r().trim().min(1).max(2048).nullable().optional(),defaultModel:r().trim().min(1).max(300).nullable().optional(),modelOverrides:p(r().trim().min(1).max(300)).max(500).optional()}),oj=c({id:r().trim().min(1).max(300),displayName:r().trim().min(1).max(300),contextWindow:u().int().positive().nullable().optional(),outputLimit:u().int().positive().nullable().optional(),lifecycleStatus:iu.optional(),capabilities:jf.partial().optional()}),rj=c({id:oi,displayName:r().trim().min(1).max(160),lifecycleStatus:iu.default("active"),credentialModes:p($x).default([]),routing:Ef,capabilities:Mf,defaultEnabled:A().optional(),defaultBaseUrl:r().trim().min(1).max(2048).nullable().optional(),defaultModel:r().trim().min(1).max(300).nullable().optional(),modelCacheSource:b(["none","hosted","provider","curated","manual"]),models:p(oj).default([])});c({version:S(1).default(1),generatedAt:r().datetime(),providers:p(rj)});const ij=c({id:oi,displayName:r().trim().min(1).max(160),lifecycleStatus:iu.default("active"),credentialModes:p($x).default([]),routing:Ef.default(()=>Ef.parse({})),capabilities:Mf.default(()=>Mf.parse({})),credential:wb.default(()=>wb.parse({})),enabled:A().default(!1),available:A().default(!1),defaultModel:r().trim().min(1).max(300).nullable().default(null),modelIds:p(r().trim().min(1).max(300)).max(1e3).default([]),lastError:r().nullable().default(null)}),Ib=c({version:S(1).default(1),providers:re(r(),nj).default({}),statuses:re(r(),ij).default({}),modelCaches:re(r(),tj).default({}),updatedAt:r().nullable().default(null)});c({providers:re(r(),aj).optional()});c({source:b(["local_secret","env"]).default("local_secret"),value:r().min(1).max(2e4).optional(),envVar:r().trim().min(1).max(160).optional()}).superRefine((e,t)=>{e.source==="env"&&!e.envVar&&t.addIssue({code:"custom",path:["envVar"],message:"envVar is required when provider credential source is env."}),e.source==="local_secret"&&!e.value&&t.addIssue({code:"custom",path:["value"],message:"value is required when provider credential source is local_secret."})});c({source:b(["local_secret","env","chatgpt_subscription"]).optional()});c({modelId:r().trim().min(1).max(300).optional(),baseUrl:r().trim().min(1).max(2048).optional()});c({query:r().trim().max(200).optional(),refresh:A().default(!1),limit:u().int().positive().max(500).default(100)});c({query:r().trim().max(200).optional(),force:A().default(!1)});const sj=["coding","research","review","test","docs","planner","summarizer"];b(sj);const ws=r().trim().min(1).max(80).regex(/^[a-z][a-z0-9_-]*$/),Nx=b(["none","worktree","copy_on_write"]),Dx=b(["read_only","workspace_write","full_tools"]),Lx=b(["disabled","parent_scoped"]),su=b(["manual","balanced","proactive"]),lj=b(["queued","running","completed","failed","cancelled","needs_resume"]),Ux=["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(Ux);const cj=[{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"}],Vh=c({id:ws,enabled:A().default(!0),modelRef:cn.nullable().default(null),isolationMode:Nx.default("none"),maxConcurrentRuns:u().int().min(1).max(16).default(1),toolPolicy:Dx.default("read_only"),background:A().default(!0),peerMessages:Lx.default("parent_scoped")}),Cl=c({enabled:A().default(!0),workspaceDefaultsVersion:S(1).default(1),toolDefaultsVersion:S(1).default(1),delegationMode:su.default("manual"),defaultModelRef:cn.nullable().default(null),roles:p(Vh).max(64).default(()=>qx()),maxConcurrentRuns:u().int().min(1).max(32).default(4),maxConcurrentRunsPerProvider:u().int().min(1).max(32).nullable().default(2),maxConcurrentRunsPerWorkspaceTarget:u().int().min(1).max(32).nullable().default(1)}).transform(e=>({...e,roles:Sj(e.roles)})),hl=c({kind:b(["session","turn","file","diff","artifact"]),id:r().trim().min(1).max(500),label:r().trim().min(1).max(500)}),dj=c({kind:b(["retain_with_parent"]).default("retain_with_parent"),messageRetentionDays:u().int().min(1).max(3650).nullable().default(null),artifactRetentionDays:u().int().min(1).max(3650).nullable().default(null),cleanupAfterExpiry:A().default(!1)}).default(()=>({kind:"retain_with_parent",messageRetentionDays:null,artifactRetentionDays:null,cleanupAfterExpiry:!1})),uj=b(["orient","edit","validate","report"]),mj=c({command:r().trim().min(1).max(2e3),status:b(["passed","failed","unknown"]).default("unknown"),exitCode:u().int().nullable().default(null),outputSummary:r().trim().max(5e3).nullable().default(null),startedAt:r().nullable().default(null),completedAt:r().nullable().default(null)}),pj=c({phase:uj.default("orient"),inspectedFiles:p(r().trim().min(1).max(1e3)).max(500).default([]),inspectedResources:p(r().trim().min(1).max(1e3)).max(500).default([]),repeatedSearches:p(r().trim().min(1).max(1e3)).max(200).default([]),repeatedReads:p(r().trim().min(1).max(1e3)).max(200).default([]),repeatedCommands:p(r().trim().min(1).max(1e3)).max(200).default([]),changedFiles:p(r().trim().min(1).max(1e3)).max(500).default([]),patchRefs:p(hl).max(100).default([]),validationAttempts:p(mj).max(100).default([]),latestMeaningfulActivity:r().trim().max(5e3).nullable().default(null),currentBlocker:r().trim().max(5e3).nullable().default(null),updatedAt:r().nullable().default(null)}).default(()=>({phase:"orient",inspectedFiles:[],inspectedResources:[],repeatedSearches:[],repeatedReads:[],repeatedCommands:[],changedFiles:[],patchRefs:[],validationAttempts:[],latestMeaningfulActivity:null,currentBlocker:null,updatedAt:null})),fj=c({summary:r().trim().max(2e4).default(""),findings:p(r().trim().min(1).max(5e3)).max(200).default([]),artifacts:p(hl).max(200).default([]),patchRef:hl.nullable().default(null),diffRef:hl.nullable().default(null),testsRun:p(r().trim().min(1).max(2e3)).max(100).default([]),blockers:p(r().trim().min(1).max(5e3)).max(100).default([]),confidence:b(["low","medium","high"]).nullable().default(null),followUpNeeded:A().default(!1)}),Hx=c({id:r().trim().min(1).max(200),parentSessionId:r().trim().min(1).max(200),parentTurnId:r().trim().min(1).max(200).nullable().default(null),childSessionId:r().trim().min(1).max(200).nullable().default(null),roleId:ws,objective:r().trim().min(1).max(5e4),modelRef:cn.nullable().default(null),isolationMode:Nx.default("none"),toolPolicy:Dx.default("read_only"),background:A().default(!0),peerMessages:Lx.default("parent_scoped"),status:lj.default("queued"),progress:pj,evidenceRetention:dj,createdAt:r(),startedAt:r().nullable().default(null),completedAt:r().nullable().default(null),updatedAt:r().nullable().default(null),error:r().nullable().default(null),report:fj.nullable().default(null),metadata:re(r(),ce()).optional().default({})}),zx=b(["cleanup","archive","cleanup_and_archive"]);c({action:zx,reason:r().trim().min(1).max(2e3).nullable().default(null)});c({action:zx,run:Hx,workspaceCleanup:re(r(),ce()).nullable().default(null),sessionArchive:re(r(),ce()).nullable().default(null),nextStep:r()});const hj=b(["question","answer","handoff","artifact","status","blocker"]),gj=b(["normal","interrupt"]),vj=c({inputIds:p(r()).default([]),status:b(["pending","delivered","undelivered"]).default("pending"),deliveredRunIds:p(r().trim().min(1).max(200)).max(200).default([]),acknowledgedRunIds:p(r().trim().min(1).max(200)).max(200).default([]),deliveredParentSessionId:r().trim().min(1).max(200).nullable().default(null),acknowledgedParentSessionId:r().trim().min(1).max(200).nullable().default(null),wakeRequestedParentSessionId:r().trim().min(1).max(200).nullable().default(null),wakeQueuedParentSessionId:r().trim().min(1).max(200).nullable().default(null),wakeDeferredParentSessionId:r().trim().min(1).max(200).nullable().default(null),wakeParentReason:r().trim().min(1).max(1e3).nullable().default(null),wakeRequestedRunIds:p(r().trim().min(1).max(200)).max(200).default([]),wakeInterruptedRunIds:p(r().trim().min(1).max(200)).max(200).default([]),wakeDeferredRunIds:p(r().trim().min(1).max(200)).max(200).default([]),reason:r().trim().min(1).max(1e3).nullable().default(null)}),bj=c({id:r().trim().min(1).max(200),fromRunId:r().trim().min(1).max(200),toRunId:r().trim().min(1).max(200).nullable().default(null),toRole:ws.nullable().default(null),kind:hj,priority:gj.optional(),body:r().trim().min(1).max(5e4),refs:p(hl).max(100).default([]),delivery:vj.optional(),createdAt:r()});function qx(){return cj.map(e=>Vh.parse({id:e.id,toolPolicy:e.defaultToolPolicy}))}function yj(){return Cl.parse({})}function Sj(e){const t=qx(),n=new Map(t.map(o=>[o.id,o])),a=[];for(const o of e??[]){const i=Vh.parse(o);n.has(i.id)?n.set(i.id,i):a.push(i)}return[...t.map(o=>n.get(o.id)??o),...a]}const xj=b(["task.inbox","task.input","task.wait","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",...Ux,"diagnostic"]),_b=c({id:r(),sequence:u().int().positive().optional(),sessionId:r().optional(),turnId:r().optional(),name:xj,timestamp:r(),source:b(["ui_button","chat_action","terminal_command","hook","provider","server"]).optional(),action:r().optional(),appId:r().nullable().optional(),args:re(r(),ce()).optional(),status:b(["started","completed","failed","pending"]).optional(),output:r().optional(),error:r().optional(),relatedDeploymentId:r().optional(),data:ce().optional()}),kj=c({id:r().trim().min(1).max(80),label:r().trim().min(1).max(160),description:r().trim().max(500).nullable().optional().default(null)}),wj=c({id:r().trim().min(1),sessionId:r().trim().min(1),turnId:r().trim().min(1),toolCallId:r().trim().min(1),question:r().trim().min(1).max(2e3),reason:r().trim().max(1e3).nullable().optional().default(null),options:p(kj).max(5).default([]),allowFreeform:A().default(!0),status:b(["pending","answered","dismissed"]),answer:c({optionId:r().trim().min(1).nullable(),text:r().max(4e3)}).nullable(),createdAt:r(),answeredAt:r().nullable()}),Ij=c({questionId:r().trim().min(1),action:b(["answer","dismiss"]),optionId:r().trim().min(1).nullable().optional().default(null),text:r().trim().max(4e3).optional().default("")});c({kind:b(["session","project","draft"]),id:r().trim().min(1).max(300)});b(["unknown","idle","running","success","failed"]);b(["none","idle","running","success","failed","unknown"]);function _j(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var $n={},zc={},lr={},Cb;function Zl(){if(Cb)return lr;Cb=1;function e(s){return typeof s>"u"||s===null}function t(s){return typeof s=="object"&&s!==null}function n(s){return Array.isArray(s)?s:e(s)?[]:[s]}function a(s,l){if(l){const m=Object.keys(l);for(let d=0,h=m.length;d<h;d+=1){const g=m[d];s[g]=l[g]}}return s}function o(s,l){let m="";for(let d=0;d<l;d+=1)m+=s;return m}function i(s){return s===0&&Number.NEGATIVE_INFINITY===1/s}return lr.isNothing=e,lr.isObject=t,lr.toArray=n,lr.repeat=o,lr.isNegativeZero=i,lr.extend=a,lr}var dp,Rb;function Jl(){if(Rb)return dp;Rb=1;function e(n,a){let o="";const i=n.reason||"(unknown reason)";return n.mark?(n.mark.name&&(o+='in "'+n.mark.name+'" '),o+="("+(n.mark.line+1)+":"+(n.mark.column+1)+")",!a&&n.mark.snippet&&(o+=`
|
|
67
|
-
|
|
68
|
-
`+n.mark.snippet),i+" "+o):i}function t(n,a){Error.call(this),this.name="YAMLException",this.reason=n,this.mark=a,this.message=e(this,!1),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||""}return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t.prototype.toString=function(a){return this.name+": "+e(this,a)},dp=t,dp}var up,Pb;function Cj(){if(Pb)return up;Pb=1;const e=Zl();function t(o,i,s,l,m){let d="",h="";const g=Math.floor(m/2)-1;return l-i>g&&(d=" ... ",i=l-g+d.length),s-l>g&&(h=" ...",s=l+g-h.length),{str:d+o.slice(i,s).replace(/\t/g,"→")+h,pos:l-i+d.length}}function n(o,i){return e.repeat(" ",i-o.length)+o}function a(o,i){if(i=Object.create(i||null),!o.buffer)return null;i.maxLength||(i.maxLength=79),typeof i.indent!="number"&&(i.indent=1),typeof i.linesBefore!="number"&&(i.linesBefore=3),typeof i.linesAfter!="number"&&(i.linesAfter=2);const s=/\r?\n|\r|\0/g,l=[0],m=[];let d,h=-1;for(;d=s.exec(o.buffer);)m.push(d.index),l.push(d.index+d[0].length),o.position<=d.index&&h<0&&(h=l.length-2);h<0&&(h=l.length-1);let g="";const y=Math.min(o.line+i.linesAfter,m.length).toString().length,w=i.maxLength-(i.indent+y+3);for(let P=1;P<=i.linesBefore&&!(h-P<0);P++){const M=t(o.buffer,l[h-P],m[h-P],o.position-(l[h]-l[h-P]),w);g=e.repeat(" ",i.indent)+n((o.line-P+1).toString(),y)+" | "+M.str+`
|
|
69
|
-
`+g}const _=t(o.buffer,l[h],m[h],o.position,w);g+=e.repeat(" ",i.indent)+n((o.line+1).toString(),y)+" | "+_.str+`
|
|
70
|
-
`,g+=e.repeat("-",i.indent+y+3+_.pos)+`^
|
|
71
|
-
`;for(let P=1;P<=i.linesAfter&&!(h+P>=m.length);P++){const M=t(o.buffer,l[h+P],m[h+P],o.position-(l[h]-l[h+P]),w);g+=e.repeat(" ",i.indent)+n((o.line+P+1).toString(),y)+" | "+M.str+`
|
|
72
|
-
`}return g.replace(/\n$/,"")}return up=a,up}var mp,Ab;function qn(){if(Ab)return mp;Ab=1;const e=Jl(),t=["kind","multi","resolve","construct","instanceOf","predicate","represent","representName","defaultStyle","styleAliases"],n=["scalar","sequence","mapping"];function a(i){const s={};return i!==null&&Object.keys(i).forEach(function(l){i[l].forEach(function(m){s[String(m)]=l})}),s}function o(i,s){if(s=s||{},Object.keys(s).forEach(function(l){if(t.indexOf(l)===-1)throw new e('Unknown option "'+l+'" is met in definition of "'+i+'" YAML type.')}),this.options=s,this.tag=i,this.kind=s.kind||null,this.resolve=s.resolve||function(){return!0},this.construct=s.construct||function(l){return l},this.instanceOf=s.instanceOf||null,this.predicate=s.predicate||null,this.represent=s.represent||null,this.representName=s.representName||null,this.defaultStyle=s.defaultStyle||null,this.multi=s.multi||!1,this.styleAliases=a(s.styleAliases||null),n.indexOf(this.kind)===-1)throw new e('Unknown kind "'+this.kind+'" is specified for "'+i+'" YAML type.')}return mp=o,mp}var pp,Tb;function Bx(){if(Tb)return pp;Tb=1;const e=Jl(),t=qn();function n(i,s){const l=[];return i[s].forEach(function(m){let d=l.length;l.forEach(function(h,g){h.tag===m.tag&&h.kind===m.kind&&h.multi===m.multi&&(d=g)}),l[d]=m}),l}function a(){const i={scalar:{},sequence:{},mapping:{},fallback:{},multi:{scalar:[],sequence:[],mapping:[],fallback:[]}};function s(l){l.multi?(i.multi[l.kind].push(l),i.multi.fallback.push(l)):i[l.kind][l.tag]=i.fallback[l.tag]=l}for(let l=0,m=arguments.length;l<m;l+=1)arguments[l].forEach(s);return i}function o(i){return this.extend(i)}return o.prototype.extend=function(s){let l=[],m=[];if(s instanceof t)m.push(s);else if(Array.isArray(s))m=m.concat(s);else if(s&&(Array.isArray(s.implicit)||Array.isArray(s.explicit)))s.implicit&&(l=l.concat(s.implicit)),s.explicit&&(m=m.concat(s.explicit));else throw new e("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");l.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.")}),m.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 d=Object.create(o.prototype);return d.implicit=(this.implicit||[]).concat(l),d.explicit=(this.explicit||[]).concat(m),d.compiledImplicit=n(d,"implicit"),d.compiledExplicit=n(d,"explicit"),d.compiledTypeMap=a(d.compiledImplicit,d.compiledExplicit),d},pp=o,pp}var fp,Eb;function Fx(){if(Eb)return fp;Eb=1;const e=qn();return fp=new e("tag:yaml.org,2002:str",{kind:"scalar",construct:function(t){return t!==null?t:""}}),fp}var hp,Mb;function Vx(){if(Mb)return hp;Mb=1;const e=qn();return hp=new e("tag:yaml.org,2002:seq",{kind:"sequence",construct:function(t){return t!==null?t:[]}}),hp}var gp,jb;function Kx(){if(jb)return gp;jb=1;const e=qn();return gp=new e("tag:yaml.org,2002:map",{kind:"mapping",construct:function(t){return t!==null?t:{}}}),gp}var vp,Ob;function Wx(){if(Ob)return vp;Ob=1;const e=Bx();return vp=new e({explicit:[Fx(),Vx(),Kx()]}),vp}var bp,$b;function Gx(){if($b)return bp;$b=1;const e=qn();function t(o){if(o===null)return!0;const i=o.length;return i===1&&o==="~"||i===4&&(o==="null"||o==="Null"||o==="NULL")}function n(){return null}function a(o){return o===null}return bp=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"}),bp}var yp,Nb;function Zx(){if(Nb)return yp;Nb=1;const e=qn();function t(o){if(o===null)return!1;const i=o.length;return i===4&&(o==="true"||o==="True"||o==="TRUE")||i===5&&(o==="false"||o==="False"||o==="FALSE")}function n(o){return o==="true"||o==="True"||o==="TRUE"}function a(o){return Object.prototype.toString.call(o)==="[object Boolean]"}return yp=new e("tag:yaml.org,2002:bool",{kind:"scalar",resolve:t,construct:n,predicate:a,represent:{lowercase:function(o){return o?"true":"false"},uppercase:function(o){return o?"TRUE":"FALSE"},camelcase:function(o){return o?"True":"False"}},defaultStyle:"lowercase"}),yp}var Sp,Db;function Jx(){if(Db)return Sp;Db=1;const e=Zl(),t=qn();function n(d){return d>=48&&d<=57||d>=65&&d<=70||d>=97&&d<=102}function a(d){return d>=48&&d<=55}function o(d){return d>=48&&d<=57}function i(d){if(d===null)return!1;const h=d.length;let g=0,y=!1;if(!h)return!1;let w=d[g];if((w==="-"||w==="+")&&(w=d[++g]),w==="0"){if(g+1===h)return!0;if(w=d[++g],w==="b"){for(g++;g<h;g++){if(w=d[g],w!=="0"&&w!=="1")return!1;y=!0}return y&&isFinite(s(d))}if(w==="x"){for(g++;g<h;g++){if(!n(d.charCodeAt(g)))return!1;y=!0}return y&&isFinite(s(d))}if(w==="o"){for(g++;g<h;g++){if(!a(d.charCodeAt(g)))return!1;y=!0}return y&&isFinite(s(d))}}for(;g<h;g++){if(!o(d.charCodeAt(g)))return!1;y=!0}return y?isFinite(s(d)):!1}function s(d){let h=d,g=1,y=h[0];if((y==="-"||y==="+")&&(y==="-"&&(g=-1),h=h.slice(1),y=h[0]),h==="0")return 0;if(y==="0"){if(h[1]==="b")return g*parseInt(h.slice(2),2);if(h[1]==="x")return g*parseInt(h.slice(2),16);if(h[1]==="o")return g*parseInt(h.slice(2),8)}return g*parseInt(h,10)}function l(d){return s(d)}function m(d){return Object.prototype.toString.call(d)==="[object Number]"&&d%1===0&&!e.isNegativeZero(d)}return Sp=new t("tag:yaml.org,2002:int",{kind:"scalar",resolve:i,construct:l,predicate:m,represent:{binary:function(d){return d>=0?"0b"+d.toString(2):"-0b"+d.toString(2).slice(1)},octal:function(d){return d>=0?"0o"+d.toString(8):"-0o"+d.toString(8).slice(1)},decimal:function(d){return d.toString(10)},hexadecimal:function(d){return d>=0?"0x"+d.toString(16).toUpperCase():"-0x"+d.toString(16).toUpperCase().slice(1)}},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}}),Sp}var xp,Lb;function Yx(){if(Lb)return xp;Lb=1;const e=Zl(),t=qn(),n=new RegExp("^(?:[-+]?(?:[0-9]+)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"),a=new RegExp("^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function o(d){return d===null||!n.test(d)?!1:isFinite(parseFloat(d,10))?!0:a.test(d)}function i(d){let h=d.toLowerCase();const g=h[0]==="-"?-1:1;return"+-".indexOf(h[0])>=0&&(h=h.slice(1)),h===".inf"?g===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:h===".nan"?NaN:g*parseFloat(h,10)}const s=/^[-+]?[0-9]+e/;function l(d,h){if(isNaN(d))switch(h){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===d)switch(h){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===d)switch(h){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(e.isNegativeZero(d))return"-0.0";const g=d.toString(10);return s.test(g)?g.replace("e",".e"):g}function m(d){return Object.prototype.toString.call(d)==="[object Number]"&&(d%1!==0||e.isNegativeZero(d))}return xp=new t("tag:yaml.org,2002:float",{kind:"scalar",resolve:o,construct:i,predicate:m,represent:l,defaultStyle:"lowercase"}),xp}var kp,Ub;function Qx(){return Ub||(Ub=1,kp=Wx().extend({implicit:[Gx(),Zx(),Jx(),Yx()]})),kp}var wp,Hb;function Xx(){return Hb||(Hb=1,wp=Qx()),wp}var Ip,zb;function ek(){if(zb)return Ip;zb=1;const e=qn(),t=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),n=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");function a(s){return s===null?!1:t.exec(s)!==null||n.exec(s)!==null}function o(s){let l=0,m=null,d=t.exec(s);if(d===null&&(d=n.exec(s)),d===null)throw new Error("Date resolve error");const h=+d[1],g=+d[2]-1,y=+d[3];if(!d[4])return new Date(Date.UTC(h,g,y));const w=+d[4],_=+d[5],P=+d[6];if(d[7]){for(l=d[7].slice(0,3);l.length<3;)l+="0";l=+l}if(d[9]){const C=+d[10],N=+(d[11]||0);m=(C*60+N)*6e4,d[9]==="-"&&(m=-m)}const M=new Date(Date.UTC(h,g,y,w,_,P,l));return m&&M.setTime(M.getTime()-m),M}function i(s){return s.toISOString()}return Ip=new e("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:a,construct:o,instanceOf:Date,represent:i}),Ip}var _p,qb;function tk(){if(qb)return _p;qb=1;const e=qn();function t(n){return n==="<<"||n===null}return _p=new e("tag:yaml.org,2002:merge",{kind:"scalar",resolve:t}),_p}var Cp,Bb;function nk(){if(Bb)return Cp;Bb=1;const e=qn(),t=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
|
|
73
|
-
\r`;function n(s){if(s===null)return!1;let l=0;const m=s.length,d=t;for(let h=0;h<m;h++){const g=d.indexOf(s.charAt(h));if(!(g>64)){if(g<0)return!1;l+=6}}return l%8===0}function a(s){const l=s.replace(/[\r\n=]/g,""),m=l.length,d=t;let h=0;const g=[];for(let w=0;w<m;w++)w%4===0&&w&&(g.push(h>>16&255),g.push(h>>8&255),g.push(h&255)),h=h<<6|d.indexOf(l.charAt(w));const y=m%4*6;return y===0?(g.push(h>>16&255),g.push(h>>8&255),g.push(h&255)):y===18?(g.push(h>>10&255),g.push(h>>2&255)):y===12&&g.push(h>>4&255),new Uint8Array(g)}function o(s){let l="",m=0;const d=s.length,h=t;for(let y=0;y<d;y++)y%3===0&&y&&(l+=h[m>>18&63],l+=h[m>>12&63],l+=h[m>>6&63],l+=h[m&63]),m=(m<<8)+s[y];const g=d%3;return g===0?(l+=h[m>>18&63],l+=h[m>>12&63],l+=h[m>>6&63],l+=h[m&63]):g===2?(l+=h[m>>10&63],l+=h[m>>4&63],l+=h[m<<2&63],l+=h[64]):g===1&&(l+=h[m>>2&63],l+=h[m<<4&63],l+=h[64],l+=h[64]),l}function i(s){return Object.prototype.toString.call(s)==="[object Uint8Array]"}return Cp=new e("tag:yaml.org,2002:binary",{kind:"scalar",resolve:n,construct:a,predicate:i,represent:o}),Cp}var Rp,Fb;function ak(){if(Fb)return Rp;Fb=1;const e=qn(),t=Object.prototype.hasOwnProperty,n=Object.prototype.toString;function a(i){if(i===null)return!0;const s=[],l=i;for(let m=0,d=l.length;m<d;m+=1){const h=l[m];let g=!1;if(n.call(h)!=="[object Object]")return!1;let y;for(y in h)if(t.call(h,y))if(!g)g=!0;else return!1;if(!g)return!1;if(s.indexOf(y)===-1)s.push(y);else return!1}return!0}function o(i){return i!==null?i:[]}return Rp=new e("tag:yaml.org,2002:omap",{kind:"sequence",resolve:a,construct:o}),Rp}var Pp,Vb;function ok(){if(Vb)return Pp;Vb=1;const e=qn(),t=Object.prototype.toString;function n(o){if(o===null)return!0;const i=o,s=new Array(i.length);for(let l=0,m=i.length;l<m;l+=1){const d=i[l];if(t.call(d)!=="[object Object]")return!1;const h=Object.keys(d);if(h.length!==1)return!1;s[l]=[h[0],d[h[0]]]}return!0}function a(o){if(o===null)return[];const i=o,s=new Array(i.length);for(let l=0,m=i.length;l<m;l+=1){const d=i[l],h=Object.keys(d);s[l]=[h[0],d[h[0]]]}return s}return Pp=new e("tag:yaml.org,2002:pairs",{kind:"sequence",resolve:n,construct:a}),Pp}var Ap,Kb;function rk(){if(Kb)return Ap;Kb=1;const e=qn(),t=Object.prototype.hasOwnProperty;function n(o){if(o===null)return!0;const i=o;for(const s in i)if(t.call(i,s)&&i[s]!==null)return!1;return!0}function a(o){return o!==null?o:{}}return Ap=new e("tag:yaml.org,2002:set",{kind:"mapping",resolve:n,construct:a}),Ap}var Tp,Wb;function Kh(){return Wb||(Wb=1,Tp=Xx().extend({implicit:[ek(),tk()],explicit:[nk(),ak(),ok(),rk()]})),Tp}var Gb;function Rj(){if(Gb)return zc;Gb=1;const e=Zl(),t=Jl(),n=Cj(),a=Kh(),o=Object.prototype.hasOwnProperty,i=1,s=2,l=3,m=4,d=1,h=2,g=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]/,_=/[,\[\]{}]/,P=/^(?:!|!!|![0-9A-Za-z-]+!)$/,M=/^(?:!|[^,\[\]{}])(?:%[0-9a-f]{2}|[0-9a-z\-#;/?:@&=+$,_.!~*'()\[\]])*$/i;function C(f){return Object.prototype.toString.call(f)}function N(f){return f===10||f===13}function $(f){return f===9||f===32}function j(f){return f===9||f===32||f===10||f===13}function x(f){return f===44||f===91||f===93||f===123||f===125}function R(f){if(f>=48&&f<=57)return f-48;const H=f|32;return H>=97&&H<=102?H-97+10:-1}function E(f){return f===120?2:f===117?4:f===85?8:0}function U(f){return f>=48&&f<=57?f-48:-1}function B(f){switch(f){case 48:return"\0";case 97:return"\x07";case 98:return"\b";case 116:return" ";case 9:return" ";case 110:return`
|
|
74
|
-
`;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 D(f){return f<=65535?String.fromCharCode(f):String.fromCharCode((f-65536>>10)+55296,(f-65536&1023)+56320)}function W(f,H,Y){H==="__proto__"?Object.defineProperty(f,H,{configurable:!0,enumerable:!0,writable:!0,value:Y}):f[H]=Y}const se=new Array(256),de=new Array(256);for(let f=0;f<256;f++)se[f]=B(f)?1:0,de[f]=B(f);function Me(f,H){this.input=f,this.filename=H.filename||null,this.schema=H.schema||a,this.onWarning=H.onWarning||null,this.legacy=H.legacy||!1,this.json=H.json||!1,this.listener=H.listener||null,this.maxDepth=typeof H.maxDepth=="number"?H.maxDepth:100,this.maxTotalMergeKeys=typeof H.maxTotalMergeKeys=="number"?H.maxTotalMergeKeys:1e4,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=f.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 ke(f,H){const Y={name:f.filename,buffer:f.input.slice(0,-1),position:f.position,line:f.line,column:f.position-f.lineStart};return Y.snippet=n(Y),new t(H,Y)}function te(f,H){throw ke(f,H)}function Ee(f,H){f.onWarning&&f.onWarning.call(null,ke(f,H))}function ye(f,H,Y){const he=f.anchorMapTransactions;if(he.length!==0){const ie=he[he.length-1];o.call(ie,H)||(ie[H]={existed:o.call(f.anchorMap,H),value:f.anchorMap[H]})}f.anchorMap[H]=Y}function ne(f){f.anchorMapTransactions.push(Object.create(null))}function be(f){const H=f.anchorMapTransactions.pop(),Y=f.anchorMapTransactions;if(Y.length===0)return;const he=Y[Y.length-1],ie=Object.keys(H);for(let K=0,I=ie.length;K<I;K+=1){const V=ie[K];o.call(he,V)||(he[V]=H[V])}}function ae(f){const H=f.anchorMapTransactions.pop(),Y=Object.keys(H);for(let he=Y.length-1;he>=0;he-=1){const ie=H[Y[he]];ie.existed?f.anchorMap[Y[he]]=ie.value:delete f.anchorMap[Y[he]]}}function ue(f){return{position:f.position,line:f.line,lineStart:f.lineStart,lineIndent:f.lineIndent,firstTabInLine:f.firstTabInLine,tag:f.tag,anchor:f.anchor,kind:f.kind,result:f.result}}function xe(f,H){f.position=H.position,f.line=H.line,f.lineStart=H.lineStart,f.lineIndent=H.lineIndent,f.firstTabInLine=H.firstTabInLine,f.tag=H.tag,f.anchor=H.anchor,f.kind=H.kind,f.result=H.result}const De={YAML:function(H,Y,he){H.version!==null&&te(H,"duplication of %YAML directive"),he.length!==1&&te(H,"YAML directive accepts exactly one argument");const ie=/^([0-9]+)\.([0-9]+)$/.exec(he[0]);ie===null&&te(H,"ill-formed argument of the YAML directive");const K=parseInt(ie[1],10),I=parseInt(ie[2],10);K!==1&&te(H,"unacceptable YAML version of the document"),H.version=he[0],H.checkLineBreaks=I<2,I!==1&&I!==2&&Ee(H,"unsupported YAML version of the document")},TAG:function(H,Y,he){let ie;he.length!==2&&te(H,"TAG directive accepts exactly two arguments");const K=he[0];ie=he[1],P.test(K)||te(H,"ill-formed tag handle (first argument) of the TAG directive"),o.call(H.tagMap,K)&&te(H,'there is a previously declared suffix for "'+K+'" tag handle'),M.test(ie)||te(H,"ill-formed tag prefix (second argument) of the TAG directive");try{ie=decodeURIComponent(ie)}catch{te(H,"tag prefix is malformed: "+ie)}H.tagMap[K]=ie}};function we(f,H,Y,he){if(H<Y){const ie=f.input.slice(H,Y);if(he)for(let K=0,I=ie.length;K<I;K+=1){const V=ie.charCodeAt(K);V===9||V>=32&&V<=1114111||te(f,"expected valid JSON character")}else y.test(ie)&&te(f,"the stream contains non-printable characters");f.result+=ie}}function oe(f,H,Y,he){e.isObject(Y)||te(f,"cannot merge mappings; the provided source object is unacceptable");const ie=Object.keys(Y);for(let K=0,I=ie.length;K<I;K+=1){const V=ie[K];f.maxTotalMergeKeys!==-1&&++f.totalMergeKeys>f.maxTotalMergeKeys&&te(f,"merge keys exceeded maxTotalMergeKeys ("+f.maxTotalMergeKeys+")"),o.call(H,V)||(W(H,V,Y[V]),he[V]=!0)}}function Se(f,H,Y,he,ie,K,I,V,ee){if(Array.isArray(ie)){ie=Array.prototype.slice.call(ie);for(let G=0,le=ie.length;G<le;G+=1)Array.isArray(ie[G])&&te(f,"nested arrays are not supported inside keys"),typeof ie=="object"&&C(ie[G])==="[object Object]"&&(ie[G]="[object Object]")}if(typeof ie=="object"&&C(ie)==="[object Object]"&&(ie="[object Object]"),ie=String(ie),H===null&&(H={}),he==="tag:yaml.org,2002:merge")if(Array.isArray(K))for(let G=0,le=K.length;G<le;G+=1)oe(f,H,K[G],Y);else oe(f,H,K,Y);else!f.json&&!o.call(Y,ie)&&o.call(H,ie)&&(f.line=I||f.line,f.lineStart=V||f.lineStart,f.position=ee||f.position,te(f,"duplicated mapping key")),W(H,ie,K),delete Y[ie];return H}function He(f){const H=f.input.charCodeAt(f.position);H===10?f.position++:H===13?(f.position++,f.input.charCodeAt(f.position)===10&&f.position++):te(f,"a line break is expected"),f.line+=1,f.lineStart=f.position,f.firstTabInLine=-1}function Ze(f,H,Y){let he=0,ie=f.input.charCodeAt(f.position);for(;ie!==0;){for(;$(ie);)ie===9&&f.firstTabInLine===-1&&(f.firstTabInLine=f.position),ie=f.input.charCodeAt(++f.position);if(H&&ie===35)do ie=f.input.charCodeAt(++f.position);while(ie!==10&&ie!==13&&ie!==0);if(N(ie))for(He(f),ie=f.input.charCodeAt(f.position),he++,f.lineIndent=0;ie===32;)f.lineIndent++,ie=f.input.charCodeAt(++f.position);else break}return Y!==-1&&he!==0&&f.lineIndent<Y&&Ee(f,"deficient indentation"),he}function Ke(f){let H=f.position,Y=f.input.charCodeAt(H);return!!((Y===45||Y===46)&&Y===f.input.charCodeAt(H+1)&&Y===f.input.charCodeAt(H+2)&&(H+=3,Y=f.input.charCodeAt(H),Y===0||j(Y)))}function tt(f,H){H===1?f.result+=" ":H>1&&(f.result+=e.repeat(`
|
|
75
|
-
`,H-1))}function qe(f,H,Y){let he,ie,K,I,V,ee;const G=f.kind,le=f.result;let pe=f.input.charCodeAt(f.position);if(j(pe)||x(pe)||pe===35||pe===38||pe===42||pe===33||pe===124||pe===62||pe===39||pe===34||pe===37||pe===64||pe===96)return!1;if(pe===63||pe===45){const fe=f.input.charCodeAt(f.position+1);if(j(fe)||Y&&x(fe))return!1}for(f.kind="scalar",f.result="",he=ie=f.position,K=!1;pe!==0;){if(pe===58){const fe=f.input.charCodeAt(f.position+1);if(j(fe)||Y&&x(fe))break}else if(pe===35){const fe=f.input.charCodeAt(f.position-1);if(j(fe))break}else{if(f.position===f.lineStart&&Ke(f)||Y&&x(pe))break;if(N(pe))if(I=f.line,V=f.lineStart,ee=f.lineIndent,Ze(f,!1,-1),f.lineIndent>=H){K=!0,pe=f.input.charCodeAt(f.position);continue}else{f.position=ie,f.line=I,f.lineStart=V,f.lineIndent=ee;break}}K&&(we(f,he,ie,!1),tt(f,f.line-I),he=ie=f.position,K=!1),$(pe)||(ie=f.position+1),pe=f.input.charCodeAt(++f.position)}return we(f,he,ie,!1),f.result?!0:(f.kind=G,f.result=le,!1)}function Ge(f,H){let Y,he,ie=f.input.charCodeAt(f.position);if(ie!==39)return!1;for(f.kind="scalar",f.result="",f.position++,Y=he=f.position;(ie=f.input.charCodeAt(f.position))!==0;)if(ie===39)if(we(f,Y,f.position,!0),ie=f.input.charCodeAt(++f.position),ie===39)Y=f.position,f.position++,he=f.position;else return!0;else N(ie)?(we(f,Y,he,!0),tt(f,Ze(f,!1,H)),Y=he=f.position):f.position===f.lineStart&&Ke(f)?te(f,"unexpected end of the document within a single quoted scalar"):(f.position++,$(ie)||(he=f.position));te(f,"unexpected end of the stream within a single quoted scalar")}function ze(f,H){let Y,he,ie,K=f.input.charCodeAt(f.position);if(K!==34)return!1;for(f.kind="scalar",f.result="",f.position++,Y=he=f.position;(K=f.input.charCodeAt(f.position))!==0;){if(K===34)return we(f,Y,f.position,!0),f.position++,!0;if(K===92){if(we(f,Y,f.position,!0),K=f.input.charCodeAt(++f.position),N(K))Ze(f,!1,H);else if(K<256&&se[K])f.result+=de[K],f.position++;else if((ie=E(K))>0){let I=ie,V=0;for(;I>0;I--)K=f.input.charCodeAt(++f.position),(ie=R(K))>=0?V=(V<<4)+ie:te(f,"expected hexadecimal character");f.result+=D(V),f.position++}else te(f,"unknown escape sequence");Y=he=f.position}else N(K)?(we(f,Y,he,!0),tt(f,Ze(f,!1,H)),Y=he=f.position):f.position===f.lineStart&&Ke(f)?te(f,"unexpected end of the document within a double quoted scalar"):(f.position++,$(K)||(he=f.position))}te(f,"unexpected end of the stream within a double quoted scalar")}function L(f,H){let Y=!0,he,ie,K;const I=f.tag;let V;const ee=f.anchor;let G,le,pe,fe;const Pe=Object.create(null);let _e,Ne,Re,Xe=f.input.charCodeAt(f.position);if(Xe===91)G=93,fe=!1,V=[];else if(Xe===123)G=125,fe=!0,V={};else return!1;for(f.anchor!==null&&ye(f,f.anchor,V),Xe=f.input.charCodeAt(++f.position);Xe!==0;){if(Ze(f,!0,H),Xe=f.input.charCodeAt(f.position),Xe===G)return f.position++,f.tag=I,f.anchor=ee,f.kind=fe?"mapping":"sequence",f.result=V,!0;if(Y?Xe===44&&te(f,"expected the node content, but found ','"):te(f,"missed comma between flow collection entries"),Ne=_e=Re=null,le=pe=!1,Xe===63){const st=f.input.charCodeAt(f.position+1);j(st)&&(le=pe=!0,f.position++,Ze(f,!0,H))}he=f.line,ie=f.lineStart,K=f.position,at(f,H,i,!1,!0),Ne=f.tag,_e=f.result,Ze(f,!0,H),Xe=f.input.charCodeAt(f.position),(pe||f.line===he)&&Xe===58&&(le=!0,Xe=f.input.charCodeAt(++f.position),Ze(f,!0,H),at(f,H,i,!1,!0),Re=f.result),fe?Se(f,V,Pe,Ne,_e,Re,he,ie,K):le?V.push(Se(f,null,Pe,Ne,_e,Re,he,ie,K)):V.push(_e),Ze(f,!0,H),Xe=f.input.charCodeAt(f.position),Xe===44?(Y=!0,Xe=f.input.charCodeAt(++f.position)):Y=!1}te(f,"unexpected end of the stream within a flow collection")}function O(f,H){let Y,he=d,ie=!1,K=!1,I=H,V=0,ee=!1,G,le=f.input.charCodeAt(f.position);if(le===124)Y=!1;else if(le===62)Y=!0;else return!1;for(f.kind="scalar",f.result="";le!==0;)if(le=f.input.charCodeAt(++f.position),le===43||le===45)d===he?he=le===43?g:h:te(f,"repeat of a chomping mode identifier");else if((G=U(le))>=0)G===0?te(f,"bad explicit indentation width of a block scalar; it cannot be less than one"):K?te(f,"repeat of an indentation width identifier"):(I=H+G-1,K=!0);else break;if($(le)){do le=f.input.charCodeAt(++f.position);while($(le));if(le===35)do le=f.input.charCodeAt(++f.position);while(!N(le)&&le!==0)}for(;le!==0;){for(He(f),f.lineIndent=0,le=f.input.charCodeAt(f.position);(!K||f.lineIndent<I)&&le===32;)f.lineIndent++,le=f.input.charCodeAt(++f.position);if(!K&&f.lineIndent>I&&(I=f.lineIndent),N(le)){V++;continue}if(!K&&I===0&&te(f,"missing indentation for block scalar"),f.lineIndent<I){he===g?f.result+=e.repeat(`
|
|
76
|
-
`,ie?1+V:V):he===d&&ie&&(f.result+=`
|
|
77
|
-
`);break}Y?$(le)?(ee=!0,f.result+=e.repeat(`
|
|
78
|
-
`,ie?1+V:V)):ee?(ee=!1,f.result+=e.repeat(`
|
|
79
|
-
`,V+1)):V===0?ie&&(f.result+=" "):f.result+=e.repeat(`
|
|
80
|
-
`,V):f.result+=e.repeat(`
|
|
81
|
-
`,ie?1+V:V),ie=!0,K=!0,V=0;const pe=f.position;for(;!N(le)&&le!==0;)le=f.input.charCodeAt(++f.position);we(f,pe,f.position,!1)}return!0}function z(f,H){const Y=f.tag,he=f.anchor,ie=[];let K=!1;if(f.firstTabInLine!==-1)return!1;f.anchor!==null&&ye(f,f.anchor,ie);let I=f.input.charCodeAt(f.position);for(;I!==0&&(f.firstTabInLine!==-1&&(f.position=f.firstTabInLine,te(f,"tab characters must not be used in indentation")),I===45);){const V=f.input.charCodeAt(f.position+1);if(!j(V))break;if(K=!0,f.position++,Ze(f,!0,-1)&&f.lineIndent<=H){ie.push(null),I=f.input.charCodeAt(f.position);continue}const ee=f.line;if(at(f,H,l,!1,!0),ie.push(f.result),Ze(f,!0,-1),I=f.input.charCodeAt(f.position),(f.line===ee||f.lineIndent>H)&&I!==0)te(f,"bad indentation of a sequence entry");else if(f.lineIndent<H)break}return K?(f.tag=Y,f.anchor=he,f.kind="sequence",f.result=ie,!0):!1}function X(f,H,Y){let he,ie,K,I;const V=f.tag,ee=f.anchor,G={},le=Object.create(null);let pe=null,fe=null,Pe=null,_e=!1,Ne=!1;if(f.firstTabInLine!==-1)return!1;f.anchor!==null&&ye(f,f.anchor,G);let Re=f.input.charCodeAt(f.position);for(;Re!==0;){!_e&&f.firstTabInLine!==-1&&(f.position=f.firstTabInLine,te(f,"tab characters must not be used in indentation"));const Xe=f.input.charCodeAt(f.position+1),st=f.line;if((Re===63||Re===58)&&j(Xe))Re===63?(_e&&(Se(f,G,le,pe,fe,null,ie,K,I),pe=fe=Pe=null),Ne=!0,_e=!0,he=!0):_e?(_e=!1,he=!0):te(f,"incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line"),f.position+=1,Re=Xe;else{if(ie=f.line,K=f.lineStart,I=f.position,!at(f,Y,s,!1,!0))break;if(f.line===st){for(Re=f.input.charCodeAt(f.position);$(Re);)Re=f.input.charCodeAt(++f.position);if(Re===58)Re=f.input.charCodeAt(++f.position),j(Re)||te(f,"a whitespace character is expected after the key-value separator within a block mapping"),_e&&(Se(f,G,le,pe,fe,null,ie,K,I),pe=fe=Pe=null),Ne=!0,_e=!1,he=!1,pe=f.tag,fe=f.result;else if(Ne)te(f,"can not read an implicit mapping pair; a colon is missed");else return f.tag=V,f.anchor=ee,!0}else if(Ne)te(f,"can not read a block mapping entry; a multiline key may not be an implicit key");else return f.tag=V,f.anchor=ee,!0}if((f.line===st||f.lineIndent>H)&&(_e&&(ie=f.line,K=f.lineStart,I=f.position),at(f,H,m,!0,he)&&(_e?fe=f.result:Pe=f.result),_e||(Se(f,G,le,pe,fe,Pe,ie,K,I),pe=fe=Pe=null),Ze(f,!0,-1),Re=f.input.charCodeAt(f.position)),(f.line===st||f.lineIndent>H)&&Re!==0)te(f,"bad indentation of a mapping entry");else if(f.lineIndent<H)break}return _e&&Se(f,G,le,pe,fe,null,ie,K,I),Ne&&(f.tag=V,f.anchor=ee,f.kind="mapping",f.result=G),Ne}function me(f){let H=!1,Y=!1,he,ie,K=f.input.charCodeAt(f.position);if(K!==33)return!1;f.tag!==null&&te(f,"duplication of a tag property"),K=f.input.charCodeAt(++f.position),K===60?(H=!0,K=f.input.charCodeAt(++f.position)):K===33?(Y=!0,he="!!",K=f.input.charCodeAt(++f.position)):he="!";let I=f.position;if(H){do K=f.input.charCodeAt(++f.position);while(K!==0&&K!==62);f.position<f.length?(ie=f.input.slice(I,f.position),K=f.input.charCodeAt(++f.position)):te(f,"unexpected end of the stream within a verbatim tag")}else{for(;K!==0&&!j(K);)K===33&&(Y?te(f,"tag suffix cannot contain exclamation marks"):(he=f.input.slice(I-1,f.position+1),P.test(he)||te(f,"named tag handle cannot contain such characters"),Y=!0,I=f.position+1)),K=f.input.charCodeAt(++f.position);ie=f.input.slice(I,f.position),_.test(ie)&&te(f,"tag suffix cannot contain flow indicator characters")}ie&&!M.test(ie)&&te(f,"tag name cannot contain such characters: "+ie);try{ie=decodeURIComponent(ie)}catch{te(f,"tag name is malformed: "+ie)}return H?f.tag=ie:o.call(f.tagMap,he)?f.tag=f.tagMap[he]+ie:he==="!"?f.tag="!"+ie:he==="!!"?f.tag="tag:yaml.org,2002:"+ie:te(f,'undeclared tag handle "'+he+'"'),!0}function $e(f){let H=f.input.charCodeAt(f.position);if(H!==38)return!1;f.anchor!==null&&te(f,"duplication of an anchor property"),H=f.input.charCodeAt(++f.position);const Y=f.position;for(;H!==0&&!j(H)&&!x(H);)H=f.input.charCodeAt(++f.position);return f.position===Y&&te(f,"name of an anchor node must contain at least one character"),f.anchor=f.input.slice(Y,f.position),!0}function Le(f){let H=f.input.charCodeAt(f.position);if(H!==42)return!1;H=f.input.charCodeAt(++f.position);const Y=f.position;for(;H!==0&&!j(H)&&!x(H);)H=f.input.charCodeAt(++f.position);f.position===Y&&te(f,"name of an alias node must contain at least one character");const he=f.input.slice(Y,f.position);return o.call(f.anchorMap,he)||te(f,'unidentified alias "'+he+'"'),f.result=f.anchorMap[he],Ze(f,!0,-1),!0}function nt(f,H,Y,he){const ie=ue(f);return ne(f),xe(f,H),f.tag=null,f.anchor=null,f.kind=null,f.result=null,X(f,Y,he)&&f.kind==="mapping"?(be(f),!0):(ae(f),xe(f,ie),!1)}function at(f,H,Y,he,ie){let K,I,V=1,ee=!1,G=!1,le=null,pe,fe,Pe;f.depth>=f.maxDepth&&te(f,"nesting exceeded maxDepth ("+f.maxDepth+")"),f.depth+=1,f.listener!==null&&f.listener("open",f),f.tag=null,f.anchor=null,f.kind=null,f.result=null;const _e=K=I=m===Y||l===Y;if(he&&Ze(f,!0,-1)&&(ee=!0,f.lineIndent>H?V=1:f.lineIndent===H?V=0:f.lineIndent<H&&(V=-1)),V===1)for(;;){const Ne=f.input.charCodeAt(f.position),Re=ue(f);if(ee&&(Ne===33&&f.tag!==null||Ne===38&&f.anchor!==null)||!me(f)&&!$e(f))break;le===null&&(le=Re),Ze(f,!0,-1)?(ee=!0,I=_e,f.lineIndent>H?V=1:f.lineIndent===H?V=0:f.lineIndent<H&&(V=-1)):I=!1}if(I&&(I=ee||ie),V===1||m===Y)if(i===Y||s===Y?fe=H:fe=H+1,Pe=f.position-f.lineStart,V===1)if(I&&(z(f,Pe)||X(f,Pe,fe))||L(f,fe))G=!0;else{const Ne=f.input.charCodeAt(f.position);le!==null&&_e&&!I&&Ne!==124&&Ne!==62&&nt(f,le,le.position-le.lineStart,fe)||K&&O(f,fe)||Ge(f,fe)||ze(f,fe)?G=!0:Le(f)?(G=!0,(f.tag!==null||f.anchor!==null)&&te(f,"alias node should not have any properties")):qe(f,fe,i===Y)&&(G=!0,f.tag===null&&(f.tag="?")),f.anchor!==null&&ye(f,f.anchor,f.result)}else V===0&&(G=I&&z(f,Pe));if(f.tag===null)f.anchor!==null&&ye(f,f.anchor,f.result);else if(f.tag==="?"){f.result!==null&&f.kind!=="scalar"&&te(f,'unacceptable node kind for !<?> tag; it should be "scalar", not "'+f.kind+'"');for(let Ne=0,Re=f.implicitTypes.length;Ne<Re;Ne+=1)if(pe=f.implicitTypes[Ne],pe.resolve(f.result)){f.result=pe.construct(f.result),f.tag=pe.tag,f.anchor!==null&&ye(f,f.anchor,f.result);break}}else if(f.tag!=="!"){if(o.call(f.typeMap[f.kind||"fallback"],f.tag))pe=f.typeMap[f.kind||"fallback"][f.tag];else{pe=null;const Ne=f.typeMap.multi[f.kind||"fallback"];for(let Re=0,Xe=Ne.length;Re<Xe;Re+=1)if(f.tag.slice(0,Ne[Re].tag.length)===Ne[Re].tag){pe=Ne[Re];break}}pe||te(f,"unknown tag !<"+f.tag+">"),f.result!==null&&pe.kind!==f.kind&&te(f,"unacceptable node kind for !<"+f.tag+'> tag; it should be "'+pe.kind+'", not "'+f.kind+'"'),pe.resolve(f.result,f.tag)?(f.result=pe.construct(f.result,f.tag),f.anchor!==null&&ye(f,f.anchor,f.result)):te(f,"cannot resolve a node with !<"+f.tag+"> explicit tag")}return f.listener!==null&&f.listener("close",f),f.depth-=1,f.tag!==null||f.anchor!==null||G}function lt(f){const H=f.position;let Y=!1,he;for(f.version=null,f.checkLineBreaks=f.legacy,f.tagMap=Object.create(null),f.anchorMap=Object.create(null);(he=f.input.charCodeAt(f.position))!==0&&(Ze(f,!0,-1),he=f.input.charCodeAt(f.position),!(f.lineIndent>0||he!==37));){Y=!0,he=f.input.charCodeAt(++f.position);let ie=f.position;for(;he!==0&&!j(he);)he=f.input.charCodeAt(++f.position);const K=f.input.slice(ie,f.position),I=[];for(K.length<1&&te(f,"directive name must not be less than one character in length");he!==0;){for(;$(he);)he=f.input.charCodeAt(++f.position);if(he===35){do he=f.input.charCodeAt(++f.position);while(he!==0&&!N(he));break}if(N(he))break;for(ie=f.position;he!==0&&!j(he);)he=f.input.charCodeAt(++f.position);I.push(f.input.slice(ie,f.position))}he!==0&&He(f),o.call(De,K)?De[K](f,K,I):Ee(f,'unknown document directive "'+K+'"')}if(Ze(f,!0,-1),f.lineIndent===0&&f.input.charCodeAt(f.position)===45&&f.input.charCodeAt(f.position+1)===45&&f.input.charCodeAt(f.position+2)===45?(f.position+=3,Ze(f,!0,-1)):Y&&te(f,"directives end mark is expected"),at(f,f.lineIndent-1,m,!1,!0),Ze(f,!0,-1),f.checkLineBreaks&&w.test(f.input.slice(H,f.position))&&Ee(f,"non-ASCII line breaks are interpreted as content"),f.documents.push(f.result),f.position===f.lineStart&&Ke(f)){f.input.charCodeAt(f.position)===46&&(f.position+=3,Ze(f,!0,-1));return}f.position<f.length-1&&te(f,"end of the stream or a document separator is expected")}function pt(f,H){f=String(f),H=H||{},f.length!==0&&(f.charCodeAt(f.length-1)!==10&&f.charCodeAt(f.length-1)!==13&&(f+=`
|
|
82
|
-
`),f.charCodeAt(0)===65279&&(f=f.slice(1)));const Y=new Me(f,H),he=f.indexOf("\0");for(he!==-1&&(Y.position=he,te(Y,"null byte is not allowed in input")),Y.input+="\0";Y.input.charCodeAt(Y.position)===32;)Y.lineIndent+=1,Y.position+=1;for(;Y.position<Y.length-1;)lt(Y);return Y.documents}function je(f,H,Y){H!==null&&typeof H=="object"&&typeof Y>"u"&&(Y=H,H=null);const he=pt(f,Y);if(typeof H!="function")return he;for(let ie=0,K=he.length;ie<K;ie+=1)H(he[ie])}function Ye(f,H){const Y=pt(f,H);if(Y.length!==0){if(Y.length===1)return Y[0];throw new t("expected a single document in the stream, but found more")}}return zc.loadAll=je,zc.load=Ye,zc}var Ep={},Zb;function Pj(){if(Zb)return Ep;Zb=1;const e=Zl(),t=Jl(),n=Kh(),a=Object.prototype.toString,o=Object.prototype.hasOwnProperty,i=65279,s=9,l=10,m=13,d=32,h=33,g=34,y=35,w=37,_=38,P=39,M=42,C=44,N=45,$=58,j=61,x=62,R=63,E=64,U=91,B=93,D=96,W=123,se=124,de=125,Me={};Me[0]="\\0",Me[7]="\\a",Me[8]="\\b",Me[9]="\\t",Me[10]="\\n",Me[11]="\\v",Me[12]="\\f",Me[13]="\\r",Me[27]="\\e",Me[34]='\\"',Me[92]="\\\\",Me[133]="\\N",Me[160]="\\_",Me[8232]="\\L",Me[8233]="\\P";const ke=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"],te=/^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;function Ee(I,V){if(V===null)return{};const ee={},G=Object.keys(V);for(let le=0,pe=G.length;le<pe;le+=1){let fe=G[le],Pe=String(V[fe]);fe.slice(0,2)==="!!"&&(fe="tag:yaml.org,2002:"+fe.slice(2));const _e=I.compiledTypeMap.fallback[fe];_e&&o.call(_e.styleAliases,Pe)&&(Pe=_e.styleAliases[Pe]),ee[fe]=Pe}return ee}function ye(I){let V,ee;const G=I.toString(16).toUpperCase();if(I<=255)V="x",ee=2;else if(I<=65535)V="u",ee=4;else if(I<=4294967295)V="U",ee=8;else throw new t("code point within a string may not be greater than 0xFFFFFFFF");return"\\"+V+e.repeat("0",ee-G.length)+G}const ne=1,be=2;function ae(I){this.schema=I.schema||n,this.indent=Math.max(1,I.indent||2),this.noArrayIndent=I.noArrayIndent||!1,this.skipInvalid=I.skipInvalid||!1,this.flowLevel=e.isNothing(I.flowLevel)?-1:I.flowLevel,this.styleMap=Ee(this.schema,I.styles||null),this.sortKeys=I.sortKeys||!1,this.lineWidth=I.lineWidth||80,this.noRefs=I.noRefs||!1,this.noCompatMode=I.noCompatMode||!1,this.condenseFlow=I.condenseFlow||!1,this.quotingType=I.quotingType==='"'?be:ne,this.forceQuotes=I.forceQuotes||!1,this.replacer=typeof I.replacer=="function"?I.replacer:null,this.implicitTypes=this.schema.compiledImplicit,this.explicitTypes=this.schema.compiledExplicit,this.tag=null,this.result="",this.duplicates=[],this.usedDuplicates=null}function ue(I,V){const ee=e.repeat(" ",V);let G=0,le="";const pe=I.length;for(;G<pe;){let fe;const Pe=I.indexOf(`
|
|
83
|
-
`,G);Pe===-1?(fe=I.slice(G),G=pe):(fe=I.slice(G,Pe+1),G=Pe+1),fe.length&&fe!==`
|
|
84
|
-
`&&(le+=ee),le+=fe}return le}function xe(I,V){return`
|
|
85
|
-
`+e.repeat(" ",I.indent*V)}function De(I,V){for(let ee=0,G=I.implicitTypes.length;ee<G;ee+=1)if(I.implicitTypes[ee].resolve(V))return!0;return!1}function we(I){return I===d||I===s}function oe(I){return I>=32&&I<=126||I>=161&&I<=55295&&I!==8232&&I!==8233||I>=57344&&I<=65533&&I!==i||I>=65536&&I<=1114111}function Se(I){return oe(I)&&I!==i&&I!==m&&I!==l}function He(I,V,ee){const G=Se(I),le=G&&!we(I);return(ee?G:G&&I!==C&&I!==U&&I!==B&&I!==W&&I!==de)&&I!==y&&!(V===$&&!le)||Se(V)&&!we(V)&&I===y||V===$&&le}function Ze(I){return oe(I)&&I!==i&&!we(I)&&I!==N&&I!==R&&I!==$&&I!==C&&I!==U&&I!==B&&I!==W&&I!==de&&I!==y&&I!==_&&I!==M&&I!==h&&I!==se&&I!==j&&I!==x&&I!==P&&I!==g&&I!==w&&I!==E&&I!==D}function Ke(I){return!we(I)&&I!==$}function tt(I,V){const ee=I.charCodeAt(V);let G;return ee>=55296&&ee<=56319&&V+1<I.length&&(G=I.charCodeAt(V+1),G>=56320&&G<=57343)?(ee-55296)*1024+G-56320+65536:ee}function qe(I){return/^\n* /.test(I)}const Ge=1,ze=2,L=3,O=4,z=5;function X(I,V,ee,G,le,pe,fe,Pe){let _e,Ne=0,Re=null,Xe=!1,st=!1;const on=G!==-1;let At=-1,tn=Ze(tt(I,0))&&Ke(tt(I,I.length-1));if(V||fe)for(_e=0;_e<I.length;Ne>=65536?_e+=2:_e++){if(Ne=tt(I,_e),!oe(Ne))return z;tn=tn&&He(Ne,Re,Pe),Re=Ne}else{for(_e=0;_e<I.length;Ne>=65536?_e+=2:_e++){if(Ne=tt(I,_e),Ne===l)Xe=!0,on&&(st=st||_e-At-1>G&&I[At+1]!==" ",At=_e);else if(!oe(Ne))return z;tn=tn&&He(Ne,Re,Pe),Re=Ne}st=st||on&&_e-At-1>G&&I[At+1]!==" "}return!Xe&&!st?tn&&!fe&&!le(I)?Ge:pe===be?z:ze:ee>9&&qe(I)?z:fe?pe===be?z:ze:st?O:L}function me(I,V,ee,G,le){I.dump=(function(){if(V.length===0)return I.quotingType===be?'""':"''";if(!I.noCompatMode&&(ke.indexOf(V)!==-1||te.test(V)))return I.quotingType===be?'"'+V+'"':"'"+V+"'";const pe=I.indent*Math.max(1,ee),fe=I.lineWidth===-1?-1:Math.max(Math.min(I.lineWidth,40),I.lineWidth-pe),Pe=G||I.flowLevel>-1&&ee>=I.flowLevel;function _e(Ne){return De(I,Ne)}switch(X(V,Pe,I.indent,fe,_e,I.quotingType,I.forceQuotes&&!G,le)){case Ge:return V;case ze:return"'"+V.replace(/'/g,"''")+"'";case L:return"|"+$e(V,I.indent)+Le(ue(V,pe));case O:return">"+$e(V,I.indent)+Le(ue(nt(V,fe),pe));case z:return'"'+lt(V)+'"';default:throw new t("impossible error: invalid scalar style")}})()}function $e(I,V){const ee=qe(I)?String(V):"",G=I[I.length-1]===`
|
|
86
|
-
`,pe=G&&(I[I.length-2]===`
|
|
87
|
-
`||I===`
|
|
88
|
-
`)?"+":G?"":"-";return ee+pe+`
|
|
89
|
-
`}function Le(I){return I[I.length-1]===`
|
|
90
|
-
`?I.slice(0,-1):I}function nt(I,V){const ee=/(\n+)([^\n]*)/g;let G=(function(){let Pe=I.indexOf(`
|
|
91
|
-
`);return Pe=Pe!==-1?Pe:I.length,ee.lastIndex=Pe,at(I.slice(0,Pe),V)})(),le=I[0]===`
|
|
92
|
-
`||I[0]===" ",pe,fe;for(;fe=ee.exec(I);){const Pe=fe[1],_e=fe[2];pe=_e[0]===" ",G+=Pe+(!le&&!pe&&_e!==""?`
|
|
93
|
-
`:"")+at(_e,V),le=pe}return G}function at(I,V){if(I===""||I[0]===" ")return I;const ee=/ [^ ]/g;let G,le=0,pe,fe=0,Pe=0,_e="";for(;G=ee.exec(I);)Pe=G.index,Pe-le>V&&(pe=fe>le?fe:Pe,_e+=`
|
|
94
|
-
`+I.slice(le,pe),le=pe+1),fe=Pe;return _e+=`
|
|
95
|
-
`,I.length-le>V&&fe>le?_e+=I.slice(le,fe)+`
|
|
96
|
-
`+I.slice(fe+1):_e+=I.slice(le),_e.slice(1)}function lt(I){let V="",ee=0;for(let G=0;G<I.length;ee>=65536?G+=2:G++){ee=tt(I,G);const le=Me[ee];!le&&oe(ee)?(V+=I[G],ee>=65536&&(V+=I[G+1])):V+=le||ye(ee)}return V}function pt(I,V,ee){let G="";const le=I.tag;for(let pe=0,fe=ee.length;pe<fe;pe+=1){let Pe=ee[pe];I.replacer&&(Pe=I.replacer.call(ee,String(pe),Pe)),(Y(I,V,Pe,!1,!1)||typeof Pe>"u"&&Y(I,V,null,!1,!1))&&(G!==""&&(G+=","+(I.condenseFlow?"":" ")),G+=I.dump)}I.tag=le,I.dump="["+G+"]"}function je(I,V,ee,G){let le="";const pe=I.tag;for(let fe=0,Pe=ee.length;fe<Pe;fe+=1){let _e=ee[fe];I.replacer&&(_e=I.replacer.call(ee,String(fe),_e)),(Y(I,V+1,_e,!0,!0,!1,!0)||typeof _e>"u"&&Y(I,V+1,null,!0,!0,!1,!0))&&((!G||le!=="")&&(le+=xe(I,V)),I.dump&&l===I.dump.charCodeAt(0)?le+="-":le+="- ",le+=I.dump)}I.tag=pe,I.dump=le||"[]"}function Ye(I,V,ee){let G="";const le=I.tag,pe=Object.keys(ee);for(let fe=0,Pe=pe.length;fe<Pe;fe+=1){let _e="";G!==""&&(_e+=", "),I.condenseFlow&&(_e+='"');const Ne=pe[fe];let Re=ee[Ne];I.replacer&&(Re=I.replacer.call(ee,Ne,Re)),Y(I,V,Ne,!1,!1)&&(I.dump.length>1024&&(_e+="? "),_e+=I.dump+(I.condenseFlow?'"':"")+":"+(I.condenseFlow?"":" "),Y(I,V,Re,!1,!1)&&(_e+=I.dump,G+=_e))}I.tag=le,I.dump="{"+G+"}"}function f(I,V,ee,G){let le="";const pe=I.tag,fe=Object.keys(ee);if(I.sortKeys===!0)fe.sort();else if(typeof I.sortKeys=="function")fe.sort(I.sortKeys);else if(I.sortKeys)throw new t("sortKeys must be a boolean or a function");for(let Pe=0,_e=fe.length;Pe<_e;Pe+=1){let Ne="";(!G||le!=="")&&(Ne+=xe(I,V));const Re=fe[Pe];let Xe=ee[Re];if(I.replacer&&(Xe=I.replacer.call(ee,Re,Xe)),!Y(I,V+1,Re,!0,!0,!0))continue;const st=I.tag!==null&&I.tag!=="?"||I.dump&&I.dump.length>1024;st&&(I.dump&&l===I.dump.charCodeAt(0)?Ne+="?":Ne+="? "),Ne+=I.dump,st&&(Ne+=xe(I,V)),Y(I,V+1,Xe,!0,st)&&(I.dump&&l===I.dump.charCodeAt(0)?Ne+=":":Ne+=": ",Ne+=I.dump,le+=Ne)}I.tag=pe,I.dump=le||"{}"}function H(I,V,ee){const G=ee?I.explicitTypes:I.implicitTypes;for(let le=0,pe=G.length;le<pe;le+=1){const fe=G[le];if((fe.instanceOf||fe.predicate)&&(!fe.instanceOf||typeof V=="object"&&V instanceof fe.instanceOf)&&(!fe.predicate||fe.predicate(V))){if(ee?fe.multi&&fe.representName?I.tag=fe.representName(V):I.tag=fe.tag:I.tag="?",fe.represent){const Pe=I.styleMap[fe.tag]||fe.defaultStyle;let _e;if(a.call(fe.represent)==="[object Function]")_e=fe.represent(V,Pe);else if(o.call(fe.represent,Pe))_e=fe.represent[Pe](V,Pe);else throw new t("!<"+fe.tag+'> tag resolver accepts not "'+Pe+'" style');I.dump=_e}return!0}}return!1}function Y(I,V,ee,G,le,pe,fe){I.tag=null,I.dump=ee,H(I,ee,!1)||H(I,ee,!0);const Pe=a.call(I.dump),_e=G;G&&(G=I.flowLevel<0||I.flowLevel>V);const Ne=Pe==="[object Object]"||Pe==="[object Array]";let Re,Xe;if(Ne&&(Re=I.duplicates.indexOf(ee),Xe=Re!==-1),(I.tag!==null&&I.tag!=="?"||Xe||I.indent!==2&&V>0)&&(le=!1),Xe&&I.usedDuplicates[Re])I.dump="*ref_"+Re;else{if(Ne&&Xe&&!I.usedDuplicates[Re]&&(I.usedDuplicates[Re]=!0),Pe==="[object Object]")G&&Object.keys(I.dump).length!==0?(f(I,V,I.dump,le),Xe&&(I.dump="&ref_"+Re+I.dump)):(Ye(I,V,I.dump),Xe&&(I.dump="&ref_"+Re+" "+I.dump));else if(Pe==="[object Array]")G&&I.dump.length!==0?(I.noArrayIndent&&!fe&&V>0?je(I,V-1,I.dump,le):je(I,V,I.dump,le),Xe&&(I.dump="&ref_"+Re+I.dump)):(pt(I,V,I.dump),Xe&&(I.dump="&ref_"+Re+" "+I.dump));else if(Pe==="[object String]")I.tag!=="?"&&me(I,I.dump,V,pe,_e);else{if(Pe==="[object Undefined]")return!1;if(I.skipInvalid)return!1;throw new t("unacceptable kind of an object to dump "+Pe)}if(I.tag!==null&&I.tag!=="?"){let st=encodeURI(I.tag[0]==="!"?I.tag.slice(1):I.tag).replace(/!/g,"%21");I.tag[0]==="!"?st="!"+st:st.slice(0,18)==="tag:yaml.org,2002:"?st="!!"+st.slice(18):st="!<"+st+">",I.dump=st+" "+I.dump}}return!0}function he(I,V){const ee=[],G=[];ie(I,ee,G);const le=G.length;for(let pe=0;pe<le;pe+=1)V.duplicates.push(ee[G[pe]]);V.usedDuplicates=new Array(le)}function ie(I,V,ee){if(I!==null&&typeof I=="object"){const G=V.indexOf(I);if(G!==-1)ee.indexOf(G)===-1&&ee.push(G);else if(V.push(I),Array.isArray(I))for(let le=0,pe=I.length;le<pe;le+=1)ie(I[le],V,ee);else{const le=Object.keys(I);for(let pe=0,fe=le.length;pe<fe;pe+=1)ie(I[le[pe]],V,ee)}}}function K(I,V){V=V||{};const ee=new ae(V);ee.noRefs||he(I,ee);let G=I;return ee.replacer&&(G=ee.replacer.call({"":G},"",G)),Y(ee,0,G,!0,!0)?ee.dump+`
|
|
97
|
-
`:""}return Ep.dump=K,Ep}var Jb;function Aj(){if(Jb)return $n;Jb=1;const e=Rj(),t=Pj();function n(a,o){return function(){throw new Error("Function yaml."+a+" is removed in js-yaml 4. Use yaml."+o+" instead, which is now safe by default.")}}return $n.Type=qn(),$n.Schema=Bx(),$n.FAILSAFE_SCHEMA=Wx(),$n.JSON_SCHEMA=Qx(),$n.CORE_SCHEMA=Xx(),$n.DEFAULT_SCHEMA=Kh(),$n.load=e.load,$n.loadAll=e.loadAll,$n.dump=t.dump,$n.YAMLException=Jl(),$n.types={binary:nk(),float:Yx(),map:Kx(),null:Gx(),pairs:ok(),set:rk(),timestamp:ek(),bool:Zx(),int:Jx(),merge:tk(),omap:ak(),seq:Vx(),str:Fx()},$n.safeLoad=n("safeLoad","load"),$n.safeLoadAll=n("safeLoadAll","loadAll"),$n.safeDump=n("safeDump","dump"),$n}var Tj=Aj();const Ej=_j(Tj),{Type:OY,Schema:$Y,FAILSAFE_SCHEMA:NY,JSON_SCHEMA:DY,CORE_SCHEMA:LY,DEFAULT_SCHEMA:UY,load:HY,loadAll:zY,dump:qY,YAMLException:BY,types:FY,safeLoad:VY,safeLoadAll:KY,safeDump:WY}=Ej,Wh=3e3,Gh=9999,GY="openpond.yaml",Mj=["google","github","x"],Zh=new Set([22,2222,2375,2376,3108,5900,5901,6080,7818]),Yb=p(r().trim().min(1).max(1e3)).max(50),Rl=r().trim().min(1).max(4096).refine(ck,{message:"path must be a relative workspace path"}),jj=r().trim().min(1).max(500).refine(e=>!e.includes("\0")&&!/\s/.test(e),"image ref must be a single OCI reference"),Oj=r().trim().regex(/^sha256:[0-9a-f]{64}$/i),ik=r().trim().min(1).max(500).refine(e=>e.startsWith("/")&&!e.includes("\0"),"workspaceRoot must be an absolute guest path"),$j=c({ref:jj,digest:Oj.optional(),registrySecretRef:r().trim().min(1).max(500).optional(),platform:S("linux/amd64").optional(),workspaceRoot:ik.optional()}).strict(),Nj=c({context:Rl.default("."),path:Rl.default("Dockerfile"),target:r().trim().min(1).max(191).optional(),buildArgs:re(r().max(191),r().max(500)).optional(),registrySecretRefs:p(r().trim().min(1).max(500)).max(10).optional(),platform:S("linux/amd64").optional(),workspaceRoot:ik.optional()}).strict(),Dj=c({base:r().trim().min(1).max(120).optional(),snapshot:r().trim().min(1).max(191).optional(),image:$j.optional(),dockerfile:Nj.optional()}).strict().superRefine((e,t)=>{[e.base,e.snapshot,e.image,e.dockerfile].filter(Boolean).length!==1&&t.addIssue({code:zn.custom,message:"runtime must declare exactly one of base, snapshot, image, or dockerfile"})}),sk=c({cpu:u().positive().max(8).optional(),memoryGb:u().positive().max(32).optional(),diskGb:u().positive().max(100).optional()}).strict(),Lj=c({provider:b(Mj),scopes:p(r().trim().min(1).max(200)).max(100).default([]),capabilities:p(r().trim().min(1).max(200)).max(100).default([])}).strict(),Uj=c({models:p(r().trim().min(1).max(200)).max(100).default([]),scopes:p(r().trim().min(1).max(200)).max(100).default([])}).strict(),Hj=c({opchat:Uj.optional()}).catchall(re(r(),ce())).default({}),zj=c({name:r().trim().regex(/^[A-Za-z_][A-Za-z0-9_-]*$/).max(63).optional(),mountPath:r().trim().min(1).max(256).optional(),storageGb:u().int().positive().max(100).optional(),deleteOnSandboxDelete:A().optional()}).strict(),qj=c({port:u().int().min(Wh).max(Gh).refine(e=>!Zh.has(e),{message:"preview port is reserved"}),protocol:S("http").default("http"),label:r().trim().min(1).max(80).optional(),access:b(["private","public"]).default("private"),path:r().trim().min(1).max(512).refine(e=>e.startsWith("/"),{message:"preview path must start with /"}).default("/")}).strict(),lk=c({command:r().trim().min(1).max(1e3),cwd:Rl.optional(),timeoutSeconds:u().int().positive().max(86400).optional(),requiresStart:A().default(!1),ports:p(qj).max(20).default([]),artifactPaths:p(Rl).max(100).default([])}).strict(),Qb=lk.extend({name:r().trim().min(1).max(80)}).strict(),Bj=c({name:r().trim().min(1).max(80).optional(),service:r().trim().min(1).max(80).optional(),port:u().int().min(Wh).max(Gh).refine(e=>!Zh.has(e),{message:"app MCP port is reserved"}),path:r().trim().min(1).max(512).refine(e=>e.startsWith("/"),{message:"app MCP path must start with /"}).default("/mcp")}).strict(),Fj=c({name:r().trim().min(1).max(80).optional(),port:u().int().min(Wh).max(Gh).refine(e=>!Zh.has(e),{message:"validation probe port is reserved"}),path:r().trim().min(1).max(512).refine(e=>e.startsWith("/"),{message:"validation probe path must start with /"}).default("/"),expectedStatus:u().int().min(100).max(599).default(200)}).strict(),Vj=re(r(),ce()).refine(e=>e.type==="object","input schema must be a JSON schema object"),Kj=c({name:r().trim().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).max(191),required:A().default(!1),secret:A().default(!0),description:r().trim().max(500).optional()}).strict(),Mp=r().trim().min(1).max(120),Wj=c({name:r().trim().min(1).max(120),description:r().trim().max(500).optional(),cron:r().trim().min(1).max(500).optional(),rate:r().trim().min(1).max(500).optional(),once:Mp.optional(),scheduleType:b(["rate","cron","once"]).optional(),scheduleExpression:r().trim().min(1).max(500).optional(),timezone:r().trim().min(1).max(100).optional(),enabled:A().default(!0),startAt:Mp.optional(),endAt:Mp.optional(),maxRuns:u().int().positive().nullable().optional(),runtimePolicy:b(["run_and_stop","run_and_archive","run_and_delete","use_existing_running"]).default("run_and_stop"),action:r().trim().min(1).max(120).optional(),actionName:r().trim().min(1).max(120).optional(),command:r().trim().min(1).max(2e3).optional(),target:c({kind:b(["start","action","service","command"]).optional(),name:r().trim().min(1).max(120).optional(),actionName:r().trim().min(1).max(120).optional(),command:r().trim().min(1).max(2e3).optional(),requiresStart:A().optional()}).strict().optional(),requiresStart:A().optional(),budget:c({maxUsd:r().trim().min(1).max(40).optional()}).strict().optional(),resources:sk.optional(),quotas:re(r(),ce()).optional(),lifecycle:re(r(),ce()).optional(),retentionPolicy:re(r(),ce()).optional(),env:p(c({name:r().trim().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).max(191),value:r().optional(),secretRef:r().optional()}).strict()).max(100).optional(),integrationLeases:p(re(r(),ce())).max(20).optional(),metadata:re(r(),ce()).optional()}).strict().superRefine((e,t)=>{[e.cron,e.rate,e.once,e.scheduleExpression].filter(l=>typeof l=="string"&&l.trim()).length!==1&&t.addIssue({code:zn.custom,path:["scheduleExpression"],message:"schedule must declare exactly one of cron, rate, once, or scheduleExpression"}),e.scheduleExpression&&!e.scheduleType&&t.addIssue({code:zn.custom,path:["scheduleType"],message:"scheduleType is required with scheduleExpression"});const a=e.command??e.target?.command??null,o=e.target?.name??null,i=e.actionName??e.action??e.target?.actionName??(e.target?.kind==="action"?o:null),s=e.target?.kind??(a?"command":"action");s==="action"&&!i&&t.addIssue({code:zn.custom,path:["action"],message:"schedule action target is required"}),s==="service"&&!o&&t.addIssue({code:zn.custom,path:["target","name"],message:"schedule service target name is required"}),s==="command"&&!a&&t.addIssue({code:zn.custom,path:["command"],message:"schedule command target is required"})}),Gj=c({schemaVersion:S(1),name:r().trim().min(1).max(80).regex(/^[a-z0-9][a-z0-9-]*[a-z0-9]$/),version:r().trim().min(1).max(40),useCase:r().trim().min(1).max(80),description:r().trim().min(1).max(500),runtime:Dj,resources:sk.optional(),setup:c({commands:Yb.default([])}).strict().default({commands:[]}),validation:c({commands:Yb.min(1),probes:p(Fj).max(20).default([])}).strict(),start:lk,actions:p(Qb).max(20).default([]),services:p(Qb).max(20).default([]),schedules:p(Wj).max(20).default([]),mcp:c({endpoints:p(Bj).max(10).default([])}).strict().default({endpoints:[]}),volumes:p(zj).max(5).default([]),integrations:c({requiredLeases:p(Lj).max(20).default([])}).strict().default({requiredLeases:[]}),permissions:Hj,inputs:c({schema:Vj.default({type:"object"}),env:p(Kj).max(100).default([])}).strict().default({schema:{type:"object"},env:[]}),artifacts:c({paths:p(Rl).max(100).default([])}).strict().default({paths:[]}),network:c({egress:b(["restricted","allow","block"]).default("restricted")}).strict().default({egress:"restricted"})}).strict().superRefine((e,t)=>{Jj(e,t),Jh(t,e.volumes.flatMap(n=>n.name?[n.name]:[]),"volume names must be unique","volumes"),Yj(e,t),Qj(e,t),Xj(e,t),eO(e,t)}),Zj=c({path:r(),message:r(),code:r()});function ZY(e){return[{kind:"start",name:"start",...e.start,artifactPaths:Op(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:Op(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:Op(t,e)}))]}function ck(e){return!e.includes("\0")&&!e.startsWith("/")&&!e.split(/[\\/]+/).some(t=>t===".."||t==="")}function Jh(e,t,n,a){const o=new Set;for(const i of t){if(o.has(i)){e.addIssue({code:zn.custom,path:[a],message:n});return}o.add(i)}}function Jj(e,t){const n=["start",...e.actions.map(a=>a.name),...e.services.map(a=>a.name)];Jh(t,n,"start, action, and service names must be unique","actions")}function Yj(e,t){const n=jp(e.inputs.schema.properties),a=new Set(e.volumes.map(o=>o.name).filter(o=>!!o));for(const[o,i]of Object.entries(n)){const s=jp(i),l=jp(s["x-openpond-upload"]??s.xOpenPondUpload),m=typeof l.targetPath=="string"&&l.targetPath.trim()?l.targetPath.trim():typeof l.path=="string"&&l.path.trim()?l.path.trim():"";if(!m)continue;const d=m.replace(/^workspace\//,"").replace(/^\/+/,"").replace(/\/+$/,"");if(!ck(d)){t.addIssue({code:zn.custom,path:["inputs","schema","properties",o,"x-openpond-upload","targetPath"],message:"upload target must be a relative workspace path"});continue}const h=d.split("/");h[0]==="volumes"&&(!h[1]||!a.has(h[1]))&&t.addIssue({code:zn.custom,path:["inputs","schema","properties",o,"x-openpond-upload","targetPath"],message:"upload target references an undeclared volume"})}}function Qj(e,t){Jh(t,e.inputs.env.map(n=>n.name),"env input names must be unique","inputs")}function Xj(e,t){const n=new Map(e.services.map(o=>[o.name,new Set(o.ports.map(i=>i.port))])),a=new Set([...e.start.ports.map(o=>o.port),...e.services.flatMap(o=>o.ports.map(i=>i.port))]);for(const[o,i]of e.mcp.endpoints.entries()){if(i.service){const s=n.get(i.service);if(!s){t.addIssue({code:zn.custom,path:["mcp","endpoints",o,"service"],message:`app MCP service does not exist: ${i.service}`});continue}s.has(i.port)||t.addIssue({code:zn.custom,path:["mcp","endpoints",o,"port"],message:`app MCP port ${i.port} is not declared on service ${i.service}`});continue}a.has(i.port)||t.addIssue({code:zn.custom,path:["mcp","endpoints",o,"port"],message:`app MCP port ${i.port} is not declared on start or services`})}}function eO(e,t){const n=new Set(e.actions.map(o=>o.name)),a=new Set(e.services.map(o=>o.name));for(const[o,i]of e.schedules.entries()){const s=i.command??i.target?.command??null;if(i.target?.kind==="command"||s)continue;const l=i.actionName??i.action??i.target?.actionName??(i.target?.kind==="action"?i.target?.name:null);if(l&&!n.has(l)&&t.addIssue({code:zn.custom,path:["schedules",o,"action"],message:`schedule action target does not exist: ${l}`}),i.target?.kind==="service"){const m=i.target.name??"";m&&!a.has(m)&&t.addIssue({code:zn.custom,path:["schedules",o,"target","name"],message:`schedule service target does not exist: ${m}`})}}}function jp(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Op(e,t){return e.artifactPaths.length>0?e.artifactPaths:t.artifacts.paths}const tO=c({id:r(),name:r(),description:r().nullable(),scheduleType:r(),scheduleExpression:r(),enabled:A(),rawEnabled:A().optional(),syncStatus:r().nullable(),syncError:r().nullable().optional(),startAt:r().nullable(),endAt:r().nullable(),maxRuns:u().nullable(),executionCount:u().nullable(),lifecycleStatus:r().nullable(),lifecycleReason:r().nullable(),lastExecutionAt:r().nullable().optional(),lastExecutionStatus:r().nullable().optional(),lastRunNowAt:r().nullable().optional(),lastRunNowStatus:r().nullable().optional(),updatedAt:r(),deploymentId:r(),isProduction:A().optional(),payload:ce().optional()}).passthrough(),nO=c({total:u().int().nonnegative(),active:u().int().nonnegative(),paused:u().int().nonnegative(),enabled:u().int().nonnegative().optional(),disabled:u().int().nonnegative().optional(),nextRunAt:r().nullable().optional(),lastRunAt:r().nullable().optional(),schedules:p(tO).optional().default([]),truncated:A().optional()}).passthrough(),$p=c({name:r(),kind:b(["start","action","service"]),command:r(),cwd:r().nullable(),timeoutSeconds:u().nullable(),requiresStart:A(),ports:p(c({port:u(),protocol:r(),label:r().nullable(),access:r(),path:r()}).passthrough()).default([]),artifactPaths:p(r()).default([])}).passthrough(),aO=c({schemaVersion:S(1),source:S("openpond.yaml"),manifestName:r(),manifestVersion:r(),manifestUseCase:r(),manifestDescription:r(),manifestPath:r(),manifestHash:r(),inputSchema:re(r(),ce()).default({}),env:p(c({name:r(),required:A(),secret:A(),description:r().nullable()}).passthrough()).default([]),start:$p,actions:p($p).default([]),services:p($p).default([]),defaultActionName:r().nullable(),updatedAt:r()}).passthrough(),oO=c({id:r(),name:r(),description:r().nullable(),visibility:r().nullable().optional(),gitOwner:r().nullable().optional(),gitRepo:r().nullable().optional(),gitHost:r().nullable().optional(),defaultBranch:r().nullable().optional(),sandbox:A().optional().default(!1),sandboxActionRegistry:aO.nullable().optional(),sandboxManifestHash:r().nullable().optional(),sandboxManifestPath:r().nullable().optional(),sandboxManifestSyncedAt:r().nullable().optional(),sandboxManifestError:r().nullable().optional(),updatedAt:r().nullable().optional(),latestDeployment:c({id:r().optional(),status:r().optional(),deploymentDomain:r().nullable().optional(),createdAt:r().optional(),isProduction:A().nullable().optional(),gitBranch:r().nullable().optional()}).nullable().optional(),scheduleSummary:nO.nullable().optional()}),rO=c({detected:A(),rootPath:r(),manifestPath:r(),manifestHash:r().nullable().optional().default(null),manifest:re(r(),ce()).nullable().optional().default(null),normalizedManifest:Gj.nullable().optional().default(null),valid:A().optional().default(!1),diagnostics:p(Zj).optional().default([])}),iO=c({appId:r(),appName:r(),gitOwner:r().nullable(),gitRepo:r().nullable(),gitHost:r().nullable(),defaultBranch:r().nullable(),linkedAt:r()}),dk=c({teamId:r(),projectId:r(),projectSlug:r().nullable().optional().default(null),projectName:r().nullable().optional().default(null),sourceRepoUrl:r().nullable().optional().default(null),defaultBranch:r().nullable().optional().default(null),lastUploadedCommit:r().nullable().optional().default(null),lastUploadTransport:b(["git_head","snapshot","api_source_upload"]).nullable().optional().default(null),manifestPath:r().nullable().optional().default(null),manifestHash:r().nullable().optional().default(null),syncedAt:r().nullable().optional().default(null),linkedAt:r()}),sO=b(["github_repo","internal_repo","template","manual"]),lO=c({id:r(),teamId:r(),name:r(),slug:r().nullable().optional().default(null),sourceType:sO.optional().default("manual"),sourceLabel:r().nullable().optional().default(null),defaultBranch:r().nullable().optional().default(null),internalRepoPath:r().nullable().optional().default(null),manifestPath:r().nullable().optional().default(null),manifestHash:r().nullable().optional().default(null),syncedAt:r().nullable().optional().default(null),organizationName:r().nullable().optional().default(null),organizationSlug:r().nullable().optional().default(null),createdAt:r().nullable().optional().default(null),updatedAt:r().nullable().optional().default(null)}),cO=c({id:r(),name:r(),path:r(),workspacePath:r(),repoPath:r().nullable(),source:b(["folder","git"]),sourceFolders:p(r().min(1)).min(1).optional(),hiddenFromDefaultSidebar:A().optional(),sandboxTemplate:rO.nullable().optional().default(null),linkedOpenPondApp:iO.nullable().optional().default(null),linkedSandboxProject:dk.nullable().optional().default(null),preferredSandboxAgentId:r().nullable().optional().default(null),createdAt:r(),updatedAt:r()});c({path:r().trim().min(1).optional(),sourceFolders:p(r().trim().min(1)).min(1).optional(),primaryFolder:r().trim().min(1).optional(),name:r().trim().min(1).max(120).optional(),createNew:A().optional(),baseDirectory:r().trim().min(1).max(4096).optional()}).superRefine((e,t)=>{if(e.createNew){(e.path||e.sourceFolders||e.primaryFolder)&&t.addIssue({code:"custom",message:"A new folder cannot be combined with existing source folders."}),e.name?.trim()||t.addIssue({code:"custom",path:["name"],message:"Project name is required when creating a new project."});return}e.path&&e.sourceFolders&&t.addIssue({code:"custom",message:"Use either path or source folders."}),!e.path?.trim()&&!e.sourceFolders?.length&&t.addIssue({code:"custom",path:["path"],message:"Project path is required."}),e.sourceFolders?.length&&!e.name?.trim()&&t.addIssue({code:"custom",path:["name"],message:"Project name is required."}),e.primaryFolder&&!e.sourceFolders?.length&&t.addIssue({code:"custom",path:["primaryFolder"],message:"Primary folder requires source folders."})});c({linkedSandboxProject:dk.nullable().optional(),preferredSandboxAgentId:r().nullable().optional(),hiddenFromDefaultSidebar:A().optional()});const dO=["connected_app_search","connected_app_read","connected_app_write"],Np="https://openpond.ai",Yh=["slack","google","github","turnkey","x","microsoft_teams","mcp"],Qh={slack:[Wt("slack.channel.bind","Bind channels","Bind Slack channels or threads to OpenPond profiles.","setup",!1),Wt("slack.message.ingest","Ingest messages","Ingest Slack channel or thread activity into OpenPond context.","setup",!1)],microsoft_teams:[Wt("microsoft_teams.channel.bind","Bind channels","Bind Teams channels or chats to OpenPond profiles.","setup",!1),Wt("microsoft_teams.message.ingest","Ingest messages","Ingest Teams channel or chat activity into OpenPond context.","setup",!1)],google:[Wt("google.drive.file.read","Read Drive files","Find and read Google Drive files.","read",!0),Wt("google.drive.file.write","Write Drive files","Create or update approved Google Drive files.","write",!0),Wt("google.docs.read","Read Docs","Read Google Docs content and structure.","read",!0),Wt("google.docs.write","Edit Docs","Apply approved Google Docs edits.","write",!0),Wt("google.comments.read","Read comments","Read Google file comments.","read",!0),Wt("google.comments.write","Write comments","Create or resolve approved Google comments.","write",!0)],github:[Wt("github.repo.read","Read repositories","Read repository metadata and file context.","read",!0),Wt("github.issue.read","Read issues","Read GitHub issues and comments.","read",!0),Wt("github.issue.write","Update issues","Create or update approved GitHub issue content.","write",!0),Wt("github.pull_request.read","Read pull requests","Read pull request metadata, diffs, checks, and reviews.","read",!0),Wt("github.pull_request.write","Update pull requests","Create approved comments or pull request updates.","write",!0)],turnkey:[Wt("turnkey.wallets.read","Read Agent Wallet","Read the connected OpenPond Agent Wallet address and metadata.","read",!0),Wt("turnkey.balances.read","Read wallet balances","Read balances for the connected OpenPond Agent Wallet.","read",!0),Wt("turnkey.activities.read","Read wallet activity","Read recent Turnkey activity for the connected OpenPond Agent Wallet.","read",!0)],x:[Wt("x.profile.read","Read profile","Read the connected X profile.","read",!0),Wt("x.search.read","Search X","Search public X posts when granted.","read",!0),Wt("x.mentions.read","Read mentions","Read mentions for the connected X account.","read",!0),Wt("x.post.write","Post","Create approved X posts.","write",!0),Wt("x.reply.write","Reply","Create approved X replies.","write",!0)],mcp:[Wt("mcp.tool.discover","Discover tools","Discover team-scoped MCP tools.","tooling",!1),Wt("mcp.tool.call","Call tools","Call approved MCP tools through the team endpoint.","tooling",!1)]},Xh={slack:[],microsoft_teams:[],google:[Lt("google.drive.search","search","Search Drive","Search Google Drive files by grounded query.",["google.drive.file.read"]),Lt("google.drive.read_file","read","Read Drive file","Read Drive file metadata or exported content by stable ref.",["google.drive.file.read"],{requiredKeys:["ref"]}),Lt("google.docs.read","read","Read Google Doc","Read Google Docs content and structure by stable ref.",["google.docs.read"],{requiredKeys:["ref"]}),Lt("google.comments.read","read","Read comments","Read comments for a grounded Google file ref.",["google.comments.read"],{requiredKeys:["ref"]}),Lt("google.docs.update","write","Update Google Doc","Apply an explicitly approved Google Docs edit and return readback verification.",["google.docs.write"],{requiredKeys:["ref","patch"]}),Lt("google.comments.create","write","Create comment","Create an explicitly approved Google file comment and return readback verification.",["google.comments.write"],{requiredKeys:["ref","body"]}),Lt("google.comments.resolve","write","Resolve comment","Resolve an explicitly approved Google comment and return readback verification.",["google.comments.write"],{requiredKeys:["ref","commentId"]})],github:[Lt("github.repo.search","search","Search repositories","Search accessible repositories by owner, name, or topic.",["github.repo.read"]),Lt("github.issue.search","search","Search issues","Search accessible GitHub issues.",["github.issue.read"]),Lt("github.pull_request.search","search","Search pull requests","Search accessible GitHub pull requests.",["github.pull_request.read"]),Lt("github.repo.read","read","Read repository","Read grounded repository metadata or file context.",["github.repo.read"],{requiredKeys:["ref"]}),Lt("github.issue.read","read","Read issue","Read a grounded GitHub issue and comments.",["github.issue.read"],{requiredKeys:["ref"]}),Lt("github.pull_request.read","read","Read pull request","Read a grounded pull request, checks, reviews, or diff summary.",["github.pull_request.read"],{requiredKeys:["ref"]}),Lt("github.issue.create","write","Create issue","Create an explicitly approved GitHub issue and return readback verification.",["github.issue.write"],{requiredKeys:["repo","title","body"]}),Lt("github.issue.comment","write","Comment on issue","Create an explicitly approved GitHub issue comment and return readback verification.",["github.issue.write"],{requiredKeys:["ref","body"]}),Lt("github.issue.update","write","Update issue","Apply an explicitly approved issue metadata/content update and return readback verification.",["github.issue.write"],{requiredKeys:["ref"]}),Lt("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"]}),Lt("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:[Lt("turnkey.wallets.read","read","Read Agent Wallet","Read the address and metadata for the connected OpenPond Agent Wallet.",["turnkey.wallets.read"]),Lt("turnkey.balances.read","read","Read wallet balances","Read supported-network balances for the connected OpenPond Agent Wallet.",["turnkey.balances.read"]),Lt("turnkey.activities.read","read","Read wallet activity","Read recent Turnkey activity for the connected OpenPond Agent Wallet.",["turnkey.activities.read"])],x:[Lt("x.profile.read","read","Read profile","Read the connected X account profile.",["x.profile.read"]),Lt("x.post.read","read","Read post","Read a public X post by stable ref, status URL, or post id.",["x.search.read"],{requiredKeys:["ref"]}),Lt("x.search.posts","search","Search recent posts","Search public X posts from the X recent-search window by grounded query.",["x.search.read"]),Lt("x.mentions.search","search","Search mentions","Search mentions for the connected X account.",["x.mentions.read"]),Lt("x.mention.read","read","Read mention","Read a grounded mention or post ref.",["x.mentions.read"],{requiredKeys:["ref"]}),Lt("x.post.create","write","Create post","Create an explicitly approved X post and return readback verification.",["x.post.write"],{requiredKeys:["text"]}),Lt("x.reply.create","write","Create reply","Create an explicitly approved X reply and return readback verification.",["x.reply.write"],{requiredKeys:["inReplyToRef","text"]})],mcp:[]},uO={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(`
|
|
98
|
-
`),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(`
|
|
99
|
-
`),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(`
|
|
100
|
-
`),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(`
|
|
101
|
-
`),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(`
|
|
102
|
-
`),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(`
|
|
103
|
-
`),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(`
|
|
104
|
-
`)},JY=Yh.map(e=>{const t=mk(e),n=uO[e];return{...t,provider:e,body:n,sourceHash:`connected-app-skill:${e}:${EO(n)}`,charCount:n.length}});function mO(e){const t=eg(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=CO(e.operation);if(e.toolName!==n)return{ok:!1,error:`Connected app tool ${e.toolName} does not match ${e.operation} operation.`};const a=e.operation==="write"?"write":"read",o=new Set(t.capabilities.filter(l=>l.access===a&&l.leaseable).map(l=>l.id)),i=e.capabilityIds.filter(l=>!o.has(l));if(i.length>0)return{ok:!1,error:`Connected app capability ${i[0]} is not allowed for ${e.provider} ${e.operation}.`};const s=fO(e);return s.ok?{ok:!0,request:e}:s}function pO(e){const t=cu(e);return t?Xh[t]:[]}function fO(e){const t=bO(e.args),n=pO(e.provider).filter(s=>s.operation===e.operation);if(n.length===0)return{ok:!1,error:`Connected app provider ${e.provider} does not declare ${e.operation} operations.`};if(!t)return e.operation==="write"?{ok:!1,error:`Connected app ${e.provider} write calls require a provider operation id.`}:{ok:!0,request:e};const a=n.find(s=>s.id===t);if(!a)return{ok:!1,error:`Connected app operation ${t} is not allowed for ${e.provider} ${e.operation}.`};const o=e.capabilityIds.filter(s=>!a.capabilityIds.includes(s));if(o.length>0)return{ok:!1,error:`Connected app operation ${a.id} does not allow capability ${o[0]}.`};const i=SO(e.args,e.operation);for(const s of a.input?.requiredKeys??[]){const l=i[s];if(l==null||typeof l=="string"&&!l.trim())return{ok:!1,error:`Connected app operation ${a.id} requires input.${s}.`}}return{ok:!0,request:e}}const hO=[{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"}],lu=hO,gO=Yh.map(e=>{const t=lu.filter(a=>a.providerFamily===e),n=t[0];return{id:e,label:gl(e),shortLabel:n.shortLabel,category:n.category,icon:n.icon,description:n.description,setupSurfaces:t,capabilities:Qh[e],skills:IO(e),tools:_O(e),operations:Xh[e],leasePolicy:RO(e)}});function uk(e){const t=vO(e);return t?lu.find(n=>n.id===t)??null:null}function eg(e){const t=cu(e);return t?gO.find(n=>n.id===t)??null:null}function YY(e){const t=uk(e.appId),n=kO(e.baseUrl),a=t?.kind==="mcp"?"/sandboxes/mcp":"/sandboxes/apps",o=new URL(a,n);t?.kind!=="mcp"&&o.searchParams.set("app",t?.deepLinkAppId??e.appId);const i=e.teamId?.trim();return i&&o.searchParams.set("teamId",i),o.toString()}function vO(e){const t=e?.trim().toLowerCase().replace(/[-\s]+/g,"_");return t?t==="teams"||t==="microsoft"?"microsoft_teams":lu.some(n=>n.id===t)?t:null:null}function cu(e){const t=e?.trim().toLowerCase().replace(/[-\s]+/g,"_");return t?t==="teams"||t==="microsoft"?"microsoft_teams":Yh.includes(t)?t:uk(t)?.providerFamily??null:null}function Dp(e={}){const t=PO(e.connections??[]);return lu.map(n=>{const a=eg(n.providerFamily),o=n.statusSource==="integration_connection"?t.filter(l=>l.provider===n.providerFamily):[],i=o.some(l=>l.status==="active"),s=AO(n,i);return{...n,providerLabel:a.label,setupSurfaceLabel:wO(n.setupSurface),status:s,statusLabel:TO(n,s,o),connections:o,connected:i,capabilities:Xb(n,a.capabilities),capabilityLabels:Xb(n,a.capabilities).map(l=>l.label),leasePolicy:a.leasePolicy}})}function Wt(e,t,n,a,o){return{id:e,label:t,description:n,access:a,leaseable:o}}function Lt(e,t,n,a,o,i){return{id:e,operation:t,label:n,description:a,capabilityIds:o,...i?{input:i}:{},requiresReadback:t==="write",requiresRuntimeLease:!1}}function bO(e){return yO(e.operation)}function yO(e){return typeof e=="string"&&e.trim()?e.trim():null}function SO(e,t){return t==="write"?xO(e.input)?e.input:{}:e}function xO(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function kO(e){const t=e?.trim();if(!t)return Np;try{const n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?Np:(n.pathname="/",n.search="",n.hash="",n.toString())}catch{return Np}}function gl(e){return e==="microsoft_teams"?"Microsoft Teams":e==="mcp"?"OpenPond MCP":e==="x"?"X":e[0].toUpperCase()+e.slice(1)}function wO(e){return e==="native_bot"?"Native app":e==="oauth_connector"?"OAuth connector":e==="wallet_connector"?"Wallet connector":"MCP endpoint"}function IO(e){return[mk(e)]}function mk(e){return{name:`${e}-connected-app`,description:`Use ${gl(e)} safely through connected app tools.`,path:`integration_skills/${e}.md`}}function _O(e){if(e==="mcp")return[];const t=Qh[e],n=Xh[e],a=t.filter(s=>s.access==="read").map(s=>s.id),o=t.filter(s=>s.access==="write").map(s=>s.id),i=[];return n.some(s=>s.operation==="search")&&i.push({name:"connected_app_search",description:`Search ${gl(e)} through a server-owned connected app connector.`,capabilityIds:a,write:!1}),n.some(s=>s.operation==="read")&&i.push({name:"connected_app_read",description:`Read a grounded ${gl(e)} object through a server-owned connected app connector.`,capabilityIds:a,write:!1}),o.length>0&&n.some(s=>s.operation==="write")&&i.push({name:"connected_app_write",description:`Perform an explicitly approved ${gl(e)} write through a server-owned connected app connector.`,capabilityIds:o,write:!0}),i}function CO(e){return e==="search"?"connected_app_search":e==="read"?"connected_app_read":"connected_app_write"}function RO(e){const t=Qh[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 Xb(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 PO(e){return e.flatMap(t=>{const n=cu(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 AO(e,t){return e.statusSource==="integration_connection"?t?"connected":"disconnected":"setup_available"}function TO(e,t,n){if(t==="connected"){const a=n.filter(o=>o.status==="active").length;return a>1?`${a} connected`:"Connected"}return t==="disconnected"?"Not connected":e.statusSource==="native_binding"?"Bot setup":"Configure"}function EO(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 MO=b(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),jO=b(["search","read","write"]),OO=b(dO);c({provider:MO,operation:jO,toolName:OO,sessionId:r().trim().min(1).max(200),turnId:r().trim().min(1).max(200),toolCallId:r().trim().min(1).max(300),userPrompt:r().max(2e5),connectionIds:p(r().trim().min(1).max(300)).min(1).max(8),capabilityIds:p(r().trim().min(1).max(200)).min(1).max(64),args:re(r(),ce()).default({})}).strict().superRefine((e,t)=>{const n=mO(e);n.ok||t.addIssue({code:zn.custom,message:n.error})});c({ok:A(),output:r().nullable().optional(),data:ce().optional()}).strict();const $O="local_path:";function pk(e){return`${$O}${e.trim()}`}c({appId:r(),source:b(["openpond","github","local_git","local_folder","unknown"]),workspacePath:r(),repoPath:r(),initialized:A(),remoteUrl:r().nullable(),expectedRemoteUrl:r().nullable(),currentBranch:r().nullable(),headCommit:r().nullable().optional().default(null),upstreamBranch:r().nullable().optional().default(null),ahead:u().int().nonnegative().optional().default(0),behind:u().int().nonnegative().optional().default(0),diverged:A().optional().default(!1),linkedSourceHeadCommit:r().nullable().optional().default(null),aheadOfLinkedSource:u().int().nonnegative().optional().default(0),behindLinkedSource:u().int().nonnegative().optional().default(0),divergedFromLinkedSource:A().optional().default(!1),linkedSourceComparisonError:r().nullable().optional().default(null),lastFetchAt:r().nullable().optional().default(null),defaultBranch:r().nullable(),branches:p(r()),dirty:A(),changedFilesCount:u(),untrackedFilesCount:u(),error:r().nullable(),updatedAt:r()});const NO=c({path:r(),status:r(),additions:u(),deletions:u(),patch:r(),content:r().nullable().optional().default(null)}),DO=c({appId:r(),repoPath:r(),initialized:A(),dirty:A(),filesChanged:u(),additions:u(),deletions:u(),repoFiles:p(r()).optional().default([]),files:p(NO),error:r().nullable(),updatedAt:r()});c({branch:r().trim().min(1).max(160)});c({path:r().trim().min(1),content:r()});const ey=c({line:u().int().nonnegative(),character:u().int().nonnegative()}),LO=c({start:ey,end:ey}),UO=c({path:r(),range:LO,severity:b(["error","warning","info","hint"]),message:r(),source:r().nullable().optional().default(null),code:r().nullable().optional().default(null)}),fk=c({id:r(),root:r(),status:b(["connected","unavailable","error"]),message:r().nullable().optional().default(null)});c({path:r().trim().min(1),content:r().optional(),waitForDiagnostics:A().optional().default(!0)});c({appId:r(),path:r(),diagnostics:p(UO),servers:p(fk),updatedAt:r()});const HO=c({operation:b(["hover","definition","references","documentSymbol"]),path:r().trim().min(1),content:r().optional(),line:u().int().nonnegative().optional(),character:u().int().nonnegative().optional()});c({appId:r(),operation:HO.shape.operation,path:r(),results:ce(),servers:p(fk),updatedAt:r()});const zO=c({pinned:A().optional(),archived:A().optional(),order:u().optional()}),qO=re(r(),zO),hk=b(["local","sandbox"]),BO=b(["pinned","saved_for_later"]),gk=c({id:r().min(1),workspaceKind:hk,workspaceId:r().min(1),workspaceName:r().min(1),path:r().min(1),status:BO,order:u().int().nonnegative().nullable().default(null),sourceSessionId:r().min(1).nullable().default(null),available:A().default(!0),createdAt:r().min(1),updatedAt:r().min(1)});c({items:p(gk)});c({workspaceKind:hk,workspaceId:r().trim().min(1),workspaceName:r().trim().min(1),path:r().trim().min(1),status:b(["pinned","saved_for_later","none"]),order:u().int().nonnegative().nullable().optional(),sourceSessionId:r().trim().min(1).nullable().optional()});b(["pin","save_for_later","remove","list"]);function FO(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 QY(e){return["sidebar-file",e.workspaceKind,encodeURIComponent(e.workspaceId),encodeURIComponent(FO(e.path))].join(":")}const VO=c({id:r(),name:r(),type:r(),status:r(),isActive:A().nullable(),price:r().nullable(),currency:r().nullable(),credits:r().nullable()}).passthrough(),KO=c({reachable:A(),authenticated:A().nullable(),apiBase:r(),latencyMs:u(),status:u().nullable(),service:r().nullable(),checkedAt:r(),error:r().nullable()}),WO=c({id:r().nullable(),email:r().nullable(),name:r().nullable(),handle:r().nullable(),image:r().nullable(),timezone:r().nullable(),isAdmin:A().nullable(),isVerified:A().nullable(),dailyAgentAppId:r().nullable(),dailyAgentDeploymentId:r().nullable(),credits:r().nullable()}),GO=c({handle:r(),baseUrl:r().nullable().optional()}),ZO=c({state:b(["signed_out","signed_in","loading","switching","auth_error"]),activeProfile:GO.nullable(),label:r(),email:r().nullable(),avatarUrl:r().nullable(),environment:r().nullable(),baseUrl:r().nullable(),apiBaseUrl:r().nullable(),chatApiBaseUrl:r().nullable().optional().default(null),creditsLabel:r().nullable(),profile:WO.nullable(),products:p(VO),apiHealth:KO.nullable(),accounts:p(c({handle:r(),baseUrl:r().nullable(),apiBaseUrl:r().nullable().optional().default(null),chatApiBaseUrl:r().nullable().optional(),environment:r().nullable(),isActive:A(),authHealth:b(["signed_out","signed_in","auth_error","unknown"]),displayLabel:r().nullable(),email:r().nullable().optional().default(null),avatarUrl:r().nullable(),apiKeyHint:r().nullable().optional(),apiKeyAccess:c({ownerType:b(["user","team","organization","service"]).nullable(),teamId:r().nullable(),scopes:p(r())}).nullable().optional().default(null)})),error:r().nullable()}),ty=c({asOf:r().nullable(),refreshing:A(),lastRefreshError:r().nullable(),source:b(["fresh","cache","empty"])}),JO=c({available:A(),binaryPath:r().nullable(),version:r().nullable(),authHealth:b(["unknown","signed_in","signed_out","auth_error"]),account:c({type:r(),email:r().nullable(),planType:r().nullable(),label:r().nullable()}).nullable().default(null),appServer:c({status:b(["idle","starting","ready","error"]),lastError:r().nullable()})}),tg="gpt-5.6-sol",us="openpond-chat",Qr="openpond",Pl=us,ng="default",ag="high",du="ask",Is=oi,og=b(["default","auto-review","full-access"]),Yl=b(["ask","full-access","disabled"]),uu=b(["off","low","medium","high","xhigh","max"]),Ql=b(["sandbox_app","local_project","sandbox","sandbox_template"]);b(["openpond"]);const YO=b(["provider_usage","provider_tokenizer","model_family","heuristic"]),QO=c({provider:Is,model:r().min(1),usedTokens:u().int().nonnegative(),maxContextTokens:u().int().positive(),usableContextTokens:u().int().positive(),percentFull:u().min(0).max(100),source:YO,updatedAtEventId:r().nullable()}),Of=c({pinned:A().default(!1),projects:A().default(!1),cloudProjects:A().default(!1),chats:A().default(!1),savedForLater:A().default(!0)}),XO=b(["auto","off"]),e2=b(["typescript","python","rust"]),vk=b(["auto","disabled","custom"]),Io=c({mode:vk.default("auto"),customCommand:r().trim().max(4096).default("")}),Td=c({languageServers:XO.default("auto"),diagnosticsWhileEditing:A().default(!0),checkOnSave:A().default(!0),languages:c({typescript:Io.optional().default(()=>Io.parse({})),python:Io.optional().default(()=>Io.parse({})),rust:Io.optional().default(()=>Io.parse({}))}).optional().default(()=>({typescript:Io.parse({}),python:Io.parse({}),rust:Io.parse({})}))}),t2=c({language:e2,label:r(),mode:vk,status:b(["found","missing","disabled","error"]),command:r().nullable(),message:r().nullable()});c({settings:Td,languages:p(t2),updatedAt:r()});const n2=c({id:r(),root:r(),status:b(["starting","connected","unavailable","error"]),message:r().nullable().optional().default(null),openedDocuments:u().int().nonnegative(),pendingRequests:u().int().nonnegative(),lastUsedAt:r(),stderrTail:r()});c({clients:p(n2),maxClients:u().int().positive(),idleTimeoutMs:u().int().positive(),updatedAt:r()});const $f=c({autoEnabled:A().default(!0),triggerPercent:u().int().min(50).max(95).default(85),summaryModel:b(["same_model"]).default("same_model")}),Nf=c({defaultModelRef:cn.nullable().default(null),creationMode:b(["defaults","customize"]).default("customize"),autoApproveEvidence:A().default(!1)}),ny=c({defaultChatProvider:Is.default(Qr),defaultChatModel:r().min(1).default(Pl),defaultChatModelRef:cn.nullable().optional(),subagents:Cl.optional().default(()=>Cl.parse({})),codexPermissionMode:og.default(ng),codexReasoningEffort:uu.default(ag),openPondCommandAccessMode:Yl.default(du),defaultBranchPrefix:r().trim().max(48).default("feat/"),defaultNewProjectDirectory:r().trim().max(4096).default(""),defaultTeamId:r().trim().max(191).nullable().default(null),advancedWorkspaceControls:A().default(!1),steerActiveResponses:A().default(!0),contextCompaction:$f.optional().default(()=>$f.parse({})),training:Nf.optional().default(()=>Nf.parse({})),sidebarWidth:u().int().min(244).max(560).default(332),diffPanelWidth:u().int().min(320).max(2400).default(560),sidebarSectionsCollapsed:Of.optional().default(()=>Of.parse({})),editor:Td.optional().default(()=>Td.parse({}))}),a2="default",bk=[{id:"default",name:"Balanced",source:"built_in",description:"Clear, useful, and concise.",content:`You are OpenPond Chat, a clear and useful AI assistant.
|
|
105
|
-
Be concise, accurate, and direct.
|
|
106
|
-
Do not use emojis.
|
|
107
|
-
Ask only when missing information would materially change the answer.
|
|
108
|
-
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.
|
|
109
|
-
Be direct, concrete, and outcome-focused.
|
|
110
|
-
Do not use emojis.
|
|
111
|
-
Prefer simple working solutions over clever abstractions.
|
|
112
|
-
Call out weak assumptions plainly.`},{id:"friendly",name:"Friendly",source:"built_in",description:"Warm, conversational, and approachable.",content:`You are a friendly AI assistant.
|
|
113
|
-
Use a warm, conversational tone without filler.
|
|
114
|
-
Do not use emojis.
|
|
115
|
-
Explain decisions clearly and keep the user moving.
|
|
116
|
-
Be patient when clarifying tradeoffs.`},{id:"formal",name:"Formal",source:"built_in",description:"Polished, careful, and professional.",content:`You are a formal AI assistant.
|
|
117
|
-
Use precise, professional language.
|
|
118
|
-
Do not use emojis.
|
|
119
|
-
Structure answers clearly and avoid casual phrasing.
|
|
120
|
-
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.
|
|
121
|
-
Prioritize correctness, implementation detail, and edge cases.
|
|
122
|
-
Do not use emojis.
|
|
123
|
-
Use concise explanations, but include necessary specifics.
|
|
124
|
-
Surface risks, constraints, and verification steps.`}],rg=r().trim().min(1).max(120),o2=c({id:rg,name:r(),source:b(["built_in","custom"]).default("custom"),description:r(),content:r()}),ay=c({activeTemplateId:rg.default(a2),customized:A().default(!1),soul:r(),soulPath:r().nullable(),updatedAt:r().nullable(),templates:p(o2).default(()=>[...bk])}),r2=c({id:r(),host:r(),port:u(),startedAt:r(),storePath:r(),version:r(),runtimeVersion:r()}),ig=b(["chat","work","development"]);b(["chat","models","console","development"]);const i2="work",Ve=r().trim().min(1).nullable(),Pa=re(r(),ce()).default({}),s2=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"]),yk=b(["/create","/edit","openpond extend","create_as_agent","suggest_workflow","local_import","lab_create","lab_improve","training"]),l2=b(["create","improve","import","promote"]),c2=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"]),qc=b(["always_require_plan_approval","approval_already_granted"]);b(["local_profile","hosted_profile","promote_local_to_hosted","managed_artifact"]);const d2=It("kind",[c({kind:S("local"),sourceAuthority:S("local_profile"),activeProfile:r().trim().min(1).nullable(),repoPath:Ve,sourcePath:Ve,localHead:Ve,confirmationPolicy:qc.default("always_require_plan_approval")}),c({kind:S("hosted"),sourceAuthority:S("hosted_profile"),teamId:Ve,projectId:Ve,activeProfile:r().trim().min(1).nullable(),sourceRef:Ve,baseSha:Ve,confirmationPolicy:qc.default("always_require_plan_approval")}),c({kind:S("promote_local_to_hosted"),sourceAuthority:S("promote_local_to_hosted"),teamId:Ve,projectId:Ve,activeProfile:r().trim().min(1).nullable(),repoPath:Ve,sourcePath:Ve,localHead:Ve,hostedHead:Ve,sourceRef:Ve,confirmationPolicy:qc.default("always_require_plan_approval")}),c({kind:S("managed_artifact"),sourceAuthority:S("managed_artifact"),activeProfile:r().trim().min(1).nullable(),confirmationPolicy:qc.default("always_require_plan_approval")})]),u2=c({id:Ve,kind:b(["user","system","automation"]).default("user"),label:Ve}),m2=c({profileId:r().trim().min(1),conversationId:Ve,originTurnId:Ve,projectId:Ve,targetProject:c({id:Ve,name:Ve,workspacePath:Ve,sourceRef:Ve,baseSha:Ve}).nullable()}),dl=c({messageIds:p(r().trim().min(1)).default([]),conversationExcerpts:p(c({messageId:Ve,role:r().trim().min(1).nullable(),excerpt:r().trim().min(1),reason:r().trim().min(1).nullable()})).default([]),attachments:p(c({id:Ve,name:r().trim().min(1),mediaType:Ve,ref:Ve})).default([]),apps:p(c({id:r().trim().min(1),name:r().trim().min(1),connectionId:Ve,required:A().default(!1)})).default([]),tools:p(c({name:r().trim().min(1),inputSummary:Ve,outputSummary:Ve,artifactRefs:p(r().trim().min(1)).default([]),sideEffects:p(r().trim().min(1)).default([])})).default([]),signalRefs:p(r().trim().min(1)).default([]),evalRefs:p(r().trim().min(1)).default([]),targetRepoAssumptions:p(r().trim().min(1)).default([])}),Ni={id:Ve,displayName:Ve},sg=It("kind",[c({kind:S("unselected"),...Ni}),c({kind:S("agent"),...Ni,defaultActionKey:Ve}),c({kind:S("skill"),...Ni,skillName:Ve}),c({kind:S("extension"),...Ni,slot:Ve}),c({kind:S("model"),...Ni,trainingPlanId:Ve,trainingJobId:Ve,artifactId:Ve}),c({kind:S("configuration"),...Ni,key:Ve})]),Df=b(["agent","skill","extension","model","configuration"]),p2=c({schemaVersion:S("openpond.createImprove.evidenceSnapshot.v1"),id:r().trim().min(1),contentHash:r().trim().min(8),consent:c({status:b(["granted","denied","revoked"]),scope:b(["metadata_only","selected_turns","full_session","direct_intent"]),reviewedBy:Ve,reviewedAt:r().trim().min(1)}),sources:p(c({kind:b(["signal","conversation","direct_correction","manual_intent","artifact"]),id:r().trim().min(1),sourceHash:r().trim().min(8),excerptRef:Ve})).min(1),reviewerIntent:r().trim().min(1),createdAt:r().trim().min(1),metadata:Pa}),Sk=c({schemaVersion:S("openpond.createImprove.tasksetRef.v1"),id:r().trim().min(1),revision:u().int().positive(),contentHash:r().trim().min(8),evidenceSnapshotIds:p(r().trim().min(1)).min(1),policyBoundary:c({policyVisibleFields:p(r().trim().min(1)).default([]),privilegedFields:p(r().trim().min(1)).default([]),hiddenGraderRefs:p(r().trim().min(1)).default([]),connectedAppScopes:p(r().trim().min(1)).default([])}),targetRecommendation:c({kind:Df,rationale:p(r().trim().min(1)).min(1),confidence:u().min(0).max(1)}),authoringSplitRefs:p(r().trim().min(1)).default([]),privateSplitRefs:p(r().trim().min(1)).default([]),approvedBy:Ve,approvedAt:r().trim().min(1),metadata:Pa}),f2=c({kind:b(["npm_package","runtime_tool","setup_command","secret","integration","volume","target_project","external_service"]),name:r().trim().min(1),status:b(["declared","required","blocked","satisfied"]).default("declared"),detail:Ve,metadata:Pa}),h2=c({mode:b(["chat","direct_action","chat_and_direct_actions"]),label:r().trim().min(1),detail:r().trim().min(1),defaultActionKey:Ve,directActionHint:Ve,artifactPolicy:r().trim().min(1)}),g2=c({schemaVersion:S("openpond.createImprove.plan.v1"),id:r().trim().min(1),runId:r().trim().min(1),status:b(["draft","pending_approval","approved","rejected","cancelled","superseded"]).default("pending_approval"),objective:r().trim().min(1),summary:r().trim().min(1),capturedContextSummary:r().trim().min(1),defaultChatAction:c({key:Ve,label:Ve,required:A().default(!0)}),sourcePlan:p(c({path:r().trim().min(1),operation:b(["create","update","delete","inspect"]),reason:r().trim().min(1)})).default([]),requirements:p(f2).default([]),checks:p(c({name:r().trim().min(1),command:r().trim().min(1),required:A().default(!0)})).default([]),approvalId:Ve,approvedAt:Ve,editedFromPlanId:Ve,metadata:Pa,createdAt:r().trim().min(1),updatedAt:r().trim().min(1)}),v2=c({id:r().trim().min(1),label:r().trim().min(1),value:r().trim().min(1),description:Ve,metadata:Pa}),b2=c({value:r().trim().min(1),label:Ve,detail:Ve,answeredAt:r().trim().min(1),metadata:Pa}),y2=c({id:r().trim().min(1),kind:b(["single_choice","free_text"]).default("single_choice"),title:r().trim().min(1),prompt:r().trim().min(1),required:A().default(!0),status:b(["pending","answered","skipped"]).default("pending"),options:p(v2).default([]),answer:b2.nullable().default(null),metadata:Pa}),S2=c({schemaVersion:S("openpond.createImprove.workflowCapture.v1"),id:r().trim().min(1),runId:r().trim().min(1),command:yk,objective:r().trim().min(1),conversationExcerpts:dl.shape.conversationExcerpts,attachments:dl.shape.attachments,apps:dl.shape.apps,tools:dl.shape.tools,sideEffects:p(r().trim().min(1)).default([]),profileActions:p(r().trim().min(1)).default([]),externalProviders:p(r().trim().min(1)).default([]),environmentVariables:p(r().trim().min(1)).default([]),files:p(r().trim().min(1)).default([]),schedules:p(r().trim().min(1)).default([]),webhooks:p(r().trim().min(1)).default([]),channelTargets:p(r().trim().min(1)).default([]),outputArtifacts:p(r().trim().min(1)).default([]),targetRepoAssumptions:p(r().trim().min(1)).default([]),traceRefs:p(r().trim().min(1)).default([]),metadata:Pa,createdAt:r().trim().min(1)}),xk=c({provider:S("github"),number:u().int().positive(),url:r().url(),state:b(["open","merged","closed"]),baseBranch:r().trim().min(1),headBranch:r().trim().min(1),mergeCommit:Ve,openedAt:r().trim().min(1),updatedAt:r().trim().min(1)}),x2=c({baseBranch:r().trim().min(1),baseCommit:r().trim().min(1),branch:r().trim().min(1),headCommit:Ve,remoteName:r().trim().min(1).default("origin"),remoteUrl:Ve,worktreePath:Ve,changedPaths:p(r().trim().min(1)).default([]),diffStat:Ve,pullRequest:xk.nullable().default(null)}),k2=c({id:r().trim().min(1),target:sg,status:b(["draft","authored","checking","evaluated","accepted","rejected","failed"]),git:x2.nullable().default(null),parentCandidateId:Ve.default(null),tasksetRef:Sk.nullable().default(null),authoringModelRef:Ve.default(null),allowedPaths:p(r().trim().min(1)).default([]),sourceRefs:p(r().trim().min(1)).default([]),artifactRefs:p(r().trim().min(1)).default([]),checkRefs:p(r().trim().min(1)).default([]),evaluationReceiptRefs:p(r().trim().min(1)).default([]),createdAt:r().trim().min(1),updatedAt:r().trim().min(1),metadata:Pa}),w2=c({id:r().trim().min(1),candidateId:Ve,target:sg,evaluatorKind:b(["agent_sdk","taskset","extension","skill","configuration","checks"]).default("checks"),subject:b(["active","candidate","post_release","standalone"]).default("standalone"),sourceCommit:Ve.default(null),sourceBranch:Ve.default(null),tasksetId:Ve.default(null),tasksetHash:Ve.default(null),taskAttemptRefs:p(r().trim().min(1)).default([]),status:b(["pending","passed","failed","blocked"]),publishGate:b(["passed","failed","not_applicable"]).default("not_applicable"),summaryCounts:c({total:u().int().nonnegative(),passed:u().int().nonnegative(),failed:u().int().nonnegative()}).nullable().default(null),evalRefs:p(r().trim().min(1)).default([]),artifactRefs:p(r().trim().min(1)).default([]),summary:Ve,createdAt:r().trim().min(1),metadata:Pa}),I2=c({mode:b(["foreground","background"]).default("background"),pauseAllowed:A().default(!0),cancellationAllowed:A().default(!0)}),_2=c({mode:b(["single","bounded","until_evals_pass"]).default("single"),maximumAttempts:u().int().min(1).max(20).default(1),currentAttempt:u().int().min(0).max(20).default(0)}),C2=c({kind:b(["candidate_authoring","local_apply","hosted_turn","training_job","evaluation","pull_request","release"]),id:r().trim().min(1),status:Ve,metadata:Pa}),R2=c({status:b(["not_requested","pending","released","rejected","rolled_back"]),profileCommit:Ve,profileTag:Ve,releaseReceiptRef:Ve,pullRequest:xk.nullable().default(null),updatedAt:Ve}),Xl=c({schemaVersion:S("openpond.createImprove.run.v1"),id:r().trim().min(1),revision:u().int().nonnegative(),operation:l2,surface:s2,command:yk,objective:r().trim().min(1),state:c2,adapter:d2,actor:u2,scope:m2,context:dl,target:sg,evidenceSnapshots:p(p2).default([]),tasksetRef:Sk.nullable().default(null),targetSelection:c({status:b(["open","recommended","confirmed"]),preselectedKind:Df.nullable(),confirmedKind:Df.nullable()}).nullable().default(null),plan:g2.nullable(),workflowCapture:S2.nullable(),executionPolicy:I2.default({mode:"background",pauseAllowed:!0,cancellationAllowed:!0}),iterationPolicy:_2.default({mode:"single",maximumAttempts:1,currentAttempt:0}),approvalIds:p(r().trim().min(1)).default([]),questionIds:p(r().trim().min(1)).default([]),questions:p(y2).default([]),candidates:p(k2).default([]),evaluationReceipts:p(w2).default([]),checkRefs:p(r().trim().min(1)).default([]),sourceRefs:p(r().trim().min(1)).default([]),externalExecutionRefs:p(C2).default([]),localProfileCommit:Ve,hostedSourceCommit:Ve,hostedSourceRef:Ve,releaseOutcome:R2.default({status:"not_requested",profileCommit:null,profileTag:null,releaseReceiptRef:null,pullRequest:null,updatedAt:null}),blockedReason:Ve,appliedActionIds:p(r().trim().min(1)).max(200).default([]),metadata:Pa,createdAt:r().trim().min(1),updatedAt:r().trim().min(1)}),to={runId:r().trim().min(1),expectedRevision:u().int().nonnegative(),actionId:r().trim().min(1)};It("type",[c({...to,type:S("answer_question"),questionId:r().trim().min(1),value:r().trim().min(1)}),c({...to,type:S("approve_plan")}),c({...to,type:S("revise_plan"),revision:r().trim().min(1)}),c({...to,type:S("cancel"),reason:Ve.optional().default(null)}),c({...to,type:S("pause")}),c({...to,type:S("resume")}),c({...to,type:S("open_pull_request"),candidateId:r().trim().min(1)}),c({...to,type:S("apply_candidate"),candidateId:r().trim().min(1)}),c({...to,type:S("reject_candidate"),candidateId:r().trim().min(1),reason:Ve.optional().default(null)}),c({...to,type:S("reconcile_pull_request"),candidateId:r().trim().min(1)})]);c({schemaVersion:S("openpond.createImprove.runList.v1"),runs:p(Xl),generatedAt:r().trim().min(1)});function XY(e){const t=h2.safeParse(e?.actionShape);return t.success?t.data:null}const kr=c({source:b(["local","github","openpond_git"]),repositoryId:r().trim().min(1),profileId:r().trim().min(1)}),P2=c({ref:kr,revision:r().nullable(),sourceHash:r()}),_s=re(r(),ce()).default({}),Sa=u().int().nonnegative(),mu=r().trim().min(1).max(1e5),kk=c({kind:b(["personal","team"]),id:T}).strict(),A2=c({name:T,release:Z.nullable(),revision:Sa}).strict();c({schemaVersion:S("openpond.harnessWorkspace.v1"),id:T,ownerScope:kk,name:r().trim().min(1).max(240),location:b(["local","hosted"]),sourceRevision:r().trim().min(1).max(500),revision:Sa,dirty:A(),currentChannel:A2,createdAt:Oe,updatedAt:Oe,metadata:_s}).strict();const ms=b(["runtime","memory","prompt","skill","agent","product","taskset","training"]),wk=b(["text_instruction","memory","dependency_selection","executable_code","business_logic","financial_logic","permission","connected_app","publication","deployment","training","model_binding","team_or_global"]),Ik=c({id:T,route:ms,operation:b(["create","update","delete"]),target:r().trim().min(1).max(2e3),summary:r().trim().min(1).max(2e3),content:r().max(1e6).nullable(),contentHash:J.nullable(),effects:p(wk).min(1).max(20)}).strict().superRefine((e,t)=>{if(e.operation==="delete"){(e.content!==null||e.contentHash!==null)&&t.addIssue({code:"custom",message:"delete edits cannot include replacement content",path:["content"]});return}if(e.content===null||e.contentHash===null){t.addIssue({code:"custom",message:"create and update edits require content and contentHash",path:["content"]});return}const n=Xt(e.content);e.contentHash!==n&&t.addIssue({code:"custom",message:`edit contentHash is ${e.contentHash}; expected ${n}`,path:["contentHash"]})}),_k=c({workspaceId:T,revision:Sa,sourceRevision:r().trim().min(1).max(500),channelRevision:Sa}).strict(),Oo=c({id:T,revision:Sa,contentHash:J}).strict(),T2=c({schemaVersion:S("openpond.harnessTurnSnapshot.v1"),workspaceId:T,workspaceRevision:Sa,sourceRevision:r().trim().min(1).max(500),channelName:T,channelRevision:Sa,harnessRelease:Z,toolCatalogHash:J.nullable().optional(),overlay:Oo.nullable().optional().default(null)}).strict(),E2=c({schemaVersion:S("openpond.harnessRunOverlay.v1"),id:T,runId:T,baseHarnessRelease:Z,workspace:_k,revision:Sa,status:b(["active","frozen","abandoned"]),edits:p(Ik).max(1e3),createdAt:Oe,updatedAt:Oe,metadata:_s}).strict();E2.extend({contentHash:J}).strict();const Ck=c({kind:b(["tool_event","recovery","validation","user_turn","work_output","work_receipt"]),id:T,contentHash:J.nullable()}).strict(),Rk=c({id:T,kind:b(["dependency","schema","package","file_render","skill","prompt","business_formula","targeted_evaluation","observed_recovery","memory","component_activation"]),description:mu,required:A()}).strict(),M2=c({schemaVersion:S("openpond.harnessImprovementProposal.v1"),id:T,overlay:Oo,baseHarnessRelease:Z,expectedWorkspace:_k,requestedScope:b(["personal","team","global"]),route:ms,risk:b(["low","review","restricted"]),effects:p(wk).min(1).max(20),evidence:p(Ck).min(1).max(1e3),edits:p(Ik).min(1).max(1e3),validationPlan:p(Rk).min(1).max(100),expectedOutcome:mu,createdAt:Oe,metadata:_s}).strict().superRefine((e,t)=>{const n=new Set(e.effects);for(const[a,o]of e.edits.entries()){o.route!==e.route&&t.addIssue({code:"custom",message:"every edit route must match the proposal route",path:["edits",a,"route"]});for(const i of o.effects)n.has(i)||t.addIssue({code:"custom",message:`edit effect ${i} is missing from proposal effects`,path:["edits",a,"effects"]})}new Set(e.validationPlan.map(a=>a.id)).size!==e.validationPlan.length&&t.addIssue({code:"custom",message:"validation plan ids must be unique",path:["validationPlan"]})});M2.extend({contentHash:J}).strict();const j2=c({schemaVersion:S("openpond.harnessTargetedValidationReceipt.v1"),id:T,proposal:Z,validationId:T,kind:Rk.shape.kind,status:b(["passed","failed","blocked","skipped"]),summary:mu,evidenceRefs:p(Ck).max(1e3),createdAt:Oe,metadata:_s}).strict();j2.extend({contentHash:J}).strict();const O2=b(["advanced","retained","conflict","rolled_back"]),$2=c({schemaVersion:S("openpond.harnessAdvanceReceipt.v1"),id:T,workspaceId:T,ownerScope:kk,proposal:Z.nullable(),expectedWorkspaceRevision:Sa,observedWorkspaceRevision:Sa,previousChannelRevision:Sa,nextChannelRevision:Sa,previousRelease:Z.nullable(),nextRelease:Z.nullable(),validationReceipts:p(Z).max(100),decision:O2,reason:mu,rollbackOf:Z.nullable(),createdAt:Oe,metadata:_s}).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"]})});$2.extend({contentHash:J}).strict();const N2=c({schemaVersion:S("openpond.harnessOverlayMergeReceipt.v1"),id:T,workspaceId:T,baseHarnessRelease:Z,leftOverlay:Oo,rightOverlay:Oo,decision:b(["merged","conflict"]),mergedOverlay:Oo.nullable(),conflictTargets:p(r().trim().min(1).max(2e3)).max(1e3),requiresRevalidation:S(!0),createdAt:Oe,metadata:_s}).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"]})});N2.extend({contentHash:J}).strict();const $o=r().trim().min(1).max(1e5),D2=b(["no_action","harness_maintenance","runtime","product","taskset","model_improvement"]),L2=b(["none","runtime_service","product_team","human_review","evaluation_system","training_system"]),Pk=b(["observation","trigger","route_decision","refiner_outcome","proposal","validation","apply_receipt","harness_advance","rollback","work_outcome","taskset","evaluation","training_qualification","model_candidate"]),lg=c({kind:b(["personal","team"]),id:T}).strict(),Ak=c({policy:Z,state:b(["authorized","revoked","deleted","expired"]),checkedAt:Oe}).strict(),Al=c({evidence:Z,kind:Pk,sourceRef:T,sourcePolicy:Ak,occurrenceKey:J,occurredAt:Oe}).strict(),U2=c({evidence:Z,sourcePolicy:Ak.nullable(),reason:b(["outside_scope","before_watermark","duplicate","resolved","revoked","deleted","expired","sensitive","unverified","budget"])}).strict(),oy=c({cursor:J,throughCreatedAt:Oe}).strict(),H2=c({fingerprint:J,recurrenceFamily:r().trim().min(1).max(1e3),statement:$o,candidateDisposition:b(["observe","confirm"]).optional(),independentOccurrences:u().int().positive().max(1e6),unresolvedOccurrences:u().int().positive().max(1e6)}).strict().refine(e=>e.unresolvedOccurrences<=e.independentOccurrences,"unresolved occurrences cannot exceed independent occurrences"),Tk=b(["harness","runtime","product","retrieval","tools","evaluation","model"]),z2=c({layer:Tk,status:b(["not_applicable","unresolved","resolved","blocked"]),reason:$o,evidenceRefs:p(Z).max(1e3)}).strict(),q2=c({schemaVersion:S("openpond.harnessEvaluationReviewReceipt.v1"),id:T,ownerScope:lg,workspaceRef:T,harnessRelease:Z,previousWatermark:oy.nullable(),nextWatermark:oy,selectedEvidence:p(Al).max(1e4),excludedEvidence:p(U2).max(1e4),claim:H2.nullable(),classification:D2,triage:p(z2).max(16),reason:$o,nextAuthority:L2,maxEstimatedCostUsd:u().finite().nonnegative(),tasksetProposal:Z.nullable(),evaluation:Z.nullable(),trainingQualification:Z.nullable(),policyVersion:T,createdAt:Oe,metadata:In}).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"})});q2.extend({contentHash:J}).strict();c({id:T,evidence:Z,kind:Pk,sourceRef:T,occurredAt:Oe,payload:re(r(),ce())}).strict();const B2=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("no_action"),reason:$o,ignoredEvidence:p(c({id:T,reason:r().trim().min(1).max(2e3)}).strict()).max(1e3)}).strict(),F2=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("review"),classification:b(["harness_maintenance","runtime","product","taskset"]),selectedEvidenceIds:p(T).min(1).max(1e3),ignoredEvidence:p(c({id:T,reason:r().trim().min(1).max(2e3)}).strict()).max(1e3),recurrenceFamily:r().trim().min(1).max(1e3),statement:$o,triageLayer:Tk,expectedOutcome:$o,counterevidence:r().trim().max(1e4),confidence:u().min(0).max(1),candidateDisposition:b(["observe","confirm"]).nullable(),reason:$o}).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"]})}),V2=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("resolve_candidate"),candidateId:T,candidateFingerprint:J,selectedEvidenceIds:p(T).min(1).max(1e3),ignoredEvidence:p(c({id:T,reason:r().trim().min(1).max(2e3)}).strict()).max(1e3),confidence:u().min(0).max(1),reason:$o}).strict();It("decision",[B2,F2,V2]);c({schemaVersion:S("openpond.harnessEvaluationReviewNavigationDecision.v1"),selectedEvidenceIds:p(T).min(1).max(50),reason:$o}).strict();const ec=c({name:r().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:r().trim().min(1).max(2e3),inputSchema:re(r(),ce()),inputSchemaHash:J,sideEffect:b(["read","write"]),timeoutMs:u().int().positive().max(36e5)}).strict(),cg=c({id:T,required:A(),scopes:p(r().trim().min(1).max(500)).max(100).default([]),portability:b(["portable","host_adapter","local_only","hosted_only"])}).strict(),K2=c({portable:A(),blockers:p(r().trim().min(1).max(2e3)).max(1e3),localOnlyAssetRefs:p(T).max(1e4),hostPrivateAssetRefs:p(T).max(1e4)}).strict(),W2=c({schemaVersion:S("openpond.agentSnapshot.v2"),id:T,sourceRelease:Z.nullable(),instructions:p(sn).max(1e4),skills:p(sn).max(1e4),agents:p(sn).max(1e4),toolDeclarations:p(ec).max(200),capabilityRequirements:p(cg).max(200),dependencyLock:sn,portability:K2,metadata:In}).strict(),G2=W2.extend({contentHash:J}).strict(),Ek=c({create:S(!0),reset:S(!0),step:S(!0),collect:S(!0),destroy:S(!0),resetScope:b(["task","attempt"])}).strict(),Mk=c({visibleEvidence:p(T).max(1e3),privilegedEvidence:p(T).max(1e3),privateVerifierIsolation:A()}).strict(),Z2=c({schemaVersion:S("openpond.harnessRelease.v2"),id:T,agentSnapshot:Z,program:sn,tools:p(ec).max(200),lifecycle:Ek,graderInterface:Mk,files:p(sn).max(1e5),metadata:In}).strict(),J2=Z2.extend({contentHash:J}).strict(),Y2=c({id:T,turn:u().int().nonnegative(),kind:b(["message","tool_call","terminal"]),name:T.nullable(),arguments:re(r(),ce()),content:r().max(1e6).nullable()}).strict(),Q2=c({actionId:T,turn:u().int().nonnegative(),terminal:A(),output:re(r(),ce()),artifactRefs:p(Fa).max(1e5)}).strict(),X2=c({sequence:u().int().nonnegative(),type:b(["created","reset","action","observation","terminal","failure","collected","destroyed"]),payloadHash:J,metadata:In}).strict();c({schemaVersion:S("openpond.harnessTrace.v1"),manifest:Z,taskId:T,seed:r().trim().min(1).max(500),events:p(X2).max(1e6),actions:p(Y2).max(1e5),observations:p(Q2).max(1e5),terminal:A(),failureClass:Gl.nullable(),output:re(r(),ce()),contentHash:J}).strict();const pu=r().trim().min(1).max(1e5),tc=re(r(),ce()).default({}),e$=b(["completed_tool_batch","before_model_step","turn_completed","turn_paused"]),jk=c({kind:e$,eventSequence:u().int().nonnegative(),occurredAt:Oe}).strict(),Ok=c({id:T,sequence:u().int().nonnegative().nullable(),contentHash:J}).strict(),t$=b(["tool_failure","retry","recovery","validation","user_turn","reusable_success","completion_detour"]),n$=b(["open","recovered","terminal"]),a$=c({name:r().trim().min(1).max(500),invocationKey:J}).strict(),o$=c({schemaVersion:S("openpond.improvementObservation.v1"),id:T,runRef:T,turnId:T,harnessRelease:Z,overlay:Oo.nullable(),eventRefs:p(Ok).min(1).max(100),kind:t$,state:n$,tool:a$.nullable(),deterministicClass:r().trim().min(1).max(500).nullable(),summary:pu,createdAt:Oe,metadata:tc}).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"]})});o$.extend({contentHash:J}).strict();const r$=c({schemaVersion:S("openpond.refinementTriggerPolicy.v1"),maxEstimatedCostUsd:u().finite().nonnegative(),cooldownMs:u().int().nonnegative(),maxPendingPlans:u().int().min(1).max(100),maxEvidenceEvents:u().int().min(1).max(1e3),maxProposalEdits:u().int().min(1).max(1e3),maxProposalBytes:u().int().min(1).max(1e7)}).strict(),i$=b(["no_action","route_deterministically","queue_refiner"]),s$=c({schemaVersion:S("openpond.refinementTriggerDecision.v1"),id:T,runRef:T,turnId:T,harnessRelease:Z,overlay:Oo.nullable(),observations:p(Z).max(100),decision:i$,deterministicRoute:ms.nullable(),suggestedRoutes:p(ms).max(8),reason:pu,deduplicationKey:J,policy:r$,estimatedMaxCostUsd:u().finite().nonnegative(),pendingPlanCount:u().int().nonnegative(),boundary:jk,cooldownUntil:Oe.nullable(),createdAt:Oe,metadata:tc}).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"]})});s$.extend({contentHash:J}).strict();const l$=b(["runtime_service","refiner_model","human_review","evaluation_system","training_system"]),c$=c({schemaVersion:S("openpond.improvementRouteDecision.v1"),id:T,trigger:Z,route:ms,authority:l$,automatic:A(),reason:pu,createdAt:Oe,metadata:tc}).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"]})});c$.extend({contentHash:J}).strict();const d$=c({schemaVersion:S("openpond.harnessRefinerOutcome.v1"),id:T,trigger:Z,decision:b(["no_action","proposed"]),proposal:Z.nullable(),reason:pu,evidenceRefs:p(Z).max(100),estimatedCostUsd:u().finite().nonnegative(),createdAt:Oe,metadata:tc}).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"]})});d$.extend({contentHash:J}).strict();const u$=b(["applied","retained","declined","conflict","rolled_back"]),m$=c({schemaVersion:S("openpond.improvementApplyReceipt.v1"),id:T,proposal:Z,beforeOverlay:Oo,afterOverlay:Oo.nullable(),decision:u$,boundary:jk,validationRefs:p(Z).max(100),outcomeEvidenceRefs:p(Ok).max(1e3),rollbackOf:Z.nullable(),createdAt:Oe,metadata:tc}).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"]})});m$.extend({contentHash:J}).strict();const p$=b(["memory","prompt","skill","agent"]),f$=b(["runtime","product","taskset","training"]),h$=c({id:r().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),text:r().trim().min(1).max(1e4)}).strict(),$k=c({schemaVersion:S("openpond.refinerReviewProfile.v1"),id:r().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),version:r().trim().min(1).max(120),name:r().trim().min(1).max(200),objective:r().trim().min(1).max(1e4),instructions:p(h$).max(100),allowedProposalRoutes:p(p$).max(4),allowedExternalRoutes:p(f$).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"]})}),ry=c({schemaVersion:S("openpond.refinerRelease.v1"),id:r().trim().min(1).max(240),coreVersion:r().trim().min(1).max(120),coreHash:J,profile:$k,profileHash:J,composedPromptHash:J,createdAt:Oe,contentHash:J}).strict(),g$=c({schemaVersion:S("openpond.refinerBinding.v1"),channel:S("active"),revision:u().int().nonnegative(),release:Z,updatedAt:Oe}).strict(),v$=c({schemaVersion:S("openpond.refinerTransitionReceipt.v1"),id:r().trim().min(1).max(240),operation:b(["initialize","update","activate","rollback"]),bindingChanged:A(),previousRelease:Z.nullable(),nextRelease:Z,actor:r().trim().min(1).max(240),reason:r().trim().min(1).max(1e4),authoringSkillHash:J.nullable(),validation:c({valid:A(),messages:p(r().max(2e3)).max(100)}).strict(),createdAt:Oe,contentHash:J}).strict(),b$=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v1"),decision:S("no_action"),reason:r().trim().min(1).max(1e4)}).strip(),y$=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v1"),decision:S("route"),route:b(["runtime","product","taskset","training"]),summary:r().trim().min(1).max(2e3),expectedOutcome:r().trim().min(1).max(1e4),reason:r().trim().min(1).max(1e4)}).strip(),S$=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v1"),decision:S("propose"),route:b(["memory","prompt","skill","agent"]),operation:b(["create","update","delete"]),target:r().trim().min(1).max(2e3),summary:r().trim().min(1).max(2e3),createContent:r().min(1).max(2e4).nullable(),find:r().min(1).max(8e3).nullable(),replace:r().max(8e3).nullable(),expectedOutcome:r().trim().min(1).max(1e4),reason:r().trim().min(1).max(1e4)}).strip().superRefine((e,t)=>{e.operation==="create"&&(e.createContent===null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"create proposals require createContent and null find/replace",path:["createContent"]}),e.operation==="update"&&(e.createContent!==null||e.find===null||e.replace===null)&&t.addIssue({code:"custom",message:"update proposals require one exact find/replace edit and null createContent",path:["find"]}),e.operation==="delete"&&(e.createContent!==null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"delete proposals require null createContent/find/replace",path:["createContent"]})}),x$=It("decision",[b$,y$,S$]),k$=x$,dg=c({kind:b(["single_deterministic","recurrent_independent"]),supportingEvidenceIds:p(r().trim().min(1).max(2e3)).min(1).max(100),counterevidence:p(r().trim().min(1).max(2e3)).max(20)}).strict().superRefine((e,t)=>{new Set(e.supportingEvidenceIds).size!==e.supportingEvidenceIds.length&&t.addIssue({code:"custom",message:"supporting evidence IDs must be unique",path:["supportingEvidenceIds"]}),e.kind==="recurrent_independent"&&e.supportingEvidenceIds.length<2&&t.addIssue({code:"custom",message:"recurrent independent evidence requires at least two supplied incidents",path:["supportingEvidenceIds"]})}),w$=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("no_action"),reason:r().trim().min(1).max(1e4)}).strict(),I$=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("route"),route:b(["runtime","product","taskset","training"]),summary:r().trim().min(1).max(2e3),evidenceBasis:dg,expectedOutcome:r().trim().min(1).max(1e4),reason:r().trim().min(1).max(1e4)}).strict(),_$=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("propose"),route:b(["memory","prompt","skill","agent"]),operation:b(["create","update","delete"]),target:r().trim().min(1).max(2e3),summary:r().trim().min(1).max(2e3),evidenceBasis:dg,createContent:r().min(1).max(2e4).nullable(),find:r().min(1).max(8e3).nullable(),replace:r().max(8e3).nullable(),expectedOutcome:r().trim().min(1).max(1e4),reason:r().trim().min(1).max(1e4)}).strict().superRefine((e,t)=>{e.operation==="create"&&(e.createContent===null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"create proposals require createContent and null find/replace",path:["createContent"]}),e.operation==="update"&&(e.createContent!==null||e.find===null||e.replace===null)&&t.addIssue({code:"custom",message:"update proposals require one exact find/replace edit and null createContent",path:["find"]}),e.operation==="delete"&&(e.createContent!==null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"delete proposals require null createContent/find/replace",path:["createContent"]})}),Nk=It("decision",[w$,I$,_$]);Dt([k$,Nk]);const ug=c({memory:A(),prompt:A(),skill:A(),agent:A()}).strict(),Dk=b(["memory","instruction","skill","agent"]),iy=c({path:r().trim().min(1).max(2e3),kind:Dk,content:r().max(6e4),loaded:A()}).strict(),sy=c({path:r().trim().min(1).max(2e3),kind:Dk,loaded:A()}).strict(),C$=c({capabilities:ug,trigger:re(r(),ce()),observations:p(re(r(),ce())).max(20),admissibleEvidenceIds:p(r().trim().min(1).max(2e3)).max(1e4),reviewPacket:c({currentTurn:c({id:r().trim().min(1).max(2e3),status:r().trim().min(1).max(100).nullable(),error:r().max(2100).nullable(),prompt:r().max(8100).nullable(),assistantOutput:r().max(8100).nullable(),assistantOutputLinkCount:u().int().nonnegative()}).strict(),priorConversation:p(c({turnId:r().trim().min(1).max(2e3),status:r().trim().min(1).max(100).nullable(),prompt:r().max(3100).nullable(),assistantOutput:r().max(3100).nullable()}).strict()).max(3),timeline:p(re(r(),ce())).max(60),artifacts:p(re(r(),ce())).max(30),artifactDiagnostics:p(re(r(),ce())).max(20),executionProfile:c({modelRequestCount:u().int().nonnegative(),failedModelRequestCount:u().int().nonnegative(),promptTokens:u().int().nonnegative(),completionTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative(),toolFailureCount:u().int().nonnegative(),retryCount:u().int().nonnegative(),recoveryCount:u().int().nonnegative()}).strict(),priorIncidents:p(re(r(),ce())).max(3),truncation:c({timelineEventCount:u().int().nonnegative(),includedTimelineEventCount:u().int().nonnegative(),timelineTruncated:A()}).strict()}).strict(),runtimeActivation:c({admittedRelease:Z,currentRelease:Z,rebasedOntoCurrent:A(),admittedSourceFiles:p(iy).max(100),admittedSourceCatalog:p(sy).max(1e3)}).strict(),sourceFiles:p(iy).max(100),sourceCatalog:p(sy).max(1e3),additionalEvidence:ce().nullable().optional()}).strict(),R$=c({id:r().trim().min(1).max(240),revision:u().int().nonnegative(),contentHash:J}).strict();c({schemaVersion:S("openpond.hostedHarnessRefinerRequest.v2"),requestId:r().trim().min(1).max(240),idempotencyKey:r().trim().min(1).max(240),evidenceHash:J,harness:c({admittedRelease:Z,currentRelease:Z,overlay:R$,workspace:c({id:r().trim().min(1).max(240),revision:u().int().nonnegative(),sourceRevision:J,channelRevision:u().int().nonnegative()}).strict(),capabilities:ug}).strict(),evidence:C$}).strict();const P$=c({promptTokens:u().int().nonnegative(),completionTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative()}).strict();c({schemaVersion:S("openpond.hostedHarnessRefinerResponse.v2"),requestId:r().trim().min(1).max(240),evidenceHash:J,admittedRelease:Z,currentRelease:Z,decision:Nk,serviceRevision:r().trim().min(1).max(240),usage:P$}).strict();const A$=r().trim().min(1).max(2e3),mg=r().trim().min(1).max(1e5),T$=b(["create","update","delete"]),E$=b(["memory","prompt","skill","agent"]),M$=b(["runtime","product","taskset","training"]),j$=b(["no_action","routed","applied","retained","failed"]),O$=b(["not_applicable","pending","passed","rejected","failed"]),$$=b(["not_applicable","pending","passed","failed"]),N$=c({schemaVersion:S("openpond.harnessRefinerActivityReceipt.v1"),id:T,runRef:T,turnId:T,result:j$,decision:b(["no_action","route","propose"]).nullable(),route:ms.nullable(),operation:T$.nullable(),target:r().trim().min(1).max(2e3).nullable(),summary:A$,evidenceBasis:dg.nullable(),critiqueStatus:O$,validationStatus:$$,trigger:Z,outcome:Z.nullable(),proposal:Z.nullable(),applyReceipt:Z.nullable(),inputHarness:Z,outputHarness:Z.nullable(),createdAt:Oe}).strict().superRefine((e,t)=>{const n=e.result==="applied"||e.result==="retained";e.result==="no_action"?ly(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"||!M$.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"}),ly(t,e,{critiqueStatus:"not_applicable",validationStatus:"not_applicable"})):n?((e.decision!=="propose"||!E$.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"]})});N$.extend({contentHash:J}).strict();const D$=b(["unresolved","confirmed","resolved","rejected","expired"]),L$=c({kind:b(["applied_change","later_success","manual_rejection","source_revoked","expired"]),reason:mg,evidenceRefs:p(Z).max(1e3),resolvedAt:Oe}).strict(),U$=c({schemaVersion:S("openpond.harnessRefinementCandidate.v1"),id:T,ownerScope:lg,workspaceRef:T,fingerprint:J,recurrenceFamily:r().trim().min(1).max(1e3),statement:mg,status:D$,occurrences:p(Al).max(1e3),counterevidence:p(Al).max(1e3),sourceReviews:p(Z).min(1).max(100),relatedHarnessReleases:p(Z).max(100),firstSeenAt:Oe,lastSeenAt:Oe,lastReviewedAt:Oe,expiresAt:Oe,resolution:L$.nullable(),createdAt:Oe,updatedAt:Oe}).strict().superRefine((e,t)=>{Br(t,e.occurrences,"occurrences"),Br(t,e.counterevidence,"counterevidence"),Br(t,e.sourceReviews,"sourceReviews"),Br(t,e.relatedHarnessReleases,"relatedHarnessReleases");const n=new Set(e.occurrences.map(o=>o.occurrenceKey));e.counterevidence.some(o=>n.has(o.occurrenceKey))&&t.addIssue({code:"custom",message:"supporting occurrences and counterevidence must be disjoint",path:["counterevidence"]});const a=e.status==="unresolved"||e.status==="confirmed";a&&e.occurrences.length===0&&t.addIssue({code:"custom",message:"actionable candidates require at least one supporting occurrence",path:["occurrences"]}),a&&[...e.occurrences,...e.counterevidence].some(o=>o.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"actionable candidates may contain only currently authorized evidence",path:["occurrences"]}),a!==(e.resolution===null)&&t.addIssue({code:"custom",message:"only resolved, rejected, or expired candidates require a resolution",path:["resolution"]}),e.status==="expired"&&e.resolution?.kind!=="expired"&&t.addIssue({code:"custom",message:"expired candidates require an expired resolution",path:["resolution","kind"]}),e.status==="rejected"&&e.resolution&&!["manual_rejection","source_revoked"].includes(e.resolution.kind)&&t.addIssue({code:"custom",message:"rejected candidates require a rejection or revocation resolution",path:["resolution","kind"]}),e.status==="resolved"&&e.resolution&&!["applied_change","later_success"].includes(e.resolution.kind)&&t.addIssue({code:"custom",message:"resolved candidates require applied-change or later-success evidence",path:["resolution","kind"]}),F$(t,e)});U$.extend({contentHash:J}).strict();const H$=b(["created","merged","rejected","expired","reopened","resolved"]),z$=c({schemaVersion:S("openpond.harnessRefinementCandidateLifecycleReceipt.v1"),id:T,candidateId:T,decision:H$,beforeCandidate:Z.nullable(),afterCandidate:Z,review:Z,addedEvidence:p(Al).max(1e3),removedEvidence:p(Z).max(1e3),reason:mg,createdAt:Oe}).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"]}),Br(t,e.addedEvidence,"addedEvidence"),Br(t,e.removedEvidence,"removedEvidence");const n=new Set(e.removedEvidence.map(a=>Lf(a)));e.addedEvidence.some(a=>n.has(Lf(a.evidence)))&&t.addIssue({code:"custom",message:"candidate lifecycle evidence cannot be added and removed together",path:["removedEvidence"]})});z$.extend({contentHash:J}).strict();const q$=c({schemaVersion:S("openpond.harnessCrossRunRefinementRequest.v1"),id:T,ownerScope:lg,workspaceRef:T,candidate:Z,candidateFingerprint:J,review:Z,admittedHarness:Z,evidence:p(Al).min(1).max(1e3),capabilities:ug,deduplicationKey:J,createdAt:Oe}).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"]}),Br(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=B$(e);e.deduplicationKey!==n&&t.addIssue({code:"custom",message:`cross-run refinement deduplicationKey is ${e.deduplicationKey}; expected ${n}`,path:["deduplicationKey"]})});q$.extend({contentHash:J}).strict();function B$(e){return Xt({schemaVersion:"openpond.harnessCrossRunRefinementIdentity.v1",workspaceRef:e.workspaceRef,candidateFingerprint:e.candidateFingerprint,admittedHarness:e.admittedHarness})}function ly(e,t,n){for(const[a,o]of Object.entries(n))t[a]!==o&&e.addIssue({code:"custom",message:`${a} must be ${String(o)}`,path:[a]})}function Br(e,t,n){const a=t.map(o=>Lf(o));new Set(a).size!==a.length&&e.addIssue({code:"custom",message:`${n} references must be unique`,path:[n]})}function Lf(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 F$(e,t){const n=[["firstSeenAt",t.firstSeenAt],["lastSeenAt",t.lastSeenAt],["lastReviewedAt",t.lastReviewedAt],["updatedAt",t.updatedAt],["expiresAt",t.expiresAt]];for(let a=1;a<n.length;a+=1){const o=n[a-1],i=n[a];Date.parse(o[1])<=Date.parse(i[1])||e.addIssue({code:"custom",message:`${i[0]} must not precede ${o[0]}`,path:[i[0]]})}Date.parse(t.createdAt)>Date.parse(t.updatedAt)&&e.addIssue({code:"custom",message:"updatedAt must not precede createdAt",path:["updatedAt"]})}const V$=25*1024*1024,K$=c({path:sn.shape.path,base64:r().max(Math.ceil(V$/3)*4)}).strict(),Lk=c({schemaVersion:S("openpond.harnessSourcePackage.v1"),agentSnapshot:G2,harnessRelease:J2,files:p(K$).max(1e4)}).strict();Lk.extend({contentHash:J}).strict();Lk.extend({schemaVersion:S("openpond.harnessPolicySourcePackage.v1"),contentHash:J}).strict();c({schemaVersion:S("openpond.harnessSourceSelection.v1"),mode:b(["taskset_owned","selected_release"]),harnessRelease:Z,sourcePackageHash:J.nullable()}).strict().superRefine((e,t)=>{e.mode==="selected_release"!=(e.sourcePackageHash!==null)&&t.addIssue({code:"custom",path:["sourcePackageHash"],message:"Only a selected release binds a source package."})});c({path:r().min(1).max(2e3),offset:u().int().nonnegative().default(0),length:u().int().positive().max(65536).default(16384)}).strict();const Uk=r().regex(/^[a-z][a-z0-9_-]{0,119}$/),Hk=r().min(1).max(2e3).refine(e=>!e.includes("\\")&&!e.includes(":")&&!e.startsWith("/")&&e.split("/").every(t=>t!==""&&t!=="."&&t!==".."),"workflow references require portable relative paths"),W$=c({id:Uk,label:r().trim().min(1).max(240),description:r().max(4e3),inputSchema:re(r(),ce()),invocation:It("kind",[c({kind:S("instructions"),instructions:r().min(1).max(1e5).refine(e=>!!e.trim())}).strict(),c({kind:S("agent_action"),actionId:r().trim().min(1).max(240)}).strict()]),skillPaths:p(Hk).max(100)}).strict();c({schemaVersion:S("openpond.profileWorkflows.v1"),workflows:p(W$).max(1e3)}).strict();const G$=c({id:r().trim().min(1).max(240),agentId:r().regex(/^[a-zA-Z0-9_-]{1,240}$/),sourceActionId:r().trim().min(1).max(240),inputSchema:re(r(),ce())}).strict();c({schemaVersion:S("openpond.profileWorkflowActions.v1"),actions:p(G$).max(200)}).strict();const Z$=c({schemaVersion:S("openpond.profileWorkflowBinding.v1"),profileId:r().trim().min(1).max(240),sourceRevision:r().trim().min(1).max(240),harnessRelease:Z,catalogHash:J,workflowId:Uk}).strict(),J$=c({schemaVersion:S("openpond.profileComponentBinding.v1"),profileId:r().trim().min(1).max(240),sourceRevision:r().trim().min(1).max(240),harnessRelease:Z,target:It("kind",[c({kind:S("profile")}).strict(),c({kind:S("skill"),skillPath:Hk}).strict(),c({kind:S("agent_action"),actionId:r().trim().min(1).max(240)}).strict()])}).strict(),pg=Symbol.for("yaml.alias"),Y$=Symbol.for("yaml.document"),Zr=Symbol.for("yaml.map"),zk=Symbol.for("yaml.pair"),fg=Symbol.for("yaml.scalar"),nc=Symbol.for("yaml.seq"),ho=Symbol.for("yaml.node.type"),Cs=e=>!!e&&typeof e=="object"&&e[ho]===pg,fu=e=>!!e&&typeof e=="object"&&e[ho]===Y$,qk=e=>!!e&&typeof e=="object"&&e[ho]===Zr,En=e=>!!e&&typeof e=="object"&&e[ho]===zk,xn=e=>!!e&&typeof e=="object"&&e[ho]===fg,hg=e=>!!e&&typeof e=="object"&&e[ho]===nc;function ia(e){if(e&&typeof e=="object")switch(e[ho]){case Zr:case nc:return!0}return!1}function Nn(e){if(e&&typeof e=="object")switch(e[ho]){case pg:case Zr:case fg:case nc:return!0}return!1}const Bk=e=>(xn(e)||ia(e))&&!!e.anchor,Ur=Symbol("break visit"),Q$=Symbol("skip children"),vl=Symbol("remove node");function hu(e,t){const n=X$(t);fu(e)?Vi(null,e.contents,n,Object.freeze([e]))===vl&&(e.contents=null):Vi(null,e,n,Object.freeze([]))}hu.BREAK=Ur;hu.SKIP=Q$;hu.REMOVE=vl;function Vi(e,t,n,a){const o=eN(e,t,n,a);if(Nn(o)||En(o))return tN(e,a,o),Vi(e,o,n,a);if(typeof o!="symbol"){if(ia(t)){a=Object.freeze(a.concat(t));for(let i=0;i<t.items.length;++i){const s=Vi(i,t.items[i],n,a);if(typeof s=="number")i=s-1;else{if(s===Ur)return Ur;s===vl&&(t.items.splice(i,1),i-=1)}}}else if(En(t)){a=Object.freeze(a.concat(t));const i=Vi("key",t.key,n,a);if(i===Ur)return Ur;i===vl&&(t.key=null);const s=Vi("value",t.value,n,a);if(s===Ur)return Ur;s===vl&&(t.value=null)}}return o}function X$(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function eN(e,t,n,a){if(typeof n=="function")return n(e,t,a);if(qk(t))return n.Map?.(e,t,a);if(hg(t))return n.Seq?.(e,t,a);if(En(t))return n.Pair?.(e,t,a);if(xn(t))return n.Scalar?.(e,t,a);if(Cs(t))return n.Alias?.(e,t,a)}function tN(e,t,n){const a=t[t.length-1];if(ia(a))a.items[e]=n;else if(En(a))e==="key"?a.key=n:a.value=n;else if(fu(a))a.contents=n;else{const o=Cs(a)?"alias":"scalar";throw new Error(`Cannot replace node with ${o} parent`)}}function Fk(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){const n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(n)}return!0}function ul(e,t,n,a){if(a&&typeof a=="object")if(Array.isArray(a))for(let o=0,i=a.length;o<i;++o){const s=a[o],l=ul(e,a,String(o),s);l===void 0?delete a[o]:l!==s&&(a[o]=l)}else if(a instanceof Map)for(const o of Array.from(a.keys())){const i=a.get(o),s=ul(e,a,o,i);s===void 0?a.delete(o):s!==i&&a.set(o,s)}else if(a instanceof Set)for(const o of Array.from(a)){const i=ul(e,a,o,o);i===void 0?a.delete(o):i!==o&&(a.delete(o),a.add(i))}else for(const[o,i]of Object.entries(a)){const s=ul(e,a,o,i);s===void 0?delete a[o]:s!==i&&(a[o]=s)}return e.call(t,n,a)}function qa(e,t,n){if(Array.isArray(e))return e.map((a,o)=>qa(a,String(o),n));if(e&&typeof e.toJSON=="function"){if(!n||!Bk(e))return e.toJSON(t,n);const a={aliasCount:0,count:1,res:void 0};n.anchors.set(e,a),n.onCreate=i=>{a.res=i,delete n.onCreate};const o=e.toJSON(t,n);return n.onCreate&&n.onCreate(o),o}return typeof e=="bigint"&&!n?.keep?Number(e):e}class gg{constructor(t){Object.defineProperty(this,ho,{value:t})}clone(){const t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:n,maxAliasCount:a,onAnchor:o,reviver:i}={}){if(!fu(t))throw new TypeError("A document argument is required");const s={anchors:new Map,doc:t,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof a=="number"?a:100},l=qa(this,"",s);if(typeof o=="function")for(const{count:m,res:d}of s.anchors.values())o(d,m);return typeof i=="function"?ul(i,{"":l},"",l):l}}class nN extends gg{constructor(t){super(pg),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let a;n?.aliasResolveCache?a=n.aliasResolveCache:(a=[],hu(t,{Node:(i,s)=>{(Cs(s)||Bk(s))&&a.push(s)}}),n&&(n.aliasResolveCache=a));let o;for(const i of a){if(i===this)break;i.anchor===this.source&&(o=i)}return o}toJSON(t,n){if(!n)return{source:this.source};const{anchors:a,doc:o,maxAliasCount:i}=n,s=this.resolve(o,n);if(!s){const m=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(m)}let l=a.get(s);if(l||(qa(s,null,n),l=a.get(s)),l?.res===void 0){const m="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(m)}if(i>=0&&(l.count+=1,l.aliasCount===0&&(l.aliasCount=ld(o,s,a)),l.count*l.aliasCount>i)){const m="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(m)}return l.res}toString(t,n,a){const o=`*${this.source}`;if(t){if(Fk(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){const i=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(i)}if(t.implicitKey)return`${o} `}return o}}function ld(e,t,n){if(Cs(t)){const a=t.resolve(e),o=n&&a&&n.get(a);return o?o.count*o.aliasCount:0}else if(ia(t)){let a=0;for(const o of t.items){const i=ld(e,o,n);i>a&&(a=i)}return a}else if(En(t)){const a=ld(e,t.key,n),o=ld(e,t.value,n);return Math.max(a,o)}return 1}const Vk=e=>!e||typeof e!="function"&&typeof e!="object";class an extends gg{constructor(t){super(fg),this.value=t}toJSON(t,n){return n?.keep?this.value:qa(this.value,t,n)}toString(){return String(this.value)}}an.BLOCK_FOLDED="BLOCK_FOLDED";an.BLOCK_LITERAL="BLOCK_LITERAL";an.PLAIN="PLAIN";an.QUOTE_DOUBLE="QUOTE_DOUBLE";an.QUOTE_SINGLE="QUOTE_SINGLE";function aN(e,t,n){return n.find(a=>a.identify?.(e)&&!a.format)}function Ed(e,t,n){if(fu(e)&&(e=e.contents),Nn(e))return e;if(En(e)){const g=n.schema[Zr].createNode?.(n.schema,null,n);return g.items.push(e),g}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());const{aliasDuplicateObjects:a,onAnchor:o,onTagObj:i,schema:s,sourceObjects:l}=n;let m;if(a&&e&&typeof e=="object"){if(m=l.get(e),m)return m.anchor??(m.anchor=o(e)),new nN(m.anchor);m={anchor:null,node:null},l.set(e,m)}let d=aN(e,t,s.tags);if(!d){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){const g=new an(e);return m&&(m.node=g),g}d=e instanceof Map?s[Zr]:Symbol.iterator in Object(e)?s[nc]:s[Zr]}i&&(i(d),delete n.onTagObj);const h=d?.createNode?d.createNode(n.schema,e,n):typeof d?.nodeClass?.from=="function"?d.nodeClass.from(n.schema,e,n):new an(e);return d.default||(h.tag=d.tag),m&&(m.node=h),h}function cy(e,t,n){let a=n;for(let o=t.length-1;o>=0;--o){const i=t[o];if(typeof i=="number"&&Number.isInteger(i)&&i>=0){const s=[];s[i]=a,a=s}else a=new Map([[i,a]])}return Ed(a,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}const oN=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done;class Kk extends gg{constructor(t,n){super(t),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(t){const n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(n.schema=t),n.items=n.items.map(a=>Nn(a)||En(a)?a.clone(t):a),this.range&&(n.range=this.range.slice()),n}addIn(t,n){if(oN(t))this.add(n);else{const[a,...o]=t,i=this.get(a,!0);if(ia(i))i.addIn(o,n);else if(i===void 0&&this.schema)this.set(a,cy(this.schema,o,n));else throw new Error(`Expected YAML collection at ${a}. Remaining path: ${o}`)}}deleteIn(t){const[n,...a]=t;if(a.length===0)return this.delete(n);const o=this.get(n,!0);if(ia(o))return o.deleteIn(a);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${a}`)}getIn(t,n){const[a,...o]=t,i=this.get(a,!0);return o.length===0?!n&&xn(i)?i.value:i:ia(i)?i.getIn(o,n):void 0}hasAllNullValues(t){return this.items.every(n=>{if(!En(n))return!1;const a=n.value;return a==null||t&&xn(a)&&a.value==null&&!a.commentBefore&&!a.comment&&!a.tag})}hasIn(t){const[n,...a]=t;if(a.length===0)return this.has(n);const o=this.get(n,!0);return ia(o)?o.hasIn(a):!1}setIn(t,n){const[a,...o]=t;if(o.length===0)this.set(a,n);else{const i=this.get(a,!0);if(ia(i))i.setIn(o,n);else if(i===void 0&&this.schema)this.set(a,cy(this.schema,o,n));else throw new Error(`Expected YAML collection at ${a}. Remaining path: ${o}`)}}}const rN=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Tl(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}const Ki=(e,t,n)=>e.endsWith(`
|
|
125
|
-
`)?Tl(n,t):n.includes(`
|
|
126
|
-
`)?`
|
|
127
|
-
`+Tl(n,t):(e.endsWith(" ")?"":" ")+n,Wk="flow",Uf="block",cd="quoted";function gu(e,t,n="flow",{indentAtStart:a,lineWidth:o=80,minContentWidth:i=20,onFold:s,onOverflow:l}={}){if(!o||o<0)return e;o<i&&(i=0);const m=Math.max(1+i,1+o-t.length);if(e.length<=m)return e;const d=[],h={};let g=o-t.length;typeof a=="number"&&(a>o-Math.max(2,i)?d.push(0):g=o-a);let y,w,_=!1,P=-1,M=-1,C=-1;n===Uf&&(P=dy(e,P,t.length),P!==-1&&(g=P+m));for(let $;$=e[P+=1];){if(n===cd&&$==="\\"){switch(M=P,e[P+1]){case"x":P+=3;break;case"u":P+=5;break;case"U":P+=9;break;default:P+=1}C=P}if($===`
|
|
128
|
-
`)n===Uf&&(P=dy(e,P,t.length)),g=P+t.length+m,y=void 0;else{if($===" "&&w&&w!==" "&&w!==`
|
|
129
|
-
`&&w!==" "){const j=e[P+1];j&&j!==" "&&j!==`
|
|
130
|
-
`&&j!==" "&&(y=P)}if(P>=g)if(y)d.push(y),g=y+m,y=void 0;else if(n===cd){for(;w===" "||w===" ";)w=$,$=e[P+=1],_=!0;const j=P>C+1?P-2:M-1;if(h[j])return e;d.push(j),h[j]=!0,g=j+m,y=void 0}else _=!0}w=$}if(_&&l&&l(),d.length===0)return e;s&&s();let N=e.slice(0,d[0]);for(let $=0;$<d.length;++$){const j=d[$],x=d[$+1]||e.length;j===0?N=`
|
|
131
|
-
${t}${e.slice(0,x)}`:(n===cd&&h[j]&&(N+=`${e[j]}\\`),N+=`
|
|
132
|
-
${t}${e.slice(j+1,x)}`)}return N}function dy(e,t,n){let a=t,o=t+1,i=e[o];for(;i===" "||i===" ";)if(t<o+n)i=e[++t];else{do i=e[++t];while(i&&i!==`
|
|
133
|
-
`);a=t,o=t+1,i=e[o]}return a}const vu=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),bu=e=>/^(%|---|\.\.\.)/m.test(e);function iN(e,t,n){if(!t||t<0)return!1;const a=t-n,o=e.length;if(o<=a)return!1;for(let i=0,s=0;i<o;++i)if(e[i]===`
|
|
134
|
-
`){if(i-s>a)return!0;if(s=i+1,o-s<=a)return!1}return!0}function bl(e,t){const n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;const{implicitKey:a}=t,o=t.options.doubleQuotedMinMultiLineLength,i=t.indent||(bu(e)?" ":"");let s="",l=0;for(let m=0,d=n[m];d;d=n[++m])if(d===" "&&n[m+1]==="\\"&&n[m+2]==="n"&&(s+=n.slice(l,m)+"\\ ",m+=1,l=m,d="\\"),d==="\\")switch(n[m+1]){case"u":{s+=n.slice(l,m);const h=n.substr(m+2,4);switch(h){case"0000":s+="\\0";break;case"0007":s+="\\a";break;case"000b":s+="\\v";break;case"001b":s+="\\e";break;case"0085":s+="\\N";break;case"00a0":s+="\\_";break;case"2028":s+="\\L";break;case"2029":s+="\\P";break;default:h.substr(0,2)==="00"?s+="\\x"+h.substr(2):s+=n.substr(m,6)}m+=5,l=m+1}break;case"n":if(a||n[m+2]==='"'||n.length<o)m+=1;else{for(s+=n.slice(l,m)+`
|
|
135
|
-
|
|
136
|
-
`;n[m+2]==="\\"&&n[m+3]==="n"&&n[m+4]!=='"';)s+=`
|
|
137
|
-
`,m+=2;s+=i,n[m+2]===" "&&(s+="\\"),m+=1,l=m+1}break;default:m+=1}return s=l?s+n.slice(l):n,a?s:gu(s,i,cd,vu(t,!1))}function Hf(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
138
|
-
`)||/[ \t]\n|\n[ \t]/.test(e))return bl(e,t);const n=t.indent||(bu(e)?" ":""),a="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
139
|
-
${n}`)+"'";return t.implicitKey?a:gu(a,n,Wk,vu(t,!1))}function Wi(e,t){const{singleQuote:n}=t.options;let a;if(n===!1)a=bl;else{const o=e.includes('"'),i=e.includes("'");o&&!i?a=Hf:i&&!o?a=bl:a=n?Hf:bl}return a(e,t)}let zf;try{zf=new RegExp(`(^|(?<!
|
|
140
|
-
))
|
|
141
|
-
+(?!
|
|
142
|
-
|$)`,"g")}catch{zf=/\n+(?!\n|$)/g}function dd({comment:e,type:t,value:n},a,o,i){const{blockQuote:s,commentString:l,lineWidth:m}=a.options;if(!s||/\n[\t ]+$/.test(n))return Wi(n,a);const d=a.indent||(a.forceBlockIndent||bu(n)?" ":""),h=s==="literal"?!0:s==="folded"||t===an.BLOCK_FOLDED?!1:t===an.BLOCK_LITERAL?!0:!iN(n,m,d.length);if(!n)return h?`|
|
|
143
|
-
`:`>
|
|
144
|
-
`;let g,y;for(y=n.length;y>0;--y){const x=n[y-1];if(x!==`
|
|
145
|
-
`&&x!==" "&&x!==" ")break}let w=n.substring(y);const _=w.indexOf(`
|
|
146
|
-
`);_===-1?g="-":n===w||_!==w.length-1?(g="+",i&&i()):g="",w&&(n=n.slice(0,-w.length),w[w.length-1]===`
|
|
147
|
-
`&&(w=w.slice(0,-1)),w=w.replace(zf,`$&${d}`));let P=!1,M,C=-1;for(M=0;M<n.length;++M){const x=n[M];if(x===" ")P=!0;else if(x===`
|
|
148
|
-
`)C=M;else break}let N=n.substring(0,C<M?C+1:M);N&&(n=n.substring(N.length),N=N.replace(/\n+/g,`$&${d}`));let j=(P?d?"2":"1":"")+g;if(e&&(j+=" "+l(e.replace(/ ?[\r\n]+/g," ")),o&&o()),!h){const x=n.replace(/\n+/g,`
|
|
149
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${d}`);let R=!1;const E=vu(a,!0);s!=="folded"&&t!==an.BLOCK_FOLDED&&(E.onOverflow=()=>{R=!0});const U=gu(`${N}${x}${w}`,d,Uf,E);if(!R)return`>${j}
|
|
150
|
-
${d}${U}`}return n=n.replace(/\n+/g,`$&${d}`),`|${j}
|
|
151
|
-
${d}${N}${n}${w}`}function sN(e,t,n,a){const{type:o,value:i}=e,{actualString:s,implicitKey:l,indent:m,indentStep:d,inFlow:h}=t;if(l&&i.includes(`
|
|
152
|
-
`)||h&&/[[\]{},]/.test(i))return Wi(i,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return l||h||!i.includes(`
|
|
153
|
-
`)?Wi(i,t):dd(e,t,n,a);if(!l&&!h&&o!==an.PLAIN&&i.includes(`
|
|
154
|
-
`))return dd(e,t,n,a);if(bu(i)){if(m==="")return t.forceBlockIndent=!0,dd(e,t,n,a);if(l&&m===d)return Wi(i,t)}const g=i.replace(/\n+/g,`$&
|
|
155
|
-
${m}`);if(s){const y=P=>P.default&&P.tag!=="tag:yaml.org,2002:str"&&P.test?.test(g),{compat:w,tags:_}=t.doc.schema;if(_.some(y)||w?.some(y))return Wi(i,t)}return l?g:gu(g,m,Wk,vu(t,!1))}function lN(e,t,n,a){const{implicitKey:o,inFlow:i}=t,s=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)});let{type:l}=e;l!==an.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(s.value)&&(l=an.QUOTE_DOUBLE);const m=h=>{switch(h){case an.BLOCK_FOLDED:case an.BLOCK_LITERAL:return o||i?Wi(s.value,t):dd(s,t,n,a);case an.QUOTE_DOUBLE:return bl(s.value,t);case an.QUOTE_SINGLE:return Hf(s.value,t);case an.PLAIN:return sN(s,t,n,a);default:return null}};let d=m(l);if(d===null){const{defaultKeyType:h,defaultStringType:g}=t.options,y=o&&h||g;if(d=m(y),d===null)throw new Error(`Unsupported default string type ${y}`)}return d}function cN(e,t){const n=Object.assign({blockQuote:!0,commentString:rN,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t);let a;switch(n.collectionStyle){case"block":a=!1;break;case"flow":a=!0;break;default:a=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:a,options:n}}function dN(e,t){if(t.tag){const o=e.filter(i=>i.tag===t.tag);if(o.length>0)return o.find(i=>i.format===t.format)??o[0]}let n,a;if(xn(t)){a=t.value;let o=e.filter(i=>i.identify?.(a));if(o.length>1){const i=o.filter(s=>s.test);i.length>0&&(o=i)}n=o.find(i=>i.format===t.format)??o.find(i=>!i.format)}else a=t,n=e.find(o=>o.nodeClass&&a instanceof o.nodeClass);if(!n){const o=a?.constructor?.name??(a===null?"null":typeof a);throw new Error(`Tag not resolved for ${o} value`)}return n}function uN(e,t,{anchors:n,doc:a}){if(!a.directives)return"";const o=[],i=(xn(e)||ia(e))&&e.anchor;i&&Fk(i)&&(n.add(i),o.push(`&${i}`));const s=e.tag??(t.default?null:t.tag);return s&&o.push(a.directives.tagString(s)),o.join(" ")}function Md(e,t,n,a){if(En(e))return e.toString(t,n,a);if(Cs(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let o;const i=Nn(e)?e:t.doc.createNode(e,{onTagObj:m=>o=m});o??(o=dN(t.doc.schema.tags,i));const s=uN(i,o,t);s.length>0&&(t.indentAtStart=(t.indentAtStart??0)+s.length+1);const l=typeof o.stringify=="function"?o.stringify(i,t,n,a):xn(i)?lN(i,t,n,a):i.toString(t,n,a);return s?xn(i)||l[0]==="{"||l[0]==="["?`${s} ${l}`:`${s}
|
|
156
|
-
${t.indent}${l}`:l}function mN({key:e,value:t},n,a,o){const{allNullValues:i,doc:s,indent:l,indentStep:m,options:{commentString:d,indentSeq:h,simpleKeys:g}}=n;let y=Nn(e)&&e.comment||null;if(g){if(y)throw new Error("With simple keys, key nodes cannot have comments");if(ia(e)||!Nn(e)&&typeof e=="object"){const E="With simple keys, collection cannot be used as a key value";throw new Error(E)}}let w=!g&&(!e||y&&t==null&&!n.inFlow||ia(e)||(xn(e)?e.type===an.BLOCK_FOLDED||e.type===an.BLOCK_LITERAL:typeof e=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!w&&(g||!i),indent:l+m});let _=!1,P=!1,M=Md(e,n,()=>_=!0,()=>P=!0);if(!w&&!n.inFlow&&M.length>1024){if(g)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");w=!0}if(n.inFlow){if(i||t==null)return _&&a&&a(),M===""?"?":w?`? ${M}`:M}else if(i&&!g||t==null&&w)return M=`? ${M}`,y&&!_?M+=Ki(M,n.indent,d(y)):P&&o&&o(),M;_&&(y=null),w?(y&&(M+=Ki(M,n.indent,d(y))),M=`? ${M}
|
|
157
|
-
${l}:`):(M=`${M}:`,y&&(M+=Ki(M,n.indent,d(y))));let C,N,$;Nn(t)?(C=!!t.spaceBefore,N=t.commentBefore,$=t.comment):(C=!1,N=null,$=null,t&&typeof t=="object"&&(t=s.createNode(t))),n.implicitKey=!1,!w&&!y&&xn(t)&&(n.indentAtStart=M.length+1),P=!1,!h&&m.length>=2&&!n.inFlow&&!w&&hg(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let j=!1;const x=Md(t,n,()=>j=!0,()=>P=!0);let R=" ";if(y||C||N){if(R=C?`
|
|
158
|
-
`:"",N){const E=d(N);R+=`
|
|
159
|
-
${Tl(E,n.indent)}`}x===""&&!n.inFlow?R===`
|
|
160
|
-
`&&$&&(R=`
|
|
161
|
-
|
|
162
|
-
`):R+=`
|
|
163
|
-
${n.indent}`}else if(!w&&ia(t)){const E=x[0],U=x.indexOf(`
|
|
164
|
-
`),B=U!==-1,D=n.inFlow??t.flow??t.items.length===0;if(B||!D){let W=!1;if(B&&(E==="&"||E==="!")){let se=x.indexOf(" ");E==="&"&&se!==-1&&se<U&&x[se+1]==="!"&&(se=x.indexOf(" ",se+1)),(se===-1||U<se)&&(W=!0)}W||(R=`
|
|
165
|
-
${n.indent}`)}}else(x===""||x[0]===`
|
|
166
|
-
`)&&(R="");return M+=R+x,n.inFlow?j&&a&&a():$&&!j?M+=Ki(M,n.indent,d($)):P&&o&&o(),M}function pN(e,t){(e==="debug"||e==="warn")&&console.warn(t)}const Bc="<<",Lp={identify:e=>e===Bc||typeof e=="symbol"&&e.description===Bc,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new an(Symbol(Bc)),{addToJSMap:Gk}),stringify:()=>Bc},fN=(e,t)=>(Lp.identify(t)||xn(t)&&(!t.type||t.type===an.PLAIN)&&Lp.identify(t.value))&&e?.doc.schema.tags.some(n=>n.tag===Lp.tag&&n.default);function Gk(e,t,n){const a=Zk(e,n);if(hg(a))for(const o of a.items)Up(e,t,o);else if(Array.isArray(a))for(const o of a)Up(e,t,o);else Up(e,t,a)}function Up(e,t,n){const a=Zk(e,n);if(!qk(a))throw new Error("Merge sources must be maps or map aliases");const o=a.toJSON(null,e,Map);for(const[i,s]of o)t instanceof Map?t.has(i)||t.set(i,s):t instanceof Set?t.add(i):Object.prototype.hasOwnProperty.call(t,i)||Object.defineProperty(t,i,{value:s,writable:!0,enumerable:!0,configurable:!0});return t}function Zk(e,t){return e&&Cs(t)?t.resolve(e.doc,e):t}function Jk(e,t,{key:n,value:a}){if(Nn(n)&&n.addToJSMap)n.addToJSMap(e,t,a);else if(fN(e,n))Gk(e,t,a);else{const o=qa(n,"",e);if(t instanceof Map)t.set(o,qa(a,o,e));else if(t instanceof Set)t.add(o);else{const i=hN(n,o,e),s=qa(a,i,e);i in t?Object.defineProperty(t,i,{value:s,writable:!0,enumerable:!0,configurable:!0}):t[i]=s}}return t}function hN(e,t,n){if(t===null)return"";if(typeof t!="object")return String(t);if(Nn(e)&&n?.doc){const a=cN(n.doc,{});a.anchors=new Set;for(const i of n.anchors.keys())a.anchors.add(i.anchor);a.inFlow=!0,a.inStringifyKey=!0;const o=e.toString(a);if(!n.mapKeyWarned){let i=JSON.stringify(o);i.length>40&&(i=i.substring(0,36)+'..."'),pN(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${i}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return o}return JSON.stringify(t)}function vg(e,t,n){const a=Ed(e,void 0,n),o=Ed(t,void 0,n);return new No(a,o)}class No{constructor(t,n=null){Object.defineProperty(this,ho,{value:zk}),this.key=t,this.value=n}clone(t){let{key:n,value:a}=this;return Nn(n)&&(n=n.clone(t)),Nn(a)&&(a=a.clone(t)),new No(n,a)}toJSON(t,n){const a=n?.mapAsMap?new Map:{};return Jk(n,a,this)}toString(t,n,a){return t?.doc?mN(this,t,n,a):JSON.stringify(this)}}function Yk(e,t,n){return(t.inFlow??e.flow?vN:gN)(e,t,n)}function gN({comment:e,items:t},n,{blockItemPrefix:a,flowChars:o,itemIndent:i,onChompKeep:s,onComment:l}){const{indent:m,options:{commentString:d}}=n,h=Object.assign({},n,{indent:i,type:null});let g=!1;const y=[];for(let _=0;_<t.length;++_){const P=t[_];let M=null;if(Nn(P))!g&&P.spaceBefore&&y.push(""),jd(n,y,P.commentBefore,g),P.comment&&(M=P.comment);else if(En(P)){const N=Nn(P.key)?P.key:null;N&&(!g&&N.spaceBefore&&y.push(""),jd(n,y,N.commentBefore,g))}g=!1;let C=Md(P,h,()=>M=null,()=>g=!0);M&&(C+=Ki(C,i,d(M))),g&&M&&(g=!1),y.push(a+C)}let w;if(y.length===0)w=o.start+o.end;else{w=y[0];for(let _=1;_<y.length;++_){const P=y[_];w+=P?`
|
|
167
|
-
${m}${P}`:`
|
|
168
|
-
`}}return e?(w+=`
|
|
169
|
-
`+Tl(d(e),m),l&&l()):g&&s&&s(),w}function vN({items:e},t,{flowChars:n,itemIndent:a}){const{indent:o,indentStep:i,flowCollectionPadding:s,options:{commentString:l}}=t;a+=i;const m=Object.assign({},t,{indent:a,inFlow:!0,type:null});let d=!1,h=0;const g=[];for(let _=0;_<e.length;++_){const P=e[_];let M=null;if(Nn(P))P.spaceBefore&&g.push(""),jd(t,g,P.commentBefore,!1),P.comment&&(M=P.comment);else if(En(P)){const N=Nn(P.key)?P.key:null;N&&(N.spaceBefore&&g.push(""),jd(t,g,N.commentBefore,!1),N.comment&&(d=!0));const $=Nn(P.value)?P.value:null;$?($.comment&&(M=$.comment),$.commentBefore&&(d=!0)):P.value==null&&N?.comment&&(M=N.comment)}M&&(d=!0);let C=Md(P,m,()=>M=null);d||(d=g.length>h||C.includes(`
|
|
170
|
-
`)),_<e.length-1?C+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(d||(d=g.reduce((N,$)=>N+$.length+2,2)+(C.length+2)>t.options.lineWidth)),d&&(C+=",")),M&&(C+=Ki(C,a,l(M))),g.push(C),h=g.length}const{start:y,end:w}=n;if(g.length===0)return y+w;if(!d){const _=g.reduce((P,M)=>P+M.length+2,2);d=t.options.lineWidth>0&&_>t.options.lineWidth}if(d){let _=y;for(const P of g)_+=P?`
|
|
171
|
-
${i}${o}${P}`:`
|
|
172
|
-
`;return`${_}
|
|
173
|
-
${o}${w}`}else return`${y}${s}${g.join(" ")}${s}${w}`}function jd({indent:e,options:{commentString:t}},n,a,o){if(a&&o&&(a=a.replace(/^\n+/,"")),a){const i=Tl(t(a),e);n.push(i.trimStart())}}function Fr(e,t){const n=xn(t)?t.value:t;for(const a of e)if(En(a)&&(a.key===t||a.key===n||xn(a.key)&&a.key.value===n))return a}class Ui extends Kk{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Zr,t),this.items=[]}static from(t,n,a){const{keepUndefined:o,replacer:i}=a,s=new this(t),l=(m,d)=>{if(typeof i=="function")d=i.call(n,m,d);else if(Array.isArray(i)&&!i.includes(m))return;(d!==void 0||o)&&s.items.push(vg(m,d,a))};if(n instanceof Map)for(const[m,d]of n)l(m,d);else if(n&&typeof n=="object")for(const m of Object.keys(n))l(m,n[m]);return typeof t.sortMapEntries=="function"&&s.items.sort(t.sortMapEntries),s}add(t,n){let a;En(t)?a=t:!t||typeof t!="object"||!("key"in t)?a=new No(t,t?.value):a=new No(t.key,t.value);const o=Fr(this.items,a.key),i=this.schema?.sortMapEntries;if(o){if(!n)throw new Error(`Key ${a.key} already set`);xn(o.value)&&Vk(a.value)?o.value.value=a.value:o.value=a.value}else if(i){const s=this.items.findIndex(l=>i(a,l)<0);s===-1?this.items.push(a):this.items.splice(s,0,a)}else this.items.push(a)}delete(t){const n=Fr(this.items,t);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(t,n){const o=Fr(this.items,t)?.value;return(!n&&xn(o)?o.value:o)??void 0}has(t){return!!Fr(this.items,t)}set(t,n){this.add(new No(t,n),!0)}toJSON(t,n,a){const o=a?new a:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(o);for(const i of this.items)Jk(n,o,i);return o}toString(t,n,a){if(!t)return JSON.stringify(this);for(const o of this.items)if(!En(o))throw new Error(`Map items must all be pairs; found ${JSON.stringify(o)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),Yk(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:a,onComment:n})}}class Qk extends Kk{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(nc,t),this.items=[]}add(t){this.items.push(t)}delete(t){const n=Fc(t);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(t,n){const a=Fc(t);if(typeof a!="number")return;const o=this.items[a];return!n&&xn(o)?o.value:o}has(t){const n=Fc(t);return typeof n=="number"&&n<this.items.length}set(t,n){const a=Fc(t);if(typeof a!="number")throw new Error(`Expected a valid index, not ${t}.`);const o=this.items[a];xn(o)&&Vk(n)?o.value=n:this.items[a]=n}toJSON(t,n){const a=[];n?.onCreate&&n.onCreate(a);let o=0;for(const i of this.items)a.push(qa(i,String(o++),n));return a}toString(t,n,a){return t?Yk(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:a,onComment:n}):JSON.stringify(this)}static from(t,n,a){const{replacer:o}=a,i=new this(t);if(n&&Symbol.iterator in Object(n)){let s=0;for(let l of n){if(typeof o=="function"){const m=n instanceof Set?l:String(s++);l=o.call(n,m,l)}i.items.push(Ed(l,void 0,a))}}return i}}function Fc(e){let t=xn(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}function bN(e,t,n){const{replacer:a}=n,o=new Qk(e);o.tag="tag:yaml.org,2002:pairs";let i=0;if(t&&Symbol.iterator in Object(t))for(let s of t){typeof a=="function"&&(s=a.call(t,String(i++),s));let l,m;if(Array.isArray(s))if(s.length===2)l=s[0],m=s[1];else throw new TypeError(`Expected [key, value] tuple: ${s}`);else if(s&&s instanceof Object){const d=Object.keys(s);if(d.length===1)l=d[0],m=s[l];else throw new TypeError(`Expected tuple with one key, not ${d.length} keys`)}else l=s;o.items.push(vg(l,m,n))}return o}class bg extends Qk{constructor(){super(),this.add=Ui.prototype.add.bind(this),this.delete=Ui.prototype.delete.bind(this),this.get=Ui.prototype.get.bind(this),this.has=Ui.prototype.has.bind(this),this.set=Ui.prototype.set.bind(this),this.tag=bg.tag}toJSON(t,n){if(!n)return super.toJSON(t);const a=new Map;n?.onCreate&&n.onCreate(a);for(const o of this.items){let i,s;if(En(o)?(i=qa(o.key,"",n),s=qa(o.value,i,n)):i=qa(o,"",n),a.has(i))throw new Error("Ordered maps must not include duplicate keys");a.set(i,s)}return a}static from(t,n,a){const o=bN(t,n,a),i=new this;return i.items=o.items,i}}bg.tag="tag:yaml.org,2002:omap";class yg extends Ui{constructor(t){super(t),this.tag=yg.tag}add(t){let n;En(t)?n=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?n=new No(t.key,null):n=new No(t,null),Fr(this.items,n.key)||this.items.push(n)}get(t,n){const a=Fr(this.items,t);return!n&&En(a)?xn(a.key)?a.key.value:a.key:a}set(t,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);const a=Fr(this.items,t);a&&!n?this.items.splice(this.items.indexOf(a),1):!a&&n&&this.items.push(new No(t))}toJSON(t,n){return super.toJSON(t,n,Set)}toString(t,n,a){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),n,a);throw new Error("Set items must all have null values")}static from(t,n,a){const{replacer:o}=a,i=new this(t);if(n&&Symbol.iterator in Object(n))for(let s of n)typeof o=="function"&&(s=o.call(n,s,s)),i.items.push(vg(s,null,a));return i}}yg.tag="tag:yaml.org,2002:set";new Set("0123456789ABCDEFabcdef");new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()");new Set(",[]{}");new Set(` ,[]{}
|
|
174
|
-
\r `);const Od=r().min(1).max(2e3).refine(e=>!e.includes("\\")&&!e.includes(":")&&!e.startsWith("/")&&e.split("/").every(t=>t!==""&&t!=="."&&t!==".."),"source paths must be portable relative paths");r().regex(/^[a-z][a-z0-9_-]{0,119}$/);const yN={type:"object",properties:{},additionalProperties:!1};c({name:r().trim().min(1).max(240).optional(),description:r().max(4e3).optional(),skillPaths:p(Od).max(100).optional(),assetPaths:p(Od).max(100).optional()}).strict();c({actionId:r().trim().min(1).max(240),name:r().trim().min(1).max(240),description:r().max(4e3).default(""),inputSchema:re(r(),ce()).default(yN),skillPaths:p(Od).max(100).default([]),assetPaths:p(Od).max(100).default([])}).strict();const Xk=b(["openpond.lab"]),El=c({id:r(),experience:ig.default(i2),provider:Is,modelRef:cn.nullable().optional(),openPondCommandAccessMode:Yl.default(du),systemKind:Xk.nullable().optional(),hiddenFromDefaultSidebar:A().optional(),parentSessionId:r().nullable().optional(),parentTurnId:r().nullable().optional(),subagentRunId:r().nullable().optional(),subagentRoleId:ws.nullable().optional(),subagentDelegationMode:su.nullable().optional(),title:r(),appId:r().nullable(),appName:r().nullable(),workspaceKind:Ql.optional(),workspaceId:r().nullable().optional(),workspaceName:r().nullable().optional(),localProjectId:r().nullable().optional(),cloudProjectId:r().nullable().optional(),cloudTeamId:r().nullable().optional(),currentProfile:kr.nullable().optional(),profileWorkflowBinding:Z$.nullable().optional(),profileComponentBinding:J$.nullable().optional(),metadata:re(r(),ce()).optional(),cwd:r().nullable(),codexThreadId:r().nullable(),createdAt:r(),updatedAt:r(),status:b(["idle","active","failed","closed"]),runtimeSeconds:u().int().nonnegative().optional(),runtimeRunningSince:r().nullable().optional(),pinned:A(),savedForLater:A().optional(),archived:A(),order:u()});c({id:r(),sessionId:r(),providerTurnId:r().nullable(),modelRef:cn.nullable().optional(),prompt:r(),startedAt:r(),completedAt:r().nullable(),status:b(["in_progress","completed","failed","interrupted"]),error:r().nullable(),metadata:re(r(),ce()).optional().default({}),createImproveRun:Xl.nullable().optional().default(null),profileSnapshot:P2.nullable().optional(),harnessSnapshot:T2.nullable().optional()});const SN=c({id:r(),sessionId:r(),turnId:r().nullable(),providerRequestId:Dt([r(),u()]),kind:b(["command","file_change","permissions","user_input","create_plan","subagent_patch_apply","legacy_exec","legacy_patch"]),title:r(),detail:r(),status:b(["pending","accepted","accepted_for_session","declined","cancelled"]),createdAt:r()}),xN=c({key:b(["files","diffs","checks","deploys","sources","schedules","tool_runs","logs","app_config"]),label:r(),status:b(["placeholder","available","error"]),summary:r()}),ew=c({id:r().trim().min(1).max(191),agentId:r().trim().min(1).max(191).optional().nullable(),sourcePath:r().trim().min(1).max(2e3).optional().nullable(),sourceActionId:r().trim().min(1).max(191).optional().nullable(),name:r().trim().min(1).max(191).optional().nullable(),label:r().trim().min(1).max(160).optional().nullable(),description:r().trim().max(1e3).optional().nullable(),visibility:r().trim().max(80).optional().nullable(),inputSchema:Dt([r().trim().max(191),re(r(),ce())]).optional().nullable(),outputSchema:Dt([r().trim().max(191),re(r(),ce())]).optional().nullable(),approvalPolicy:re(r(),ce()).optional().nullable(),artifactPolicy:re(r(),ce()).optional().nullable(),setupRequirements:p(re(r(),ce())).optional(),mcp:re(r(),ce()).optional().nullable(),schedulePolicy:re(r(),ce()).optional().nullable(),trace:re(r(),ce()).optional().nullable(),implementation:re(r(),ce()).optional().nullable(),invokesModel:A().optional()}),kN=c({command:b(["inspect","build","validate","eval","traces","run"]),status:b(["passed","failed"]),checkedAt:r(),exitCode:u().nullable().optional(),sourceHead:r().nullable().optional()}),wN=c({id:r(),name:r(),path:r(),enabled:A()}),IN=c({name:r(),description:r(),path:r(),scope:S("profile"),enabled:A(),sourcePath:r(),charCount:u(),sourceHash:r(),validationStatus:b(["valid","warning","error"]),validationMessages:p(r()),resourceFiles:p(r()).optional().default([])}),_N=c({id:r(),name:r(),path:r(),agentId:r().nullable(),sourcePath:r()}),tw=c({path:r(),originalPath:r().nullable().optional(),indexStatus:r().nullable(),worktreeStatus:r().nullable(),status:r(),category:b(["added","modified","deleted","renamed","untracked","changed"])}),CN=c({isRepo:A(),branch:r().nullable(),head:r().nullable(),shortHead:r().nullable(),dirty:A(),upstream:r().nullable(),ahead:u().nullable(),behind:u().nullable(),remoteUrl:r().nullable(),files:p(tw),fileCount:u().int().nonnegative().optional(),error:r().nullable()}),RN=c({actionCount:u(),generatedAt:r().nullable(),manifestPath:r().nullable(),registryPath:r().nullable(),stale:A(),error:r().nullable()}),PN=c({skillCount:u(),generatedAt:r().nullable(),stale:A(),error:r().nullable()}),uy=c({ref:r(),source:b(["action_catalog","source_upload_metadata"]),actionId:r().nullable(),kind:r().nullable(),label:r(),status:r(),required:A(),blocking:A()}),AN=c({status:b(["ready","setup_required","blocked"]),requirementCount:u(),blockingCount:u(),optionalMissingCount:u(),readyCount:u(),requirements:p(uy),blockingRequirements:p(uy)}),TN=c({changedAgents:p(r()),newAgents:p(r()),deletedAgents:p(r()),changedSkills:p(r()).optional().default([]),changedActions:p(r()),changedExtensions:p(r()),setupChanges:p(r()),envRequirementChanges:p(r()),files:p(tw),fileCount:u().int().nonnegative().optional()}),EN=c({status:r(),agentId:r().nullable().optional(),deployPlanStatus:r().nullable().optional(),canRun:A().nullable().optional(),canDeploy:A().nullable().optional(),sourceRef:r().nullable().optional(),sourceCommitSha:r().nullable().optional(),manifestHash:r().nullable().optional(),manifestPath:r().nullable().optional(),setupCommands:p(r()).optional(),validationCommands:p(r()).optional(),requiredChecks:p(r()).optional(),evalNames:p(r()).optional(),blockedReasons:p(r()).optional(),staleReasons:p(r()).optional(),runtimeId:r().nullable().optional(),sandboxId:r().nullable().optional(),traceArtifactRefs:p(r()).optional(),evalResultArtifactRefs:p(r()).optional(),validatorArtifactRefs:p(r()).optional(),checkedAt:r().nullable().optional(),error:r().nullable().optional()}),MN=c({status:r(),agentId:r().nullable().optional(),runtimeAgentId:r().nullable().optional(),projectId:r().nullable().optional(),sourceRoot:r().nullable().optional(),sourceRef:r().nullable().optional(),sourceCommitSha:r().nullable().optional(),manifestHash:r().nullable().optional(),manifestPath:r().nullable().optional(),manifestSyncedAt:r().nullable().optional(),fileCount:u().nullable().optional(),totalBytes:u().nullable().optional(),generatedManifestPath:r().nullable().optional(),synthesizedOpenPondYaml:A().nullable().optional(),uploadMetadataPath:r().nullable().optional(),setupCommands:p(r()).optional(),validationCommands:p(r()).optional(),materializedAt:r().nullable().optional(),error:r().nullable().optional()}),jN=c({status:r(),agentId:r().nullable().optional(),snapshotId:r().nullable().optional(),sourceRef:r().nullable().optional(),sourceCommitSha:r().nullable().optional(),manifestHash:r().nullable().optional(),manifestPath:r().nullable().optional(),buildStatus:r().nullable().optional(),validationStatus:r().nullable().optional(),evalStatus:r().nullable().optional(),publishedAt:r().nullable().optional(),error:r().nullable().optional()}),ON=c({status:r(),agentId:r().nullable().optional(),runId:r().nullable().optional(),runtimeId:r().nullable().optional(),sandboxId:r().nullable().optional(),sourceRef:r().nullable().optional(),sourceCommitSha:r().nullable().optional(),manifestHash:r().nullable().optional(),setupGateStatus:r().nullable().optional(),setupRequirementRefs:p(r()).optional(),artifactRefs:p(r()).optional(),traceArtifactRefs:p(r()).optional(),evalArtifactRefs:p(r()).optional(),startedAt:r().nullable().optional(),completedAt:r().nullable().optional(),error:r().nullable().optional()}),$N=c({teamId:r().nullable(),projectId:r().nullable(),sourceRef:r().nullable(),sourceCommitSha:r().nullable(),lastPushedAt:r().nullable(),lastPushedLocalHead:r().nullable(),lastPushedHostedHead:r().nullable(),promotionStatus:r().nullable().optional().default(null),hostedRunStatus:r().nullable().optional().default(null),hostedRunAgentId:r().nullable().optional().default(null),hostedRunId:r().nullable().optional().default(null),hostedRunAt:r().nullable().optional().default(null),hostedSourceMaterialization:MN.nullable().optional().default(null),hostedSourceCheck:EN.nullable().optional().default(null),hostedPublish:jN.nullable().optional().default(null),hostedRun:ON.nullable().optional().default(null)}),NN=c({state:b(["none","ready","dirty","pending_commit","error"]),message:r(),agentCount:u(),actionCount:u(),defaultAction:r().nullable(),checkFresh:A(),checkStaleReason:r().nullable(),localHead:r().nullable(),hostedHead:r().nullable()}),nw=c({mode:b(["none","local"]),repoPath:r().nullable(),activeProfile:r().nullable(),sourcePath:r().nullable(),manifestPath:r().nullable(),agents:p(wN),skills:p(IN).optional().default([]),evals:p(_N).optional().default([]),git:CN.nullable(),catalog:RN,skillCatalog:PN.optional().default({skillCount:0,generatedAt:null,stale:!0,error:null}),actionCatalog:p(ew),sourceSetupRequirements:p(re(r(),ce())),setupGate:AN,diff:TN,hosted:$N.nullable(),summary:NN,lastCheck:kN.nullable(),error:r().nullable()}),DN=c({ref:kr,name:r(),repoPath:r(),sourcePath:r().nullable(),state:nw}),LN=c({lastUsed:kr.nullable(),profiles:p(DN)});function UN(){return{lastUsed:null,profiles:[]}}function HN(){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 zN=c({name:r(),description:r(),path:r(),sourcePath:r(),enabled:A(),charCount:u().int().nonnegative(),sourceHash:r(),validationStatus:b(["valid","error"]),validationMessages:p(r()),resourceFiles:p(r()),updatedAt:r().nullable()}),qN=b(["codex","profile","extension"]);c({skillName:r(),scope:qN,path:r(),byteSize:u().int().nonnegative(),isBinary:A(),content:r().nullable()});const BN=[{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"]}],FN=c({name:r(),description:r(),relativePath:r(),sourcePath:r(),charCount:u().int().nonnegative(),sourceHash:r(),resourceFiles:p(r()),validationStatus:b(["valid","error"]),validationMessages:p(r())}),aw=c({id:r(),source:S("github"),owner:r(),repo:r(),repositoryUrl:r().url(),requestedRef:r(),resolvedCommit:r(),sourcePath:r(),readmePath:r().nullable(),installedAt:r(),updatedAt:r(),packageHash:r(),skills:p(FN),validationStatus:b(["valid","error"]),validationMessages:p(r())});aw.omit({installedAt:!0,updatedAt:!0,sourcePath:!0}).extend({sourcePath:ru()});const VN=c({rootPath:r(),registryPath:r(),extensions:p(aw),error:r().nullable()});c({source:r().trim().min(1),ref:r().trim().min(1).optional()});const KN=c({latestSequence:u().int().nonnegative(),oldestSequence:u().int().nonnegative(),totalEvents:u().int().nonnegative(),limit:u().int().nonnegative(),hasMoreBefore:A()});c({server:r2,account:ZO,codex:JO,configuration:c({rawRevision:r(),effectiveRevision:r(),sources:p(c({layer:r(),path:r(),revision:r()})),provenance:re(r(),c({layer:r(),path:r(),revision:r()}))}).optional(),preferences:ny.optional().default(()=>ny.parse({})),providers:Ib.optional().default(()=>Ib.parse({})),personalization:ay.optional().default(()=>ay.parse({soul:bk[0].content,soulPath:null,updatedAt:null})),apps:p(oO),localProjects:p(cO).optional().default([]),cloudProjects:p(lO).optional().default([]),profile:nw.optional().default(HN),profileLibrary:LN.optional().default(UN),codexPersonalSkills:p(zN).optional().default([]),extensionCatalog:VN.optional().default({rootPath:"",registryPath:"",extensions:[],error:null}),codexHistorySessions:p(El).optional().default([]),sidebarAppPreferences:qO,sidebarFileBookmarks:p(gk).optional().default([]),appsError:r().nullable(),appsMeta:ty,accountMeta:ty,sessions:p(El),events:p(_b),eventWindow:KN.optional(),approvals:p(SN),placeholders:p(xN),diagnostics:p(_b)});const Sg=b(["openpond_hosted","local_byok","codex_app_server","unknown"]),ow=b(["provider_usage","codex_context_usage","missing"]),WN=b(["provider_usage_body","provider_response_headers"]),GN=b(["chat_turn","tool_loop","slash_command","create_improve_planner","harness_refiner","context_compaction","subagent","codex_context","other"]),ZN=b(["foreground","tool_loop","compaction","subagent","refiner","other"]),rw=b(["user_facing","background","system"]),iw=b(["started","completed","failed","interrupted"]),xg=b(["composer_selection","prompt_parse","server_parser","model_tool","api"]),sw=b(["chat","settings","goal","create_improve","compaction","system"]),lw=b(["direct_chat","tool_loop","slash_command","planner","summary","scan","subagent","other"]),JN=c({surface:sw,workflowKind:lw,sessionId:r().trim().min(1).nullable().default(null),turnId:r().trim().min(1).nullable().default(null),goalId:r().trim().min(1).nullable().default(null),subagentRunId:r().trim().min(1).nullable().default(null),subagentRoleId:r().trim().min(1).nullable().default(null),createImproveRunId:r().trim().min(1).nullable().default(null),commandName:r().trim().min(1).max(160).nullable().default(null),commandSource:xg.nullable().default(null),appId:r().trim().min(1).nullable().default(null),workspaceKind:Ql.nullable().default(null),workspaceId:r().trim().min(1).nullable().default(null),localProjectId:r().trim().min(1).nullable().default(null),cloudProjectId:r().trim().min(1).nullable().default(null),sourceEventSequence:u().int().nonnegative().nullable().default(null)}),YN=c({surface:sw.optional(),workflowKind:lw.optional(),goalId:r().trim().min(1).nullable().optional(),subagentRunId:r().trim().min(1).nullable().optional(),subagentRoleId:r().trim().min(1).nullable().optional(),createImproveRunId:r().trim().min(1).nullable().optional(),commandName:r().trim().min(1).max(160).nullable().optional(),commandSource:xg.nullable().optional()}).strict(),ri=r().trim().min(1).max(160),QN=c({id:r().trim().min(1),requestId:r().trim().min(1),requestOrdinal:u().int().nonnegative(),sessionId:r().trim().min(1).nullable(),turnId:r().trim().min(1).nullable(),provider:ri,model:r().trim().min(1),route:Sg,source:ow,requestKind:GN,visibility:rw,status:iw,startedAt:r().trim().min(1),completedAt:r().trim().min(1).nullable(),durationMs:u().int().nonnegative().nullable(),firstTokenMs:u().int().nonnegative().nullable(),promptTokens:u().int().nonnegative().nullable(),cachedPromptTokens:u().int().nonnegative().nullable(),uncachedPromptTokens:u().int().nonnegative().nullable(),cacheWritePromptTokens:u().int().nonnegative().nullable(),cacheTelemetrySource:WN.nullable(),completionTokens:u().int().nonnegative().nullable(),totalTokens:u().int().nonnegative().nullable(),errorType:r().trim().min(1).max(160).nullable(),errorMessage:r().trim().min(1).max(2e3).nullable(),attribution:JN}),cw=c({from:r().trim().min(1),to:r().trim().min(1),bucket:b(["day","all_time"])}),kg=Dt([S("all"),rw]),wg=b(["all","started","completed","failed","interrupted","missing"]),XN=c({range:b(["7d","30d","90d","all"]).default("30d"),visibility:kg.default("all"),status:wg.default("all"),provider:ri.optional(),model:r().trim().min(1).optional()});XN.extend({sessionId:r().trim().min(1).optional(),turnId:r().trim().min(1).optional(),limit:u().int().positive().max(500).default(100)});c({sessionId:r().trim().min(1)});const ii=c({requests:u().int().nonnegative(),promptTokens:u().int().nonnegative().nullable(),cacheTelemetryRequests:u().int().nonnegative(),cacheHitRequests:u().int().nonnegative(),cachedPromptTokens:u().int().nonnegative().nullable(),uncachedPromptTokens:u().int().nonnegative().nullable(),cacheWritePromptTokens:u().int().nonnegative().nullable(),cacheHitRate:u().min(0).max(1).nullable(),cacheRequestHitRate:u().min(0).max(1).nullable(),cacheTelemetryCoverage:u().min(0).max(1),completionTokens:u().int().nonnegative().nullable(),totalTokens:u().int().nonnegative().nullable(),averageLatencyMs:u().nonnegative().nullable(),p95LatencyMs:u().nonnegative().nullable(),averageFirstTokenMs:u().nonnegative().nullable(),p95FirstTokenMs:u().nonnegative().nullable(),failures:u().int().nonnegative(),failureRate:u().nonnegative(),firstSeenAt:r().trim().min(1),lastSeenAt:r().trim().min(1)}),eD=ii.extend({provider:ri,model:r().trim().min(1),route:Sg}),tD=ii.extend({sessionId:r().trim().min(1),title:r().trim().min(1).nullable(),workspaceKind:Ql.nullable(),workspaceId:r().trim().min(1).nullable()}),nD=ii.extend({commandName:r().trim().min(1),commandSource:xg.nullable()}),aD=ii.extend({route:Sg}),oD=ii.extend({status:iw}),rD=ii.extend({source:ow}),iD=ii.extend({cohort:ZN}),sD=c({date:r().trim().min(1),totalTokens:u().int().nonnegative(),requests:u().int().nonnegative(),models:p(c({provider:ri,model:r().trim().min(1),totalTokens:u().int().nonnegative(),requests:u().int().nonnegative()}))}),lD=c({requests:u().int().nonnegative(),completedRequests:u().int().nonnegative(),failedRequests:u().int().nonnegative(),missingUsageRequests:u().int().nonnegative(),promptTokens:u().int().nonnegative().nullable(),cacheTelemetryRequests:u().int().nonnegative(),cacheHitRequests:u().int().nonnegative(),cachedPromptTokens:u().int().nonnegative().nullable(),uncachedPromptTokens:u().int().nonnegative().nullable(),cacheWritePromptTokens:u().int().nonnegative().nullable(),cacheHitRate:u().min(0).max(1).nullable(),cacheRequestHitRate:u().min(0).max(1).nullable(),cacheTelemetryCoverage:u().min(0).max(1),completionTokens:u().int().nonnegative().nullable(),totalTokens:u().int().nonnegative().nullable(),averageLatencyMs:u().nonnegative().nullable(),p95LatencyMs:u().nonnegative().nullable(),averageFirstTokenMs:u().nonnegative().nullable(),p95FirstTokenMs:u().nonnegative().nullable(),failureRate:u().nonnegative(),activeModelCount:u().int().nonnegative(),peakDailyTokens:u().int().nonnegative(),longestRequestMs:u().int().nonnegative().nullable(),activeDays:u().int().nonnegative(),currentStreakDays:u().int().nonnegative(),longestStreakDays:u().int().nonnegative()});c({generatedAt:r().trim().min(1),range:cw,filters:c({visibility:kg,status:wg,provider:ri.nullable(),model:r().trim().min(1).nullable()}),totals:lD,daily:p(sD),models:p(eD),threads:p(tD),commands:p(nD),routes:p(aD),statuses:p(oD),sources:p(rD),cohorts:p(iD)});c({generatedAt:r().trim().min(1),range:cw,filters:c({visibility:kg,status:wg,provider:ri.nullable(),model:r().trim().min(1).nullable(),sessionId:r().trim().min(1).nullable(),turnId:r().trim().min(1).nullable()}),limit:u().int().positive(),hasMore:A(),records:p(QN)});const cD=c({turnId:r().trim().min(1),requests:u().int().nonnegative(),cacheTelemetryRequests:u().int().nonnegative(),cachedPromptTokens:u().int().nonnegative().nullable(),uncachedPromptTokens:u().int().nonnegative().nullable(),cacheWritePromptTokens:u().int().nonnegative().nullable(),cacheHitRate:u().min(0).max(1).nullable(),cacheTelemetryCoverage:u().min(0).max(1),providers:p(ri)});c({generatedAt:r().trim().min(1),sessionId:r().trim().min(1),turns:p(cD)});const dD=b(["usage_spike","model_usage_spike","latency_regression","failure_cluster","missing_usage_frames"]);c({type:dD,title:r().trim().min(1),summary:r().trim().min(1),severity:b(["nit","concern","blocker"]),payload:re(r(),ce()).default({})});const uD=b(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),mD=b(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),pD=b(["native_bot","oauth_connector","wallet_connector","mcp_endpoint"]),fD=c({kind:S("integration"),provider:uD,appIds:p(mD).min(1).max(4),setupSurfaces:p(pD).min(1).max(4),connectionIds:p(r().trim().min(1)).max(8).optional(),capabilities:p(r().trim().min(1)).max(64).optional()}).strict(),Vr={maxAttachments:10,maxAttachmentBytes:12*1024*1024,maxAttachmentBase64Chars:Math.ceil(12*1024*1024*4/3)+16,maxTextChars:2e5},hD=b(["image","text","file"]),gD=c({sessionId:r().trim().min(1).max(200),turnId:r().trim().min(1).max(200),attachmentId:r().trim().min(1).max(200),storageName:r().trim().min(1).max(240),contentType:r().trim().min(1).max(160)}),vD=c({sessionId:r().trim().min(1).max(200),turnId:r().trim().min(1).max(200),attachmentId:r().trim().min(1).max(200),storageName:r().trim().min(1).max(1024),contentType:r().trim().min(1).max(160)}),dw=c({id:r().trim().min(1),name:r().trim().min(1).max(240),mediaType:r().trim().min(1).max(160),sizeBytes:u().int().nonnegative().max(Vr.maxAttachmentBytes),kind:hD,lineCount:u().int().nonnegative().max(Vr.maxAttachmentBytes+1).optional(),relativePath:r().trim().min(1).max(1024).optional(),text:r().max(Vr.maxTextChars).optional(),contentsBase64:r().max(Vr.maxAttachmentBase64Chars).optional()}),bD=dw.omit({text:!0,contentsBase64:!0}).extend({imagePreview:gD.optional(),filePreview:vD.optional()});c({experience:ig.optional(),provider:Is.default(Qr),modelRef:cn.optional(),openPondCommandAccessMode:Yl.optional(),systemKind:Xk.nullable().optional(),hiddenFromDefaultSidebar:A().optional(),parentSessionId:r().trim().min(1).max(200).nullable().optional(),parentTurnId:r().trim().min(1).max(200).nullable().optional(),subagentRunId:r().trim().min(1).max(200).nullable().optional(),subagentRoleId:ws.nullable().optional(),subagentDelegationMode:su.nullable().optional(),appId:r().nullable().optional(),appName:r().nullable().optional(),workspaceKind:Ql.optional(),workspaceId:r().nullable().optional(),workspaceName:r().nullable().optional(),localProjectId:r().nullable().optional(),cloudProjectId:r().nullable().optional(),cloudTeamId:r().nullable().optional(),currentProfile:kr.nullable().optional(),profileWorkflowBinding:El.shape.profileWorkflowBinding,profileComponentBinding:El.shape.profileComponentBinding,metadata:re(r(),ce()).optional(),cwd:r().nullable().optional(),title:r().optional(),autoTitlePrompt:r().trim().min(1).max(2e4).optional()});c({teamId:r().trim().min(1),projectName:r().trim().min(1).max(120).optional(),branch:r().trim().min(1).max(120).optional(),chatSessionId:r().trim().min(1).max(200).optional(),displayPrompt:r().trim().min(1).max(2e3).optional()});c({branch:r().trim().min(1).max(120).optional()});c({prompt:r().min(1),workflowInput:ce().optional(),metadata:re(r(),ce()).optional(),usageAttribution:YN.optional().nullable(),cwd:r().nullable().optional(),model:r().nullable().optional(),modelRef:cn.optional(),mentionedAppIds:p(r().trim().min(1)).max(8).optional(),mentionedConnectedApps:p(fD).max(8).optional(),openPondActionCatalog:p(ew).max(100).optional(),attachments:p(dw).max(Vr.maxAttachments).optional(),createImproveRun:Xl.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:og.default("default"),codexReasoningEffort:uu.optional()});c({prompt:r().min(1),error:r().min(1),target:b(["cloud_workspace","hybrid_sandbox"])});c({reason:b(["manual"]).default("manual"),model:r().nullable().optional(),modelRef:cn.optional()});c({experience:ig.optional(),provider:Is.optional(),modelRef:cn.nullable().optional(),openPondCommandAccessMode:Yl.optional(),pinned:A().optional(),savedForLater:A().optional(),archived:A().optional(),order:u().optional(),title:r().optional(),parentSessionId:r().trim().min(1).max(200).nullable().optional(),parentTurnId:r().trim().min(1).max(200).nullable().optional(),subagentRunId:r().trim().min(1).max(200).nullable().optional(),subagentRoleId:ws.nullable().optional(),subagentDelegationMode:su.nullable().optional(),appId:r().nullable().optional(),appName:r().nullable().optional(),workspaceKind:Ql.optional(),workspaceId:r().nullable().optional(),workspaceName:r().nullable().optional(),localProjectId:r().nullable().optional(),cloudProjectId:r().nullable().optional(),cloudTeamId:r().nullable().optional(),currentProfile:kr.nullable().optional(),metadata:re(r(),ce()).optional(),cwd:r().nullable().optional()});c({command:r().trim().min(1),cwd:r().trim().min(1).max(4096).nullable().optional(),timeoutSeconds:u().int().min(1).max(3600).optional()});c({appIds:p(r()).min(1)});c({expectedRevision:r().optional(),defaultChatProvider:Is.optional(),defaultChatModel:r().min(1).optional(),defaultChatModelRef:cn.nullable().optional(),subagents:Cl.optional(),codexPermissionMode:og.optional(),codexReasoningEffort:uu.optional(),openPondCommandAccessMode:Yl.optional(),defaultBranchPrefix:r().trim().max(48).optional(),defaultNewProjectDirectory:r().trim().max(4096).optional(),defaultTeamId:r().trim().max(191).nullable().optional(),advancedWorkspaceControls:A().optional(),steerActiveResponses:A().optional(),contextCompaction:$f.optional(),training:Nf.optional(),sidebarWidth:u().int().min(244).max(560).optional(),diffPanelWidth:u().int().min(320).max(2400).optional(),sidebarSectionsCollapsed:Of.optional(),editor:Td.optional()});c({message:r().trim().min(1).max(4e3),surface:r().trim().min(1).max(120).default("app"),stack:r().max(12e3).nullable().optional(),context:re(r(),ce()).optional()}).strict();c({activeTemplateId:rg,templateName:r().trim().min(1).max(80),soul:r().trim().min(1).max(8e3),saveAsNew:A().optional().default(!1)});c({decision:b(["accept","acceptForSession","decline","cancel"])});c({branch:r().trim().min(1).max(240).nullable().optional(),surface:b(["desktop","terminal"])});c({handle:r().min(1),baseUrl:r().nullable().optional()});c({handle:r().min(1),baseUrl:r().nullable().optional()});c({handle:r().min(1).optional(),apiKey:r().min(1),baseUrl:r().nullable().optional(),apiBaseUrl:r().nullable().optional(),chatApiBaseUrl:r().nullable().optional(),environment:r().nullable().optional(),setActive:A().optional()});c({handle:r().min(1),currentBaseUrl:r().nullable().optional(),apiKey:r().min(1).optional(),baseUrl:r().nullable().optional(),apiBaseUrl:r().nullable().optional(),chatApiBaseUrl:r().nullable().optional(),environment:r().nullable().optional(),setActive:A().optional()});c({appId:r(),exists:A(),configPath:r().nullable().optional(),envVar:r().nullable(),toolName:r().nullable(),version:Dt([r(),u()]).nullable(),source:b(["hosted_env","local_file","defaults","missing"]),currentConfig:re(r(),ce()).nullable(),defaults:re(r(),ce()).nullable(),schema:re(r(),ce()).nullable(),error:r().nullable().optional(),updatedAt:r()}).passthrough();const $d=b(["create_sandbox_template_scaffold","resource_read","resource_search","list_files","read_files","search_files","preview_write_files","preview_write_file","preview_edit_file","preview_delete_file","write_files","write_file","edit_file","delete_file","workspace_status","validate_sandbox_template","build_sandbox_template","run_sandbox_template","git_init","git_status","git_diff","git_fetch","git_commit","git_push","publish_openpond_repo","sandbox_create","sandbox_templates","sandbox_template_launch","sandbox_status","sandbox_start","sandbox_list_files","sandbox_read_file","sandbox_search_files","sandbox_upload_file","sandbox_write_file","sandbox_edit_file","sandbox_delete_file","sandbox_mkdir","sandbox_move_file","sandbox_exec","sandbox_git_status","sandbox_git_diff","sandbox_git_export_patch","sandbox_git_apply_patch_local","sandbox_git_branch","sandbox_git_commit","sandbox_git_pull","sandbox_git_push","sandbox_preserve_source","sandbox_promote_source","sandbox_run_action","sandbox_open_port","sandbox_snapshot_catalog","sandbox_snapshot_create","sandbox_snapshot_update","sandbox_snapshot_validate","sandbox_snapshot_publish","sandbox_replays","sandbox_replay_start","sandbox_replay_get","sandbox_replay_logs","sandbox_replay_artifacts","sandbox_replay_cancel","sandbox_logs","sandbox_receipts","sandbox_prepare_agent","sandbox_save_agent_package","sandbox_save_output","work_agent_package_install","work_output_delete","work_output_read","sandbox_schedule_create","sandbox_stop"]);c({action:$d,args:re(r(),ce()).optional().default({}),source:b(["ui_button","chat_action","terminal_command","hook"]).default("chat_action")});c({ok:A(),action:$d,appId:r().nullable().optional(),output:r(),data:ce().optional()});const ac=c({id:r().trim().min(1).max(200),title:r().trim().min(1).max(240),sourceTaskId:r().trim().min(1).max(200),sourceTurnId:r().trim().min(1).max(200),revision:u().int().positive().default(1),createdAt:r().datetime()}),oc=c({kind:b(["structural","visual","test","user_review"]),status:b(["passed","failed","not_run"]),label:r().trim().min(1).max(240),detail:r().trim().max(4e3).nullable().optional(),ref:r().trim().max(4096).nullable().optional()}),uw=c({kind:S("local"),path:r().trim().min(1).max(4096),deviceId:r().trim().min(1).max(200)}),mw=c({kind:S("managed"),fileId:r().trim().min(1).max(200),downloadPath:r().trim().min(1).max(4096)}),yD=c({kind:S("external"),provider:r().trim().min(1).max(120),resourceId:r().trim().min(1).max(500),url:r().url().nullable()}),pw=ac.extend({kind:S("file"),contentType:r().trim().min(1).max(200),sizeBytes:u().int().nonnegative(),sha256:r().regex(/^[a-f0-9]{64}$/),location:It("kind",[uw,mw,yD]),validation:p(oc).max(32).default([])}),SD=ac.extend({kind:S("source_change"),projectId:r().trim().min(1).max(200),ref:r().trim().min(1).max(500),url:r().url().nullable(),validation:p(oc).max(32).default([])}),xD=ac.extend({kind:S("deployment"),deploymentId:r().trim().min(1).max(200),url:r().url(),validation:p(oc).max(32).default([])}),kD=ac.extend({kind:S("external_resource"),provider:r().trim().min(1).max(120),resourceId:r().trim().min(1).max(500),url:r().url(),contentType:r().trim().min(1).max(200).nullable(),validation:p(oc).max(32).default([])}),fw=c({id:r().trim().min(1).max(191),label:r().trim().min(1).max(160).nullable(),description:r().trim().max(1e3).nullable(),inputSchema:re(r(),ce()).nullable(),outputSchema:re(r(),ce()).nullable(),schedulePolicy:re(r(),ce()).nullable()}),hw=c({base:r().trim().min(1).max(200),resources:re(r(),ce()),modelPolicy:re(r(),ce()).nullable(),setup:re(r(),ce()).nullable()}),wD=c({id:r().trim().min(1).max(200),kind:b(["sdk_validation","sdk_eval"]),status:b(["passed","failed"]),summary:r().trim().min(1).max(2e3),artifactPath:r().trim().min(1).max(4096),artifactSha256:r().regex(/^[a-f0-9]{64}$/)}),ID=c({path:r().trim().min(1).max(4096),sizeBytes:u().int().nonnegative(),sha256:r().regex(/^[a-f0-9]{64}$/),contentsBase64:r()});c({schema:S("openpond.agent-package.v1"),agentId:r().trim().min(1).max(191),versionId:r().trim().min(1).max(200),digest:r().regex(/^[a-f0-9]{64}$/),title:r().trim().min(1).max(240),source:c({files:p(ID).min(1).max(1e3),totalSizeBytes:u().int().nonnegative()}),manifest:re(r(),ce()),actions:p(fw).min(1).max(256),runtimeRequirements:hw,receipts:p(wD).min(2).max(64)});const _D=ac.extend({kind:S("agent_package"),agentId:r().trim().min(1).max(191),versionId:r().trim().min(1).max(200),digest:r().regex(/^[a-f0-9]{64}$/),packageFileId:r().trim().min(1).max(200),manifestFileId:r().trim().min(1).max(200),actions:p(fw).min(1).max(256),runtimeRequirements:hw,validationReceiptIds:p(r().trim().min(1).max(200)).min(1).max(32),evalReceiptIds:p(r().trim().min(1).max(200)).min(1).max(32),sourceFileCount:u().int().positive(),sourceSizeBytes:u().int().nonnegative(),location:It("kind",[uw,mw]),validation:p(oc).max(32).default([])}),eQ=It("kind",[pw,SD,xD,kD,_D]);c({outputs:p(pw)});const CD=b(["sandbox_template","sandbox","generic_git","plain_folder"]),RD=b(["sandbox_template"]).nullable();c({productKind:CD,actions:c({files:A(),git:A(),sandboxRuntime:A(),sandboxTemplate:A()}),checks:c({validate:$d.nullable(),build:$d.nullable(),postEdit:RD}),ui:c({showSandboxTemplateActions:A(),showSandboxRuntimeActions:A()})});const PD=c({id:r(),name:r(),dnsName:r().nullable(),os:r().nullable(),online:A(),active:A(),isSelf:A(),tailscaleIps:p(r()),lastSeen:r().nullable()}),AD=c({installed:A(),running:A(),version:r().nullable(),backendState:r().nullable(),tailnetName:r().nullable(),magicDnsSuffix:r().nullable(),machineName:r().nullable(),dnsName:r().nullable(),authUrl:r().nullable(),tailscaleIps:p(r()),health:p(r()),error:r().nullable(),peers:p(PD)}),TD=c({enabled:A(),reachable:A(),targetUrl:r().nullable(),httpsUrl:r().nullable(),httpsHost:r().nullable(),httpsPort:u().nullable(),setupUrl:r().nullable(),configText:r().nullable(),error:r().nullable()}),ED=c({localUrl:r(),localWebUrl:r(),remoteUrl:r().nullable(),remoteWebUrl:r().nullable(),tokenHash:r(),tailscaleUpCommand:r(),serveCommand:r(),disableCommand:r(),operatorCommand:r(),webUiAvailable:A(),updatedAt:r(),tailscale:AD,serve:TD});c({message:r(),status:ED});const gw=b(["github","openpond_git"]),vw=b(["private","public"]),MD=b(["actions","workflows","instructions","prompts","goals","evals","examples","tasksets","extensions"]),jD=c({agentIds:p(r().trim().min(1)).max(100),skillNames:p(r().trim().min(1)).max(200),optionalContent:p(MD).max(20).default([])}),bw=c({provider:gw,owner:r().trim().min(1).max(191).nullable().optional(),repository:r().trim().min(1).max(191),visibility:vw.default("private")}),OD=c({ref:kr,selection:jD,target:bw}),$D=c({path:r(),sizeBytes:u().int().nonnegative(),category:r()});c({sourceHash:r(),sourceRevision:r().nullable(),clean:A(),blockedReasons:p(r()),warnings:p(r()),files:p($D),excludedFiles:p(r()),target:bw,replacesExisting:A()});OD.extend({expectedSourceHash:r().trim().min(1),confirmed:S(!0)});c({provider:gw,owner:r(),repository:r(),visibility:vw,remoteUrl:r(),webUrl:r(),revision:r()});const ND=b(["cron","rate"]),yw=b(["queued","running","succeeded","failed","skipped"]),Ig=c({id:r(),localProjectId:r(),localProjectName:r(),agentRootPath:r(),agentName:r(),scheduleName:r(),scheduleType:ND,scheduleExpression:r(),timezone:r().nullable(),targetAction:r(),input:re(r(),ce()).optional().default({}),enabledByDefault:A(),enabled:A(),sourceHash:r(),manifestHash:r().nullable(),agentVersionId:r().nullable().optional(),agentPackageDigest:r().nullable().optional(),nextRunAt:r().nullable(),lastRunAt:r().nullable(),lastRunStatus:yw.nullable(),lastRunId:r().nullable(),lastError:r().nullable(),createdAt:r(),updatedAt:r()}),Sw=c({id:r(),scheduleId:r(),definitionSnapshot:Ig.optional(),configurationSnapshot:re(r(),ce()).optional(),inputSnapshot:re(r(),ce()).optional(),localProjectId:r(),scheduleName:r(),scheduledFor:r(),trigger:b(["schedule","manual"]),status:yw,targetAction:r(),agentVersionId:r().nullable().optional(),agentPackageDigest:r().nullable().optional(),startedAt:r().nullable(),completedAt:r().nullable(),exitCode:u().int().nullable(),stdout:r().nullable(),stderr:r().nullable(),result:re(r(),ce()).nullable(),traceArtifactRef:r().nullable(),error:r().nullable(),createdAt:r(),updatedAt:r()});c({schedules:p(Ig),scheduler:c({running:A(),nextTickAt:r().nullable(),lastSyncAt:r().nullable(),scanRunning:A()})});c({runs:p(Sw)});c({enabled:A().optional()});c({input:re(r(),ce()).optional()});c({schedule:Ig,run:Sw});const DD=b(["sunday","monday","tuesday","wednesday","thursday","friday","saturday"]),Rs=c({version:S(1),kind:b(["once","daily","weekdays","weekly","monthly"]),timeZone:r().trim().min(1).max(100),startDate:r().regex(/^\d{4}-\d{2}-\d{2}$/),localTime:r().regex(/^([01]\d|2[0-3]):([0-5]\d)$/),weekdays:p(DD).min(1).max(7).optional(),dayOfMonth:u().int().min(1).max(31).optional(),end:It("kind",[c({kind:S("never")}),c({kind:S("on_date"),date:r().regex(/^\d{4}-\d{2}-\d{2}$/)}),c({kind:S("after_occurrences"),occurrences:u().int().min(1).max(1e5)})])}).superRefine((e,t)=>{e.kind==="weekly"&&!e.weekdays?.length&&t.addIssue({code:"custom",message:"Weekly recurrence requires at least one weekday.",path:["weekdays"]}),e.kind==="monthly"&&e.dayOfMonth===void 0&&t.addIssue({code:"custom",message:"Monthly recurrence requires a day of month.",path:["dayOfMonth"]})}),LD=c({id:r(),expression:r().nullable(),timeZone:r(),recurrence:Rs.nullable(),configurationVersion:u().int(),enabled:A(),nextRunAt:r().nullable(),lastTriggeredAt:r().nullable(),delivery:re(r(),ce()).default({})}),UD=c({id:r(),definitionKey:r(),version:u().int(),name:r(),prompt:r(),modelId:r(),schedules:p(LD)}),HD=c({id:r(),definitionId:r(),scheduleId:r().nullable(),definitionName:r(),definitionVersion:u().int(),conversationId:r(),triggerKind:b(["manual","schedule","webhook","retry"]),status:r(),notificationStatus:r(),deliveryStatus:r(),deliveryError:r().nullable(),createdAt:r()});c({definitions:p(UD),runs:p(HD),asOf:r(),webBaseUrl:r().url().optional()});c({clientRequestId:r().trim().min(1).max(191),sourceTurnId:r().trim().min(1).max(191).nullable().optional(),targetSessionId:r().trim().min(1).max(191).nullable().optional(),name:r().trim().min(1).max(180),prompt:r().trim().min(1).max(2e4),recurrence:Rs,modelId:r().trim().min(1).max(191).default("openpond-chat")});Dt([c({enabled:A()}),c({name:r().trim().min(1).max(180),prompt:r().trim().min(1).max(2e4),recurrence:Rs})]);const xw=b(["queued","running","succeeded","failed"]),kw=c({id:r(),sessionId:r(),sessionTitle:r(),sourceTurnId:r().nullable(),name:r(),prompt:r(),profileRef:kr.optional(),profileWorkflowId:r().optional(),profileMigrationError:r().nullable().optional(),recurrence:Rs,enabled:A(),nextRunAt:r().nullable(),lastRunAt:r().nullable(),lastRunStatus:xw.nullable(),lastRunId:r().nullable(),lastError:r().nullable(),scheduledRunCount:u().int().nonnegative(),createdAt:r(),updatedAt:r()}),zD=c({definitionSnapshot:kw.optional(),configurationSnapshot:re(r(),ce()).optional(),id:r(),workflowId:r(),sessionId:r(),scheduledFor:r(),trigger:b(["schedule","manual"]),status:xw,turnId:r().nullable(),error:r().nullable(),createdAt:r(),startedAt:r().nullable(),completedAt:r().nullable(),updatedAt:r()});c({sessionId:r().trim().min(1).max(191),sourceTurnId:r().trim().min(1).max(191).nullable().optional(),name:r().trim().min(1).max(180),prompt:r().trim().min(1).max(2e4),recurrence:Rs});Dt([c({enabled:A()}),c({name:r().trim().min(1).max(180),prompt:r().trim().min(1).max(2e4),recurrence:Rs})]);c({workflows:p(kw),runs:p(zD),asOf:r()});const _g=re(r(),ce());c({userId:r(),role:b(["owner","admin","member"]),name:r(),handle:r().nullable(),image:r().nullable()});const qD=c({userId:r(),role:b(["owner","admin","member"]),name:r(),handle:r().nullable(),image:r().nullable(),lastReadSequence:u().int().nonnegative()}),BD=c({id:r(),messageId:r(),refType:b(["hosted_ai_thread","goal","openpond_session","project","agent_run","message_reply"]),refId:r(),preview:_g,createdAt:r()}),ww=c({id:r(),messageId:r().nullable(),clientAttachmentId:r(),kind:S("image"),name:r(),mediaType:b(["image/png","image/jpeg","image/webp","image/gif"]),sizeBytes:u().int().positive(),status:b(["pending","ready","failed"]),createdAt:r(),readyAt:r().nullable()});c({attachment:ww,uploadUrl:r().url().nullable(),uploadHeaders:re(r(),r()),expiresAt:r().nullable()});c({url:r().url(),expiresAt:r()});const Cg=c({id:r(),threadId:r(),teamId:r(),clientRequestId:r().nullable(),authorType:b(["user","agent","system"]),authorUserId:r().nullable(),authorAgentId:r().nullable(),sequence:u().int().nonnegative(),kind:b(["text","system","command_result"]),body:r(),metadata:_g,editedAt:r().nullable(),deletedAt:r().nullable(),createdAt:r(),refs:p(BD),attachments:p(ww)}),FD=c({id:r(),teamId:r(),kind:b(["general","dm","group","channel"]),title:r().nullable(),createdByUserId:r(),lastMessageId:r().nullable(),lastMessageSequence:u().int().nonnegative(),lastMessageAt:r(),createdAt:r(),updatedAt:r(),unreadCount:u().int().nonnegative(),pinnedAt:r().nullable(),mutedAt:r().nullable(),archivedAt:r().nullable(),participants:p(qD),lastMessage:Cg.nullable()});c({thread:FD,messages:p(Cg),hasMoreBefore:A()});c({threadId:r(),mutedAt:r().nullable()});const VD=b(["pending","running","completed","failed","interrupted","cancelled"]),my=c({id:r(),conversationId:r(),threadId:r(),teamId:r(),requestedByUserId:r(),executorUserId:r().nullable(),providerId:r(),modelId:r(),clientRequestId:r(),baseMessageSequence:u().int().nonnegative(),status:VD,partialBody:r().nullable(),userMessageId:r(),assistantMessageId:r().nullable(),errorCode:r().nullable(),cancelledByUserId:r().nullable(),leaseExpiresAt:r().nullable(),heartbeatAt:r().nullable(),createdAt:r(),updatedAt:r()}),KD=c({id:r(),conversationId:r(),sequence:u().int().nonnegative(),role:b(["user","assistant","system","action"]),body:r(),createdByUserId:r().nullable(),createdAt:r()});c({conversationId:r(),parentThreadId:r(),parentMessageId:r(),teamId:r(),title:r().nullable(),providerId:r().nullable(),modelId:r(),createdByUserId:r(),messages:p(KD),turns:p(my),activeTurn:my.nullable(),createdAt:r(),updatedAt:r()});const Iw=c({id:u().int().nonnegative(),teamId:r(),threadId:r(),conversationId:r().nullable(),type:b(["thread.created","message.created","message.updated","message.deleted","read.updated","ai_thread.created","ai_turn.updated"]),payload:_g,createdAt:r()});c({events:p(Iw),cursor:u().int().nonnegative(),hasMore:A()});c({httpUrl:r().min(1),realtimeUrl:r().min(1),region:r().min(1),token:r().min(1),expiresAt:r().min(1),teamId:r().min(1),userId:r().min(1)});const Rg=re(r(),ce()),wa=r().nullable(),WD=b(["draft","published","archived"]),Pg=b(["owner","admin","member"]),_w=b(["active","left"]),Cw=b(["mentions","all","none"]),Rw=b(["public_preview","members"]),GD=b(["members","admins"]),ZD=c({canPreview:A(),canJoin:A(),canLeave:A(),canRead:A(),canPost:A(),canUpload:A(),canMention:A(),canManage:A(),requiresRulesAcceptance:A(),currentRulesVersionId:r().nullable()}),Pw=c({id:r(),communityId:r(),version:u().int().positive(),title:r(),requiresReacceptance:A(),publishedAt:r()}),JD=Pw.extend({bodyMarkdown:r(),contentHash:r()}),YD=c({role:Pg,status:_w,notificationMode:Cw}),QD=c({id:r(),communityId:r(),userId:r(),role:Pg,status:_w,notificationMode:Cw,joinedAt:r(),leftAt:wa,createdAt:r(),updatedAt:r()}),Aw=c({id:r(),slug:r(),displayName:r(),description:r(),imageUrl:r().nullable(),status:WD,visibility:b(["public","private"]),joinPolicy:b(["open","closed"]),historyVisibility:Rw,featuredAt:wa,publishedAt:wa,archivedAt:wa,memberCount:u().int().nonnegative(),membership:YD.nullable(),capabilities:ZD,currentRules:Pw.nullable()});c({items:p(Aw),nextCursor:r().nullable()});const Tw=c({lastReadSequence:u().int().nonnegative(),lastReadAt:wa.optional(),mutedAt:wa,pinnedAt:wa}),Ag=c({id:r(),communityId:r(),chatThreadId:r().nullable(),slug:r(),displayName:r(),topic:r(),position:u().int().nonnegative(),visibility:Rw,postingPolicy:GD,isDefault:A(),archivedAt:wa,lastMessageSequence:u().int().nonnegative(),unreadCount:u().int().nonnegative(),readState:Tw.nullable()});Aw.omit({currentRules:!0}).extend({currentRules:JD.nullable(),channels:p(Ag),previewMessageLimit:u().int().positive()});const XD=c({id:r(),messageId:r(),refType:b(["hosted_ai_thread","goal","openpond_session","project","agent_run","message_reply"]),refId:r(),preview:Rg,createdAt:r()}),Ew=c({id:r(),messageId:r().nullable(),clientAttachmentId:r(),kind:S("image"),name:r(),mediaType:b(["image/png","image/jpeg","image/webp","image/gif"]),sizeBytes:u().int().positive(),status:b(["pending","ready","failed"]),createdAt:r(),readyAt:wa});c({attachment:Ew,uploadUrl:r().url().nullable(),uploadHeaders:re(r(),r()),expiresAt:wa});c({url:r().url(),expiresAt:r()});const Mw=c({id:r(),threadId:r(),teamId:ru(),clientRequestId:r().nullable(),authorType:b(["user","agent","system"]),authorUserId:r().nullable(),authorAgentId:r().nullable(),sequence:u().int().nonnegative(),kind:b(["text","system","command_result"]),body:r(),metadata:Rg,editedAt:wa,deletedAt:wa,createdAt:r(),refs:p(XD),attachments:p(Ew)});c({messages:p(Mw),hasMoreBefore:A(),channelId:r(),readState:Tw.omit({lastReadAt:!0}).nullable(),preview:A()});const eL=c({userId:r(),handle:r().nullable(),name:r().nullable(),role:Pg});c({items:p(eL),nextCursor:r().nullable()});const jw=c({id:u().int().nonnegative(),communityId:r(),channelId:r(),threadId:r(),type:b(["thread.created","message.created","message.updated","message.deleted","read.updated"]),payload:Rg,createdAt:r()});c({events:p(jw),cursor:u().int().nonnegative(),hasMore:A()});c({httpUrl:r().min(1),realtimeUrl:r().min(1),region:r().min(1),token:r().min(1),expiresAt:r().min(1),communityId:r().min(1),userId:r().min(1),channel:r().min(1)});c({membership:QD,channels:p(Ag)});c({channels:p(Ag)});var Ml=r().trim().min(1).max(500),tL=r().regex(/^[a-f0-9]{64}$/),qf=c({id:Ml,revision:u().int().positive(),contentHash:tL}).strict(),nL=c({schemaVersion:S("openpond.hostedTasksetSummary.v1"),id:Ml,teamId:Ml,release:qf,name:r().min(1).max(500),description:r().max(2e4),taskCount:u().int().nonnegative(),buildIntent:r().min(1).max(100),methodHint:r().min(1).max(100).nullable(),packageBytes:u().int().nonnegative().nullable(),storedBytes:u().int().nonnegative().nullable(),createdAt:r().datetime({offset:!0})}).strict();c({afterId:r().trim().min(1).max(2e3).optional(),limit:u().int().min(1).max(100).default(30),modelProjectId:Ml.optional(),projectId:Ml.optional(),search:r().trim().max(100).optional(),sort:b(["id","name","updated"]).default("id")}).strict();c({items:p(nL).max(100),nextCursor:r().trim().min(1).max(2e3).nullable()}).strict();c({code:r().min(1),message:r().min(1)}).strict();class Ow extends Error{code;status;constructor(t,n=422,a){super(a?`${t}: ${a}`:t),this.code=t,this.status=n,this.name="LearningDomainError"}}var $w=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},aL=$w((e,t)=>{"use strict";t.exports=function n(a,o){if(a===o)return!0;if(a&&o&&typeof a=="object"&&typeof o=="object"){if(a.constructor!==o.constructor)return!1;var i,s,l;if(Array.isArray(a)){if(i=a.length,i!=o.length)return!1;for(s=i;s--!==0;)if(!n(a[s],o[s]))return!1;return!0}if(a.constructor===RegExp)return a.source===o.source&&a.flags===o.flags;if(a.valueOf!==Object.prototype.valueOf)return a.valueOf()===o.valueOf();if(a.toString!==Object.prototype.toString)return a.toString()===o.toString();if(l=Object.keys(a),i=l.length,i!==Object.keys(o).length)return!1;for(s=i;s--!==0;)if(!Object.prototype.hasOwnProperty.call(o,l[s]))return!1;for(s=i;s--!==0;){var m=l[s];if(!n(a[m],o[m]))return!1}return!0}return a!==a&&o!==o}}),oL=$w(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var t=aL();t.code='require("ajv/dist/runtime/equal").default',e.default=t}),py=$t,fy={type:["object","boolean"],properties:{$schema:{const:"https://json-schema.org/draft/2020-12/schema"},$ref:{type:"string"},$comment:{type:"string"},$defs:{$ref:"#/$defs/schemaMap"},properties:{$ref:"#/$defs/schemaMap"},dependentSchemas:{$ref:"#/$defs/schemaMap"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},prefixItems:{$ref:"#/$defs/schemaArray"},items:{$ref:"#"},additionalProperties:{$ref:"#"},not:{$ref:"#"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},contains:{$ref:"#"},unevaluatedProperties:{$ref:"#"},unevaluatedItems:{$ref:"#"},propertyNames:{$ref:"#"},type:{anyOf:[{$ref:"#/$defs/schemaType"},{type:"array",items:{$ref:"#/$defs/schemaType"},minItems:1,uniqueItems:!0}]},enum:{type:"array",minItems:1},const:!0,default:!0,title:{type:"string"},description:{type:"string"},examples:{type:"array"},readOnly:{type:"boolean"},writeOnly:{type:"boolean"},deprecated:{type:"boolean"},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/natural"},minLength:{$ref:"#/$defs/natural"},maxItems:{$ref:"#/$defs/natural"},minItems:{$ref:"#/$defs/natural"},maxContains:{$ref:"#/$defs/natural"},minContains:{$ref:"#/$defs/natural"},maxProperties:{$ref:"#/$defs/natural"},minProperties:{$ref:"#/$defs/natural"},uniqueItems:{type:"boolean"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}},contentEncoding:{type:"string"},contentMediaType:{type:"string"}}},rL=Object.prototype.hasOwnProperty,iL=oL().default,kt={validate:$t};function ra(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:i={}}={}){let s=null,l=0,m=ra.evaluated;if(m.dynamicProps&&(m.props=void 0),m.dynamicItems&&(m.items=void 0),l===0)if(e&&typeof e=="object"&&!Array.isArray(e))for(let h in e){let g=l;kt.validate(e[h],{instancePath:t+"/"+h.replace(/~/g,"~0").replace(/\//g,"~1"),parentData:e,parentDataProperty:h,rootData:o,dynamicAnchors:i})||(s=s===null?kt.validate.errors:s.concat(kt.validate.errors),l=s.length);var d=g===l;if(!d)break}else return ra.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"object"}}],!1;return ra.errors=s,l===0}ra.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};function wn(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:i={}}={}){let s=null,l=0,m=wn.evaluated;if(m.dynamicProps&&(m.props=void 0),m.dynamicItems&&(m.items=void 0),l===0)if(Array.isArray(e)){if(e.length>32)return wn.errors=[{instancePath:t,schemaPath:"#/maxItems",keyword:"maxItems",params:{limit:32}}],!1;if(e.length<1)return wn.errors=[{instancePath:t,schemaPath:"#/minItems",keyword:"minItems",params:{limit:1}}],!1;{var d=!0;let h=e.length;for(let g=0;g<h;g++){let y=l;kt.validate(e[g],{instancePath:t+"/"+g,parentData:e,parentDataProperty:g,rootData:o,dynamicAnchors:i})||(s=s===null?kt.validate.errors:s.concat(kt.validate.errors),l=s.length);var d=y===l;if(!d)break}}}else return wn.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"array"}}],!1;return wn.errors=s,l===0}wn.evaluated={items:!0,dynamicProps:!1,dynamicItems:!1};var sL={enum:["array","boolean","integer","null","number","object","string"]};function io(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:i={}}={}){let s=null,l=0,m=io.evaluated;return m.dynamicProps&&(m.props=void 0),m.dynamicItems&&(m.items=void 0),e==="array"||e==="boolean"||e==="integer"||e==="null"||e==="number"||e==="object"||e==="string"?(io.errors=s,l===0):(io.errors=[{instancePath:t,schemaPath:"#/enum",keyword:"enum",params:{allowedValues:sL.enum}}],!1)}io.evaluated={dynamicProps:!1,dynamicItems:!1};function Nt(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:i={}}={}){let s=null,l=0,m=Nt.evaluated;return m.dynamicProps&&(m.props=void 0),m.dynamicItems&&(m.items=void 0),typeof e=="number"&&!(e%1)&&!isNaN(e)&&isFinite(e)?typeof e=="number"&&isFinite(e)&&(e<0||isNaN(e))?(Nt.errors=[{instancePath:t,schemaPath:"#/minimum",keyword:"minimum",params:{comparison:">=",limit:0}}],!1):(Nt.errors=s,l===0):(Nt.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"integer"}}],!1)}Nt.evaluated={dynamicProps:!1,dynamicItems:!1};function ya(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:i={}}={}){let s=null,l=0,m=ya.evaluated;if(m.dynamicProps&&(m.props=void 0),m.dynamicItems&&(m.items=void 0),l===0)if(Array.isArray(e)){var d=!0;let h=e.length;for(let g=0;g<h;g++){let y=l;if(typeof e[g]!="string")return ya.errors=[{instancePath:t+"/"+g,schemaPath:"#/items/type",keyword:"type",params:{type:"string"}}],!1;var d=y===l;if(!d)break}if(d){let g=e.length,y;if(g>1){let w={};for(;g--;){let _=e[g];if(typeof _=="string"){if(typeof w[_]=="number")return y=w[_],ya.errors=[{instancePath:t,schemaPath:"#/uniqueItems",keyword:"uniqueItems",params:{i:g,j:y}}],!1;w[_]=g}}}}}else return ya.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"array"}}],!1;return ya.errors=s,l===0}ya.evaluated={items:!0,dynamicProps:!1,dynamicItems:!1};function $t(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:i={}}={}){let s=null,l=0,m=$t.evaluated;if(m.dynamicProps&&(m.props=void 0),m.dynamicItems&&(m.items=void 0),!(e&&typeof e=="object"&&!Array.isArray(e))&&typeof e!="boolean")return $t.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:fy.type}}],!1;if(l===0&&e&&typeof e=="object"&&!Array.isArray(e)){let w=l;for(let _ in e)if(!rL.call(fy.properties,_))return $t.errors=[{instancePath:t,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:_}}],!1;if(w===l){if(e.$schema!==void 0){let _=l;if(e.$schema!=="https://json-schema.org/draft/2020-12/schema")return $t.errors=[{instancePath:t+"/$schema",schemaPath:"#/properties/%24schema/const",keyword:"const",params:{allowedValue:"https://json-schema.org/draft/2020-12/schema"}}],!1;var d=_===l}else var d=!0;if(d){if(e.$ref!==void 0){let P=l;if(typeof e.$ref!="string")return $t.errors=[{instancePath:t+"/$ref",schemaPath:"#/properties/%24ref/type",keyword:"type",params:{type:"string"}}],!1;var d=P===l}else var d=!0;if(d){if(e.$comment!==void 0){let M=l;if(typeof e.$comment!="string")return $t.errors=[{instancePath:t+"/$comment",schemaPath:"#/properties/%24comment/type",keyword:"type",params:{type:"string"}}],!1;var d=M===l}else var d=!0;if(d){if(e.$defs!==void 0){let C=l;ra(e.$defs,{instancePath:t+"/$defs",parentData:e,parentDataProperty:"$defs",rootData:o,dynamicAnchors:i})||(s=s===null?ra.errors:s.concat(ra.errors),l=s.length);var d=C===l}else var d=!0;if(d){if(e.properties!==void 0){let N=l;ra(e.properties,{instancePath:t+"/properties",parentData:e,parentDataProperty:"properties",rootData:o,dynamicAnchors:i})||(s=s===null?ra.errors:s.concat(ra.errors),l=s.length);var d=N===l}else var d=!0;if(d){if(e.dependentSchemas!==void 0){let $=l;ra(e.dependentSchemas,{instancePath:t+"/dependentSchemas",parentData:e,parentDataProperty:"dependentSchemas",rootData:o,dynamicAnchors:i})||(s=s===null?ra.errors:s.concat(ra.errors),l=s.length);var d=$===l}else var d=!0;if(d){if(e.allOf!==void 0){let j=l;wn(e.allOf,{instancePath:t+"/allOf",parentData:e,parentDataProperty:"allOf",rootData:o,dynamicAnchors:i})||(s=s===null?wn.errors:s.concat(wn.errors),l=s.length);var d=j===l}else var d=!0;if(d){if(e.anyOf!==void 0){let x=l;wn(e.anyOf,{instancePath:t+"/anyOf",parentData:e,parentDataProperty:"anyOf",rootData:o,dynamicAnchors:i})||(s=s===null?wn.errors:s.concat(wn.errors),l=s.length);var d=x===l}else var d=!0;if(d){if(e.oneOf!==void 0){let R=l;wn(e.oneOf,{instancePath:t+"/oneOf",parentData:e,parentDataProperty:"oneOf",rootData:o,dynamicAnchors:i})||(s=s===null?wn.errors:s.concat(wn.errors),l=s.length);var d=R===l}else var d=!0;if(d){if(e.prefixItems!==void 0){let E=l;wn(e.prefixItems,{instancePath:t+"/prefixItems",parentData:e,parentDataProperty:"prefixItems",rootData:o,dynamicAnchors:i})||(s=s===null?wn.errors:s.concat(wn.errors),l=s.length);var d=E===l}else var d=!0;if(d){if(e.items!==void 0){let U=l;kt.validate(e.items,{instancePath:t+"/items",parentData:e,parentDataProperty:"items",rootData:o,dynamicAnchors:i})||(s=s===null?kt.validate.errors:s.concat(kt.validate.errors),l=s.length);var d=U===l}else var d=!0;if(d){if(e.additionalProperties!==void 0){let B=l;kt.validate(e.additionalProperties,{instancePath:t+"/additionalProperties",parentData:e,parentDataProperty:"additionalProperties",rootData:o,dynamicAnchors:i})||(s=s===null?kt.validate.errors:s.concat(kt.validate.errors),l=s.length);var d=B===l}else var d=!0;if(d){if(e.not!==void 0){let D=l;kt.validate(e.not,{instancePath:t+"/not",parentData:e,parentDataProperty:"not",rootData:o,dynamicAnchors:i})||(s=s===null?kt.validate.errors:s.concat(kt.validate.errors),l=s.length);var d=D===l}else var d=!0;if(d){if(e.if!==void 0){let W=l;kt.validate(e.if,{instancePath:t+"/if",parentData:e,parentDataProperty:"if",rootData:o,dynamicAnchors:i})||(s=s===null?kt.validate.errors:s.concat(kt.validate.errors),l=s.length);var d=W===l}else var d=!0;if(d){if(e.then!==void 0){let se=l;kt.validate(e.then,{instancePath:t+"/then",parentData:e,parentDataProperty:"then",rootData:o,dynamicAnchors:i})||(s=s===null?kt.validate.errors:s.concat(kt.validate.errors),l=s.length);var d=se===l}else var d=!0;if(d){if(e.else!==void 0){let de=l;kt.validate(e.else,{instancePath:t+"/else",parentData:e,parentDataProperty:"else",rootData:o,dynamicAnchors:i})||(s=s===null?kt.validate.errors:s.concat(kt.validate.errors),l=s.length);var d=de===l}else var d=!0;if(d){if(e.contains!==void 0){let Me=l;kt.validate(e.contains,{instancePath:t+"/contains",parentData:e,parentDataProperty:"contains",rootData:o,dynamicAnchors:i})||(s=s===null?kt.validate.errors:s.concat(kt.validate.errors),l=s.length);var d=Me===l}else var d=!0;if(d){if(e.unevaluatedProperties!==void 0){let ke=l;kt.validate(e.unevaluatedProperties,{instancePath:t+"/unevaluatedProperties",parentData:e,parentDataProperty:"unevaluatedProperties",rootData:o,dynamicAnchors:i})||(s=s===null?kt.validate.errors:s.concat(kt.validate.errors),l=s.length);var d=ke===l}else var d=!0;if(d){if(e.unevaluatedItems!==void 0){let te=l;kt.validate(e.unevaluatedItems,{instancePath:t+"/unevaluatedItems",parentData:e,parentDataProperty:"unevaluatedItems",rootData:o,dynamicAnchors:i})||(s=s===null?kt.validate.errors:s.concat(kt.validate.errors),l=s.length);var d=te===l}else var d=!0;if(d){if(e.propertyNames!==void 0){let Ee=l;kt.validate(e.propertyNames,{instancePath:t+"/propertyNames",parentData:e,parentDataProperty:"propertyNames",rootData:o,dynamicAnchors:i})||(s=s===null?kt.validate.errors:s.concat(kt.validate.errors),l=s.length);var d=Ee===l}else var d=!0;if(d){if(e.type!==void 0){let ye=e.type,ne=l,be=l,ae=!1,ue=l;io(ye,{instancePath:t+"/type",parentData:e,parentDataProperty:"type",rootData:o,dynamicAnchors:i})||(s=s===null?io.errors:s.concat(io.errors),l=s.length);var g=ue===l;ae=ae||g;let xe=l;if(l===xe)if(Array.isArray(ye))if(ye.length<1){let we={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf/1/minItems",keyword:"minItems",params:{limit:1}};s===null?s=[we]:s.push(we),l++}else{var h=!0;let we=ye.length;for(let oe=0;oe<we;oe++){let Se=l;io(ye[oe],{instancePath:t+"/type/"+oe,parentData:ye,parentDataProperty:oe,rootData:o,dynamicAnchors:i})||(s=s===null?io.errors:s.concat(io.errors),l=s.length);var h=Se===l;if(!h)break}if(h){let oe=ye.length,Se;if(oe>1){e:for(;oe--;)for(Se=oe;Se--;)if(iL(ye[oe],ye[Se])){let He={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf/1/uniqueItems",keyword:"uniqueItems",params:{i:oe,j:Se}};s===null?s=[He]:s.push(He),l++;break e}}}}else{let we={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf/1/type",keyword:"type",params:{type:"array"}};s===null?s=[we]:s.push(we),l++}var g=xe===l;if(ae=ae||g,ae)l=be,s!==null&&(be?s.length=be:s=null);else{let we={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf",keyword:"anyOf",params:{}};return s===null?s=[we]:s.push(we),l++,$t.errors=s,!1}var d=ne===l}else var d=!0;if(d){if(e.enum!==void 0){let ne=e.enum,be=l;if(l===be)if(Array.isArray(ne)){if(ne.length<1)return $t.errors=[{instancePath:t+"/enum",schemaPath:"#/properties/enum/minItems",keyword:"minItems",params:{limit:1}}],!1}else return $t.errors=[{instancePath:t+"/enum",schemaPath:"#/properties/enum/type",keyword:"type",params:{type:"array"}}],!1;var d=be===l}else var d=!0;if(d){if(e.title!==void 0){let be=l;if(typeof e.title!="string")return $t.errors=[{instancePath:t+"/title",schemaPath:"#/properties/title/type",keyword:"type",params:{type:"string"}}],!1;var d=be===l}else var d=!0;if(d){if(e.description!==void 0){let ae=l;if(typeof e.description!="string")return $t.errors=[{instancePath:t+"/description",schemaPath:"#/properties/description/type",keyword:"type",params:{type:"string"}}],!1;var d=ae===l}else var d=!0;if(d){if(e.examples!==void 0){let ue=l;if(!Array.isArray(e.examples))return $t.errors=[{instancePath:t+"/examples",schemaPath:"#/properties/examples/type",keyword:"type",params:{type:"array"}}],!1;var d=ue===l}else var d=!0;if(d){if(e.readOnly!==void 0){let xe=l;if(typeof e.readOnly!="boolean")return $t.errors=[{instancePath:t+"/readOnly",schemaPath:"#/properties/readOnly/type",keyword:"type",params:{type:"boolean"}}],!1;var d=xe===l}else var d=!0;if(d){if(e.writeOnly!==void 0){let De=l;if(typeof e.writeOnly!="boolean")return $t.errors=[{instancePath:t+"/writeOnly",schemaPath:"#/properties/writeOnly/type",keyword:"type",params:{type:"boolean"}}],!1;var d=De===l}else var d=!0;if(d){if(e.deprecated!==void 0){let we=l;if(typeof e.deprecated!="boolean")return $t.errors=[{instancePath:t+"/deprecated",schemaPath:"#/properties/deprecated/type",keyword:"type",params:{type:"boolean"}}],!1;var d=we===l}else var d=!0;if(d){if(e.multipleOf!==void 0){let oe=e.multipleOf,Se=l;if(l===Se)if(typeof oe=="number"&&isFinite(oe)){if(oe<=0||isNaN(oe))return $t.errors=[{instancePath:t+"/multipleOf",schemaPath:"#/properties/multipleOf/exclusiveMinimum",keyword:"exclusiveMinimum",params:{comparison:">",limit:0}}],!1}else return $t.errors=[{instancePath:t+"/multipleOf",schemaPath:"#/properties/multipleOf/type",keyword:"type",params:{type:"number"}}],!1;var d=Se===l}else var d=!0;if(d){if(e.maximum!==void 0){let Se=e.maximum,He=l;if(!(typeof Se=="number"&&isFinite(Se)))return $t.errors=[{instancePath:t+"/maximum",schemaPath:"#/properties/maximum/type",keyword:"type",params:{type:"number"}}],!1;var d=He===l}else var d=!0;if(d){if(e.exclusiveMaximum!==void 0){let He=e.exclusiveMaximum,Ze=l;if(!(typeof He=="number"&&isFinite(He)))return $t.errors=[{instancePath:t+"/exclusiveMaximum",schemaPath:"#/properties/exclusiveMaximum/type",keyword:"type",params:{type:"number"}}],!1;var d=Ze===l}else var d=!0;if(d){if(e.minimum!==void 0){let Ze=e.minimum,Ke=l;if(!(typeof Ze=="number"&&isFinite(Ze)))return $t.errors=[{instancePath:t+"/minimum",schemaPath:"#/properties/minimum/type",keyword:"type",params:{type:"number"}}],!1;var d=Ke===l}else var d=!0;if(d){if(e.exclusiveMinimum!==void 0){let Ke=e.exclusiveMinimum,tt=l;if(!(typeof Ke=="number"&&isFinite(Ke)))return $t.errors=[{instancePath:t+"/exclusiveMinimum",schemaPath:"#/properties/exclusiveMinimum/type",keyword:"type",params:{type:"number"}}],!1;var d=tt===l}else var d=!0;if(d){if(e.maxLength!==void 0){let tt=l;Nt(e.maxLength,{instancePath:t+"/maxLength",parentData:e,parentDataProperty:"maxLength",rootData:o,dynamicAnchors:i})||(s=s===null?Nt.errors:s.concat(Nt.errors),l=s.length);var d=tt===l}else var d=!0;if(d){if(e.minLength!==void 0){let qe=l;Nt(e.minLength,{instancePath:t+"/minLength",parentData:e,parentDataProperty:"minLength",rootData:o,dynamicAnchors:i})||(s=s===null?Nt.errors:s.concat(Nt.errors),l=s.length);var d=qe===l}else var d=!0;if(d){if(e.maxItems!==void 0){let Ge=l;Nt(e.maxItems,{instancePath:t+"/maxItems",parentData:e,parentDataProperty:"maxItems",rootData:o,dynamicAnchors:i})||(s=s===null?Nt.errors:s.concat(Nt.errors),l=s.length);var d=Ge===l}else var d=!0;if(d){if(e.minItems!==void 0){let ze=l;Nt(e.minItems,{instancePath:t+"/minItems",parentData:e,parentDataProperty:"minItems",rootData:o,dynamicAnchors:i})||(s=s===null?Nt.errors:s.concat(Nt.errors),l=s.length);var d=ze===l}else var d=!0;if(d){if(e.maxContains!==void 0){let L=l;Nt(e.maxContains,{instancePath:t+"/maxContains",parentData:e,parentDataProperty:"maxContains",rootData:o,dynamicAnchors:i})||(s=s===null?Nt.errors:s.concat(Nt.errors),l=s.length);var d=L===l}else var d=!0;if(d){if(e.minContains!==void 0){let O=l;Nt(e.minContains,{instancePath:t+"/minContains",parentData:e,parentDataProperty:"minContains",rootData:o,dynamicAnchors:i})||(s=s===null?Nt.errors:s.concat(Nt.errors),l=s.length);var d=O===l}else var d=!0;if(d){if(e.maxProperties!==void 0){let z=l;Nt(e.maxProperties,{instancePath:t+"/maxProperties",parentData:e,parentDataProperty:"maxProperties",rootData:o,dynamicAnchors:i})||(s=s===null?Nt.errors:s.concat(Nt.errors),l=s.length);var d=z===l}else var d=!0;if(d){if(e.minProperties!==void 0){let X=l;Nt(e.minProperties,{instancePath:t+"/minProperties",parentData:e,parentDataProperty:"minProperties",rootData:o,dynamicAnchors:i})||(s=s===null?Nt.errors:s.concat(Nt.errors),l=s.length);var d=X===l}else var d=!0;if(d){if(e.uniqueItems!==void 0){let me=l;if(typeof e.uniqueItems!="boolean")return $t.errors=[{instancePath:t+"/uniqueItems",schemaPath:"#/properties/uniqueItems/type",keyword:"type",params:{type:"boolean"}}],!1;var d=me===l}else var d=!0;if(d){if(e.required!==void 0){let $e=l;ya(e.required,{instancePath:t+"/required",parentData:e,parentDataProperty:"required",rootData:o,dynamicAnchors:i})||(s=s===null?ya.errors:s.concat(ya.errors),l=s.length);var d=$e===l}else var d=!0;if(d){if(e.dependentRequired!==void 0){let Le=e.dependentRequired,nt=l;if(l===nt)if(Le&&typeof Le=="object"&&!Array.isArray(Le))for(let lt in Le){let pt=l;ya(Le[lt],{instancePath:t+"/dependentRequired/"+lt.replace(/~/g,"~0").replace(/\//g,"~1"),parentData:Le,parentDataProperty:lt,rootData:o,dynamicAnchors:i})||(s=s===null?ya.errors:s.concat(ya.errors),l=s.length);var y=pt===l;if(!y)break}else return $t.errors=[{instancePath:t+"/dependentRequired",schemaPath:"#/properties/dependentRequired/type",keyword:"type",params:{type:"object"}}],!1;var d=nt===l}else var d=!0;if(d){if(e.contentEncoding!==void 0){let nt=l;if(typeof e.contentEncoding!="string")return $t.errors=[{instancePath:t+"/contentEncoding",schemaPath:"#/properties/contentEncoding/type",keyword:"type",params:{type:"string"}}],!1;var d=nt===l}else var d=!0;if(d)if(e.contentMediaType!==void 0){let nt=l;if(typeof e.contentMediaType!="string")return $t.errors=[{instancePath:t+"/contentMediaType",schemaPath:"#/properties/contentMediaType/type",keyword:"type",params:{type:"string"}}],!1;var d=nt===l}else var d=!0}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}return $t.errors=s,l===0}$t.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};const hy="https://json-schema.org/draft/2020-12/schema",lL=1048576,cL=32768,dL=new Set(["properties","$defs","dependentSchemas"]),uL=new Set(["allOf","anyOf","oneOf","prefixItems"]),mL=new Set(["items","additionalProperties","not","if","then","else","contains","unevaluatedProperties","unevaluatedItems","propertyNames"]);function Wo(e,t=lL){const n=[{value:e,depth:0}],a=new Set;let o=0;for(;n.length;){const i=n.pop();if(i.exit){a.delete(i.value);continue}if(++o>1e5||i.depth>48)throw new Error("task_json_complexity_exceeded");if(i.value===null||typeof i.value=="string"||typeof i.value=="boolean"||typeof i.value=="number"&&Number.isFinite(i.value))continue;if(typeof i.value!="object")throw new Error("task_json_value_invalid");if(a.has(i.value))throw new Error("task_json_cycle");a.add(i.value),n.push({...i,exit:!0});const s=Object.getPrototypeOf(i.value);if(!Array.isArray(i.value)&&s!==Object.prototype&&s!==null)throw new Error("task_json_object_invalid");if(Object.getOwnPropertySymbols(i.value).length)throw new Error("task_json_symbol_invalid");if(Object.hasOwn(i.value,"toJSON"))throw new Error("task_json_serializer_invalid");if(Array.isArray(i.value)&&(i.value.length>1e4||Object.keys(i.value).length!==i.value.length))throw new Error("task_json_array_invalid");for(const[l,m]of Object.entries(Object.getOwnPropertyDescriptors(i.value))){if(m.get||m.set)throw new Error("task_json_accessor_invalid");if(Array.isArray(i.value)&&l!=="length"&&(!/^(0|[1-9]\d*)$/u.test(l)||Number(l)>=i.value.length))throw new Error("task_json_array_invalid");m.enumerable&&n.push({value:m.value,depth:i.depth+1})}}if(new TextEncoder().encode(JSON.stringify(e)).byteLength>t)throw new Error("task_json_size_exceeded")}function Tg(e){try{return pL(e),{valid:!0,issues:[]}}catch(t){return{valid:!1,issues:[{path:"",code:"task_schema_invalid",message:t instanceof Error?t.message:"Task schema is invalid."}]}}}function pL(e){if(Wo(e,cL),ml(e,e,new Set,0,{remaining:2048}),!py(e)){const t=py.errors?.[0];throw new Error(`Task schema ${t?.instancePath||"/"} violates ${t?.keyword??"schema"}.`)}}function ml(e,t,n,a,o){if(--o.remaining<0)throw new Error("Task schema reference expansion exceeds the validation budget.");if(typeof e=="boolean")return;if(!e||typeof e!="object"||Array.isArray(e))throw new Error("A task schema must be an object or boolean.");if(a>24||n.has(e))throw new Error("Recursive or deeply nested task schemas are not supported.");const i=new Set(n).add(e),s=e;if(s.$schema!==void 0&&s.$schema!==hy)throw new Error(`Task schemas must use ${hy}.`);for(const[l,m]of Object.entries(s))if(l==="$ref"){if(typeof m!="string"||!m.startsWith("#/$defs/"))throw new Error("Task schema references must be local JSON pointers into $defs.");let d=t;for(const h of m.slice(2).split("/")){if(/~(?![01])/u.test(h))throw new Error("Invalid task schema JSON pointer.");const g=h.replaceAll("~1","/").replaceAll("~0","~");if(!d||typeof d!="object"||!Object.hasOwn(d,g))throw new Error(`Task schema reference ${m} is missing.`);d=d[g]}ml(d,t,i,a+1,o)}else if(dL.has(l)){if(!m||typeof m!="object"||Array.isArray(m))throw new Error(`Invalid schema map ${l}.`);for(const d of Object.values(m))ml(d,t,i,a+1,o)}else if(uL.has(l)){if(!Array.isArray(m)||m.length>32)throw new Error(`Schema ${l} must contain at most 32 alternatives.`);for(const d of m)ml(d,t,i,a+1,o)}else mL.has(l)&&ml(m,t,i,a+1,o)}const fL=c({schemaVersion:S("openpond.modelJudgeReceipt.v1"),providerId:r().trim().min(1).max(200),modelId:r().trim().min(1).max(500),modelRevision:r().trim().min(1).max(500).nullable(),responseId:r().trim().min(1).max(500).nullable(),requestHash:J,responseHash:J,inputTokens:u().int().nonnegative().nullable(),outputTokens:u().int().nonnegative().nullable(),costUsd:u().finite().nonnegative().nullable()}).strict(),hL=c({schemaVersion:S("openpond.graderEvidence.v1"),graderId:T,graderVersion:r().trim().min(1).max(100),score:u().min(0).max(1).nullable(),passed:A(),rewardEligible:A(),failureClass:Gl.nullable(),feedback:p(r().max(2e4)).max(1e3),visibleEvidenceRefs:p(T).max(1e4),privilegedEvidenceRefs:p(T).max(1e4),modelJudgeReceipt:fL.optional()}).strict(),Nw=hL.extend({contentHash:J}).strict(),gL=c({score:u().min(0).max(1).nullable(),passed:A(),rewardEligible:A(),failureClass:Gl.nullable(),gradingStatus:b(["scored","unscorable","not_configured"])}).strict(),tQ=gL.extend({schemaVersion:S("openpond.taskGrade.v1"),taskHash:J,evidenceHash:J,graderSetHash:J,components:p(Nw).max(1e3),contentHash:J}).strict(),gy=r().trim().min(1).max(240),vL=r().trim().min(1).max(1e3).refine(e=>!/[\\:\0]/.test(e)&&e.split("/").every(t=>t&&t!=="."&&t!==".."&&!t.startsWith(".env")),"Metric modules must use a safe relative path."),yu=c({schemaVersion:S("openpond.tasksetMetricPolicy.v1"),primaryMetric:gy,aggregation:b(["mean_score","pass_rate","weighted_mean","custom"]),missingReward:b(["zero","exclude"]),taskWeights:re(gy,u().positive().max(1e6)).optional(),customAggregator:c({module:vL,exportName:r().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),contentHash:J,timeoutMs:u().int().positive().max(3e5),networkPolicy:S("none")}).strict().nullable()}).strict().superRefine((e,t)=>{e.aggregation==="custom"!=(e.customAggregator!==null)&&t.addIssue({code:"custom",path:["customAggregator"],message:"Only custom aggregation requires a content-hashed module."}),(e.aggregation==="weighted_mean"?!e.taskWeights||!Object.keys(e.taskWeights).length:e.taskWeights!==void 0)&&t.addIssue({code:"custom",path:["taskWeights"],message:"Only weighted means require explicit positive task weights."})}),bL=c({schemaVersion:S("openpond.tasksetMetricResult.v1"),runManifest:Z,tasksetRelease:Z,policy:yu,policyHash:J,receiptRefs:p(Z).min(1).max(1e6),includedCount:u().int().nonnegative(),missingRewardCount:u().int().nonnegative(),excludedCount:u().int().nonnegative(),value:u().min(0).max(1).nullable()}).strict(),yL=bL.extend({contentHash:J}).strict(),Go=b(["train","validation","test","frozen_eval"]),SL=c({path:r().trim().min(1).max(2e3).refine(kL),mediaType:r().trim().min(1).max(200),schemaRef:sn.nullable().default(null),maxBytes:u().int().positive().max(25e7).nullable().default(null),metadata:In}).strict(),xL=c({policyVisibleFields:p(T).max(1e3).default([]),privilegedFields:p(T).max(1e3).default([]),hiddenGraderRefs:p(T).max(1e3).default([]),connectedAppScopes:p(T).max(100).default([])}).strict(),Dw=c({protocolVersion:S("openpond.environment.v1"),kind:b(["text","agent","work","custom_program"]),entrypoint:r().trim().min(1).max(1e3),stateful:A(),deterministicSeeds:A(),lifecycle:p(b(["create","reset","step","collect","destroy"])).min(5).max(5),networkPolicy:b(["none","declared_read_only","declared_scoped"]),defaultTimeoutMs:u().int().positive().max(36e5)}).strict(),Su=c({id:T,version:r().trim().min(1).max(100),weight:u().nonnegative().max(1e3).default(1),hardGate:A().default(!1),rewardEligible:A().default(!1),privileged:A().default(!1)}),Lw=Su.extend({kind:b(["content","schema","artifact","runtime_event","state"]),config:re(r(),ce())}).strict(),Uw=Su.extend({kind:S("model_judge"),rubricRef:sn,calibrationStatus:b(["pending","passed","failed"]),model:c({providerId:T,modelId:T,revision:r().trim().min(1).max(500).nullable()}).strict().optional(),temperature:u().min(0).max(2).optional()}).strict(),Hw=b(["isolated_javascript","sandbox_process"]),zw=Su.extend({kind:S("custom_verifier"),runtime:Hw.optional(),verifierRef:sn,exportName:r().trim().min(1).max(240).optional(),timeoutMs:u().int().positive().max(3e5),networkPolicy:S("none")}).strict(),qw=Su.extend({kind:S("human"),rubricRef:sn,reviewerRole:r().trim().min(1).max(500)}).strict(),Bw=Dt([Lw,Uw,zw,qw]),Eg=c({id:T,clusterKey:T,split:Go,input:re(r(),ce()),expectedOutput:re(r(),ce()).nullable(),policyVisibleContext:re(r(),ce()).default({}),privilegedContextRef:T.nullable(),artifactRefs:p(sn).max(1e3).default([]),requiredOutputs:p(SL).max(1e3).optional(),tags:p(T).max(100).default([])}).strict(),Fw=c({schemaVersion:S("openpond.tasksetRelease.v2"),id:T,revision:u().int().positive(),policy:xL,environment:Dw,environmentRelease:c({id:T,contentHash:J}).strict().optional(),tools:p(ec).max(200),capabilities:p(cg).max(200),tasks:p(Eg).min(1).max(1e6),graders:p(Bw).min(1).max(1e3),verifierSetRelease:c({id:T,contentHash:J}).strict().optional(),metrics:yu.optional(),metadata:In}).strict(),Vw=Fw.extend({contentHash:J}).strict();function kL(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}const Vc={id:!0,version:!0,weight:!0,hardGate:!0,rewardEligible:!0,privileged:!0},wL=r().regex(/^[a-z][a-z0-9_]{0,79}$/);function nQ(e){return e.feedbackKey??`reward_${Xt(e.id).slice(0,24)}`}const IL=Dt([Lw.omit(Vc),Uw.omit(Vc),zw.omit(Vc),qw.omit(Vc),c({kind:S("learned_model"),modelVersion:Z,inputContract:sn}).strict()]),Kw=c({schemaVersion:S("openpond.rewardRelease.v1"),id:T,revision:u().int().positive(),name:r().trim().min(1).max(500),description:r().max(1e4),feedbackKey:wL.optional(),implementation:IL,rawScore:c({minimum:u().finite(),maximum:u().finite()}).strict(),assets:p(sn).max(1e3),fixtureSetRef:sn.optional(),calibrationCheckRef:Z.extend({revision:u().int().positive()}).optional()}).strict().superRefine((e,t)=>{if(e.fixtureSetRef&&(e.fixtureSetRef.visibility!=="verifier"||!e.assets.some(n=>Xt(n)===Xt(e.fixtureSetRef)))&&t.addIssue({code:"custom",path:["fixtureSetRef"],message:"Reward fixtures must be included as a private verifier asset."}),e.rawScore.minimum>=e.rawScore.maximum&&t.addIssue({code:"custom",path:["rawScore"],message:"A raw score contract requires minimum < maximum."}),e.implementation.kind!=="learned_model"&&(e.rawScore.minimum!==0||e.rawScore.maximum!==1)&&t.addIssue({code:"custom",path:["rawScore"],message:"Portable graders currently return scores in [0, 1]."}),e.implementation.kind==="schema"){const n=Tg(e.implementation.config.jsonSchema);n.valid||t.addIssue({code:"custom",path:["implementation","config","jsonSchema"],message:n.issues[0].message})}}),xu=Kw.safeExtend({contentHash:J}).strict(),rc=Z.extend({revision:u().int().positive()}).strict(),_L=It("kind",[c({kind:S("identity")}).strict(),c({kind:S("linear"),minimum:u().finite(),maximum:u().finite(),direction:b(["higher","lower"])}).strict()]),CL=c({graderId:T,reward:rc,role:b(["training","evaluation"]),normalization:_L,weight:u().nonnegative().max(1e3),required:A(),hardGate:A(),privileged:A(),fixtureRefs:p(Z).max(1e3)}).strict(),RL=c({schemaVersion:S("openpond.rewardBinding.v1"),id:T,revision:u().int().positive(),name:r().trim().min(1).max(500).optional(),description:r().max(1e4).optional(),recipeRef:rc.optional(),sources:p(CL).max(100),aggregation:S("weighted_mean"),unscorable:S("exclude_optional_require_all_required")}).strict().superRefine((e,t)=>{new Set(e.sources.map(n=>n.graderId)).size!==e.sources.length&&t.addIssue({code:"custom",path:["sources"],message:"Bound grader identities must be unique."}),e.sources.length&&!e.sources.some(n=>n.weight>0)&&t.addIssue({code:"custom",path:["sources"],message:"A configured binding needs at least one positively weighted source."});for(const[n,a]of e.sources.entries())a.hardGate&&!a.required&&t.addIssue({code:"custom",path:["sources",n],message:"A hard gate must be required."}),a.normalization.kind==="linear"&&a.normalization.minimum>=a.normalization.maximum&&t.addIssue({code:"custom",path:["sources",n,"normalization"],message:"Linear normalization requires minimum < maximum."})}),ku=RL.safeExtend({contentHash:J}).strict(),PL=c({graderId:T,reward:rc,role:b(["training","evaluation"]),status:b(["scored","pending","unavailable","failed"]),rawScore:u().finite().nullable(),normalizedScore:u().min(0).max(1).nullable(),passed:A().nullable(),evidenceHashes:p(J).max(1e3),graderEvidence:Nw.optional(),message:r().max(2e4).nullable()}).strict(),AL=c({schemaVersion:S("openpond.rewardComposition.v1"),binding:rc,taskHash:J,outputHash:J,results:p(PL).max(100),training:c({status:b(["scored","unscorable","not_configured"]),score:u().min(0).max(1).nullable(),passed:A().nullable()}).strict(),evaluation:c({status:b(["scored","unscorable","not_configured"]),score:u().min(0).max(1).nullable(),passed:A().nullable()}).strict()}).strict(),Nd=AL.extend({contentHash:J}).strict();function aQ(e){Wo(e);const t=Kw.parse(e);return xu.parse({...t,contentHash:Xt(t)})}const TL=c({text:r().max(1e5),modelId:r().trim().min(1).max(500),modelRevision:r().trim().min(1).max(500).nullable(),responseId:r().trim().min(1).max(500).nullable(),inputTokens:u().int().nonnegative().nullable(),outputTokens:u().int().nonnegative().nullable(),costUsd:u().finite().nonnegative().nullable()}).strict(),EL=c({id:T,requestHash:J,reservedUsd:u().finite().positive(),status:b(["reserved","settled","not_dispatched"]),response:TL.nullable()}).strict().superRefine((e,t)=>{e.status==="settled"!=(e.response!==null)&&t.addIssue({code:"custom",path:["response"],message:"Only settled calls have a provider response."})}),Ww=c({localTime:r().regex(/^(?:[01]\d|2[0-3]):[0-5]\d$/),timeZone:r().min(1).max(200).refine(e=>{try{return new Intl.DateTimeFormat("en",{timeZone:e}),!0}catch{return!1}},"Choose a valid IANA timezone.")}).strict(),Ft=re(r(),Yr()),xt=rc,cr=r().max(2e3).refine(e=>e===""||e.startsWith("/")&&!/~(?![01])/u.test(e),"Use an RFC 6901 JSON pointer."),ML=c({schemaVersion:S("openpond.taskDefinition.v1"),id:T,revision:u().int().positive(),name:r().trim().min(1).max(500),description:r().max(1e4),instructions:r().trim().min(1).max(2e4),category:b(["structured","question_answering","coding","tool_workflow","custom"]),familyNamespace:T,inputSchema:re(r(),ce()),outputSchema:re(r(),ce()),requiredOutputs:Eg.shape.requiredOutputs,contextRequirements:p(r().trim().min(1).max(2e3)).max(100).optional(),rewardBinding:xt,harness:Z.nullable(),execution:Fw.pick({policy:!0,environment:!0,environmentRelease:!0,tools:!0,capabilities:!0,verifierSetRelease:!0}).strict()}).strict().superRefine((e,t)=>{for(const n of["inputSchema","outputSchema"]){const a=e[n];a.type!=="object"&&t.addIssue({code:"custom",path:[n],message:"Task input/output use object envelopes; declare type: object."});const o=Tg(a);o.valid||t.addIssue({code:"custom",path:[n],message:o.issues[0].message})}!!e.execution.environmentRelease!=!!e.execution.verifierSetRelease&&t.addIssue({code:"custom",path:["execution"],message:"Bind both the environment and verifier-set releases."})}),wu=ML.safeExtend({contentHash:J}).strict(),jL=c({schemaVersion:S("openpond.taskSourceMapping.v1"),exampleId:cr,attemptId:cr,occurredAt:cr,input:cr,observedOutput:cr.nullable(),expected:cr.nullable(),evaluatorContext:cr.nullable(),familyKey:cr,split:Go}).strict(),OL=c({modelId:T,packageHash:J,taskset:xt,batch:xt,rewardBinding:xt}).strict(),$L=c({schemaVersion:S("openpond.learningSource.v1"),id:T,revision:u().int().positive(),name:r().trim().min(1).max(500),kind:b(["direct","benchmark","work","opentelemetry","provider"]),taskDefinition:xt,enabled:A(),allowedSplits:p(Go).min(1).max(4),mapping:jL.nullable(),adapterVersion:r().trim().min(1).max(200).nullable(),reviewOrigin:OL.optional()}).strict().superRefine((e,t)=>{e.kind!=="direct"&&!e.mapping&&t.addIssue({code:"custom",path:["mapping"],message:"Mapped sources require an explicit mapping."}),e.mapping&&!e.allowedSplits.includes(e.mapping.split)&&t.addIssue({code:"custom",path:["allowedSplits"],message:"The mapping split must be allowed by this source."}),["opentelemetry","provider"].includes(e.kind)&&!e.adapterVersion&&t.addIssue({code:"custom",path:["adapterVersion"],message:"Trace adapters require a pinned version."})}),Mg=$L.safeExtend({contentHash:J}).strict(),NL=c({schemaVersion:S("openpond.taskExample.v1"),sourceId:T,idempotencyKey:T,taskDefinition:xt,exampleId:T,attemptId:T,occurredAt:Oe,familyKey:T.nullable(),split:Go,input:Ft,observedOutput:Ft.nullable(),expected:Ft.nullable(),evaluatorContext:Ft.nullable(),assets:p(sn).max(1e3),requiredOutputs:Eg.shape.requiredOutputs,provenance:c({sourceRecordRef:r().max(2e3).nullable(),mappingHash:J.nullable()}).strict()}).strict(),DL=c({schemaVersion:S("openpond.taskEvidence.v1"),id:T,revision:u().int().positive(),source:xt,submission:NL,supersedes:xt.nullable(),correctionFeedbackId:T.nullable(),receivedAt:Oe}).strict(),Iu=DL.extend({contentHash:J}).strict(),LL=c({schemaVersion:S("openpond.taskRating.v1"),criteria:r().trim().min(1).max(2e4),scale:c({minimum:u().finite(),maximum:u().finite()}).strict(),score:u().finite(),evidence:r().max(2e4),explanation:r().max(2e4)}).strict().superRefine((e,t)=>{e.scale.minimum>=e.scale.maximum&&t.addIssue({code:"custom",path:["scale"],message:"The score scale must have an increasing range."}),(e.score<e.scale.minimum||e.score>e.scale.maximum)&&t.addIssue({code:"custom",path:["score"],message:"The score must be within its declared scale."})}),UL=c({schemaVersion:S("openpond.taskFeedback.v1"),sourceId:T,idempotencyKey:T,exampleId:T,attemptId:T,expectedEvidenceHash:J.nullable(),occurredAt:Oe,kind:b(["outcome","target_correction","ground_truth_correction","input_correction","family_resolution"]),value:Ft,note:r().max(2e4)}).strict().superRefine((e,t)=>{if(e.value.schemaVersion!=="openpond.taskRating.v1")return;e.expectedEvidenceHash===null&&t.addIssue({code:"custom",path:["expectedEvidenceHash"],message:"A rating must identify the exact evidence revision."}),e.kind!=="outcome"&&t.addIssue({code:"custom",path:["kind"],message:"Ratings must be submitted as outcomes."});const n=LL.safeParse(e.value);if(!n.success)for(const a of n.error.issues)t.addIssue({code:"custom",path:["value",...a.path],message:a.message})}),Gw=c({schemaVersion:S("openpond.taskFeedbackRecord.v1"),id:T,submission:UL,status:b(["pending_example","pending_review","applied","superseded","rejected"]),evidence:xt.nullable(),createdAt:Oe,revision:u().int().positive(),submittedBy:c({id:T,role:b(["editor","reviewer","source"]),sourceId:T.nullable()}).strict().nullable().default(null),review:c({actorId:T,decision:xt.nullable(),note:r().max(2e4),resolvedAt:Oe}).strict().nullable().default(null)}).strict(),HL=c({schemaVersion:S("openpond.taskAdmissionDecision.v1"),id:T,revision:u().int().positive(),evidence:xt,supersedes:xt.nullable(),actor:c({kind:b(["human","qualified_policy"]),id:T,policy:xt.nullable()}).strict(),evidenceValidity:b(["valid","invalid","pending"]),taskAdmissibility:b(["approved","rejected","pending"]),observedQuality:b(["passed","failed","unscored","unavailable"]),targetApproval:b(["approved","rejected","pending","not_required"]),approvedTarget:Ft.nullable(),grade:Nd.nullable(),targetGrade:Nd.nullable(),note:r().max(2e4),decidedAt:Oe}).strict().superRefine((e,t)=>{e.targetApproval==="approved"&&e.approvedTarget===null&&t.addIssue({code:"custom",path:["approvedTarget"],message:"Target approval requires an actual target."}),e.targetApproval!=="approved"&&e.approvedTarget!==null&&t.addIssue({code:"custom",path:["approvedTarget"],message:"Only approved targets may be selected for supervised learning."}),e.actor.kind==="qualified_policy"&&!e.actor.policy&&t.addIssue({code:"custom",path:["actor"],message:"Automatic admission must pin its qualified policy."}),e.taskAdmissibility==="approved"&&e.evidenceValidity!=="valid"&&t.addIssue({code:"custom",path:["taskAdmissibility"],message:"Only valid evidence can produce an approved task."})}),jg=HL.safeExtend({contentHash:J}).strict(),zL=c({schemaVersion:S("openpond.taskBatch.v1"),id:T,revision:S(1),taskDefinition:xt,rewardBinding:xt,purpose:b(["supervised_training","reward_training","evaluation"]),examples:p(c({evidence:xt,decision:xt,familyKey:T,inputHash:J,split:Go}).strict()).min(1).max(1e4),sealedAt:Oe,sealedBy:T}).strict().superRefine((e,t)=>{new Set(e.examples.map(a=>a.evidence.id)).size!==e.examples.length&&t.addIssue({code:"custom",path:["examples"],message:"Each evidence identity can occur only once in a batch."});const n=new Map;for(const[a,o]of e.examples.entries()){e.purpose==="evaluation"==(o.split==="train")&&t.addIssue({code:"custom",path:["examples",a,"split"],message:"Training uses train examples; evaluation uses held-out examples."});for(const i of[`family:${o.familyKey}`,`input:${o.inputHash}`])n.has(i)&&n.get(i)!==o.split&&t.addIssue({code:"custom",path:["examples",a],message:"A task family or identical input cannot cross splits."}),n.set(i,o.split)}}),Zw=zL.safeExtend({contentHash:J}).strict(),qL=c({schemaVersion:S("openpond.learningPolicy.v1"),id:T,revision:u().int().positive(),modelProjectId:T,executionOwner:b(["local","hosted"]),enabled:A(),sources:p(xt).min(1).max(100),taskDefinition:xt,rewardBinding:xt,admission:c({mode:b(["human","qualified_automatic"]),qualification:Z.nullable(),minimumApprovedExamples:u().int().positive().max(1e5)}).strict(),trigger:It("kind",[c({kind:S("manual")}).strict(),c({kind:S("approved_count")}).strict(),c({kind:S("schedule"),intervalSeconds:u().int().min(60).max(31536e3)}).strict(),Ww.extend({kind:S("nightly")}).strict(),c({kind:S("upstream_accepted"),modelProjectId:T}).strict()]),trainingParent:Z,teacher:Z.nullable(),training:c({method:b(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),recipe:Z,retentionEvaluation:Z,replayBatches:p(Z).max(100)}).strict(),limits:c({maxIterationSpendUsd:u().positive().max(1e5),maxDailySpendUsd:u().positive().max(1e6),cooldownSeconds:u().int().nonnegative().max(31536e3),maxRetries:u().int().nonnegative().max(10),maxBatchExamples:u().int().positive().max(1e4),maxBacklogExamples:u().int().positive().max(1e6)}).strict(),automation:c({collect:A(),train:A(),accept:A(),serve:A()}).strict(),acceptance:c({minimumScore:u().min(0).max(1),maximumRetentionRegression:u().min(0).max(1),requireImprovement:A(),rollbackVersion:Z.nullable()}).strict()}).strict().superRefine((e,t)=>{e.admission.mode==="qualified_automatic"&&!e.admission.qualification&&t.addIssue({code:"custom",path:["admission"],message:"Automatic admission requires qualification evidence."}),e.automation.serve&&!e.automation.accept&&t.addIssue({code:"custom",path:["automation"],message:"Automatic serving requires configured acceptance."}),e.automation.accept&&!e.acceptance.rollbackVersion&&t.addIssue({code:"custom",path:["acceptance"],message:"Automatic acceptance requires a rollback version."}),e.trigger.kind==="upstream_accepted"&&e.trigger.modelProjectId===e.modelProjectId&&t.addIssue({code:"custom",path:["trigger"],message:"A model cannot trigger itself through upstream acceptance."}),e.limits.maxBatchExamples<e.admission.minimumApprovedExamples&&t.addIssue({code:"custom",path:["limits"],message:"The batch limit must permit the minimum approved example count."}),e.limits.maxDailySpendUsd<e.limits.maxIterationSpendUsd&&t.addIssue({code:"custom",path:["limits"],message:"Daily spend must permit the iteration budget."})}),BL=qL.safeExtend({contentHash:J}).strict(),FL=c({iterationId:T,iterationRevision:u().int().positive(),candidate:Z,decision:xt,decidedAt:Oe}).strict(),VL=b(["waiting_for_data","waiting_for_review","ready","dispatching","training","evaluating","candidate_ready","accepted","rejected","paused","failed","cancelling","cancelled","completed_without_candidate"]),KL=c({schemaVersion:S("openpond.learningIteration.v1"),id:T,revision:u().int().positive(),policy:xt,status:VL,triggerIdentity:T,batch:xt.nullable(),sourceWatermarks:re(T,u().int().nonnegative()),trainingParent:Z,trainingParentSelection:FL.nullable().optional(),teacher:Z.nullable(),upstreamEvent:Z.nullable(),trainingJob:Z.nullable(),evaluationJob:Z.nullable(),candidateVersion:Z.nullable(),candidateDecision:xt.nullable().default(null),candidateDecisionAt:Oe.nullable().optional(),dispatchId:T,retryCount:u().int().nonnegative(),spendUsd:u().nonnegative(),failure:c({code:T,message:r().max(2e4)}).strict().nullable(),createdAt:Oe,updatedAt:Oe}).strict(),WL=c({schemaVersion:S("openpond.taskGradeRun.v1"),id:T,revision:u().int().positive(),evidence:xt,binding:xt,target:b(["observed","proposed_target"]),output:Ft,status:b(["queued","running","completed","failed","cancelling","cancelled"]),composition:Nd.nullable(),leaseOwner:T.nullable(),leaseExpiresAt:Oe.nullable(),attemptCount:u().int().nonnegative(),timeoutMs:u().int().min(100).max(3e5),maximumSpendUsd:u().nonnegative().max(1e3),judgeCalls:p(EL).max(1e4).optional(),requestedBy:T.optional(),failure:r().max(2e4).nullable(),createdAt:Oe,updatedAt:Oe}).strict();Dt([wu,xu,ku,Mg,Iu,Gw,jg,Zw,BL,KL,WL]);function GL(e){return xt.parse({id:e.id,revision:e.revision,contentHash:e.contentHash})}function oQ(e,t){return e.id===t.id&&e.revision===t.revision&&e.contentHash===t.contentHash}function rQ(e){return Wo(e,16777216),{...e,contentHash:Xt(e)}}function iQ(e){const{contentHash:t,...n}=e;if(Wo(n,16777216),Xt(n)!==t)throw new Ow("learning_content_hash_mismatch",422)}const Jw=c({schemaVersion:S("openpond.learningTextAsset.v1"),id:T,revision:S(1),asset:sn,text:r().max(524288)}).strict().superRefine((e,t)=>{e.asset.id!==e.id&&t.addIssue({code:"custom",path:["asset","id"],message:"Asset identity must match the stored resource."}),(e.asset.sizeBytes!==new TextEncoder().encode(e.text).byteLength||e.asset.sizeBytes>524288)&&t.addIssue({code:"custom",path:["asset","sizeBytes"],message:"Authored source must match its byte count and fit within 512 KiB."}),e.asset.contentHash!==qh(e.text)&&t.addIssue({code:"custom",path:["asset","contentHash"],message:"Asset source does not match its SHA-256."})}),_u=Jw.safeExtend({contentHash:J}).strict();function sQ(e){Wo(e);const{text:t,...n}=e,a=qh(t),o=`asset-${a}-${Xt(n).slice(0,16)}`,i=Jw.parse({schemaVersion:"openpond.learningTextAsset.v1",id:o,revision:1,asset:{...n,id:o,contentHash:a,sizeBytes:new TextEncoder().encode(t).byteLength},text:t});return _u.parse({...i,contentHash:Xt(i)})}function lQ(e,t){const{contentHash:n,...a}=_u.parse(e);if(Xt(a)!==n||Xt(a.asset)!==Xt(t))throw new Ow("learning_asset_reference_mismatch",409);return a.text}const Ua={bytes:5*1024*1024,records:1e3,files:100,messages:2e3},Yw=b(["json","jsonl","csv","hermes","openclaw"]),ZL=c({path:r().min(1).max(500),text:r()}).strict(),Og=c({id:r().min(1).max(200),familyKey:r().min(1).max(200),split:Go,kind:b(["task","attempt"]),input:Ft,observedOutput:Ft.nullable(),expected:Ft.nullable(),sourceId:r().min(1).max(2e3),sourceHash:r().length(64),occurredAt:r().datetime().nullable(),metadata:Ft,warnings:p(r().max(2e3)).max(100),needsContext:A()}).strict(),Qw=c({schemaVersion:S("openpond.taskIntakePreview.v1"),format:Yw,contentHash:r().length(64),records:p(Og).max(Ua.records),issues:p(c({file:r(),row:u().int().positive().nullable(),message:r()}).strict()).max(1e3)}).strict();function Dd(e,t){return`${e}-${Xt(t)}`}function Xw(e){if(typeof e!="string"&&typeof e!="number")return null;const t=new Date(typeof e=="number"?e*1e3:e);return Number.isFinite(t.getTime())?t.toISOString():null}function JL(e){const t=[];let n=[],a="",o=!1,i=!1;const s=()=>{n.push(a),a="",i=!1},l=()=>{if(s(),n.some(h=>h.length)&&t.push(n),n=[],t.length>Ua.records+1)throw new Error("CSV exceeds the 1,000-record limit.")};for(let h=0;h<e.length;h++){const g=e[h];if(o)g==='"'&&e[h+1]==='"'?(a+='"',h++):g==='"'?(o=!1,i=!0):a+=g;else if(g===",")s();else if(g===`
|
|
175
|
-
`||g==="\r")g==="\r"&&e[h+1]===`
|
|
176
|
-
`&&h++,l();else if(g==='"'&&!a&&!i)o=!0;else{if(i||g==='"')throw new Error("CSV has an invalid quoted field.");a+=g}}if(o)throw new Error("CSV has an unterminated quoted field.");(a||n.length||i)&&l();const m=t.shift()?.map(h=>h.trim().replace(/^\uFEFF/u,""));if(!m?.includes("instruction"))throw new Error("CSV requires an instruction column.");const d=new Set(["instruction","context","reference","labels","id","familyKey","split"]);if(m.some(h=>!d.has(h))||new Set(m).size!==m.length)throw new Error("CSV has duplicate or unsupported columns. Use instruction, context, reference, labels, id, familyKey and split.");return t.map((h,g)=>{if(h.length!==m.length)throw new Error(`CSV record ${g+2} has a different number of columns from its header.`);return Object.fromEntries(m.map((y,w)=>[y,h[w]]).filter(([,y])=>y!==""))})}function cQ(e){try{return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(e)}catch{throw new Error("Import files must contain valid UTF-8 text. Binary attachments are not supported by this import format.")}}function e1(e){return e.startsWith("\uFEFF")?e.slice(1):e}const t1=c({role:r().min(1),content:Yr().nullable().optional()}).catchall(Yr()),YL=c({id:r().min(1),messages:p(t1).min(1).max(Ua.messages),lineage_session_ids:p(r()).optional(),parent_session_id:r().nullable().optional()}).catchall(Yr());function QL(e){const t=YL.parse(e),n=t.lineage_session_ids?.[0]??t.parent_session_id??t.id,{messages:a,segments:o,...i}=t;return n1("hermes",t.id,n,t.messages,{sourceHash:Xt(e),metadata:{session:i},warnings:["Imported session context and tools need review before this can become an executable task."]})}const XL=c({traceSchema:S("openclaw-trajectory"),schemaVersion:S(1),traceId:r().min(1),sessionId:r().min(1),leafId:r().nullable(),eventCount:u().int().nonnegative(),warnings:p(Ft).optional()}).catchall(Yr()),eU=c({traceSchema:S("openclaw-trajectory"),schemaVersion:S(1),traceId:r(),sessionId:r(),seq:u().int().nonnegative(),type:r(),ts:r()}).catchall(Yr()),tU=c({header:Ft.nullable(),leafId:r().nullable(),entries:p(c({id:r().min(1),type:r().min(1),parentId:r().nullable().optional(),message:t1.optional()}).catchall(Yr())).max(Ua.messages)}).strict();function nU(e){const t=l=>{const m=e.find(d=>d.path===l);if(!m)throw new Error(`OpenClaw bundle is missing ${l}.`);return e1(m.text)},n=XL.parse(JSON.parse(t("manifest.json"))),a=tU.parse(JSON.parse(t("session-branch.json")));if(a.leafId!==n.leafId)throw new Error("OpenClaw manifest and session branch identify different leaves.");const o=t("events.jsonl").split(/\r?\n/u).filter(l=>l.trim()).map(l=>eU.parse(JSON.parse(l)));if(o.length!==n.eventCount||o.some(l=>l.traceId!==n.traceId||l.sessionId!==n.sessionId))throw new Error("OpenClaw events do not match the manifest identity or count.");if(a.header&&a.header.id!==n.sessionId)throw new Error("OpenClaw session header does not match the manifest.");const i=new Set;for(const[l,m]of a.entries.entries()){if(i.has(m.id))throw new Error("OpenClaw branch contains duplicate entry IDs.");if(l&&m.parentId!==a.entries[l-1].id)throw new Error("OpenClaw branch is incomplete or out of order.");i.add(m.id)}if(a.entries.length&&a.entries.at(-1).id!==a.leafId)throw new Error("OpenClaw branch does not reach its declared leaf.");const s=a.entries.filter(l=>l.type==="message"&&l.message).map(l=>({...l.message,entryId:l.id,timestamp:typeof l.timestamp=="string"?l.timestamp:typeof l.message.timestamp=="number"?new Date(l.message.timestamp).toISOString():null}));return n1("openclaw",n.sessionId,n.sessionId,s,{sourceHash:Xt(e),metadata:{manifest:n,sourceFiles:e.map(l=>l.path)},warnings:["Imported trajectory context and tools need review before this can become an executable task.",...(n.warnings??[]).map(l=>typeof l.message=="string"?l.message.slice(0,2e3):"The source exporter reported incomplete context.")]})}function n1(e,t,n,a,o){const i=a.flatMap((l,m)=>l.role==="user"?[m]:[]);if(!i.length)throw new Error("This history contains no user request. Supply a session with its request context.");let s=0;return i.map((l,m)=>{const d=i[m+1]??a.length,h=a.slice(l+1,d),g=h.filter(P=>P.role==="assistant").at(-1),y=a[l],w=y.entryId??y.message_id??y.id??Xt({start:l,request:y}),_={id:Dd(e,[t,w]),familyKey:Dd(e,n),split:"train",kind:"attempt",input:{request:y.content??null,messages:a.slice(0,l+1)},observedOutput:g?{response:g.content??null,messages:h}:null,expected:null,sourceId:`${e}:${t}:${String(w)}`,sourceHash:o.sourceHash,occurredAt:Xw(g?.timestamp??y.timestamp),metadata:o.metadata,warnings:[...o.warnings,...g?[]:["No assistant response was recorded for this request."]],needsContext:!0};if(Wo(_),s+=new TextEncoder().encode(JSON.stringify(_)).length,s>Ua.bytes)throw new Error("Expanded history exceeds the 5 MiB preview limit. Export a smaller session selection.");return Og.parse(_)})}const aU=c({instruction:r().trim().min(1).max(1e5),context:Dt([r(),Ft]).optional(),reference:Dt([r(),Ft]).optional(),labels:Dt([r(),p(r()),Ft]).optional(),id:r().min(1).max(200).optional(),familyKey:r().min(1).max(200).optional(),split:Go.optional()}).strict(),oU=c({input:Ft,observedOutput:Ft.nullable().optional(),expectedOutput:Ft.nullable().optional(),id:r().min(1).max(200).optional(),familyKey:r().min(1).max(200).optional(),split:Go.optional(),occurredAt:r().datetime().optional(),labels:Ft.optional()}).strict();function rU(e){const t=Yw.parse(e.format),n=p(ZL).min(1).max(Ua.files).parse(e.files);if(n.reduce((d,h)=>d+new TextEncoder().encode(h.text).length,0)>Ua.bytes)throw new Error("Import exceeds the 5 MiB size limit.");if(n.some(d=>d.path.startsWith("/")||d.path.includes("\\")||d.path.split("/").some(h=>!h||h==="."||h===".."))||new Set(n.map(d=>d.path)).size!==n.length)throw new Error("Import contains an unsafe or duplicate file path.");const a=[],o=[],i=new Map,s=new Map;let l=0;function m(d,h,g){try{const y=g();if(a.length+y.length>Ua.records)throw new Error("Import exceeds the 1,000-record limit.");const w=new Map(i),_=new Map(s);let P=0;for(const M of y){Wo(M);const C=Xt(M),N=w.get(M.id);if(N&&N!==C)throw new Error("The same record identity has different content in this upload.");N||(P+=new TextEncoder().encode(JSON.stringify(M)).length),w.set(M.id,C);for(const $ of[`family:${M.familyKey}`,`input:${Xt(M.input)}`]){if(_.has($)&&_.get($)!==M.split)throw new Error("The same task family or request occurs in different splits.");_.set($,M.split)}}if(l+P>Ua.bytes*2)throw new Error("Expanded import exceeds the 10 MiB preview limit. Select fewer source files.");for(const M of y)i.has(M.id)||a.push(M),i.set(M.id,Xt(M));for(const[M,C]of _)s.set(M,C);l+=P}catch(y){o.push({file:d,row:h,message:y instanceof HE?`Unsupported record fields or values (${y.issues.slice(0,3).map(w=>w.path.join(".")||"record").join(", ")}).`:y instanceof SyntaxError?"Invalid JSON.":y instanceof Error?y.message:"Invalid import record."})}}if(t==="openclaw")m("manifest.json",null,()=>nU(n));else for(const d of n){const h=e1(d.text);if(t==="jsonl"||t==="hermes"){for(const[g,y]of h.split(/\r?\n/u).entries())if(y.trim()){if(o.length>=Ua.records)break;m(d.path,g+1,()=>t==="hermes"?QL(JSON.parse(y)):[vy(JSON.parse(y))])}}else{let g;try{const y=t==="csv"?JL(h):JSON.parse(h);g=Array.isArray(y)?y:[y]}catch(y){m(d.path,null,()=>{throw y});continue}if(g.length>Ua.records){m(d.path,null,()=>{throw new Error("Import exceeds the 1,000-record limit.")});continue}g.forEach((y,w)=>m(d.path,w+(t==="csv"?2:1),()=>[vy(y)]))}}return Qw.parse({schemaVersion:"openpond.taskIntakePreview.v1",format:t,contentHash:Xt({format:t,files:n}),records:a,issues:o.slice(0,1e3)})}function vy(e){const t=Dt([aU,oU]).parse(e),n="instruction"in t,a=n?{instruction:t.instruction,...t.context===void 0?{}:{context:t.context}}:t.input,o=n?t.reference===void 0?null:typeof t.reference=="string"?{text:t.reference}:t.reference:t.expectedOutput??null,i=n?null:t.observedOutput??null,s=t.familyKey??Dd("family",a),l=t.id??Dd("task",{input:a,expected:o,observedOutput:i});return Og.parse({id:l,familyKey:s,split:t.split??"train",kind:i?"attempt":"task",input:a,expected:o,observedOutput:i,sourceId:l,sourceHash:Xt(e),occurredAt:n?null:Xw(t.occurredAt),metadata:t.labels===void 0?{}:{importedLabels:t.labels,labelOrigin:"unverified_import"},warnings:[],needsContext:!1})}const jl=r().trim().min(1).max(240),mr=r().regex(/^[a-f0-9]{64}$/),iU=c({id:jl,name:r().trim().min(1).max(200),required:A(),role:b(["quality","retention","diagnostic"]).optional(),unit:r().trim().min(1).max(80).optional(),baselineReuse:c({maximumAgeSeconds:u().int().positive().max(31536e3),qualification:Z}).strict().optional(),dataset:Z,evaluator:Z,executionHash:mr,populationHash:mr,metric:jl,direction:b(["higher","lower"]),minimumCoverage:u().positive().max(1),threshold:u().finite(),maximumRegression:u().finite().nonnegative(),maximumSpendUsd:u().finite().positive()}).strict().superRefine((e,t)=>{e.role==="diagnostic"&&e.required&&t.addIssue({code:"custom",message:"Diagnostic checks cannot be required acceptance gates."})}),sU=c({schemaVersion:S("openpond.acceptancePlan.v1"),id:jl,revision:u().int().positive(),checks:p(iU).min(1).max(100),maximumSpendUsd:u().finite().positive()}).strict().superRefine((e,t)=>{new Set(e.checks.map(n=>n.id)).size!==e.checks.length&&t.addIssue({code:"custom",message:"Acceptance check IDs must be unique."}),e.checks.some(n=>n.required)||t.addIssue({code:"custom",message:"An acceptance plan needs at least one required check."}),e.checks.reduce((n,a)=>n+a.maximumSpendUsd,0)>e.maximumSpendUsd+1e-9&&t.addIssue({code:"custom",message:"Check budgets exceed the total plan budget."})}),lU=sU.safeExtend({contentHash:mr}),cU=c({runId:jl,artifact:Z,checkHash:mr,populationHash:mr,scoredPopulationHash:mr,executionHash:mr,evaluator:Z,metric:jl,expectedCount:u().int().positive(),scoredCount:u().int().nonnegative(),score:u().finite().nullable(),status:b(["pending","running","completed","failed","cancelled"]),evidenceHash:mr}).strict().superRefine((e,t)=>{e.scoredCount>e.expectedCount&&t.addIssue({code:"custom",message:"Scored count exceeds declared population."}),e.scoredCount===0!=(e.score===null)&&t.addIssue({code:"custom",message:"Scores require a nonempty scored population."})}),pr=r().trim().min(1).max(240),$g=r().regex(/^[a-f0-9]{64}$/),Ld=xx(),by=u().finite().nonnegative(),dU=new Set(["completed","failed","cancelled","budget_exhausted"]),uU=c({schemaVersion:S("openpond.acceptanceGroupManifest.v1"),id:pr,teamId:pr,trainingJob:Z,baseline:Z,candidate:Z,plan:lU,maximumParallelAttempts:u().int().min(1).max(8),createdAt:Ld}).strict().superRefine((e,t)=>{e.plan.checks.some(n=>!n.role||!n.unit)&&t.addIssue({code:"custom",message:"Durable acceptance checks require explicit roles and score units."})}),mU=uU.safeExtend({contentHash:$g}),pU=c({id:pr,checkId:pr,subject:b(["baseline","candidate"]),ordinal:u().int().positive(),dispatchId:pr,state:b(["queued","dispatching","running","grading","cleaning","completed","failed","cancelled","budget_exhausted"]),artifact:Z,checkHash:$g,measurement:cU.nullable(),executionReceipt:Z.nullable(),reusedFrom:c({group:Z,attemptId:pr}).strict().nullable(),spendUsd:by,reservedUsd:by,cleanupComplete:A(),accountingComplete:A(),failureCode:pr.nullable(),createdAt:Ld,updatedAt:Ld}).strict().superRefine((e,t)=>{Date.parse(e.updatedAt)<Date.parse(e.createdAt)&&t.addIssue({code:"custom",message:"Attempt timestamps are reversed."}),dU.has(e.state)&&(!e.cleanupComplete||!e.accountingComplete||e.reservedUsd!==0)&&t.addIssue({code:"custom",message:"Terminal attempts require cleanup and settled accounting."}),e.state==="completed"&&(e.measurement?.status!=="completed"||!e.executionReceipt)&&t.addIssue({code:"custom",message:"Completed attempts require retained measurement and execution receipts."}),e.reusedFrom&&(e.subject!=="baseline"||e.state!=="completed"||e.spendUsd!==0)&&t.addIssue({code:"custom",message:"Only completed baselines may reuse retained evidence without new spend."})}),fU=c({schemaVersion:S("openpond.acceptanceGroupSnapshot.v1"),manifest:mU,revision:u().int().positive(),state:b(["queued","running","blocked","cancelling","cleaning","completed","failed","cancelled","budget_exhausted"]),attempts:p(pU).max(2e3),failureCode:pr.nullable(),updatedAt:Ld}).strict(),hU=fU.extend({contentHash:$g});var Xr=xt.shape.id,Ol=r().regex(/^[a-f0-9]{64}$/),gU=c({scopeId:Xr,modelId:Xr}).strict(),vU=c({schemaVersion:S("openpond.modelTasksetAuthoring.v1"),owner:gU,root:xt,parent:xt}).strict(),dQ=c({schemaVersion:S("openpond.modelTasksetDraftRequest.v1"),operationId:Xr,modelId:Xr,expectedModelRevision:u().int().positive(),sourcePackageHash:Ol}).strict(),bU=c({schemaVersion:S("openpond.modelTasksetDraftPreparation.v1"),draftId:Xr,requestHash:Ol,sourcePackageHash:Ol,sourceTasksetRef:xt,tasksetId:Xr,tasksetRevision:u().int().positive(),lineage:vU,authoringGraph:S("bound").optional()}).strict(),Cu=r().min(1).max(1024).refine(e=>!e.includes("\\")&&!e.includes(":")&&!e.includes("\0")&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."||t.startsWith(".env")),"Use a relative Taskset file path without environment files."),a1=c({path:Cu,sizeBytes:u().int().nonnegative(),writable:A()}).strict(),o1=c({encoding:b(["utf8","base64"]),data:r().max(8e6)}).strict(),yU=a1.extend({contentHash:Ol,content:o1}).strict();c({draftId:Xr,expectedDraftRevision:u().int().positive(),path:Cu,expectedFileHash:Ol.nullable(),content:o1.nullable()}).strict();var SU=Ww.extend({mode:b(["nightly","approved_count"]),minimumTasks:u().int().min(1).max(1e4),maximumSpendUsd:u().positive().max(1e5),maximumDailySpendUsd:u().positive().max(1e6)}).strict().superRefine((e,t)=>{e.maximumDailySpendUsd<e.maximumSpendUsd&&t.addIssue({code:"custom",path:["maximumDailySpendUsd"],message:"The daily budget must cover one update."})}),xU=67108864,Bf=524288,pl=class extends Error{code;constructor(e,t){super(t),this.name="OpenPondProtocolError",this.code=e}};function r1(e){return JSON.stringify(Ff(e))}function kU(e){return new TextEncoder().encode(r1(e)).byteLength}async function wU(e){const t=new TextEncoder().encode(r1(e)),n=await globalThis.crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n),a=>a.toString(16).padStart(2,"0")).join("")}function IU(e,t,n){const a=kU(e);if(a>t)throw new pl("payload_too_large",`${n} is ${a} bytes; the maximum is ${t} bytes.`)}function Ff(e){if(e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number"){if(!Number.isFinite(e))throw new pl("non_json_value","Canonical JSON cannot contain a non-finite number.");return Object.is(e,-0)?0:e}if(Array.isArray(e))return e.map(t=>Ff(t));if(typeof e=="object"){const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)throw new pl("non_json_value","Canonical JSON accepts only plain objects.");const n={};for(const a of Object.keys(e).sort()){const o=e[a];if(o===void 0||typeof o=="function"||typeof o=="symbol")throw new pl("non_json_value",`Canonical JSON cannot contain ${typeof o} at ${a}.`);n[a]=Ff(o)}return n}throw new pl("non_json_value",`Canonical JSON cannot contain ${typeof e}.`)}var Mt=r().trim().min(1).max(500),so=r().regex(/^[a-f0-9]{64}$/),Ia=r().datetime({offset:!0}),Ct=c({id:Mt,contentHash:so}).strict(),Do=Ct.extend({revision:u().int().positive()}).strict(),si=c({schemaVersion:S("openpond.baseModelPreference.v1"),modelId:Mt,revision:r().trim().min(1).max(256).nullable(),tokenizerRevision:r().trim().min(1).max(256).nullable(),chatTemplateHash:r().trim().min(8).max(256).nullable(),modelAssetId:Mt.nullable(),source:b(["managed","local","builtin"])}).strict(),i1=b(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),s1=c({schemaVersion:r().regex(/^openpond\.[A-Za-z0-9]+Recipe\.v\d+$/),method:i1,parameterization:b(["lora","full"])}).catchall(ce()),_U=c({profileProjectId:Mt,sourceRevision:r().regex(/^[a-f0-9]{40,64}$/),harnessRelease:Ct}).strict(),CU=c({profileProjectId:Mt,sourceRevision:r().regex(/^[a-f0-9]{40,64}$/),catalogHash:so,definitionId:Mt,harnessRelease:Ct,tasksetRelease:Ct}).strict(),l1=c({tasksetRef:Do.nullable().default(null),evaluationTasksetRef:Do.nullable().optional(),profileSource:_U.nullable().optional(),profileEvaluation:CU.nullable().optional(),rewardBindingRef:Do.nullable().optional(),tasksetRelease:Ct.nullable().default(null),harnessRelease:Ct.nullable().default(null),baseModel:si.nullable().default(null),method:i1.nullable().default(null),destinationId:Mt.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:s1.nullable().default(null),preferredMaximumSpendUsd:u().nonnegative().nullable().default(null),preferredRetentionDays:u().int().nonnegative().nullable().default(null)}).strict(),Ng=l1.omit({managedGpuRequirement:!0}),RU=c({schemaVersion:S("openpond.hostedModelProjectLink.v1"),apiOrigin:r().url().refine(e=>new URL(e).origin===e,"Use a canonical API origin.").nullable().default(null),teamId:Mt,projectId:Mt,portableProjectId:Mt,revision:u().int().positive(),etag:so,syncedSourceRevision:u().int().positive(),syncedAt:Ia,tasksets:p(c({localTasksetId:Mt,localTasksetHash:so.nullable().default(null),releaseId:Mt,releaseRevision:u().int().positive(),releaseHash:so,packageHash:so.nullable().default(null),hostedTasksetId:Mt,syncedAt:Ia}).strict()).max(1e4).default([])}).strict(),PU=c({localTasksetId:Mt,releaseId:Mt,releaseRevision:u().int().positive(),releaseHash:so,state:b(["syncing","synced","sync_failed"]),hostedTasksetId:Mt.nullable().default(null),lastAttemptAt:Ia,syncedAt:Ia.nullable().default(null),lastError:r().trim().min(1).max(5e3).nullable().default(null)}).strict(),c1=c({schemaVersion:S("openpond.modelProject.v2"),id:Mt,profileId:Mt,revision:u().int().positive().default(1),name:r().trim().min(1).max(200),objective:r().trim().max(5e3).nullable(),defaultBaseModel:si.nullable(),defaultDestinationId:Mt.nullable(),trainingSetup:l1,hosted:RU.nullable().default(null),tasksetSyncs:p(PU).max(1e4).default([]),createdAt:Ia,updatedAt:Ia}).strict(),d1=c1.pick({id:!0,profileId:!0,name:!0,objective:!0,defaultBaseModel:!0,defaultDestinationId:!0,trainingSetup:!0}),AU=c({schemaVersion:S("openpond.modelProjectSave.v1"),operationId:Mt,expectedRevision:u().int().nonnegative(),project:d1,learning:SU.optional()}).strict().superRefine((e,t)=>{e.learning&&e.expectedRevision!==0&&t.addIssue({code:"custom",path:["learning"],message:"Use learning settings to edit an existing Model's policy."})}),u1=c({schemaVersion:S("openpond.modelProjectConfigurationCheck.v1"),configurationHash:so,projectId:Mt,expectedRevision:u().int().nonnegative(),checkedAt:Ia,canSave:A(),deferred:p(b(["base_model","taskset"])).max(2),findings:p(c({code:Mt,severity:b(["error","warning"]),message:r().min(1).max(5e3),field:r().min(1).max(500).nullable()}).strict()).max(100)}).strict();c({id:Mt,name:r().min(1).max(500),available:A(),preference:si}).strict();function TU(e){try{Wo(e,Bf)}catch{throw new OU(400,{schemaVersion:"openpond.modelProjectApiError.v2",code:"model_configuration_json_invalid",message:"Model configuration must be bounded JSON data.",retryable:!1,requestId:null,details:{}})}return AU.parse(e)}async function EU(e,t,n){Wo(e,Bf);const a=d1.parse(e);IU(a,Bf,"Model configuration");const o=await wU({project:a,expectedRevision:t});return TU({schemaVersion:"openpond.modelProjectSave.v1",operationId:`model-save:${o}`,expectedRevision:t,project:a})}var MU=c({schemaVersion:S("openpond.hostedModelProjectSync.v2"),portableProjectId:Mt,name:r().trim().min(1).max(200),objective:r().trim().max(5e3).nullable(),defaultBaseModel:si.nullable(),defaultDestinationId:Mt.nullable(),trainingSetup:Ng,sourceRevision:u().int().positive(),sourceUpdatedAt:Ia,expectedEtag:so.nullable().default(null)}).strict(),m1=c({id:Mt,teamId:Mt,portableProjectId:Mt,name:r().trim().min(1).max(200),objective:r().trim().max(5e3).nullable(),defaultBaseModel:si.nullable(),defaultDestinationId:Mt.nullable(),trainingSetup:Ng,sourceRevision:u().int().positive(),sourceUpdatedAt:Ia,revision:u().int().positive(),etag:so,createdAt:Ia,updatedAt:Ia}).strict(),jU=c({kind:b(["taskset_release","harness_release","dataset_release","evidence_set","model_version","reward_model_version","evaluation_receipt"]),ref:Ct,role:r().trim().min(1).max(200).nullable().default(null),updatedAt:Ia}).strict();c({project:m1,resources:p(jU).max(1e4),jobCount:u().int().nonnegative(),latestJobIds:p(Mt).max(100)}).strict();c({schemaVersion:S("openpond.modelProjectApiError.v2"),code:r().trim().min(1).max(200),message:r().trim().min(1).max(5e3),retryable:A().default(!1),requestId:r().trim().min(1).max(500).nullable().default(null),details:re(r(),ce()).default({})}).strict();var OU=class extends Error{status;code;retryable;requestId;details;constructor(e,t){super(t.message),this.name="OpenPondModelProjectApiError",this.status=e,this.code=t.code,this.retryable=t.retryable,this.requestId=t.requestId,this.details=t.details}},$U=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),NU=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 DU(e){const t=typeof e=="string"?new TextEncoder().encode(e):e,n=Math.ceil((t.byteLength+9)/64)*64,a=new Uint8Array(n);a.set(t),a[t.byteLength]=128;const o=t.byteLength*8,i=new DataView(a.buffer);i.setUint32(n-8,Math.floor(o/4294967296),!1),i.setUint32(n-4,o>>>0,!1);const s=new Uint32Array($U),l=new Uint32Array(64);for(let m=0;m<n;m+=64){for(let C=0;C<16;C+=1)l[C]=i.getUint32(m+C*4,!1);for(let C=16;C<64;C+=1){const N=l[C-15],$=l[C-2],j=no(N,7)^no(N,18)^N>>>3,x=no($,17)^no($,19)^$>>>10;l[C]=l[C-16]+j+l[C-7]+x>>>0}let d=s[0],h=s[1],g=s[2],y=s[3],w=s[4],_=s[5],P=s[6],M=s[7];for(let C=0;C<64;C+=1){const N=w&_^~w&P,$=d&h^d&g^h&g,j=no(d,2)^no(d,13)^no(d,22),x=no(w,6)^no(w,11)^no(w,25),R=M+x+N+NU[C]+l[C]>>>0,E=j+$>>>0;M=P,P=_,_=w,w=y+R>>>0,y=g,g=h,h=d,d=R+E>>>0}s[0]=s[0]+d>>>0,s[1]=s[1]+h>>>0,s[2]=s[2]+g>>>0,s[3]=s[3]+y>>>0,s[4]=s[4]+w>>>0,s[5]=s[5]+_>>>0,s[6]=s[6]+P>>>0,s[7]=s[7]+M>>>0}return Array.from(s,m=>m.toString(16).padStart(8,"0")).join("")}function no(e,t){return e>>>t|e<<32-t}var LU=2e3,p1=25e7,Fe=r().trim().min(1).max(240),Qe=r().regex(/^[a-f0-9]{64}$/),wt=r().datetime({offset:!0}),Ru=re(r(),ce()).default({}),Je=c({id:Fe,contentHash:Qe}).strict(),UU=Je.extend({revision:u().int().positive()}).strict(),gr=c({id:Fe,path:r().trim().min(1).max(LU).refine(BU),contentHash:Qe,sizeBytes:u().int().nonnegative().max(p1),mediaType:r().trim().min(1).max(200),visibility:b(["policy","verifier","host_private"])}).strict(),HU=c({id:Fe,contentHash:Qe,mediaType:r().trim().min(1).max(200).nullable().default(null),sizeBytes:u().int().nonnegative().max(p1).nullable().default(null)}).strict(),zU=b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]);function qU(e){return`${JSON.stringify(Vf(e),null,2)}
|
|
177
|
-
`}function f1(e){return DU(e)}function Jr(e){return f1(qU(e))}function BU(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function Vf(e){return Array.isArray(e)?e.map(Vf):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,Vf(n)]))}var FU=b(["memory","prompt","skill","agent"]),VU=b(["runtime","product","taskset","training"]),KU=c({id:r().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),text:r().trim().min(1).max(1e4)}).strict(),WU=c({schemaVersion:S("openpond.refinerReviewProfile.v1"),id:r().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),version:r().trim().min(1).max(120),name:r().trim().min(1).max(200),objective:r().trim().min(1).max(1e4),instructions:p(KU).max(100),allowedProposalRoutes:p(FU).max(4),allowedExternalRoutes:p(VU).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"]})});c({schemaVersion:S("openpond.refinerRelease.v1"),id:r().trim().min(1).max(240),coreVersion:r().trim().min(1).max(120),coreHash:Qe,profile:WU,profileHash:Qe,composedPromptHash:Qe,createdAt:wt,contentHash:Qe}).strict();c({schemaVersion:S("openpond.refinerBinding.v1"),channel:S("active"),revision:u().int().nonnegative(),release:Je,updatedAt:wt}).strict();c({schemaVersion:S("openpond.refinerTransitionReceipt.v1"),id:r().trim().min(1).max(240),operation:b(["initialize","update","activate","rollback"]),bindingChanged:A(),previousRelease:Je.nullable(),nextRelease:Je,actor:r().trim().min(1).max(240),reason:r().trim().min(1).max(1e4),authoringSkillHash:Qe.nullable(),validation:c({valid:A(),messages:p(r().max(2e3)).max(100)}).strict(),createdAt:wt,contentHash:Qe}).strict();var GU=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v1"),decision:S("no_action"),reason:r().trim().min(1).max(1e4)}).strip(),ZU=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v1"),decision:S("route"),route:b(["runtime","product","taskset","training"]),summary:r().trim().min(1).max(2e3),expectedOutcome:r().trim().min(1).max(1e4),reason:r().trim().min(1).max(1e4)}).strip(),JU=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v1"),decision:S("propose"),route:b(["memory","prompt","skill","agent"]),operation:b(["create","update","delete"]),target:r().trim().min(1).max(2e3),summary:r().trim().min(1).max(2e3),createContent:r().min(1).max(2e4).nullable(),find:r().min(1).max(8e3).nullable(),replace:r().max(8e3).nullable(),expectedOutcome:r().trim().min(1).max(1e4),reason:r().trim().min(1).max(1e4)}).strip().superRefine((e,t)=>{e.operation==="create"&&(e.createContent===null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"create proposals require createContent and null find/replace",path:["createContent"]}),e.operation==="update"&&(e.createContent!==null||e.find===null||e.replace===null)&&t.addIssue({code:"custom",message:"update proposals require one exact find/replace edit and null createContent",path:["find"]}),e.operation==="delete"&&(e.createContent!==null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"delete proposals require null createContent/find/replace",path:["createContent"]})}),YU=It("decision",[GU,ZU,JU]),QU=YU,Dg=c({kind:b(["single_deterministic","recurrent_independent"]),supportingEvidenceIds:p(r().trim().min(1).max(2e3)).min(1).max(100),counterevidence:p(r().trim().min(1).max(2e3)).max(20)}).strict().superRefine((e,t)=>{new Set(e.supportingEvidenceIds).size!==e.supportingEvidenceIds.length&&t.addIssue({code:"custom",message:"supporting evidence IDs must be unique",path:["supportingEvidenceIds"]}),e.kind==="recurrent_independent"&&e.supportingEvidenceIds.length<2&&t.addIssue({code:"custom",message:"recurrent independent evidence requires at least two supplied incidents",path:["supportingEvidenceIds"]})}),XU=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("no_action"),reason:r().trim().min(1).max(1e4)}).strict(),eH=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("route"),route:b(["runtime","product","taskset","training"]),summary:r().trim().min(1).max(2e3),evidenceBasis:Dg,expectedOutcome:r().trim().min(1).max(1e4),reason:r().trim().min(1).max(1e4)}).strict(),tH=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("propose"),route:b(["memory","prompt","skill","agent"]),operation:b(["create","update","delete"]),target:r().trim().min(1).max(2e3),summary:r().trim().min(1).max(2e3),evidenceBasis:Dg,createContent:r().min(1).max(2e4).nullable(),find:r().min(1).max(8e3).nullable(),replace:r().max(8e3).nullable(),expectedOutcome:r().trim().min(1).max(1e4),reason:r().trim().min(1).max(1e4)}).strict().superRefine((e,t)=>{e.operation==="create"&&(e.createContent===null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"create proposals require createContent and null find/replace",path:["createContent"]}),e.operation==="update"&&(e.createContent!==null||e.find===null||e.replace===null)&&t.addIssue({code:"custom",message:"update proposals require one exact find/replace edit and null createContent",path:["find"]}),e.operation==="delete"&&(e.createContent!==null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"delete proposals require null createContent/find/replace",path:["createContent"]})}),h1=It("decision",[XU,eH,tH]);Dt([QU,h1]);var Lg=c({memory:A(),prompt:A(),skill:A(),agent:A()}).strict(),g1=b(["memory","instruction","skill","agent"]),yy=c({path:r().trim().min(1).max(2e3),kind:g1,content:r().max(6e4),loaded:A()}).strict(),Sy=c({path:r().trim().min(1).max(2e3),kind:g1,loaded:A()}).strict(),nH=c({capabilities:Lg,trigger:re(r(),ce()),observations:p(re(r(),ce())).max(20),admissibleEvidenceIds:p(r().trim().min(1).max(2e3)).max(1e4),reviewPacket:c({currentTurn:c({id:r().trim().min(1).max(2e3),status:r().trim().min(1).max(100).nullable(),error:r().max(2100).nullable(),prompt:r().max(8100).nullable(),assistantOutput:r().max(8100).nullable(),assistantOutputLinkCount:u().int().nonnegative()}).strict(),priorConversation:p(c({turnId:r().trim().min(1).max(2e3),status:r().trim().min(1).max(100).nullable(),prompt:r().max(3100).nullable(),assistantOutput:r().max(3100).nullable()}).strict()).max(3),timeline:p(re(r(),ce())).max(60),artifacts:p(re(r(),ce())).max(30),artifactDiagnostics:p(re(r(),ce())).max(20),executionProfile:c({modelRequestCount:u().int().nonnegative(),failedModelRequestCount:u().int().nonnegative(),promptTokens:u().int().nonnegative(),completionTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative(),toolFailureCount:u().int().nonnegative(),retryCount:u().int().nonnegative(),recoveryCount:u().int().nonnegative()}).strict(),priorIncidents:p(re(r(),ce())).max(3),truncation:c({timelineEventCount:u().int().nonnegative(),includedTimelineEventCount:u().int().nonnegative(),timelineTruncated:A()}).strict()}).strict(),runtimeActivation:c({admittedRelease:Je,currentRelease:Je,rebasedOntoCurrent:A(),admittedSourceFiles:p(yy).max(100),admittedSourceCatalog:p(Sy).max(1e3)}).strict(),sourceFiles:p(yy).max(100),sourceCatalog:p(Sy).max(1e3),additionalEvidence:ce().nullable().optional()}).strict(),aH=c({id:r().trim().min(1).max(240),revision:u().int().nonnegative(),contentHash:Qe}).strict();c({schemaVersion:S("openpond.hostedHarnessRefinerRequest.v2"),requestId:r().trim().min(1).max(240),idempotencyKey:r().trim().min(1).max(240),evidenceHash:Qe,harness:c({admittedRelease:Je,currentRelease:Je,overlay:aH,workspace:c({id:r().trim().min(1).max(240),revision:u().int().nonnegative(),sourceRevision:Qe,channelRevision:u().int().nonnegative()}).strict(),capabilities:Lg}).strict(),evidence:nH}).strict();var oH=c({promptTokens:u().int().nonnegative(),completionTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative()}).strict();c({schemaVersion:S("openpond.hostedHarnessRefinerResponse.v2"),requestId:r().trim().min(1).max(240),evidenceHash:Qe,admittedRelease:Je,currentRelease:Je,decision:h1,serviceRevision:r().trim().min(1).max(240),usage:oH}).strict();const rH=c({adapterId:T,placement:b(["local","remote","colocated","provider_native"]),runtimeVersion:r().trim().min(1).max(200),capabilityReceipt:J}).strict(),iH=c({maxTurns:u().int().positive().max(1e5),timeoutMs:u().int().positive().max(864e5),maxOutputBytes:u().int().positive().max(25e7),maximumSpendUsd:u().nonnegative().nullable()}).strict(),sH=c({schemaVersion:S("openpond.runManifest.v1"),id:T,harnessRelease:Z,tasksetRelease:Z,model:Bh,runtimeTarget:rH,limits:iH,approval:c({id:T,contentHash:J}).strict().nullable(),createdAt:Oe,metadata:In}).strict();sH.extend({contentHash:J}).strict();const lH=c({schemaVersion:S("openpond.attemptReceipt.v1"),id:T,runManifest:Z,taskId:T,seed:r().trim().min(1).max(500),terminal:A(),failureClass:Gl.nullable(),outputHash:J.nullable(),traceHash:J,artifactRefs:p(Fa).max(1e5),graderEvidenceRefs:p(Fa).max(1e4),startedAt:Oe,completedAt:Oe,latencyMs:u().int().nonnegative(),costUsd:u().nonnegative().nullable(),legacyAttemptRef:T.nullable().default(null),metadata:In}).strict(),uQ=lH.extend({contentHash:J}).strict(),cH=c({schemaVersion:S("openpond.evaluationResult.v1"),id:T,runManifest:Z,harnessRelease:Z,tasksetRelease:Z,model:Bh,receiptRefs:p(Z).min(1).max(1e6),attemptCount:u().int().positive(),rewardEligibleCount:u().int().nonnegative(),terminalCount:u().int().nonnegative(),meanScore:u().min(0).max(1).nullable(),failureCounts:re(Gl,u().int().nonnegative()),authoredMetric:yL.optional(),metadata:In}).strict(),dH=cH.extend({contentHash:J}).strict(),uH=c({schemaVersion:S("openpond.harnessCompatibility.v1"),id:T,baseHarnessRelease:Z,candidateHarnessRelease:Z,tasksetRelease:Z,environmentHash:J,toolContractHash:J,policyHash:J,graderInterfaceHash:J,metadata:In}).strict();uH.extend({contentHash:J}).strict();const Ug=b(["scored","unscorable"]),Pu=b(["policy","environment","collector","verifier","provider","host","user","scheduler"]),v1=b(["completed","policy_failure","incomplete_output","task_deadline","environment_failure","collector_failure","verifier_failure","provider_failure","host_failure","infrastructure_timeout","cancelled"]),mH=c({schemaVersion:S("openpond.environmentRelease.v1"),id:T,revision:u().int().positive(),contract:Dw,actionSchemaRef:sn.nullable(),observationSchemaRef:sn.nullable(),stateSchemaRef:sn.nullable(),artifactCollection:c({maxArtifacts:u().int().positive().max(1e5),maxTotalBytes:u().int().positive().max(1e10)}).strict(),adapterConformanceHashes:re(T,J),metadata:In}).strict(),Hg=mH.extend({contentHash:J}).strict(),pH=b(["collected","missing","skipped","failed"]),xy=b(["not_requested","passed","failed"]),fH=c({requiredOutputPath:r().trim().min(1).max(2e3).nullable(),collectedPath:r().trim().min(1).max(4e3).nullable(),declaredMediaType:r().trim().min(1).max(200).nullable(),detectedMediaType:r().trim().min(1).max(200).nullable(),artifact:Fa.nullable(),status:pH,parseStatus:xy,schemaStatus:xy,errorCode:T.nullable(),failureOwner:Pu.nullable(),evidenceRefs:p(Fa).max(1e4),metadata:In}).strict(),hH=c({schemaVersion:S("openpond.artifactManifest.v1"),id:T,attemptRef:Z,entries:p(fH).max(1e5),createdAt:Oe,metadata:In}).strict();hH.extend({contentHash:J}).strict();const gH=c({schemaVersion:S("openpond.verifierSetRelease.v1"),id:T,revision:u().int().positive(),graders:p(Bw).min(1).max(1e3),isolation:c({processBoundary:b(["same_process","isolated_process","container"]),networkPolicy:S("none"),defaultTimeoutMs:u().int().positive().max(3e5)}).strict(),calibrationReceiptRefs:p(Z).max(1e4),metadata:In}).strict(),zg=gH.extend({contentHash:J}).strict(),vH=c({verifierId:T,verifierVersion:r().trim().min(1).max(100),status:Ug,rawScore:u().finite().nullable(),normalizedScore:u().min(0).max(1).nullable(),weight:u().nonnegative().max(1e3),passed:A(),hardGate:A(),rewardEligible:A(),rewardContribution:u().min(0).max(1).nullable(),failureOwner:Pu.nullable(),feedback:p(r().max(2e4)).max(1e3),visibleEvidenceRefs:p(Fa).max(1e4),privilegedEvidenceRefs:p(Fa).max(1e4),metadata:In}).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"]})}),b1=c({schemaVersion:S("openpond.rewardReceipt.v1"),id:T,attemptRef:Z,verifierSetRef:Z,artifactManifestRef:Z,status:Ug,reward:u().min(0).max(1).nullable(),learningEligible:A(),passed:A(),outcomeClass:v1,failureOwner:Pu.nullable(),components:p(vH).min(1).max(1e4),visibleEvidenceRefs:p(Fa).max(1e5),privilegedEvidenceRefs:p(Fa).max(1e5),supersedes:Z.nullable(),createdAt:Oe,metadata:In}).strict();function y1(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"]})}b1.superRefine(y1);b1.extend({contentHash:J}).strict().superRefine(y1);const S1=c({schemaVersion:S("openpond.optimizerTrainingSample.v1"),tokenIds:p(u().int().nonnegative()).min(2).max(32768),mask:p(A()).min(2).max(32768),logprobs:p(u().finite()).min(2).max(32768),temperatures:p(u().positive().finite()).min(2).max(32768),envName:r().trim().min(1).max(200),modelRequestId:r().trim().min(1).max(1e3),promptTokenCount:u().int().positive(),completionTokenCount:u().int().positive(),servedPolicyVersion:u().int().nonnegative()}).strict().superRefine((e,t)=>{const n=e.tokenIds.length;for(const[a,o]of[["mask",e.mask],["logprobs",e.logprobs],["temperatures",e.temperatures]])o.length!==n&&t.addIssue({code:"custom",path:[a],message:`${a} must align with tokenIds`});e.promptTokenCount+e.completionTokenCount!==n&&t.addIssue({code:"custom",path:["completionTokenCount"],message:"prompt and completion token counts must span tokenIds"}),e.mask.filter(a=>!a).length!==e.promptTokenCount&&t.addIssue({code:"custom",path:["mask"],message:"promptTokenCount must equal the non-trainable mask count"}),e.mask.filter(Boolean).length!==e.completionTokenCount&&t.addIssue({code:"custom",path:["mask"],message:"completionTokenCount must equal the trainable mask count"})}),bH=c({id:T,environmentRelease:Z,status:b(["completed","failed","timed_out","cancelled"]),startedAt:Oe,completedAt:Oe,traceRefs:p(Fa).max(1e4),metadata:In}).strict(),yH=c({receiptRef:Z,status:Ug,value:u().min(0).max(1).nullable(),learningEligible:A(),passed:A(),outcomeClass:v1,failureOwner:Pu.nullable(),components:re(T,u().min(0).max(1).nullable())}).strict(),x1=c({schemaVersion:S("openpond.canonicalRolloutRecord.v1"),id:T,attemptRef:Z,artifactManifestRef:Z,tasksetRelease:Z,environmentRelease:Z,verifierSetRelease:Z,harnessRelease:Z,taskId:T,split:Go,model:Bh,seed:r().trim().min(1).max(500),reward:yH,traceRef:Fa,optimizerSample:S1.nullable(),environmentExecutions:p(bH).min(1).max(1e5),startedAt:Oe,completedAt:Oe,metadata:In}).strict();function k1(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."})}x1.superRefine(k1);c({...x1.shape,contentHash:J}).strict().superRefine(k1);const SH=r().regex(/^(0|-?[1-9][0-9]*)$/).max(20).refine(e=>{if(e.length>20||!/^(0|-?[1-9][0-9]*)$/.test(e))return!1;const t=BigInt(e);return t>=-(1n<<63n)&&t<1n<<63n},"SQL integers must fit signed 64-bit storage."),w1=Dt([ru(),r().max(262144),u().finite(),c({integer:SH}).strict(),c({blobBase64:r().max(349528).regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/)}).strict()]),ky=r().min(1).max(128).refine(e=>!e.includes("\0")),xH=c({tables:p(c({name:ky,columns:p(c({name:ky,type:b(["INTEGER","REAL","TEXT","BLOB"])}).strict()).min(1).max(128),rows:p(p(w1).max(128)).max(4096)}).strict()).max(64)}).strict().superRefine((e,t)=>{const n=new Set;for(const[a,o]of e.tables.entries()){const i=o.name.toLowerCase();(n.has(i)||i.startsWith("sqlite_"))&&t.addIssue({code:"custom",path:["tables",a,"name"],message:"Table names must be unique and outside SQLite's reserved namespace."}),n.add(i),new Set(o.columns.map(s=>s.name.toLowerCase())).size!==o.columns.length&&t.addIssue({code:"custom",path:["tables",a,"columns"],message:"Column names must be unique."}),o.rows.some(s=>s.length!==o.columns.length)&&t.addIssue({code:"custom",path:["tables",a,"rows"],message:"Each row must match the declared columns."})}}),wy=c({schemaVersion:S("openpond.sqlExecution.v1"),snapshot:xH,sql:r().min(1).max(65536).refine(e=>!e.includes("\0")),maxRows:u().int().min(1).max(4096),maxResultBytes:u().int().min(256).max(262144)}).strict();It("status",[c({status:S("completed"),columns:p(r()).max(128),rows:p(p(w1).max(128)).max(4096)}).strict(),c({status:S("rejected"),code:b(["invalid_query","multiple_statements","result_too_large","memory_limit"])}).strict()]);const Kc=c({scope:b(["input","initialState","state","arguments"]),path:p(r().min(1).max(256)).max(16)}).strict(),Iy={id:r().min(1).max(128),operation:b(["step","collect"]),toolName:r().min(1).max(500).optional(),timeoutMs:u().int().min(1).max(2e4)},kH=It("kind",[c({...Iy,kind:S("sqlite.v1"),sql:Kc,snapshot:Kc,maxRows:wy.shape.maxRows,maxResultBytes:wy.shape.maxResultBytes}).strict(),c({...Iy,kind:S("javascript.v1"),source:Kc,cases:Kc,exportName:r().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/).max(128),maxCases:u().int().min(1).max(32),maxResultBytes:u().int().min(256).max(262144)}).strict()]).superRefine((e,t)=>{e.operation==="step"!=(e.toolName!==void 0)&&t.addIssue({code:"custom",path:["toolName"],message:"Only step services require a declared tool name."}),e.operation==="collect"&&(e.kind==="sqlite.v1"?[e.sql,e.snapshot]:[e.source,e.cases]).some(a=>a.scope==="arguments")&&t.addIssue({code:"custom",message:"Collection has no tool arguments."})}),wH=c({schemaVersion:S("openpond.javascriptEnvironment.v1"),id:r().trim().min(1).max(500),revision:u().int().positive(),module:sn.refine(e=>e.visibility==="host_private","Environment code belongs to the execution owner."),tools:p(ec).min(1).max(200),maxSteps:u().int().min(1).max(1e3),maxStateBytes:u().int().min(1).max(1048576),maxObservationBytes:u().int().min(1).max(262144),operationTimeoutMs:u().int().min(1).max(3e4),executionServices:p(kH).min(1).max(16).optional()}).strict().superRefine((e,t)=>{new Set(e.tools.map(a=>a.name)).size!==e.tools.length&&t.addIssue({code:"custom",path:["tools"],message:"Environment tool names must be unique."}),e.tools.forEach((a,o)=>{Tg(a.inputSchema).valid||t.addIssue({code:"custom",path:["tools",o,"inputSchema"],message:"Environment tools require a supported JSON schema."}),a.inputSchemaHash!==Xt(a.inputSchema)&&t.addIssue({code:"custom",path:["tools",o,"inputSchemaHash"],message:"Tool schema identity differs from its declared schema."})});const n=e.executionServices??[];new Set(n.map(a=>a.id)).size!==n.length&&t.addIssue({code:"custom",path:["executionServices"],message:"Execution service identities must be unique."}),n.forEach((a,o)=>{const i=e.tools.find(s=>s.name===a.toolName);a.operation==="step"&&!i&&t.addIssue({code:"custom",path:["executionServices",o,"toolName"],message:"Execution services must target a declared tool."}),a.timeoutMs>=Math.min(e.operationTimeoutMs,i?.timeoutMs??e.operationTimeoutMs)&&t.addIssue({code:"custom",path:["executionServices",o,"timeoutMs"],message:"Service budgets must leave time for the authored controller."})})}),IH=wH.safeExtend({contentHash:r().regex(/^[a-f0-9]{64}$/)});b(["create","reset","step","collect","destroy"]);c({state:re(r(),ce()),observation:re(r(),ce())}).strict();r().regex(/^[a-f0-9]{64}$/);var _H=c({environment:Hg,verifierSet:zg,javascript:IH}).strict();c({actions:p(c({name:r().min(1).max(64),arguments:re(r(),ce())}).strict()).max(1e3)}).strict();var CH=c({environment:Hg,verifierSet:zg}).strict(),RH=c({scopeId:r().trim().min(1).max(500),modelId:r().trim().min(1).max(500)}).strict();c({schemaVersion:S("openpond.modelTasksetDerivation.v1"),owner:RH,root:Do,parent:Do}).strict();var PH=c({taskset:Vw,taskDefinition:wu,rewardBinding:ku,rewards:p(xu).min(1).max(100),assets:p(_u).max(1e3),executionResources:CH.optional(),execution:_H.optional(),instructionMode:S("per_task").optional()}).strict(),AH=c({batch:Zw,evidence:p(Iu).min(1).max(1e4),decisions:p(jg).min(1).max(1e4),sources:p(Mg).min(1).max(1e4),assets:p(_u).max(1e3)}).strict(),TH=64*1024*1024,EH=c({asset:gr,base64:r().max(Math.ceil(TH/3)*4)}).strict(),MH=PH.omit({taskset:!0,executionResources:!0}),jH=c({schemaVersion:S("openpond.tasksetPackage.v1"),taskset:Vw,environment:Hg,verifierSet:zg,files:p(EH).max(1e4),modelResources:MH.optional(),learningResources:AH.optional()}).strict(),Kf=jH.extend({contentHash:r().regex(/^[a-f0-9]{64}$/)}).strict(),To=r().trim().min(1).max(500),ud=r().regex(/^[a-f0-9]{64}$/),OH=MU.pick({portableProjectId:!0,name:!0,objective:!0,defaultBaseModel:!0,defaultDestinationId:!0,sourceRevision:!0,sourceUpdatedAt:!0}).extend({trainingSetup:Ng.omit({tasksetRef:!0,rewardBindingRef:!0,tasksetRelease:!0})}).strict();c({schemaVersion:S("openpond.tasksetPackagePublication.v1"),operationId:To,modelProjectId:To,expectedProjectEtag:ud.nullable(),name:r().trim().min(1).max(200),description:r().max(5e3),buildIntent:b(["demonstrations","preferences","verifiable_reward","rubric","discovery"]),methodHint:b(["sft","dpo","grpo","ppo"]).nullable(),package:Kf,modelConfiguration:OH.optional(),evaluationPackage:Kf.optional(),selection:b(["select","attach"]).optional()}).strict().refine(e=>e.selection!=="attach"||e.modelConfiguration===void 0,"Attachment-only publication cannot replace Model configuration.").refine(e=>!e.evaluationPackage||e.modelConfiguration!==void 0&&e.modelConfiguration.trainingSetup.evaluationTasksetRef!=null&&Jr(e.modelConfiguration.trainingSetup.evaluationTasksetRef)===Jr(GL(e.evaluationPackage.taskset)),"Evaluation package must match the selected immutable evaluation in Model configuration.");c({schemaVersion:S("openpond.tasksetPackageReceipt.v1"),teamId:To,modelProjectId:To,operationId:To,taskset:qf,packageHash:ud,hostedTasksetId:To,projectEtag:ud,project:m1.optional(),selection:b(["select","attach"]).optional(),evaluation:c({taskset:qf,packageHash:ud,hostedTasksetId:To}).strict().optional()}).strict();c({schemaVersion:S("openpond.tasksetPackageReadback.v1"),teamId:To,modelProjectId:To,package:Kf}).strict();var I1=c({name:r().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:r().trim().min(1).max(2e3),inputSchema:re(r(),ce()),inputSchemaHash:Qe,sideEffect:b(["read","write"]),timeoutMs:u().int().positive().max(36e5)}).strict(),$H=c({id:Fe,required:A(),scopes:p(r().trim().min(1).max(500)).max(100).default([]),portability:b(["portable","host_adapter","local_only","hosted_only"])}).strict(),NH=c({portable:A(),blockers:p(r().trim().min(1).max(2e3)).max(1e3),localOnlyAssetRefs:p(Fe).max(1e4),hostPrivateAssetRefs:p(Fe).max(1e4)}).strict(),DH=c({schemaVersion:S("openpond.agentSnapshot.v2"),id:Fe,sourceRelease:Je.nullable(),instructions:p(gr).max(1e4),skills:p(gr).max(1e4),agents:p(gr).max(1e4),toolDeclarations:p(I1).max(200),capabilityRequirements:p($H).max(200),dependencyLock:gr,portability:NH,metadata:Ru}).strict(),LH=DH.extend({contentHash:Qe}).strict(),UH=c({create:S(!0),reset:S(!0),step:S(!0),collect:S(!0),destroy:S(!0),resetScope:b(["task","attempt"])}).strict(),HH=c({visibleEvidence:p(Fe).max(1e3),privilegedEvidence:p(Fe).max(1e3),privateVerifierIsolation:A()}).strict(),zH=c({schemaVersion:S("openpond.harnessRelease.v2"),id:Fe,agentSnapshot:Je,program:gr,tools:p(I1).max(200),lifecycle:UH,graderInterface:HH,files:p(gr).max(1e5),metadata:Ru}).strict(),qH=zH.extend({contentHash:Qe}).strict(),BH=c({id:Fe,turn:u().int().nonnegative(),kind:b(["message","tool_call","terminal"]),name:Fe.nullable(),arguments:re(r(),ce()),content:r().max(1e6).nullable()}).strict(),FH=c({actionId:Fe,turn:u().int().nonnegative(),terminal:A(),output:re(r(),ce()),artifactRefs:p(HU).max(1e5)}).strict(),VH=c({sequence:u().int().nonnegative(),type:b(["created","reset","action","observation","terminal","failure","collected","destroyed"]),payloadHash:Qe,metadata:Ru}).strict();c({schemaVersion:S("openpond.harnessTrace.v1"),manifest:Je,taskId:Fe,seed:r().trim().min(1).max(500),events:p(VH).max(1e6),actions:p(BH).max(1e5),observations:p(FH).max(1e5),terminal:A(),failureClass:zU.nullable(),output:re(r(),ce()),contentHash:Qe}).strict();var KH=25*1024*1024,WH=c({path:gr.shape.path,base64:r().max(Math.ceil(KH/3)*4)}).strict(),_1=c({schemaVersion:S("openpond.harnessSourcePackage.v1"),agentSnapshot:LH,harnessRelease:qH,files:p(WH).max(1e4)}).strict();_1.extend({contentHash:Qe}).strict();_1.extend({schemaVersion:S("openpond.harnessPolicySourcePackage.v1"),contentHash:Qe}).strict();c({schemaVersion:S("openpond.harnessSourceSelection.v1"),mode:b(["taskset_owned","selected_release"]),harnessRelease:Je,sourcePackageHash:Qe.nullable()}).strict().superRefine((e,t)=>{e.mode==="selected_release"!=(e.sourcePackageHash!==null)&&t.addIssue({code:"custom",path:["sourcePackageHash"],message:"Only a selected release binds a source package."})});var Lo=r().trim().min(1).max(1e5),GH=b(["no_action","harness_maintenance","runtime","product","taskset","model_improvement"]),ZH=b(["none","runtime_service","product_team","human_review","evaluation_system","training_system"]),C1=b(["observation","trigger","route_decision","refiner_outcome","proposal","validation","apply_receipt","harness_advance","rollback","work_outcome","taskset","evaluation","training_qualification","model_candidate"]),qg=c({kind:b(["personal","team"]),id:Fe}).strict(),R1=c({policy:Je,state:b(["authorized","revoked","deleted","expired"]),checkedAt:wt}).strict(),$l=c({evidence:Je,kind:C1,sourceRef:Fe,sourcePolicy:R1,occurrenceKey:Qe,occurredAt:wt}).strict(),JH=c({evidence:Je,sourcePolicy:R1.nullable(),reason:b(["outside_scope","before_watermark","duplicate","resolved","revoked","deleted","expired","sensitive","unverified","budget"])}).strict(),_y=c({cursor:Qe,throughCreatedAt:wt}).strict(),YH=c({fingerprint:Qe,recurrenceFamily:r().trim().min(1).max(1e3),statement:Lo,candidateDisposition:b(["observe","confirm"]).optional(),independentOccurrences:u().int().positive().max(1e6),unresolvedOccurrences:u().int().positive().max(1e6)}).strict().refine(e=>e.unresolvedOccurrences<=e.independentOccurrences,"unresolved occurrences cannot exceed independent occurrences"),P1=b(["harness","runtime","product","retrieval","tools","evaluation","model"]),QH=c({layer:P1,status:b(["not_applicable","unresolved","resolved","blocked"]),reason:Lo,evidenceRefs:p(Je).max(1e3)}).strict(),XH=c({schemaVersion:S("openpond.harnessEvaluationReviewReceipt.v1"),id:Fe,ownerScope:qg,workspaceRef:Fe,harnessRelease:Je,previousWatermark:_y.nullable(),nextWatermark:_y,selectedEvidence:p($l).max(1e4),excludedEvidence:p(JH).max(1e4),claim:YH.nullable(),classification:GH,triage:p(QH).max(16),reason:Lo,nextAuthority:ZH,maxEstimatedCostUsd:u().finite().nonnegative(),tasksetProposal:Je.nullable(),evaluation:Je.nullable(),trainingQualification:Je.nullable(),policyVersion:Fe,createdAt:wt,metadata:Ru}).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"})});XH.extend({contentHash:Qe}).strict();c({id:Fe,evidence:Je,kind:C1,sourceRef:Fe,occurredAt:wt,payload:re(r(),ce())}).strict();var ez=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("no_action"),reason:Lo,ignoredEvidence:p(c({id:Fe,reason:r().trim().min(1).max(2e3)}).strict()).max(1e3)}).strict(),tz=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("review"),classification:b(["harness_maintenance","runtime","product","taskset"]),selectedEvidenceIds:p(Fe).min(1).max(1e3),ignoredEvidence:p(c({id:Fe,reason:r().trim().min(1).max(2e3)}).strict()).max(1e3),recurrenceFamily:r().trim().min(1).max(1e3),statement:Lo,triageLayer:P1,expectedOutcome:Lo,counterevidence:r().trim().max(1e4),confidence:u().min(0).max(1),candidateDisposition:b(["observe","confirm"]).nullable(),reason:Lo}).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"]})}),nz=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("resolve_candidate"),candidateId:Fe,candidateFingerprint:Qe,selectedEvidenceIds:p(Fe).min(1).max(1e3),ignoredEvidence:p(c({id:Fe,reason:r().trim().min(1).max(2e3)}).strict()).max(1e3),confidence:u().min(0).max(1),reason:Lo}).strict();It("decision",[ez,tz,nz]);c({schemaVersion:S("openpond.harnessEvaluationReviewNavigationDecision.v1"),selectedEvidenceIds:p(Fe).min(1).max(50),reason:Lo}).strict();var Ps=re(r(),ce()).default({}),xa=u().int().nonnegative(),Au=r().trim().min(1).max(1e5),A1=c({kind:b(["personal","team"]),id:Fe}).strict(),az=c({name:Fe,release:Je.nullable(),revision:xa}).strict();c({schemaVersion:S("openpond.harnessWorkspace.v1"),id:Fe,ownerScope:A1,name:r().trim().min(1).max(240),location:b(["local","hosted"]),sourceRevision:r().trim().min(1).max(500),revision:xa,dirty:A(),currentChannel:az,createdAt:wt,updatedAt:wt,metadata:Ps}).strict();var ps=b(["runtime","memory","prompt","skill","agent","product","taskset","training"]),T1=b(["text_instruction","memory","dependency_selection","executable_code","business_logic","financial_logic","permission","connected_app","publication","deployment","training","model_binding","team_or_global"]),E1=c({id:Fe,route:ps,operation:b(["create","update","delete"]),target:r().trim().min(1).max(2e3),summary:r().trim().min(1).max(2e3),content:r().max(1e6).nullable(),contentHash:Qe.nullable(),effects:p(T1).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=Jr(e.content);e.contentHash!==n&&t.addIssue({code:"custom",message:`edit contentHash is ${e.contentHash}; expected ${n}`,path:["contentHash"]})}),M1=c({workspaceId:Fe,revision:xa,sourceRevision:r().trim().min(1).max(500),channelRevision:xa}).strict(),Uo=c({id:Fe,revision:xa,contentHash:Qe}).strict();c({schemaVersion:S("openpond.harnessTurnSnapshot.v1"),workspaceId:Fe,workspaceRevision:xa,sourceRevision:r().trim().min(1).max(500),channelName:Fe,channelRevision:xa,harnessRelease:Je,toolCatalogHash:Qe.nullable().optional(),overlay:Uo.nullable().optional().default(null)}).strict();var oz=c({schemaVersion:S("openpond.harnessRunOverlay.v1"),id:Fe,runId:Fe,baseHarnessRelease:Je,workspace:M1,revision:xa,status:b(["active","frozen","abandoned"]),edits:p(E1).max(1e3),createdAt:wt,updatedAt:wt,metadata:Ps}).strict();oz.extend({contentHash:Qe}).strict();var j1=c({kind:b(["tool_event","recovery","validation","user_turn","work_output","work_receipt"]),id:Fe,contentHash:Qe.nullable()}).strict(),O1=c({id:Fe,kind:b(["dependency","schema","package","file_render","skill","prompt","business_formula","targeted_evaluation","observed_recovery","memory","component_activation"]),description:Au,required:A()}).strict(),rz=c({schemaVersion:S("openpond.harnessImprovementProposal.v1"),id:Fe,overlay:Uo,baseHarnessRelease:Je,expectedWorkspace:M1,requestedScope:b(["personal","team","global"]),route:ps,risk:b(["low","review","restricted"]),effects:p(T1).min(1).max(20),evidence:p(j1).min(1).max(1e3),edits:p(E1).min(1).max(1e3),validationPlan:p(O1).min(1).max(100),expectedOutcome:Au,createdAt:wt,metadata:Ps}).strict().superRefine((e,t)=>{const n=new Set(e.effects);for(const[a,o]of e.edits.entries()){o.route!==e.route&&t.addIssue({code:"custom",message:"every edit route must match the proposal route",path:["edits",a,"route"]});for(const i of o.effects)n.has(i)||t.addIssue({code:"custom",message:`edit effect ${i} is missing from proposal effects`,path:["edits",a,"effects"]})}new Set(e.validationPlan.map(a=>a.id)).size!==e.validationPlan.length&&t.addIssue({code:"custom",message:"validation plan ids must be unique",path:["validationPlan"]})});rz.extend({contentHash:Qe}).strict();var iz=c({schemaVersion:S("openpond.harnessTargetedValidationReceipt.v1"),id:Fe,proposal:Je,validationId:Fe,kind:O1.shape.kind,status:b(["passed","failed","blocked","skipped"]),summary:Au,evidenceRefs:p(j1).max(1e3),createdAt:wt,metadata:Ps}).strict();iz.extend({contentHash:Qe}).strict();var sz=b(["advanced","retained","conflict","rolled_back"]),lz=c({schemaVersion:S("openpond.harnessAdvanceReceipt.v1"),id:Fe,workspaceId:Fe,ownerScope:A1,proposal:Je.nullable(),expectedWorkspaceRevision:xa,observedWorkspaceRevision:xa,previousChannelRevision:xa,nextChannelRevision:xa,previousRelease:Je.nullable(),nextRelease:Je.nullable(),validationReceipts:p(Je).max(100),decision:sz,reason:Au,rollbackOf:Je.nullable(),createdAt:wt,metadata:Ps}).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"]})});lz.extend({contentHash:Qe}).strict();var cz=c({schemaVersion:S("openpond.harnessOverlayMergeReceipt.v1"),id:Fe,workspaceId:Fe,baseHarnessRelease:Je,leftOverlay:Uo,rightOverlay:Uo,decision:b(["merged","conflict"]),mergedOverlay:Uo.nullable(),conflictTargets:p(r().trim().min(1).max(2e3)).max(1e3),requiresRevalidation:S(!0),createdAt:wt,metadata:Ps}).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"]})});cz.extend({contentHash:Qe}).strict();var Tu=r().trim().min(1).max(1e5),ic=re(r(),ce()).default({}),dz=b(["completed_tool_batch","before_model_step","turn_completed","turn_paused"]),$1=c({kind:dz,eventSequence:u().int().nonnegative(),occurredAt:wt}).strict(),N1=c({id:Fe,sequence:u().int().nonnegative().nullable(),contentHash:Qe}).strict(),uz=b(["tool_failure","retry","recovery","validation","user_turn","reusable_success","completion_detour"]),mz=b(["open","recovered","terminal"]),pz=c({name:r().trim().min(1).max(500),invocationKey:Qe}).strict(),fz=c({schemaVersion:S("openpond.improvementObservation.v1"),id:Fe,runRef:Fe,turnId:Fe,harnessRelease:Je,overlay:Uo.nullable(),eventRefs:p(N1).min(1).max(100),kind:uz,state:mz,tool:pz.nullable(),deterministicClass:r().trim().min(1).max(500).nullable(),summary:Tu,createdAt:wt,metadata:ic}).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"]})});fz.extend({contentHash:Qe}).strict();var hz=c({schemaVersion:S("openpond.refinementTriggerPolicy.v1"),maxEstimatedCostUsd:u().finite().nonnegative(),cooldownMs:u().int().nonnegative(),maxPendingPlans:u().int().min(1).max(100),maxEvidenceEvents:u().int().min(1).max(1e3),maxProposalEdits:u().int().min(1).max(1e3),maxProposalBytes:u().int().min(1).max(1e7)}).strict(),gz=b(["no_action","route_deterministically","queue_refiner"]),vz=c({schemaVersion:S("openpond.refinementTriggerDecision.v1"),id:Fe,runRef:Fe,turnId:Fe,harnessRelease:Je,overlay:Uo.nullable(),observations:p(Je).max(100),decision:gz,deterministicRoute:ps.nullable(),suggestedRoutes:p(ps).max(8),reason:Tu,deduplicationKey:Qe,policy:hz,estimatedMaxCostUsd:u().finite().nonnegative(),pendingPlanCount:u().int().nonnegative(),boundary:$1,cooldownUntil:wt.nullable(),createdAt:wt,metadata:ic}).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"]})});vz.extend({contentHash:Qe}).strict();var bz=b(["runtime_service","refiner_model","human_review","evaluation_system","training_system"]),yz=c({schemaVersion:S("openpond.improvementRouteDecision.v1"),id:Fe,trigger:Je,route:ps,authority:bz,automatic:A(),reason:Tu,createdAt:wt,metadata:ic}).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"]})});yz.extend({contentHash:Qe}).strict();var Sz=c({schemaVersion:S("openpond.harnessRefinerOutcome.v1"),id:Fe,trigger:Je,decision:b(["no_action","proposed"]),proposal:Je.nullable(),reason:Tu,evidenceRefs:p(Je).max(100),estimatedCostUsd:u().finite().nonnegative(),createdAt:wt,metadata:ic}).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"]})});Sz.extend({contentHash:Qe}).strict();var xz=b(["applied","retained","declined","conflict","rolled_back"]),kz=c({schemaVersion:S("openpond.improvementApplyReceipt.v1"),id:Fe,proposal:Je,beforeOverlay:Uo,afterOverlay:Uo.nullable(),decision:xz,boundary:$1,validationRefs:p(Je).max(100),outcomeEvidenceRefs:p(N1).max(1e3),rollbackOf:Je.nullable(),createdAt:wt,metadata:ic}).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"]})});kz.extend({contentHash:Qe}).strict();c({provider:Fe,model:Fe,revision:r().trim().min(1).max(500).nullable().default(null),artifactHash:Qe.nullable().default(null),tokenizerRevision:r().trim().min(1).max(500).nullable().default(null),chatTemplateHash:Qe.nullable().default(null)}).strict();var wz=["openpond","codex","anthropic","openai","xai","google","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],Iz=b(wz),D1=c({providerId:Iz,modelId:r().trim().min(1).max(300)}),_z=r().trim().min(1).max(2e3),Bg=r().trim().min(1).max(1e5),Cz=b(["create","update","delete"]),Rz=b(["memory","prompt","skill","agent"]),Pz=b(["runtime","product","taskset","training"]),Az=b(["no_action","routed","applied","retained","failed"]),Tz=b(["not_applicable","pending","passed","rejected","failed"]),Ez=b(["not_applicable","pending","passed","failed"]),Mz=c({schemaVersion:S("openpond.harnessRefinerActivityReceipt.v1"),id:Fe,runRef:Fe,turnId:Fe,result:Az,decision:b(["no_action","route","propose"]).nullable(),route:ps.nullable(),operation:Cz.nullable(),target:r().trim().min(1).max(2e3).nullable(),summary:_z,evidenceBasis:Dg.nullable(),critiqueStatus:Tz,validationStatus:Ez,trigger:Je,outcome:Je.nullable(),proposal:Je.nullable(),applyReceipt:Je.nullable(),inputHarness:Je,outputHarness:Je.nullable(),createdAt:wt}).strict().superRefine((e,t)=>{const n=e.result==="applied"||e.result==="retained";e.result==="no_action"?Cy(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"||!Pz.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"}),Cy(t,e,{critiqueStatus:"not_applicable",validationStatus:"not_applicable"})):n?((e.decision!=="propose"||!Rz.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"]})});Mz.extend({contentHash:Qe}).strict();var jz=b(["unresolved","confirmed","resolved","rejected","expired"]),Oz=c({kind:b(["applied_change","later_success","manual_rejection","source_revoked","expired"]),reason:Bg,evidenceRefs:p(Je).max(1e3),resolvedAt:wt}).strict(),$z=c({schemaVersion:S("openpond.harnessRefinementCandidate.v1"),id:Fe,ownerScope:qg,workspaceRef:Fe,fingerprint:Qe,recurrenceFamily:r().trim().min(1).max(1e3),statement:Bg,status:jz,occurrences:p($l).max(1e3),counterevidence:p($l).max(1e3),sourceReviews:p(Je).min(1).max(100),relatedHarnessReleases:p(Je).max(100),firstSeenAt:wt,lastSeenAt:wt,lastReviewedAt:wt,expiresAt:wt,resolution:Oz.nullable(),createdAt:wt,updatedAt:wt}).strict().superRefine((e,t)=>{Kr(t,e.occurrences,"occurrences"),Kr(t,e.counterevidence,"counterevidence"),Kr(t,e.sourceReviews,"sourceReviews"),Kr(t,e.relatedHarnessReleases,"relatedHarnessReleases");const n=new Set(e.occurrences.map(o=>o.occurrenceKey));e.counterevidence.some(o=>n.has(o.occurrenceKey))&&t.addIssue({code:"custom",message:"supporting occurrences and counterevidence must be disjoint",path:["counterevidence"]});const a=e.status==="unresolved"||e.status==="confirmed";a&&e.occurrences.length===0&&t.addIssue({code:"custom",message:"actionable candidates require at least one supporting occurrence",path:["occurrences"]}),a&&[...e.occurrences,...e.counterevidence].some(o=>o.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"actionable candidates may contain only currently authorized evidence",path:["occurrences"]}),a!==(e.resolution===null)&&t.addIssue({code:"custom",message:"only resolved, rejected, or expired candidates require a resolution",path:["resolution"]}),e.status==="expired"&&e.resolution?.kind!=="expired"&&t.addIssue({code:"custom",message:"expired candidates require an expired resolution",path:["resolution","kind"]}),e.status==="rejected"&&e.resolution&&!["manual_rejection","source_revoked"].includes(e.resolution.kind)&&t.addIssue({code:"custom",message:"rejected candidates require a rejection or revocation resolution",path:["resolution","kind"]}),e.status==="resolved"&&e.resolution&&!["applied_change","later_success"].includes(e.resolution.kind)&&t.addIssue({code:"custom",message:"resolved candidates require applied-change or later-success evidence",path:["resolution","kind"]}),Hz(t,e)});$z.extend({contentHash:Qe}).strict();var Nz=b(["created","merged","rejected","expired","reopened","resolved"]),Dz=c({schemaVersion:S("openpond.harnessRefinementCandidateLifecycleReceipt.v1"),id:Fe,candidateId:Fe,decision:Nz,beforeCandidate:Je.nullable(),afterCandidate:Je,review:Je,addedEvidence:p($l).max(1e3),removedEvidence:p(Je).max(1e3),reason:Bg,createdAt:wt}).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"]}),Kr(t,e.addedEvidence,"addedEvidence"),Kr(t,e.removedEvidence,"removedEvidence");const n=new Set(e.removedEvidence.map(a=>Wf(a)));e.addedEvidence.some(a=>n.has(Wf(a.evidence)))&&t.addIssue({code:"custom",message:"candidate lifecycle evidence cannot be added and removed together",path:["removedEvidence"]})});Dz.extend({contentHash:Qe}).strict();var Lz=c({schemaVersion:S("openpond.harnessCrossRunRefinementRequest.v1"),id:Fe,ownerScope:qg,workspaceRef:Fe,candidate:Je,candidateFingerprint:Qe,review:Je,admittedHarness:Je,evidence:p($l).min(1).max(1e3),capabilities:Lg,deduplicationKey:Qe,createdAt:wt}).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"]}),Kr(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=Uz(e);e.deduplicationKey!==n&&t.addIssue({code:"custom",message:`cross-run refinement deduplicationKey is ${e.deduplicationKey}; expected ${n}`,path:["deduplicationKey"]})});Lz.extend({contentHash:Qe}).strict();function Uz(e){return Jr({schemaVersion:"openpond.harnessCrossRunRefinementIdentity.v1",workspaceRef:e.workspaceRef,candidateFingerprint:e.candidateFingerprint,admittedHarness:e.admittedHarness})}function Cy(e,t,n){for(const[a,o]of Object.entries(n))t[a]!==o&&e.addIssue({code:"custom",message:`${a} must be ${String(o)}`,path:[a]})}function Kr(e,t,n){const a=t.map(o=>Wf(o));new Set(a).size!==a.length&&e.addIssue({code:"custom",message:`${n} references must be unique`,path:[n]})}function Wf(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 Hz(e,t){const n=[["firstSeenAt",t.firstSeenAt],["lastSeenAt",t.lastSeenAt],["lastReviewedAt",t.lastReviewedAt],["updatedAt",t.updatedAt],["expiresAt",t.expiresAt]];for(let a=1;a<n.length;a+=1){const o=n[a-1],i=n[a];Date.parse(o[1])<=Date.parse(i[1])||e.addIssue({code:"custom",message:`${i[0]} must not precede ${o[0]}`,path:[i[0]]})}Date.parse(t.createdAt)>Date.parse(t.updatedAt)&&e.addIssue({code:"custom",message:"updatedAt must not precede createdAt",path:["updatedAt"]})}c({path:r().min(1).max(2e3),offset:u().int().nonnegative().default(0),length:u().int().positive().max(65536).default(16384)}).strict();var L1=r().regex(/^[a-z][a-z0-9_-]{0,119}$/),U1=r().min(1).max(2e3).refine(e=>!e.includes("\\")&&!e.includes(":")&&!e.startsWith("/")&&e.split("/").every(t=>t!==""&&t!=="."&&t!==".."),"workflow references require portable relative paths"),zz=c({id:L1,label:r().trim().min(1).max(240),description:r().max(4e3),inputSchema:re(r(),ce()),invocation:It("kind",[c({kind:S("instructions"),instructions:r().min(1).max(1e5).refine(e=>!!e.trim())}).strict(),c({kind:S("agent_action"),actionId:r().trim().min(1).max(240)}).strict()]),skillPaths:p(U1).max(100)}).strict();c({schemaVersion:S("openpond.profileWorkflows.v1"),workflows:p(zz).max(1e3)}).strict();var qz=c({id:r().trim().min(1).max(240),agentId:r().regex(/^[a-zA-Z0-9_-]{1,240}$/),sourceActionId:r().trim().min(1).max(240),inputSchema:re(r(),ce())}).strict();c({schemaVersion:S("openpond.profileWorkflowActions.v1"),actions:p(qz).max(200)}).strict();c({schemaVersion:S("openpond.profileWorkflowBinding.v1"),profileId:r().trim().min(1).max(240),sourceRevision:r().trim().min(1).max(240),harnessRelease:Je,catalogHash:Qe,workflowId:L1}).strict();c({schemaVersion:S("openpond.profileComponentBinding.v1"),profileId:r().trim().min(1).max(240),sourceRevision:r().trim().min(1).max(240),harnessRelease:Je,target:It("kind",[c({kind:S("profile")}).strict(),c({kind:S("skill"),skillPath:U1}).strict(),c({kind:S("agent_action"),actionId:r().trim().min(1).max(240)}).strict()])}).strict();var Ud=r().min(1).max(2e3).refine(e=>!e.includes("\\")&&!e.includes(":")&&!e.startsWith("/")&&e.split("/").every(t=>t!==""&&t!=="."&&t!==".."),"source paths must be portable relative paths");r().regex(/^[a-z][a-z0-9_-]{0,119}$/);var Bz={type:"object",properties:{},additionalProperties:!1};c({name:r().trim().min(1).max(240).optional(),description:r().max(4e3).optional(),skillPaths:p(Ud).max(100).optional(),assetPaths:p(Ud).max(100).optional()}).strict();c({actionId:r().trim().min(1).max(240),name:r().trim().min(1).max(240),description:r().max(4e3).default(""),inputSchema:re(r(),ce()).default(Bz),skillPaths:p(Ud).max(100).default([]),assetPaths:p(Ud).max(100).default([])}).strict();var _a=r().trim().min(1).max(240),Ho=r().trim().min(1),yr=r().trim().min(8).max(256),H1=r().trim().min(1).max(1e3).refine(e=>!e.startsWith("/")&&!e.startsWith("\\")&&!e.split(/[\\/]/).includes(".."),"Artifact paths must be relative and stay inside the Dataset."),wr=b(["train","validation","test","frozen_eval"]),Fz=c({name:r().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:A(),policy:b(["visible","privileged","metadata"])}),Vz=c({schemaVersion:S("openpond.datasetSemanticSchema.v1"),fields:p(Fz).min(1).max(1e4),schemaHash:yr}),Kz=c({id:_a,split:wr,path:H1,contentHash:yr,schemaHash:yr,sizeBytes:u().int().nonnegative(),rowCount:u().int().positive(),rowGroupCount:u().int().positive()}),Fg=c({schemaVersion:S("openpond.datasetArtifact.v1"),id:_a,tasksetId:_a,tasksetRevision:u().int().positive(),contentHash:yr,format:S("parquet"),schema:Vz,shards:p(Kz).min(1).max(1e5),rowCount:u().int().positive(),splitCounts:re(wr,u().int().nonnegative()),sourceReceiptRefs:p(_a).min(1).max(1e5),mappingHash:yr,qualityReportHash:yr,createdAt:Ho}),Wz=c({schemaVersion:S("openpond.datasetArtifactSummary.v1"),artifactId:_a,tasksetId:_a,tasksetRevision:u().int().positive(),format:S("parquet"),rowCount:u().int().positive(),splitCounts:re(wr,u().int().nonnegative()),sizeBytes:u().int().nonnegative(),contentHash:yr,available:A(),unavailableReason:r().trim().min(1).max(2e3).nullable(),createdAt:Ho}),Gz=c({schemaVersion:S("openpond.datasetCatalogItem.v1"),tasksetId:_a,tasksetRevision:u().int().positive(),artifactId:_a.nullable(),name:r().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:u().int().nonnegative(),splitCounts:re(wr,u().int().nonnegative()),sizeBytes:u().int().nonnegative().nullable(),available:A(),unavailableReason:r().trim().min(1).max(2e3).nullable(),createdAt:Ho,updatedAt:Ho});c({schemaVersion:S("openpond.datasetCatalog.v1"),profileId:_a,datasets:p(Gz),generatedAt:Ho});c({schemaVersion:S("openpond.datasetArtifactRegistry.v1"),manifest:Fg,profileId:_a,storageRoot:r().trim().min(1).max(4e3),relativeManifestPath:H1,available:A(),unavailableReason:r().trim().min(1).max(2e3).nullable(),verifiedAt:Ho.nullable(),createdAt:Ho,updatedAt:Ho});c({split:wr.nullable().default(null),cursor:r().trim().min(1).max(2e3).nullable().default(null),limit:u().int().min(1).max(100).default(25),columns:p(r().trim().min(1).max(500)).max(100).default([])});c({schemaVersion:S("openpond.datasetRowPage.v1"),tasksetId:_a,tasksetRevision:u().int().positive(),artifactHash:yr,split:wr.nullable(),rows:p(re(r(),ce())).max(100),nextCursor:r().max(2e3).nullable(),totalRows:u().int().nonnegative(),returnedRows:u().int().nonnegative()});var Zz=c({schemaVersion:S("openpond.datasetStorageSettings.v1"),datasetStorePath:r().trim().min(1).max(4e3),updatedAt:Ho}),Jz=c({id:_a,label:r().trim().min(1).max(500),path:r().trim().min(1).max(4e3),datasetStorePath:r().trim().min(1).max(4e3),kind:b(["local","network","removable","cache"]),configured:A(),mounted:A(),writable:A(),totalBytes:u().int().nonnegative().nullable(),freeBytes:u().int().nonnegative().nullable()});c({schemaVersion:S("openpond.datasetStorageState.v1"),settings:Zz,storageRoots:p(Jz)});c({datasetStorePath:r().trim().min(1).max(4e3)});var as=r().trim().min(1).max(240),Yz=r().trim().min(1),fs=r().trim().min(8).max(256),Qz=re(r(),ce()).default({}),Xz=r().trim().min(7).max(256),eq=b(["pending","approved","review","blocked"]),Eu=c({id:as,profileId:as,title:r().trim().min(1).max(500),sourceHash:fs,occurredAt:Yz,licensingStatus:eq,secretScanStatus:b(["pending","passed","blocked"]),piiScanStatus:b(["pending","passed","review","blocked"]),metadata:Qz}),tq=Eu.extend({schemaVersion:S("openpond.huggingFaceDatasetSource.v1"),kind:S("huggingface"),repositoryId:r().trim().regex(/^[^/\s]+\/[^/\s]+$/).max(500),repositoryUrl:r().url().max(2e3),revision:Xz,configuration:r().trim().min(1).max(500),upstreamSplits:p(r().trim().min(1).max(500)).min(1).max(1e3),gated:A(),private:A(),declaredLicense:r().trim().min(1).max(500).nullable(),sourceFileHashes:p(fs).min(1).max(1e5)}),nq=Eu.extend({schemaVersion:S("openpond.uploadedFileDatasetSource.v1"),kind:S("uploaded_file"),originalFileNames:p(r().trim().min(1).max(500)).min(1).max(1e3),mediaTypes:p(r().trim().min(1).max(200)).min(1).max(1e3),sourceFileHashes:p(fs).min(1).max(1e3),totalBytes:u().int().nonnegative(),parserVersion:r().trim().min(1).max(200)}),aq=Eu.extend({schemaVersion:S("openpond.generatedDatasetSource.v1"),kind:S("generated"),generatorId:as,generatorVersion:r().trim().min(1).max(200),seed:u().int(),generatorHash:fs}),oq=Eu.extend({schemaVersion:S("openpond.learningBatchDatasetSource.v1"),kind:S("learning_batch"),batch:c({id:as,revision:u().int().positive(),contentHash:fs}).strict(),taskDefinition:c({id:as,revision:u().int().positive(),contentHash:fs}).strict(),admittedBy:as}),rq=It("kind",[tq,nq,aq,oq]),iq=c({schemaVersion:S("openpond.harnessActionBinding.v1"),actionId:Fe,modelToolName:r().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:r().trim().min(1).max(1e3),inputSchema:re(r(),ce()),actionSchemaHash:Qe,agentRelease:Je,implementationHash:Qe,runtimeBindingId:Fe,capabilityReceiptHash:Qe,sideEffect:b(["read","write"]),studentVisible:A(),timeoutMs:u().int().positive().max(36e5),episodeArgumentBindings:p(c({argument:Fe,source:S("case_id")}).strict()).max(20).default([])}).strict(),Rt=r().trim().min(1).max(240),Vg=r().trim().min(1),sq=r().trim().min(8).max(256),Kg=r().trim().regex(/^[a-f0-9]{64}$/),lq=r().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),Ka=re(r(),ce()).default({}),Mu=Rt.nullable();function sc(e){const t=e.trim().replaceAll("\\","/");return!t||t.startsWith("/")||t==="."||t===".."?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function cq(e){const t=e.trim();return t.length>0&&t!=="."&&t!==".."&&!t.includes("/")&&!t.includes("\\")&&!t.includes("\0")}var hs=wr,z1=b(["general","benchmark"]),q1=c({schemaVersion:S("openpond.tasksetBenchmark.v1"),definitionId:Rt,releaseId:Rt,releaseHash:Kg,managedReleasePath:r().trim().min(1).max(1e3).refine(sc,"Benchmark release paths must remain relative."),adaptationSplit:hs,evaluationSplit:hs,primaryMetric:b(["foreground_tokens","success_rate","latency_ms","cost_usd"]),qualityGate:b(["none","non_regression","all_pass"]),source:b(["builtin","imported"]),metadata:Ka}),B1=c({schemaVersion:S("openpond.tasksetPreferenceComparisonBinding.v1"),releaseId:Rt,releaseHash:Kg,publishedAt:Vg,metadata:Ka}),dq=c({status:b(["pending","granted","denied","revoked"]),scope:b(["metadata_only","selected_turns","full_session"]),grantedBy:Mu,grantedAt:Vg.nullable(),purpose:S("task_authoring_and_evaluation")}),F1=c({schemaVersion:S("openpond.trainingSource.v1"),id:Rt,profileId:Rt,sessionId:Rt,turnIds:p(Rt).max(1e3).default([]),workspaceId:Mu,sourceHash:sq,clusterKey:Rt,title:r().trim().min(1).max(500),occurredAt:Vg,consent:dq,connectedAppIds:p(Rt).max(100).default([]),secretScanStatus:b(["pending","passed","blocked"]),piiScanStatus:b(["pending","passed","review","blocked"]),licensingStatus:b(["pending","approved","review","blocked"]),metadata:Ka}),V1=Dt([F1,rq]),Wg=c({policyVisibleFields:p(Rt).max(1e3).default([]),privilegedFields:p(Rt).max(1e3).default([]),hiddenGraderRefs:p(Rt).max(100).default([]),connectedAppScopes:p(Rt).max(100).default([])}),uq=c({id:Rt,sourceRefId:Rt,artifactRef:r().trim().min(1).max(4e3).refine(sc,"Task asset references must be safe relative paths."),fileName:r().trim().min(1).max(500).refine(cq,"Task asset file names must not contain path separators."),mediaType:r().trim().min(1).max(200),sha256:Kg,sizeBytes:u().int().nonnegative().max(25e7),split:hs,metadata:Ka}),mq=c({path:r().trim().min(1).max(1e3).refine(sc,"Required output paths must stay inside the Work output directory."),mediaType:r().trim().min(1).max(200),schemaRef:Rt.nullable().optional(),maxBytes:u().int().positive().max(1e7).optional(),metadata:Ka}),Gg=c({schemaVersion:S("openpond.taskData.v1"),id:Rt,clusterKey:Rt,split:hs,input:re(r(),ce()),expectedOutput:re(r(),ce()).nullable(),policyVisibleContext:re(r(),ce()).default({}),privilegedContextRef:Mu,sourceRefs:p(Rt).min(1).max(100),assets:p(uq).max(1e3).optional(),resourceRefs:p(Rt).max(1e3).optional(),requiredOutputs:p(mq).max(100).optional(),tags:p(Rt).max(100).default([]),metadata:Ka}),pq=c({id:Rt,kind:b(["file","catalog","configuration","code_module"]),path:r().trim().min(1).max(1e3).refine(sc,"Environment resource paths must remain relative."),mediaType:r().trim().min(1).max(200).nullable().optional(),visibility:b(["policy_visible","policy_hidden","privileged"]),required:A(),metadata:Ka}),As=c({id:Rt,taskId:Mu,sourceRefs:p(Rt).min(1).max(100),artifactRef:Rt,approved:A(),confidence:u().min(0).max(1),metadata:Ka}),K1=As.extend({kind:S("demonstration"),prompt:r().max(1e5).nullable().default(null),response:r().max(2e5).nullable().default(null)}),W1=As.extend({kind:S("preference"),prompt:r().max(1e5),chosen:r().max(2e5),rejected:r().max(2e5),rationale:r().max(1e5).nullable().default(null)}),G1=As.extend({kind:S("correction"),original:r().max(2e5),corrected:r().max(2e5),rationale:r().max(1e5).nullable().default(null)}),Z1=As.extend({kind:S("feedback"),feedback:r().max(1e5),polarity:b(["positive","negative","mixed","neutral"])}),J1=As.extend({kind:S("reward"),task:r().max(1e5),rules:p(c({id:Rt,points:u().finite(),condition:r().trim().min(1).max(1e5)})).min(1).max(1e3),otherwisePoints:u().finite(),executable:A()}),Y1=As.extend({kind:S("label"),labelKind:S("rubric"),task:r().max(1e5),criteria:p(c({id:Rt,label:r().trim().min(1).max(500),description:r().trim().min(1).max(1e5)})).min(1).max(1e3),calibrationExamples:c({positive:r().trim().min(1).max(2e5),negative:r().trim().min(1).max(2e5),boundary:r().trim().min(1).max(2e5)})});It("kind",[K1,W1,G1,Z1,J1,Y1]);var Q1=c({demonstrations:p(K1).max(1e5).default([]),preferences:p(W1).max(1e5).default([]),corrections:p(G1).max(1e5).default([]),feedback:p(Z1).max(1e5).default([]),rewards:p(J1).max(1e5).default([]),labels:p(Y1).max(1e5).default([])}),X1=c({protocolVersion:S("openpond.taskEnvironment.v1"),kind:b(["chat","agent","program","stateful_harness","work"]),entrypoint:r().trim().min(1).max(1e3),stateful:A(),deterministicSeeds:A(),toolNames:p(Rt).max(200).default([]),actionBindings:p(iq).max(200).optional(),lifecycle:p(b(["create","reset","step","grade","cleanup"])).min(1),defaultTimeoutMs:u().int().positive().max(36e5),networkPolicy:b(["none","declared_read_only","declared_scoped"]),resources:p(pq).max(1e4).optional(),metadata:Ka}),Zg=c({schemaVersion:S("openpond.tasksetCapabilities.v1"),taskKind:b(["chat","single_agent","multi_agent","custom_program"]),supportedSignals:p(b(["demonstration","preference","correction","feedback","reward","label"])),compatibleMethods:p(b(["none","retrieval","sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"])),rewardKinds:p(b(["none","exact","deterministic","model_judge","human"])),requiresTools:A(),requiresState:A(),requiresPrivilegedGrading:A(),environmentPlacements:p(b(["local","remote","colocated","provider_native"])),exportable:A(),portabilityBlockers:p(r().trim().min(1).max(2e3)).default([])}),ju=c({id:Rt,version:r().trim().min(1).max(100),label:r().trim().min(1).max(500),weight:u().min(0).max(1e3).default(1),hardGate:A().default(!1),rewardEligible:A().default(!1),privileged:A().default(!1),metadata:Ka}),fq=ju.extend({kind:b(["content","schema","file","diff","test","runtime_event","state"]),config:re(r(),ce())}),hq=ju.extend({kind:S("model_judge"),rubric:r().trim().min(1).max(5e4),judge:D1,calibrationFixtureRefs:p(Rt).min(1).max(500),calibrationStatus:b(["pending","passed","failed"]),temperature:u().min(0).max(2).default(0)}),gq=ju.extend({kind:S("human"),rubric:r().trim().min(1).max(5e4),reviewerRole:r().trim().min(1).max(500)}),vq=ju.extend({kind:S("custom_verifier"),runtime:Hw.optional(),module:r().trim().min(1).max(1e3).refine(sc,"Custom verifier modules must use a safe relative path."),exportName:lq,timeoutMs:u().int().positive().max(3e5),networkPolicy:S("none")}),Ou=Dt([fq,hq,gq,vq]),Jg=b(["positive","negative","boundary","adversarial","prompt_injection","infrastructure_failure"]),eI=c({id:Rt,taskId:Rt,label:Jg,output:re(r(),ce()),infrastructureError:r().trim().min(1).max(1e4).nullable(),expectedPassed:A(),expectedRewardEligible:A(),metadata:Ka}),lo=r().trim().min(1).max(240),Nl=r().trim().min(1),Hd=r().trim().min(8).max(256),tI=re(r(),ce()).default({}),bq=lo.nullable(),yq=b(["draft","awaiting_disclosure_approval","awaiting_materialization_approval","materializing","validating","needs_review","baselining","ready","blocked","failed","archived"]),nI=b(["demonstrations","preferences","verifiable_reward","rubric","discovery"]),Ln=r().trim().max(1e5),aI=It("kind",[c({kind:S("demonstrations"),behavior:Ln,examples:p(c({id:lo,prompt:Ln,response:Ln})).max(1e3).default([])}),c({kind:S("preferences"),preference:Ln,pairs:p(c({id:lo,prompt:Ln,chosen:Ln,rejected:Ln,rationale:Ln})).max(1e3).default([])}),c({kind:S("verifiable_reward"),task:Ln,rules:p(c({id:lo,points:u().finite(),condition:Ln})).max(1e3).default([]),otherwisePoints:u().finite().default(0)}),c({kind:S("rubric"),task:Ln,criteria:p(c({id:lo,label:r().trim().max(500),description:Ln})).max(1e3).default([]),positiveExample:Ln,negativeExample:Ln,boundaryExample:Ln})]),Sq=c({path:r().trim().min(1).max(1e3),role:b(["environment","verifier","fixture"]),content:r().max(25e4)}),oI=c({primaryMethod:b(["sft","dpo","grpo","ppo","sdft","opsd","sdpo"]),bootstrap:c({method:S("sft"),purpose:S("trajectory_bootstrap"),demonstrationRefs:p(lo).min(1).max(1e5),limitations:p(r().trim().min(1).max(5e3)).min(1).max(100)}).nullable()}),rI=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"]),xq=c({method:b(["sft","dpo","grpo","ppo"]),status:b(["recommended","compatible","needs_dataset_work"]),reasonCodes:p(rI).default([]),reasons:p(r().trim().min(1).max(5e3)).default([])}),Ry=c({code:lo,message:r().trim().min(1).max(5e3),path:r().trim().max(2e3).nullable()}),iI=c({schemaVersion:S("openpond.tasksetReadiness.v1"),tasksetId:lo,tasksetHash:Hd,ready:A(),recommendedMethod:b(["none","retrieval","sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),trainingPath:oI.nullable().default(null),methodReadiness:p(xq).default([]),compatibleDestinationClasses:p(b(["export","custom","hosted_managed"])),blockers:p(Ry).default([]),advisories:p(Ry).default([]),warnings:p(r().trim().min(1).max(5e3)).default([]),generatedAt:Nl}),sI=c({attempt:u().int().positive(),summary:r().trim().min(1).max(5e3),createdAt:Nl}),kq=c({schemaVersion:S("openpond.taskAuthoringProvenance.v1"),model:D1.nullable(),modelConfig:tI,skillHash:Hd,promptTemplateVersion:r().trim().min(1).max(200),buildIntent:nI.default("demonstrations"),buildSpecification:aI.nullable().default(null),evidenceHashes:p(Hd).max(1e5),tasksetSdkVersion:r().trim().min(1).max(100),sourceCommit:r().trim().min(1).max(256).nullable(),repairHistory:p(sI).max(1e3),createdAt:Nl}),Py=c({schemaVersion:S("openpond.taskset.v1"),id:lo,revision:u().int().positive().default(1),profileId:lo,profileRelease:UU.nullable().optional(),createImproveRunId:bq.default(null),name:r().trim().min(1).max(500),objective:r().trim().max(2e4),purpose:z1.default("general"),benchmark:q1.nullable().default(null),preferenceComparison:B1.nullable().default(null),status:yq,sourceRefs:p(V1).min(1).max(1e5),datasetArtifact:Fg.nullable().optional(),policy:Wg,environment:X1,capabilities:Zg,metrics:yu.optional(),tasks:p(Gg).max(1e6),graders:p(Ou).min(1).max(1e3),graderFixtures:p(eI).max(1e5),learningSignals:Q1,authoringProvenance:kq,readiness:iI.nullable(),contentHash:Hd,createdAt:Nl,updatedAt:Nl,metadata:tI}).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"]})});function wq(e){return e.schemaVersion==="openpond.trainingSource.v1"}var Gi=r().trim().min(1).max(240),Ay=r().trim().min(1),Iq=r().trim().min(8).max(256),_q=r().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),Cq=re(r(),ce()).default({});function Ty(e){const t=e.trim().replaceAll("\\","/");return!t||t.startsWith("/")||t==="."||t===".."?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}var lI=Gg.extend({sourceRefs:p(Gi).max(100).default([])}),cI=b(["draft","validating","needs_review","published"]),Rq=c({enabled:A(),candidateCount:u().int().min(2).max(4),minimumSamples:u().int().min(1).max(1e4).default(100),allowTies:A(),allowRejectAll:A(),rubric:r().trim().max(5e4),criteria:p(c({id:Gi,label:r().trim().min(1).max(500),description:r().trim().max(1e4),weight:u().nonnegative().max(1e3)})).max(100)}),Pq=c({mode:b(["text","structured_json","artifacts"]),jsonSchema:re(r(),ce()).nullable(),renderer:c({module:r().trim().min(1).max(1e3).refine(Ty,"Renderer modules must use a safe relative path."),exportName:_q,configRef:r().trim().min(1).max(1e3).refine(Ty,"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"]})}),uo=c({schemaVersion:S("openpond.tasksetDraft.v1"),id:Gi,revision:u().int().positive(),profileId:Gi,modelScope:c({modelId:Gi,expectedModelRevision:u().int().positive(),source:bU.optional()}).strict().nullable().default(null),name:r().trim().max(500),objective:r().trim().max(2e4),purpose:z1.default("general"),benchmark:q1.nullable().default(null),preferenceComparison:B1.nullable().default(null),status:cI,sourceRefs:p(V1).max(1e5).default([]),datasetArtifact:Fg.nullable().optional(),policy:Wg,environment:X1,output:Pq.default({mode:"text",jsonSchema:null,renderer:null}),capabilities:Zg,metrics:yu,review:Rq,tasks:p(lI).max(1e6).default([]),graders:p(Ou).max(1e3).default([]),graderFixtures:p(eI).max(1e5).default([]),learningSignals:Q1,publishedTasksetRef:c({id:Gi,revision:u().int().positive(),contentHash:Iq}).nullable(),createdAt:Ay,updatedAt:Ay,metadata:Cq}).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"]})}),Aq=6e6,Tq=new Set(["taskset.json","capabilities.json","data/tasks.jsonl","tasks/tasks.jsonl","graders/graders.json","fixtures/grader-fixtures.json","metrics/policy.json","assets/manifest.json","environment/contract.json","environment/taskset.ts","rubrics/preference-review.md","comparisons/policy.json"]);function Eq(e){const t=Cu.parse(e);return!Tq.has(t)&&!t.startsWith("source-artifacts/")}function Ey(e,t){const n=Eq(e);if(t.byteLength>Aq)throw new Error("Taskset draft file content is invalid or exceeds 6 MB.");let a;try{const o=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(t);a=/[\u0000-\u0008\u000e-\u001f]/.test(o)?My(t):{encoding:"utf8",data:o}}catch{a=My(t)}return{path:e,writable:n,content:a,sizeBytes:t.byteLength,contentHash:f1(t)}}function My(e){let t="";for(let n=0;n<e.length;n+=8192)t+=String.fromCharCode(...e.subarray(n,n+8192));return{encoding:"base64",data:btoa(t)}}var jy=64*1024*1024,dI=r().regex(/^[a-f0-9]{64}$/),Mq=c({path:Cu,contentHash:dI,sizeBytes:u().int().nonnegative().max(jy),base64:r().max(jy)}).strict(),jq=c({schemaVersion:S("openpond.tasksetDraftWorkspace.v1"),draft:uo,files:p(Mq).max(1e4)}).strict();jq.extend({contentHash:dI}).strict();function mQ(e){const t=[];e.name.trim()||t.push({code:"name_missing",message:"Name is required.",path:"name"}),e.objective.trim()||t.push({code:"objective_missing",message:"Objective is required.",path:"objective"}),!e.datasetArtifact&&e.tasks.length===0&&t.push({code:"tasks_missing",message:"Add at least one task or Dataset artifact.",path:"tasks"}),e.graders.length===0&&t.push({code:"graders_missing",message:"Add at least one grader.",path:"graders"}),e.graderFixtures.length===0&&t.push({code:"grader_fixtures_missing",message:"Add grader fixtures before publishing.",path:"graderFixtures"});const n=new Set(e.sourceRefs.map(a=>a.id));for(const a of e.tasks)for(const o of a.sourceRefs)n.has(o)||t.push({code:"task_source_missing",message:`Task ${a.id} references missing source ${o}.`,path:`tasks.${a.id}.sourceRefs`});return t}var os=r().trim().min(1).max(240),Oq=Ct.extend({revision:u().int().positive()}).strict(),$q=Oq.extend({teamId:os,jobId:os,plan:Ct,baseline:Ct,candidate:Ct,state:hU.shape.state,updatedAt:r().datetime()}).strict();c({schemaVersion:S("openpond.trainingAcceptanceGroupPage.v1"),teamId:os,jobId:os,groups:p($q).max(100),nextCursor:os.nullable()}).strict();c({cursor:os.optional(),limit:u().int().min(1).max(100).default(25)}).strict();var ka=r().trim().min(1).max(191),Dl=r().regex(/^[a-f0-9]{64}$/),Nq=c({schemaVersion:S("openpond.trainingPreparationRequest.v1"),teamId:ka,operationId:ka,projectId:ka.nullable(),configuration:c({id:ka,expectedRevision:u().int().positive(),expectedEtag:Dl}).strict(),batch:Do,name:r().trim().min(1).max(191),maximumSpendUsd:u().finite().positive().max(1e6)}).strict(),Dq=c({schemaVersion:S("openpond.trainingPreparationPlan.v1"),id:ka,creatorUserId:ka,request:Nq,requestHash:Dl,source:Mx(()=>mI),submissionHash:Dl,createdAt:r().datetime({offset:!0})}).strict(),Lq=Dq.extend({contentHash:Dl}).strict(),Uq=c({schemaVersion:S("openpond.trainingPreparationReceipt.v1"),plan:Lq,revision:u().int().positive(),state:b(["prepared","submitted","cancelled"]),jobId:ka.nullable()}).strict().superRefine((e,t)=>{e.state==="submitted"!=!!e.jobId&&t.addIssue({code:"custom",path:["jobId"],message:"Only submitted preparations identify a job."})});c({teamId:ka,planHash:Dl,expectedRevision:u().int().positive()}).strict();c({projectId:ka.optional(),state:b(["prepared","submitted","cancelled"]).optional(),afterId:ka.optional(),limit:u().int().min(1).max(100).default(25)}).strict();c({schemaVersion:S("openpond.trainingPreparationPage.v1"),teamId:ka,items:p(Uq).max(100),nextCursor:ka.nullable()}).strict();c({schemaVersion:S("openpond.trainingHarnessSourcePublication.v1"),harnessRelease:Je,sourcePackageHash:r().regex(/^[a-f0-9]{64}$/),sizeBytes:u().int().positive().max(xU)}).strict();p(c({id:r().trim().min(1)}).catchall(ce())).min(1).max(1e3);c({binding:ku,rewards:p(xu).min(1).max(100)}).strict();var Hq=c({id:r().trim().min(1),clusterKey:r().trim().min(1),split:b(["train","validation","frozen_eval"])}).passthrough();c({schemaVersion:S("openpond.trainingEvaluationSource.v1"),taskset:Do,tasks:p(Hq).min(1).max(1e4),assets:p(c({path:r().trim().min(1).max(2e3),sha256:r().regex(/^[a-f0-9]{64}$/),sizeBytes:u().int().nonnegative(),encoding:S("base64"),content:r().max(32*1024*1024)}).strict()).max(1e4)}).strict().superRefine((e,t)=>{const n=new Set;e.tasks.forEach((a,o)=>{a.split==="train"&&t.addIssue({code:"custom",path:["tasks",o,"split"],message:"Evaluation sources require held-out tasks."}),n.has(a.id)&&t.addIssue({code:"custom",path:["tasks",o,"id"],message:"Evaluation task identities must be unique."}),n.add(a.id)})});var Tn=r().trim().min(1).max(500),sa=r().regex(/^[a-f0-9]{64}$/),Ba=r().datetime({offset:!0});c({schemaVersion:S("openpond.trainingInputArtifactUpload.v2"),kind:b(["portable_training_bundle","reward_model_dataset"]),idempotencyKey:r().trim().min(1).max(500),sourceManifest:Ct,payload:ce(),contentHash:sa}).strict();c({schemaVersion:S("openpond.trainingInputArtifact.v2"),kind:b(["portable_training_bundle","reward_model_dataset"]),sourceManifest:Ct,artifactRef:r().trim().min(1).max(2e3),contentHash:sa,sizeBytes:u().int().positive(),createdAt:Ba}).strict();var uI=b(["reward_model_train","policy_optimize"]),zq=b(["queued","admitting","provisioning","running","stopping","cancelling","succeeded","failed","cancelled"]),qq=c({id:Tn,version:r().trim().min(1).max(200).nullable().default(null),required:A().default(!0)}).strict(),mI=c({modelProject:c({id:Tn,portableProjectId:Tn,revision:u().int().positive(),contentHash:sa}).strict(),harnessRunManifest:Ct,harnessRelease:Ct,taskset:Do,tasksetRelease:Ct,evaluation:c({taskset:Do,dataset:Ct}).strict().nullable().optional(),dataset:Ct,evidenceSets:p(Ct).max(1e4)}).strict(),Bq=c({kind:S("reward_model_train"),baseModel:si,preferenceDatasetRelease:Ct,processorRelease:Ct,recipe:c({schemaVersion:S("openpond.rewardModelRecipe.v1"),method:S("reward_model"),parameterization:S("lora_with_scalar_head")}).catchall(ce())}).strict(),Fq=c({kind:S("deterministic"),grader:Ct,composer:Ct.nullable().default(null)}).strict(),Vq=c({kind:S("learned_reward"),rewardModelVersion:Ct,qualificationReport:Ct.nullable().default(null),evaluationReferences:p(Ct).max(1e3).default([]),scorerArtifact:c({artifactRef:r().trim().min(1).max(2e3),contentHash:sa,executionReceipt:Ct}).strict(),processorRelease:Ct,rewardComposerRelease:Ct}).strict(),Kq=c({kind:S("policy_optimize"),baseModel:si,recipe:s1,rewardSource:It("kind",[Fq,Vq]),resumeFrom:Ct.nullable().default(null)}).strict(),Wq=It("kind",[Bq,Kq]),Gq=c({approvalHash:sa,approvedAt:Ba,exportApproved:A(),maximumSpendUsd:u().nonnegative(),retentionDays:u().int().nonnegative().nullable(),region:r().trim().min(1).max(200).nullable().default(null)}).strict();c({schemaVersion:S("openpond.trainingJobSubmission.v2"),idempotencyKey:r().trim().min(1).max(500),name:r().trim().min(1).max(200),source:mI,job:Wq,requestedCapabilities:p(qq).max(1e3),placementObjective:b(["fast","balanced","economical"]),budget:c({maximumSpendUsd:u().nonnegative(),maximumWallSeconds:u().int().positive()}).strict(),approval:Gq,contentHash:sa}).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 Zq=c({schemaVersion:S("openpond.trainingJob.v2"),id:Tn,teamId:Tn,kind:uI,modelProjectId:Tn,portableProjectId:Tn,sourceProjectRevision:u().int().positive(),submissionHash:sa,state:zq,phase:r().trim().min(1).max(200),version:u().int().nonnegative(),progress:u().min(0).max(1),rolloutProgress:c({groupsCompleted:u().int().nonnegative(),groupsTarget:u().int().nonnegative(),optimizerUpdatesApplied:u().int().nonnegative(),optimizerUpdatesSkipped:u().int().nonnegative()}).strict(),accruedSpendUsd:u().nonnegative(),terminalReason:r().trim().min(1).max(5e3).nullable(),createdAt:Ba,updatedAt:Ba,completedAt:Ba.nullable()}).strict();c({schemaVersion:S("openpond.trainingJobPage.v2"),jobs:p(Zq).max(1e3),nextCursor:r().trim().min(1).max(2e3).nullable()}).strict();c({schemaVersion:S("openpond.trainingJobEvent.v2"),id:Tn,jobId:Tn,sequence:u().int().nonnegative(),type:Tn,phase:r().trim().min(1).max(200),message:r().trim().min(1).max(5e3).nullable(),data:re(r(),ce()).default({}),createdAt:Ba}).strict();c({schemaVersion:S("openpond.trainingJobLog.v2"),jobId:Tn,sequence:u().int().nonnegative(),level:b(["debug","info","warning","error"]),message:r().max(2e4),createdAt:Ba}).strict();c({expectedVersion:u().int().nonnegative()}).strict();var Jq=c({schemaVersion:S("openpond.trainingJobOutput.v2"),id:Tn,jobId:Tn,kind:b(["checkpoint","adapter","scorer","metrics","evaluation","trace","receipt"]),artifactRef:r().trim().min(1).max(2e3),contentHash:sa,sizeBytes:u().int().nonnegative(),metadata:re(r(),ce()).default({}),createdAt:Ba}).strict(),Yq=c({schemaVersion:S("openpond.trainingExecutionReceipt.v2"),id:Tn,teamId:Tn,jobId:Tn,submissionHash:sa,manifestHash:sa,recipeHash:sa,capabilityHash:sa,runtimeRelease:Ct,inputs:p(Ct).max(1e4),outputs:p(Ct).max(1e4),spendUsd:u().nonnegative(),durationSeconds:u().nonnegative(),cleanupComplete:A(),issuer:Tn,issuedAt:Ba,signature:r().trim().min(1).max(1e4).nullable()}).strict();c({schemaVersion:S("openpond.trainingJobOutputs.v2"),outputs:p(Jq).max(1e4),receipt:Yq.nullable()}).strict();c({schemaVersion:S("openpond.trainingApiError.v2"),code:r().trim().min(1).max(200),message:r().trim().min(1).max(5e3),retryable:A().default(!1),requestId:r().trim().min(1).max(500).nullable().default(null),details:re(r(),ce()).default({})}).strict();c({schemaVersion:S("openpond.trainingCapabilities.v2"),capabilityHash:sa,jobKinds:p(uI),methods:p(r().trim().min(1).max(200)),placements:p(b(["local","remote","colocated","provider_native"])),controls:c({cancel:A(),stopAfterGroup:A(),resumeFromCheckpoint:A()}).strict(),limits:c({maximumSpendUsd:u().nonnegative(),maximumWallSeconds:u().int().positive(),maximumArtifactBytes:u().int().positive()}).strict(),checkedAt:Ba,expiresAt:Ba}).strict();var mo=uo.shape.id,Va=u().int().positive(),ei=r().regex(/^[a-f0-9]{64}$/),li={teamId:mo,modelId:mo};c({schemaVersion:S("openpond.tasksetDraftCreate.v1"),operationId:mo,modelId:mo,expectedModelRevision:Va,name:uo.shape.name}).strict();c({schemaVersion:S("openpond.tasksetDraftSourceDescriptor.v1"),...li,expectedModelRevision:Va,sourcePackageHash:ei}).strict();c({schemaVersion:S("openpond.tasksetDraftReadback.v1"),...li,draft:uo,workspaceHash:ei,projectEtag:ei}).strict().refine(e=>e.draft.profileId===e.teamId&&e.draft.modelScope?.modelId===e.modelId,"The hosted draft must belong to its declared workspace and Model.");var Qq=c({id:mo,revision:Va,name:uo.shape.name,status:cI,updatedAt:uo.shape.updatedAt,sourceTasksetRef:xt.nullable()}).strict();c({schemaVersion:S("openpond.tasksetDraftList.v1"),...li,drafts:p(Qq).max(100),nextCursor:r().min(1).max(2e3).nullable()}).strict();c({expectedDraftRevision:Va,draft:uo}).strict();c({expectedDraftRevision:Va,expectedModelRevision:Va}).strict();var Xq=c({expectedDraftRevision:Va,expectedWorkspaceHash:ei}).strict();c({schemaVersion:S("openpond.tasksetDraftValidation.v1"),...li,draftId:mo,draftRevision:Va,workspaceHash:ei,valid:A(),issues:p(c({code:r().min(1),severity:b(["warning","error"]),message:r(),path:r().nullable()}).strict()),packageHash:ei.nullable(),tasksetRef:xt.nullable()}).strict().refine(e=>e.valid?e.packageHash!==null&&e.tasksetRef!==null&&e.issues.every(t=>t.severity!=="error"):e.packageHash===null&&e.tasksetRef===null&&e.issues.some(t=>t.severity==="error"),"Validation must retain either a compiled package or publication errors.");Xq.extend({operationId:mo,expectedPackageHash:ei,expectedTasksetRef:xt}).strict();c({schemaVersion:S("openpond.tasksetDraftFileList.v1"),...li,draftId:mo,draftRevision:Va,files:p(a1).max(10020)}).strict();c({schemaVersion:S("openpond.tasksetDraftFileReadback.v1"),...li,draftId:mo,draftRevision:Va,file:yU}).strict();c({schemaVersion:S("openpond.tasksetDraftDeletion.v1"),...li,draftId:mo,revision:Va,deleted:S(!0)}).strict();uo.shape.id;u().int().positive();var jo=r().trim().min(1).max(500),eB=c({projectId:jo.optional(),tasksetId:jo.optional(),draftId:jo.optional(),taskId:jo.optional(),query:r().trim().max(1e3).default(""),split:b(["train","validation","test","frozen_eval"]).optional(),after:r().min(1).max(2e3).optional(),limit:u().int().min(1).max(100).default(30)}).strict(),tB=c({id:jo,method:b(["code","judge","human"]),required:A()}),pI=c({tasksetId:jo,tasksetName:r(),tasksetRevision:u().int().positive(),tasksetHash:r(),taskId:jo,ordinal:u().int().nonnegative(),title:r(),description:r(),split:r(),scoring:p(tB),configuration:b(["configured","needs_reward","needs_checks"]),draftId:jo.nullable().default(null),modelId:jo.nullable().default(null)}),nB=c({items:p(pI).max(100),nextCursor:r().nullable()});function pQ(e,t){if(rU({format:e.format,files:t}).contentHash!==e.contentHash)throw new Error("The source files differ from the import preview.");const n=`private/intake/${e.contentHash}`,a=t.map((i,s)=>({file:i,path:`${n}/${String(s).padStart(4,"0")}.txt`})),o={schemaVersion:"openpond.taskIntakeSources.v1",format:e.format,previewHash:e.contentHash,files:a.map(({file:i,path:s})=>({originalPath:i.path,retainedPath:s}))};return[...a.map(({file:i,path:s})=>Ey(s,new TextEncoder().encode(i.text))),Ey(`${n}/manifest.json`,new TextEncoder().encode(JSON.stringify(o)))]}function fQ(e,t,n){const a=Qw.parse(t);if(!n.length||new Set(n).size!==n.length)throw new Error("Select unique task records to import.");const o=[...e.tasks];for(const s of n){const l=a.records.find(h=>h.id===s);if(!l||l.kind!=="task"||l.needsContext)throw new Error("Recorded attempts and incomplete histories must be imported into Labeling for review.");const m=lI.parse({schemaVersion:"openpond.taskData.v1",id:l.id,clusterKey:l.familyKey,split:l.split,input:l.input,expectedOutput:l.expected,privilegedContextRef:null,metadata:{intake:{format:a.format,uploadHash:a.contentHash,sourceId:l.sourceId,sourceHash:l.sourceHash,metadata:l.metadata}}}),d=o.find(h=>h.id===m.id);if(d&&Jr(d)!==Jr(m))throw new Error(`Task ${m.id} already exists with different content. Import will not replace saved edits.`);d||o.push(m)}const i=new Map;for(const s of o)for(const l of[`family:${s.clusterKey}`,`input:${Jr(s.input)}`]){if(i.has(l)&&i.get(l)!==s.split)throw new Error("The imported task family or request already occurs in another split.");i.set(l,s.split)}return uo.parse({...e,tasks:o})}const Yn=r().trim().min(1).max(240),vr=r().trim().min(1),fI=re(r(),ce()).default({}),hI=b(["nominated","needs_review","approved_for_creation","creating","needs_task_review","baselining","ready_for_export","rejected","dismissed","retired","blocked"]),gI=b(["no_training","prompting","retrieval","sft","preference","grpo_rft","sdft_opsd","sdpo","agentic_rl"]),aB=c({id:Yn,kind:b(["repeated_success","accepted_correction","agent_action_recurrence","outcome_linked_change","frontier_cost","expert_label","runtime_feedback"]),sourceRefIds:p(Yn).min(1).max(1e4),occurredAt:vr,signature:r().trim().min(1).max(2e3),summary:r().trim().min(1).max(5e3),confidence:u().min(0).max(1),consented:A(),metadata:fI}),oB=c({frequency:u().min(0).max(1),businessValue:u().min(0).max(1),frontierCost:u().min(0).max(1),signalQuality:u().min(0).max(1),verifiability:u().min(0).max(1),repeatability:u().min(0).max(1),privacyRisk:u().min(0).max(1),overall:u().min(0).max(1)}),rB=c({tactic:gI,eligible:A(),reasons:p(r().trim().min(1).max(5e3)).min(1).max(100),blockers:p(r().trim().min(1).max(5e3)).max(100).default([]),requiredSignals:p(r().trim().min(1).max(500)).max(100).default([]),generatedBy:b(["decision_table","baseline_reassessment"])}),vI=c({schemaVersion:S("openpond.taskCandidate.v1"),id:Yn,profileId:Yn,status:hI,fingerprint:r().trim().min(1).max(512),title:r().trim().min(1).max(500),summary:r().trim().min(1).max(1e4),workflowSignature:r().trim().min(1).max(2e3),evidence:p(aB).min(1).max(1e5),scorecard:oB,recommendation:rB,mergedIntoId:Yn.nullable(),createdAt:vr,updatedAt:vr,metadata:fI}),$u=c({schemaVersion:S("openpond.taskMinerConfig.v1"),enabled:A().default(!1),localOnly:A().default(!0),observationWindowDays:u().int().min(1).max(365).default(30),minimumRecurrence:u().int().min(2).max(100).default(3),clustering:S("hybrid_deterministic_first").default("hybrid_deterministic_first"),consentRequired:A().default(!0)});c({items:p(vI),generatedAt:vr,config:$u});c({status:hI.optional(),mergeIntoId:Yn.nullable().optional()});c({profileId:Yn,sourceIds:p(Yn).max(1e5).default([]),sessionIds:p(Yn).max(1e5).default([]),config:$u.optional()});const iB=c({schemaVersion:S("openpond.taskMinerRun.v1"),id:Yn,profileId:Yn,status:b(["queued","running","cancelling","cancelled","succeeded","failed"]),config:$u,sourceIds:p(Yn).max(1e5),sessionIds:p(Yn).max(1e5).default([]),progress:c({stage:b(["queued","ingesting","preparing","clustering","persisting","complete"]),processedSources:u().int().nonnegative(),totalSources:u().int().nonnegative(),candidatesFound:u().int().nonnegative(),skippedSources:u().int().nonnegative().default(0)}),candidateIds:p(Yn).max(1e5),cancelRequested:A(),error:r().trim().min(1).max(2e4).nullable(),createdAt:vr,startedAt:vr.nullable(),completedAt:vr.nullable(),updatedAt:vr});var sB=c({id:Fe,purpose:r().trim().min(1).max(500),audience:b(["orchestrator","environment","privileged_scorer","trainer","infrastructure"]),required:A(),ttlSeconds:u().int().positive().max(86400),scopes:p(r().trim().min(1).max(500)).max(100).default([])}).strict(),lB=c({declarationId:Fe,leaseRef:r().trim().min(8).max(1e3),audience:sB.shape.audience,expiresAt:wt}).strict(),Yg=c({adapterId:Fe,placement:b(["local","remote","colocated","provider_native"]),capabilityReceipt:Qe,runtimeVersion:r().trim().min(1).max(200),dataPlane:c({provider:Fe,dataPlaneId:Fe,cellId:Fe,runnerPoolId:Fe,runtimeImageDigest:r().regex(/^sha256:[a-f0-9]{64}$/),capabilityReceipt:Qe}).strict().nullable()}).strict(),Qg=c({adapterId:Fe,kind:b(["local","ssh","managed","custom"]),deviceOrPool:r().trim().min(1).max(1e3),capabilityReceipt:Qe,provider:Fe.nullable()}).strict(),Xg=c({adapterId:Fe,workerVersion:r().trim().min(1).max(200),workerImageDigest:r().regex(/^sha256:[a-f0-9]{64}$/).nullable(),upstreamRevision:r().trim().min(1).max(500),capabilityReceipt:Qe}).strict(),cB=c({schemaVersion:S("openpond.harnessRunManifest.v1"),id:Fe,harnessRelease:Je,datasetRelease:Je,evidenceSets:p(Je).max(1e4),model:c({source:r().trim().min(1).max(200),revision:r().trim().min(1).max(500),artifactHash:Qe.nullable(),tokenizerRevision:r().trim().min(1).max(500),chatTemplateHash:Qe}).strict(),recipe:c({method:r().trim().min(1).max(100),version:r().trim().min(1).max(200),configHash:Qe}).strict(),runtimeTarget:Yg,computeTarget:Qg,engine:Xg,resolvedBundleHash:Qe,secretLeaseRefs:p(lB).max(1e3),approval:c({approvalHash:Qe,approvedAt:wt,maximumSpendUsd:u().nonnegative().nullable()}).strict(),createdAt:wt}).strict(),dB=cB.extend({contentHash:Qe}).strict(),uB=c({schemaVersion:S("openpond.resolvedTrainingBundle.v1"),projection:S("trainer"),harnessRelease:Je,datasetRelease:Je,evidenceSetRelease:Je.nullable(),files:p(c({path:r().trim().min(1).max(2e3),sha256:Qe,sizeBytes:u().int().nonnegative()}).strict()).max(1e5)}).strict();uB.extend({contentHash:Qe}).strict();var bI=c({name:S("adamw").default("adamw"),weightDecay:u().nonnegative().max(1).default(0),beta1:u().positive().lt(1).default(.9),beta2:u().positive().lt(1).default(.999),epsilon:u().positive().max(.01).default(1e-8)}).strict().default({name:"adamw",weightDecay:0,beta1:.9,beta2:.999,epsilon:1e-8});const ft=r().trim().min(1).max(240),Qn=r().trim().min(1),gs=r().trim().min(8).max(256),ev=re(r(),ce()).default({}),co=ft.nullable(),mB=b(["slash_train","session_menu","bulk_selection","training_page","task_candidate"]),pB=b(["defaults","customize"]),fB=b(["automated","manual"]);c({schemaVersion:S("openpond.trainingSourceEstimate.v1"),sessionId:ft,messageCount:u().int().nonnegative(),estimatedTokens:u().int().nonnegative(),textBytes:u().int().nonnegative()});c({query:r().max(500).default(""),offset:u().int().nonnegative().default(0),limit:u().int().min(1).max(100).default(20),candidates:p(c({sessionId:ft,title:r().trim().min(1).max(500),updatedAt:Qn})).max(500).default([])});const hB=c({sessionId:ft,title:r().trim().min(1).max(500),updatedAt:Qn,snippet:r().max(2e3).nullable()});c({schemaVersion:S("openpond.trainingChatSearchResult.v1"),query:r(),offset:u().int().nonnegative(),limit:u().int().positive(),total:u().int().nonnegative(),hasMore:A(),indexedChats:u().int().nonnegative(),totalChats:u().int().nonnegative(),indexing:A(),entries:p(hB)});const tv=b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]),gB=c({graderId:ft.nullable(),path:r().trim().min(1).max(1e3),language:b(["javascript","typescript","python","json","text"]),content:r().max(2e6),sha256:gs,declaredSha256:gs.nullable(),integrity:b(["verified","unverified","mismatch"])}),vB=c({protocolVersion:r().trim().min(1).max(200),module:r().trim().min(1).max(1e3),moduleSha256:gs,command:p(r().max(2e3)).max(100),cwd:r().trim().min(1).max(4e3),maxTurns:u().int().positive().max(100)});c({schemaVersion:S("openpond.tasksetGraderDetails.v1"),taskset:Vt,sourceTasksetId:ft,graders:p(Ou).max(1e3),runtime:vB.nullable(),sources:p(gB).max(1e3),unavailableReason:r().max(2e3).nullable()});const bB=c({id:ft,taskIndex:u().int().nonnegative(),label:Jg,output:re(r(),ce()),infrastructureError:r().trim().min(1).max(1e4).nullable(),expectedPassed:A(),expectedRewardEligible:A(),metadata:ev}),yB=c({schemaVersion:S("openpond.taskAttempt.v1"),id:ft,tasksetId:ft,taskId:ft,split:hs,attempt:u().int().nonnegative(),seed:u().int(),modelRef:cn.nullable(),startedAt:Qn,completedAt:Qn,output:re(r(),ce()),runtimeEventRefs:p(ft).max(1e4).default([]),artifactRefs:p(ft).max(1e4).default([]),privilegedOutcomeRef:co,infrastructureError:r().trim().min(1).max(1e4).nullable(),costUsd:u().nonnegative().nullable(),latencyMs:u().int().nonnegative(),userInterventions:u().int().nonnegative().default(0),metadata:ev}),SB=c({schemaVersion:S("openpond.taskAttemptArtifact.v1"),id:ft,tasksetId:ft,taskId:ft,attemptId:ft,kind:b(["raw_model_response","runtime_trace","environment_state","grader_evidence","output_artifact"]),path:r().trim().min(1).max(4e3),mediaType:r().trim().min(1).max(200).nullable().optional(),sha256:gs,sizeBytes:u().int().nonnegative(),createdAt:Qn,metadata:ev}),xB=c({graderId:ft,graderVersion:r().trim().min(1).max(100),score:u().min(0).max(1).nullable(),passed:A(),hardGate:A(),rewardEligible:A(),feedback:r().trim().max(2e4).nullable(),evidenceRefs:p(ft).max(1e4).default([]),judge:cn.nullable().optional().default(null),calibrationStatus:b(["not_applicable","pending","passed","failed"])}),kB=c({schemaVersion:S("openpond.gradeResult.v1"),id:ft,attemptId:ft,graderSetHash:gs,score:u().min(0).max(1).nullable(),passed:A(),components:p(xB).min(1).max(1e3),failureClass:tv.nullable(),feedback:p(r().trim().min(1).max(2e4)).max(1e3).default([]),rewardEligible:A(),rewardComposition:Nd.optional(),createdAt:Qn});b(["stable_hash_top_n","rft_easy_curriculum_v1"]);const wB=c({schemaVersion:S("openpond.graderAuditReport.v1"),id:ft,tasksetId:ft,tasksetHash:gs,fixtureRefs:p(ft).min(1).max(1e5),gradeRefs:p(ft).min(1).max(1e5),passed:A(),hackingChecksPassed:A(),leakageChecksPassed:A(),infrastructureSafetyPassed:A(),failures:p(c({fixtureId:ft,label:Jg,gradeId:ft,reason:r().trim().min(1).max(5e3)})).max(1e5),createdAt:Qn}),IB=c({schemaVersion:S("openpond.capabilityDiagnosis.v1"),summary:r().trim().min(1).max(1e4),stableBehavior:p(r().trim().min(1).max(5e3)).max(100).default([]),changingKnowledge:p(r().trim().min(1).max(5e3)).max(100).default([]),requiredContext:p(r().trim().min(1).max(5e3)).max(100).default([]),requiredTools:p(ft).max(100).default([]),intervention:gI,trainingEligible:A(),rationale:p(r().trim().min(1).max(5e3)).min(1).max(100),confidence:u().min(0).max(1)}),_B=c({id:ft,sourceId:ft,sourceTurnId:co,split:hs,origin:b(["extracted","corrected","synthetic","expert_authored"]),inputPrompt:r().trim().min(1).max(1e5),expectedOutputText:r().trim().min(1).max(2e5).nullable(),rationale:r().trim().min(1).max(5e3)}),CB=c({schemaVersion:S("openpond.taskDesignProposal.v1"),id:ft,name:r().trim().min(1).max(500),objective:r().trim().min(1).max(2e4),diagnosis:IB.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:Zg.shape.taskKind,sourceIds:p(ft).min(1).max(1e5),assumptions:p(r().trim().min(1).max(5e3)).max(1e3),successCriteria:p(r().trim().min(1).max(5e3)).min(1).max(1e3),proposedGraders:p(Ou).max(1e3).default([]),graderFixtures:p(bB).max(1e5).default([]),generatedFiles:p(Sq).max(1e3).default([]),proposedExamples:p(_B).max(1e5).default([]),proposedMethod:iI.shape.recommendedMethod,trainingPath:oI.nullable().default(null),policy:Wg,warnings:p(r().trim().min(1).max(5e3)).default([]),createdAt:Qn}),RB=5;function hQ(e,t="New model"){const n=e?.trim().split(/\s+/).filter(Boolean)??[];return n.length===0?t:n.slice(0,RB).join(" ")}const lc=c({schemaVersion:S("openpond.baseModelPreference.v1"),modelId:ft,revision:r().trim().min(1).max(256).nullable(),tokenizerRevision:r().trim().min(1).max(256).nullable(),chatTemplateHash:r().trim().min(8).max(256).nullable(),modelAssetId:co,source:b(["managed","local","builtin"])}),PB=c({schemaVersion:S("openpond.taskCreationRequest.v1"),id:ft,profileId:ft,surface:mB,mode:pB,entryMode:fB.default("manual"),resourceIntent:b(["workproduct","dataset"]).default("workproduct"),buildIntent:nI.default("demonstrations"),buildSpecification:aI.nullable().default(null),objective:r().trim().min(1).max(2e4).nullable(),methodHint:b(["sft","dpo","grpo","ppo"]).nullable().default(null),preferredBaseModelId:ft.nullable().default(null),preferredBaseModel:lc.nullable().default(null),sourceIds:p(ft).max(1e5),candidateId:co,analysisModel:cn.nullable(),analysisReasoningEffort:uu.nullable().default(null),createImproveRunId:co.default(null),targetIntent:c({kind:b(["agent","skill","extension","model","configuration"]).nullable(),id:co,displayName:r().trim().min(1).max(500).nullable(),operation:b(["create","improve"])}).default({kind:"model",id:null,displayName:null,operation:"create"}),disclosure:c({status:b(["not_required","pending","approved","declined"]),content:S("raw_excerpts"),sourceIds:p(ft).max(1e5),providerModel:cn.nullable(),approvalId:co,approvedAt:Qn.nullable()}).default({status:"not_required",content:"raw_excerpts",sourceIds:[],providerModel:null,approvalId:null,approvedAt:null}),createdAt:Qn}),yI=c({schemaVersion:S("openpond.taskCreationSnapshot.v1"),id:ft,request:PB,state:b(["planning","awaiting_disclosure_approval","awaiting_questions","recommendation_ready","awaiting_materialization_approval","materializing","validating","ready","blocked","failed","cancelled"]),proposal:CB.nullable(),materializedTasksetId:co,disclosureApprovalId:co,materializationApprovalId:co,blockingQuestions:p(c({id:ft,kind:b(["objective","consent","success_signal","privacy_licensing","interpretation"]),prompt:r().trim().min(1).max(5e3),answer:r().trim().min(1).max(2e4).nullable()})).default([]),transcript:p(c({id:ft,role:b(["user","assistant","system","tool"]),text:r().max(1e5),createdAt:Qn})).max(1e4).default([]),repairHistory:p(sI).max(1e3).default([]),blockedReason:r().trim().min(1).max(1e4).nullable(),createdAt:Qn,updatedAt:Qn});c({schemaVersion:S("openpond.taskCreationTranscript.v1"),creationId:ft,profileId:ft,messages:yI.shape.transcript,updatedAt:Qn});const Zi=r().trim().min(1).max(240),md=r().trim().min(1),Gf=r().trim().min(8).max(256),SI=re(r(),ce()).default({}),AB=b(["created","inspecting","awaiting_source_review","awaiting_mapping","awaiting_materialization_approval","materializing","validating","ready","cancelling","cancelled","failed"]),xI=c({schemaVersion:S("openpond.huggingFaceDatasetLocator.v1"),repositoryId:r().trim().regex(/^[^/\s]+\/[^/\s]+$/).max(500),repositoryUrl:r().url().max(2e3),requestedRevision:r().trim().min(1).max(256).nullable()}),TB=c({path:r().trim().min(1).max(1e3),logicalType:r().trim().min(1).max(500),nullable:A(),sampleValues:p(ce()).max(5)}),EB=c({configuration:r().trim().min(1).max(500),split:r().trim().min(1).max(500),rowCount:u().int().nonnegative().nullable(),sizeBytes:u().int().nonnegative().nullable()}),MB=c({schemaVersion:S("openpond.huggingFaceDatasetInspection.v1"),id:Zi,locator:xI,resolvedRevision:r().trim().min(7).max(256),title:r().trim().min(1).max(500),description:r().max(2e4).nullable(),declaredLicense:r().trim().min(1).max(500).nullable(),gated:A(),private:A(),configurations:p(r().trim().min(1).max(500)).min(1).max(1e3),splits:p(EB).min(1).max(1e4),columns:p(TB).min(1).max(1e4),previewRows:p(re(r(),ce())).max(25),sourceFiles:p(c({path:r().trim().min(1).max(2e3),configuration:r().trim().min(1).max(500),split:r().trim().min(1).max(500),revision:r().trim().min(7).max(256),sizeBytes:u().int().nonnegative().nullable(),contentHash:Gf.nullable()})).max(1e5),inspectedAt:md,metadata:SI}),jB=b(["row_id","cluster_id","prompt","messages","demonstration","chosen","rejected","expected_output","privileged_context","reward","feedback","tag","metadata"]),OB=c({sourcePath:r().trim().min(1).max(1e3),target:jB,transform:b(["identity","string","json","messages","numeric","math_final_answer"]),policy:b(["visible","privileged","metadata"]),required:A()}),kI=c({schemaVersion:S("openpond.datasetImportMapping.v1"),sourceSchemaHash:Gf,configuration:r().trim().min(1).max(500),upstreamSplits:p(r().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:p(OB).min(1).max(1e4),nullPolicy:b(["reject","drop","preserve"]),invalidRowPolicy:b(["reject_import","drop_with_receipt"]),splitPolicy:c({seed:u().int(),assignments:re(r(),wr),validationPercent:u().min(0).max(100),frozenEvalPercent:u().min(0).max(100)}),importerVersion:r().trim().min(1).max(200),mappingHash:Gf}),$B=c({phase:b(["idle","metadata","download","mapping","parquet_write","verification","publish"]),completedBytes:u().int().nonnegative(),totalBytes:u().int().nonnegative().nullable(),completedRows:u().int().nonnegative(),totalRows:u().int().nonnegative().nullable(),message:r().trim().min(1).max(2e3).nullable()}),NB=c({schemaVersion:S("openpond.datasetImportJob.v1"),id:Zi,profileId:Zi,sourceKind:b(["huggingface","uploaded_file"]),status:AB,locator:xI.nullable(),inspection:MB.nullable(),mapping:kI.nullable(),progress:$B,targetStorageRoot:r().trim().min(1).max(4e3).nullable(),tasksetId:Zi.nullable(),tasksetRevision:u().int().positive().nullable(),artifactId:Zi.nullable(),error:r().trim().min(1).max(2e4).nullable(),cancellationRequested:A(),createdAt:md,updatedAt:md,completedAt:md.nullable(),metadata:SI});c({profileId:Zi,url:r().trim().min(1).max(2e3)});c({name:r().trim().min(1).max(500),objective:r().trim().min(1).max(2e4),mapping:kI,targetStorageRoot:r().trim().min(1).max(4e3).nullable(),licenseApproved:A().default(!1)});const dr=T.nullable(),_o=u().int().nonnegative(),DB=r().regex(/^[a-f0-9]{40}$/),LB=c({name:r().trim().min(1).max(160),startedAt:Oe,completedAt:Oe,durationMs:u().nonnegative(),clock:b(["monotonic","provider","wall"]),outcome:b(["succeeded","failed","cancelled"])}).strict(),UB=c({schemaVersion:S("openpond.correlatedTelemetryReceipt.v1"),stage:b(["training","evaluation","deployment","inference"]),correlation:c({modelRunId:dr,modelVersionId:dr,policyVersion:_o.nullable(),taskId:dr,rolloutGroupId:dr,providerResourceId:dr,deploymentId:dr,inferenceRequestId:dr}).strict(),spans:p(LB).max(1e4),usage:c({promptTokens:_o.nullable(),generatedTokens:_o.nullable(),gpuSeconds:u().nonnegative().nullable(),workerActiveSeconds:u().nonnegative().nullable(),optimizerSteps:_o.nullable(),rolloutGroups:_o.nullable(),successfulTrajectories:_o.nullable(),failedTrajectories:_o.nullable(),peakGpuMemoryBytes:_o.nullable(),peakGpuUtilizationPercent:u().min(0).max(100).nullable()}).strict(),resource:c({provider:T,resourceIds:p(T).max(1e3),gpuType:r().trim().min(1).max(300).nullable(),gpuCount:_o.nullable(),baseProfileId:dr,baseRepository:r().trim().min(1).max(512).nullable(),baseRevision:DB.nullable(),adapterContentHash:J.nullable()}).strict(),cost:c({currency:S("USD"),providerReportedUsd:u().nonnegative().nullable(),quotedHourlyUsd:u().nonnegative().nullable(),estimatedUsd:u().nonnegative().nullable(),methodologyVersion:r().trim().min(1).max(160),pricingInputs:re(r().trim().min(1).max(160),u().finite()),unitEstimates:re(r().trim().min(1).max(160),u().nonnegative())}).strict(),recordedAt:Oe,contentHash:J}).strict(),gn=r().trim().min(1).max(240),zo=r().regex(/^[a-f0-9]{64}$/),fr=r().datetime({offset:!0}),Sn=c({id:gn,contentHash:zo}).strict(),HB=Sn.extend({revision:u().int().positive()}).strict(),wI=c({providerId:gn,modelId:r().trim().min(1).max(300)}).strict(),Nu=b(["correction","sibling_verification","cumulative_known","development","retained","frozen_final","training_eligible"]),zB=c({taskId:gn,taskContentHash:zo,panelRole:Nu,passLabel:gn.nullable(),optimizerEligible:A(),criticalInvariantIds:p(gn).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."})}),qB=c({schemaVersion:S("openpond.continualBenchIssuePacket.v1"),id:gn,revision:u().int().positive(),contentHash:zo,familyId:gn,familyLabel:r().trim().min(1).max(500),severity:b(["low","medium","high","critical"]),cases:p(zB).min(2).max(1e4),duplicateEvidence:Sn,leakageEvidence:Sn,priorExposureEvidence:Sn,observedAt:fr,reviewedAt:fr,queuedAt:fr.nullable(),runAt:fr.nullable(),createdBy:gn,createdAt:fr}).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."})}),BB=c({id:gn,role:Nu,passLabel:gn.nullable(),taskset:HB,familyIds:p(gn).min(1).max(1e5),taskCount:u().int().positive().max(1e6),sealedAt:fr}).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."})}),Hp=It("kind",[c({kind:S("base_model"),id:gn,revision:r().trim().min(1).max(500),contentHash:zo}).strict(),c({kind:S("model_version"),id:gn,contentHash:zo}).strict(),c({kind:S("external_reference"),id:gn,model:wI,providerRevision:r().trim().min(1).max(500),contentHash:zo}).strict()]),FB=c({scheduleEntryId:gn,ordinal:u().int().nonnegative(),label:gn,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:u().int().positive().max(1024),correctionPanelIds:p(gn).min(1).max(1e3),optimizerGroupsPerTask:u().int().positive().max(1e3),trajectoriesPerGroup:u().int().min(4).max(1e3)}).strict(),VB=c({revision:u().int().positive(),requireAllAttemptsTerminal:S(!0),criticalCorrectionPassRate:u().min(0).max(1),siblingPassRate:u().min(0).max(1),behavioralRetentionRate:u().min(0).max(1),maximumRetainedRegressionPoints:u().min(0).max(100),blockCriticalPriorRegression:A(),authorizedClaims:p(b(["systems_complete","correction_absorbed","issue_generalized","continually_current","frontier_pareto_result"])).min(1).max(5)}).strict(),KB=c({schemaVersion:S("openpond.continualBenchmarkProtocol.v1"),id:gn,revision:u().int().positive(),contentHash:zo,ownerId:gn,createdAt:fr,sealedAt:fr,creationReceipt:Sn,predecessorSeries:c({id:gn,revision:u().int().positive(),contentHash:zo}).strict().nullable(),scenarioPack:Sn,issueFamilyLedger:Sn,issuePacketRelease:Sn,panels:p(BB).min(6).max(1e4),grader:Sn,judge:c({release:Sn,rubricRelease:Sn,calibrationRelease:Sn,model:wI}).strict().nullable(),policies:c({base:Hp,master:Hp.nullable(),externalReferences:p(Hp).min(1).max(20)}).strict(),invariants:c({systemPromptHash:zo,toolSchema:Sn,application:Sn,harness:Sn,runtime:Sn,workerImage:Sn,autoRefiner:c({enabled:A(),release:Sn.nullable()}).strict()}).strict(),schedule:p(FB).min(1).max(1e3),evaluation:c({seeds:p(u().int()).min(3).max(100),repetitions:u().int().min(3).max(20),powerRule:Sn,pairedBootstrapSamples:u().int().min(1e3).max(1e6),confidenceLevel:S(.95)}).strict(),resources:c({maximumTrainingGpuSeconds:u().int().positive(),maximumEvaluationGpuSeconds:u().int().positive(),maximumProviderSpendUsd:u().positive(),maximumTotalSpendUsd:u().positive(),maximumConcurrentGroups:u().int().positive().max(1e3)}).strict(),currencyThresholds:VB}).strict().superRefine((e,t)=>{const n=e.panels.map(i=>i.id);new Set(n).size!==n.length&&t.addIssue({code:"custom",path:["panels"],message:"Protocol panel ids must be unique."});for(const i of["development","retained","frozen_final","training_eligible"])e.panels.filter(s=>s.role===i).length!==1&&t.addIssue({code:"custom",path:["panels"],message:`A protocol requires exactly one ${i} panel.`});[...e.schedule].sort((i,s)=>i.ordinal-s.ordinal).some((i,s)=>i.ordinal!==s)&&t.addIssue({code:"custom",path:["schedule"],message:"Protocol schedule ordinals must be contiguous from zero."});const o=new Set(n);e.schedule.some(i=>i.correctionPanelIds.some(s=>!o.has(s)))&&t.addIssue({code:"custom",path:["schedule"],message:"Every scheduled correction panel must belong to the protocol."})}),WB=b(["draft","active","completed","archived"]),GB=b(["draft","ready","queued","running","candidate","accepted","rejected","no_signal","failed","cancelled"]),II=b(["seed","daily_residual","rank_candidate","weekly_rollup","full_refresh"]),ZB=b(["base_model","previous_release","seed_release","accepted_daily_head","accepted_seed"]),JB=b(["seed_taskset","nightly_selection","daily_cohort_union","eligible_task_pool"]),YB=b(["live_client","evaluation_attempt","replay_evidence","manual"]),QB=c({id:T,ordinal:u().int().nonnegative(),label:r().trim().min(1).max(100),role:II,parentRule:ZB,taskSource:JB,trainableRank:u().int().positive().max(1024),minimumTasks:u().int().nonnegative().max(1e5),maximumTasks:u().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:o}=n[e.role];a.includes(e.parentRule)||t.addIssue({code:"custom",path:["parentRule"],message:`${e.role} requires parent rule ${a.join(" or ")}.`}),e.taskSource!==o&&t.addIssue({code:"custom",path:["taskSource"],message:`${e.role} requires task source ${o}.`}),e.ordinal===0&&e.role!=="seed"&&t.addIssue({code:"custom",path:["role"],message:"The first series entry must be the seed."})}),XB=c({id:T,version:u().int().positive(),requireCheckpoint:A(),requireAppliedOptimizerUpdate:A(),minimumCurrentCohortMeanImprovement:u().finite(),maximumRetainedMeanRegression:u().finite().nonnegative(),blockCriticalInvariantRegression:A(),automaticDailyAdvancement:A()}).strict(),eF=c({schemaVersion:S("openpond.modelComparisonSeries.v1"),id:T,profileId:T,modelProjectId:T,name:r().trim().min(1).max(500),objective:r().trim().min(1).max(2e4),status:WB,revision:u().int().positive(),productionBinding:c({role:S("chat_manual"),roleTargetId:T}).strict(),baseModel:c({id:T,revision:r().trim().min(1).max(256)}).strict(),seedTaskset:Vt,eligibleTaskPool:Vt,evaluationTasksets:c({development:Vt,retained:Vt,frozenFinal:Vt}).strict(),grader:Z,benchmarkProtocol:KB.nullable().default(null),automaticEvaluation:c({enabled:A()}).strict().default({enabled:!1}),residualProfile:c({profileId:T,serializedEnvelopeRank:u().int().positive().max(1024),maximumEnabledRank:u().int().positive().max(1024),topology:S("uniform_block_masked")}).strict(),schedule:p(QB).min(1).max(1e3),scheduleSealedAt:Oe.nullable(),advancementPolicy:XB,executionPolicy:c({startWhenReady:S(!1)}).strict(),acceptedSeedEntryId:T.nullable(),acceptedDailyHeadEntryId:T.nullable(),promotedBindingId:T.nullable(),createdBy:T,createdAt:Oe,updatedAt:Oe}).strict().superRefine((e,t)=>{[...e.schedule].sort((m,d)=>m.ordinal-d.ordinal).some((m,d)=>m.ordinal!==d)&&t.addIssue({code:"custom",path:["schedule"],message:"Schedule ordinals must be unique and contiguous from zero."}),(new Set(e.schedule.map(m=>m.id)).size!==e.schedule.length||new Set(e.schedule.map(m=>m.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(m=>`${m.id}:${m.revision}:${m.contentHash}`)).size!==a.length&&t.addIssue({code:"custom",path:["evaluationTasksets"],message:"Development, retained, and frozen-final cohorts require distinct immutable Taskset releases."});const o=e.schedule.find(m=>m.role==="seed");if(!o||e.schedule.filter(m=>m.role==="seed").length!==1){t.addIssue({code:"custom",path:["schedule"],message:"A series requires exactly one seed entry."});return}const i=e.schedule.filter(m=>m.role==="rank_candidate");i.length===1&&t.addIssue({code:"custom",path:["schedule"],message:"A causal rank comparison requires at least two rank candidates."}),new Set(i.map(m=>m.trainableRank)).size!==i.length&&t.addIssue({code:"custom",path:["schedule"],message:"Causal rank candidates must use distinct trainable ranks."}),[o.trainableRank+e.schedule.filter(m=>m.role==="daily_residual").reduce((m,d)=>m+d.trainableRank,0),...e.schedule.filter(m=>m.role==="weekly_rollup").map(m=>o.trainableRank+m.trainableRank),...e.schedule.filter(m=>m.role==="rank_candidate").map(m=>o.trainableRank+m.trainableRank),...e.schedule.filter(m=>m.role==="full_refresh").map(m=>m.trainableRank)].some(m=>m>e.residualProfile.maximumEnabledRank)&&t.addIssue({code:"custom",path:["schedule"],message:"A declared branch exceeds the maximum enabled rank."})}),_I=c({source:YB,taskIds:p(T).min(1).max(1e5),observedFrom:Oe,observedTo:Oe,reviewedAt:Oe,reviewedBy:T,sourceTaskset:Vt}).strict(),tF=_I.extend({derivedFamilyKeys:p(T).min(1).max(1e5),familyDerivation:c({algorithm:T,sourceTasksetHash:J}).strict(),selectionHash:J}).strict(),CI=It("kind",[c({kind:S("base_model"),id:T,revision:r().trim().min(1).max(256)}).strict(),c({kind:S("model_version"),id:T,contentHash:J}).strict()]),nF=c({id:T,branchOrdinal:u().int().nonnegative(),rank:u().int().positive().max(1024),offsetStart:u().int().nonnegative(),offsetEnd:u().int().positive(),optimizationRole:b(["frozen","trainable"]),artifactLineageId:T.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."})}),aF=c({disposition:b(["advance","hold","no_signal"]),policy:c({id:T,version:u().int().positive()}).strict(),reasonCodes:p(T).min(1).max(100),summary:r().trim().min(1).max(5e3),decidedBy:T,decidedAt:Oe}).strict(),oF=c({evaluationRunId:T,modelVersionId:T,taskset:Vt,grader:Z,cohortRole:b(["current","correction","sibling_verification","cumulative_known","development","retained","prior_disclosed","frozen_final"]),panelId:T.nullable().default(null),protocol:c({id:T,revision:u().int().positive(),contentHash:J}).strict().nullable().default(null)}).strict(),rF=c({attemptOrdinal:u().int().positive(),trainingPlanId:T.nullable(),modelRunId:T.nullable(),terminalStatus:b(["failed","cancelled"]),queuedAt:Oe.nullable(),startedAt:Oe.nullable(),completedAt:Oe}).strict(),vs=c({seriesId:T,entryId:T,scheduleEntryId:T,ordinal:u().int().nonnegative(),releaseHash:J}).strict(),iF=c({schemaVersion:S("openpond.modelComparisonSeriesEntry.v1"),id:T,seriesId:T,profileId:T,modelProjectId:T,scheduleEntryId:T,releaseHash:J,ordinal:u().int().nonnegative(),label:r().trim().min(1).max(100),role:II,branch:b(["daily","rank_candidate","weekly_rollup","full_refresh"]),status:GB,parent:CI,taskset:Vt,sourceTasksets:p(Vt).min(1).max(1e3),taskSelection:tF.nullable(),trainableRank:u().int().positive().max(1024),serializedEnvelopeRank:u().int().positive().max(1024),enabledCumulativeRank:u().int().positive().max(1024),trainableBlockId:T,residualBlocks:p(nF).min(1).max(1024),attemptOrdinal:u().int().positive().default(1),priorRunAttempts:p(rF).max(100).default([]),trainingPlanId:T.nullable(),modelRunId:T.nullable(),modelVersionId:T.nullable(),evaluations:p(oF).max(1e5),decision:aF.nullable(),promotionBindingId:T.nullable(),queuedAt:Oe.nullable(),startedAt:Oe.nullable(),completedAt:Oe.nullable(),createdAt:Oe,updatedAt:Oe}).strict().superRefine((e,t)=>{const n=[...e.residualBlocks].sort((s,l)=>s.offsetStart-l.offsetStart);n.some((s,l)=>s.offsetStart!==(l===0?0:n[l-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 o=e.residualBlocks.filter(s=>s.optimizationRole==="trainable");(o.length!==1||o[0]?.id!==e.trainableBlockId||o[0]?.rank!==e.trainableRank)&&t.addIssue({code:"custom",path:["trainableBlockId"],message:"Exactly one block must be trainable during the Run and match trainableRank."});const i=e.priorRunAttempts.map(s=>s.attemptOrdinal);(e.priorRunAttempts.length!==e.attemptOrdinal-1||i.some((s,l)=>s!==l+1))&&t.addIssue({code:"custom",path:["priorRunAttempts"],message:"Prior Run attempts must be a contiguous history before the active attempt."})});c({seriesId:T,scheduleEntryId:T,taskSelection:_I.nullable(),expectedSeriesRevision:u().int().positive()}).strict();const sF=b(["base_reference","lora_adapter"]),RI=c({baseModel:c({source:S("huggingface"),repoId:T,revision:r().regex(/^[a-f0-9]{40}$/),configHash:J,tokenizerHash:J,licenseId:T,gated:A()}).strict(),processor:c({repository:T,revision:r().regex(/^[a-f0-9]{40}$/),configHash:J}).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."})}),lF=c({schemaVersion:S("openpond.modelVersion.v1"),id:T,modelId:T,profileId:T,version:u().int().nonnegative(),kind:sF,status:b(["available","failed"]),baseModel:lc,taskset:Vt,comparisonSeriesEntry:vs.nullable().optional(),evaluationTasksetRef:Vt.nullable().optional(),releaseGraph:c({resolvedBundleHash:J,profileRelease:Vt,harnessRelease:Z,agentRelease:Z.nullable(),grader:c({id:T,contentHash:J}).strict()}).strict(),artifactLineageId:T.nullable(),adapterStatus:b(["not_trained","trained"]),createdAt:Oe,contentHash:J}).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."})}),cF=c({schemaVersion:S("openpond.rewardModelVersion.v1"),id:T,modelId:T,profileId:T,version:u().int().positive(),role:S("reward"),status:b(["available","failed"]),scope:b(["synthetic_smoke","human_preference"]),baseModel:lc,runtime:RI.nullable().default(null),taskset:Vt,preferenceDatasetRelease:Z,releaseGraph:c({resolvedBundleHash:J,profileRelease:Vt,harnessRelease:Z,grader:c({id:T,contentHash:J}).strict()}).strict(),artifacts:c({checkpoint:Z.extend({objectRef:r().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/),files:p(c({path:r().trim().min(1).max(512),sizeBytes:u().int().positive(),sha256:J}).strict()).min(4).max(128)}).strict(),adapter:Z,scalarHead:Z,bucketHead:Z.nullable(),processorRelease:Z}).strict(),qualificationReport:Z.nullable(),createdAt:Oe,contentHash:J}).strict(),dF=c({schemaVersion:S("openpond.rewardModelRunReceipt.v1"),provider:T,providerRunId:T,resolvedBundleHash:J,finalCheckpoint:Z.extend({objectRef:r().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/)}).strict(),adapter:Z,scalarHead:Z,bucketHead:Z.nullable(),processorRelease:Z,optimizerEvidence:Z,managedExecutionReceipt:Z.nullable().default(null),parameterDeltaHash:J,cleanup:c({computeReleased:A(),providerTerminalObserved:A()}).strict(),contentHash:J}).strict(),uF=FM(e=>{if(!e||typeof e!="object"||Array.isArray(e))return e;const t=e;if(t.tasksetRelease!==void 0)return e;const n=t.taskset;if(!n||typeof n!="object"||Array.isArray(n))return e;const a=n;return typeof a.id!="string"||typeof a.contentHash!="string"?e:{...t,tasksetRelease:{id:a.id,contentHash:a.contentHash}}},c({schemaVersion:S("openpond.rewardModelRun.v1"),id:T,rewardModelId:T,rewardModelVersionId:T.nullable(),profileId:T,role:S("reward"),scope:b(["synthetic_smoke","human_preference"]),status:b(["prepared","running","succeeded","failed","cancelled"]),taskset:Vt,tasksetRelease:Z,preferenceDatasetRelease:Z,recipeRelease:Z,destinationId:T,quote:c({maximumSpendUsd:u().positive(),hourlyCostUsd:u().nonnegative().nullable()}).strict(),managedRunId:T.nullable(),progress:c({completedSteps:u().int().nonnegative(),totalSteps:u().int().positive(),latestLoss:u().finite().nullable()}).strict(),receipt:dF.nullable(),qualificationReport:Z.nullable(),accruedSpendUsd:u().nonnegative().nullable(),failureOwner:b(["authoring","admission","provider","runner","artifact","qualification","cleanup"]).nullable(),failure:r().trim().min(1).max(5e3).nullable(),startedAt:Oe,completedAt:Oe.nullable(),updatedAt:Oe}).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."})}),mF=c({schemaVersion:S("openpond.modelRunReceipt.v1"),provider:T,providerRunId:T,assignmentHash:J,resultHash:J,transcriptHash:J,traceHash:J.nullable(),resolvedBundleHash:J,artifactPath:r().trim().min(1).max(2e3),cleanup:c({computeReleased:A(),tunnelClosed:A()}).strict(),telemetry:UB.nullable().default(null),contentHash:J}).strict(),ur=c({inputTokens:u().int().nonnegative(),outputTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative(),costUsd:u().nonnegative().nullable()}).strict(),Oy=r().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),nv=c({phase:b(["baseline","adaptation","candidate_adaptation","candidate"]),taskId:T,attemptId:T,sessionId:T.nullable(),turnId:T.nullable(),passed:A(),score:u().min(0).max(1).nullable(),failureClass:tv.nullable(),inputTokens:u().int().nonnegative(),outputTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative(),latencyMs:u().int().nonnegative(),costUsd:u().nonnegative().nullable(),startedAt:Oe}).strict(),$y=c({targetTaskCount:u().int().nonnegative(),comparedTaskCount:u().int().nonnegative(),passedTaskCount:u().int().nonnegative(),failedTaskCount:u().int().nonnegative(),lowerTaskCount:u().int().nonnegative(),higherTaskCount:u().int().nonnegative(),unchangedTaskCount:u().int().nonnegative()}).strict(),PI=c({target:S("all_tasks_lower"),targetTaskCount:u().int().nonnegative(),comparedTaskCount:u().int().nonnegative(),passedTaskCount:u().int().nonnegative(),failedTaskCount:u().int().nonnegative(),lowerTaskCount:u().int().nonnegative(),higherTaskCount:u().int().nonnegative(),unchangedTaskCount:u().int().nonnegative(),baselineTokens:u().int().nonnegative(),refinedTokens:u().int().nonnegative(),tokenDelta:u().int(),tokenDeltaPercent:u().finite().nullable(),complete:A(),passed:A(),cohorts:c({adaptation:$y,heldOut:$y}).strict()}).strict(),av=c({baseline:ur,adaptation:ur,candidateAdaptation:ur,candidate:ur,refiner:ur,grader:ur}).strict(),pF=c({usage:av,observedSpendUsd:u().nonnegative(),attempts:p(nv).max(1e4)}).strict(),fF=c({id:T,contentHash:J,artifactPath:r().trim().min(1).max(2e3)}).strict(),hF=c({schemaVersion:S("openpond.modelEvaluationReceipt.v1"),benchmarkId:T,resultManifest:c({id:T,contentHash:J,artifactPath:r().trim().min(1).max(2e3)}).strict(),stages:c({baseline:Z,adaptation:Z,refiner:Z,candidateAdaptation:Z,candidate:Z,comparison:Z}).strict(),usage:av,quality:c({baselinePassRate:u().min(0).max(1),candidatePassRate:u().min(0).max(1),adaptationBaselinePassRate:u().min(0).max(1),adaptationCandidatePassRate:u().min(0).max(1),adaptationCandidatePassed:A(),heldOutCandidatePassed:A(),passed:A()}).strict(),foregroundTokenDelta:u().int(),foregroundTokenDeltaPercent:u().finite().nullable(),taskEfficiency:PI.optional(),efficiency:c({grossForegroundTokenSavings:u().int(),overheadTokens:u().int().nonnegative(),firstPassNetTokenSavings:u().int(),breakEvenReuseCount:u().int().nonnegative().nullable(),amortizedTokenSavings:u().int(),amortizedReuseCount:u().int().positive()}).strict(),budget:c({maximumSpendUsd:u().nonnegative(),observedSpendUsd:u().nonnegative(),enforced:A()}).strict(),evidenceSnapshot:Z,lineage:c({adaptationEvidenceHash:J,refinerInputHash:J,refinerOutcomeHash:J,validationHash:J,applyReceiptHash:J,candidateRelease:Z,valid:A()}).strict(),invalidReasons:p(r().trim().min(1).max(2e3)).max(100),attempts:p(nv).max(1e4).default([]),terminalClassification:b(["improved","no_improvement","regressed","inconclusive","cancelled","infrastructure_failure"]),profileGit:c({ref:r().trim().min(1).max(2e3),commit:Oy,baseCommit:Oy}).strict().nullable(),contentHash:J}).strict(),gF=c({schemaVersion:S("openpond.modelEvaluationStopReceipt.v1"),benchmarkId:T,terminalClassification:S("inconclusive"),stopReason:b(["candidate_harness_unchanged","candidate_lineage_invalid"]),reason:r().trim().min(1).max(5e3),stoppedAfter:S("refiner"),baselineHarness:Z,candidateHarness:Z,refiner:c({id:T,contentHash:J,outcomeCount:u().int().nonnegative()}).strict(),usage:av,budget:c({maximumSpendUsd:u().nonnegative(),observedSpendUsd:u().nonnegative(),enforced:A()}).strict(),evidenceSnapshot:Z,attempts:p(nv).max(1e4),contentHash:J}).strict(),Ny=c({level:S(.95),lower:u().finite(),upper:u().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."})}),vF=c({schemaVersion:S("openpond.modelComparisonBenchmarkReceipt.v1"),benchmarkId:S("model-comparison"),target:c({kind:b(["base_model","model_version","external_reference"]),label:r().trim().min(1).max(300),modelVersionId:T.nullable(),model:cn.nullable()}).strict(),taskset:Vt,grader:Z,sampling:c({seeds:p(u().int()).min(1).max(100),repetitions:u().int().positive().max(20)}).strict(),deterministic:c({attemptedTaskCount:u().int().nonnegative(),completedTaskCount:u().int().nonnegative(),passedTaskCount:u().int().nonnegative(),failedTaskCount:u().int().nonnegative(),meanScore:u().finite().nullable(),passRate:u().min(0).max(1).nullable(),passRateCi95:Ny.nullable()}).strict(),judge:c({judgeModel:cn,judgeRelease:Z,rubricRelease:Z,calibrationRelease:Z,score:u().min(0).max(100),scoreCi95:Ny,comparisonCount:u().int().positive(),wins:u().int().nonnegative(),ties:u().int().nonnegative(),losses:u().int().nonnegative(),referenceLabel:r().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:p(c({attemptId:T.nullable().default(null),taskId:T,seed:u().int(),repetition:u().int().nonnegative(),status:b(["succeeded","failed"]),deterministicScore:u().finite().nullable(),passed:A().nullable(),judgeScore:u().min(0).max(100).nullable(),judgePreference:b(["win","tie","loss"]).nullable(),transcriptHash:J.nullable(),traceHash:J.nullable(),transcriptArtifact:c({artifactPath:r().trim().min(1).max(2e3),jsonPointer:r().trim().min(1).max(1e3)}).strict().nullable().default(null),traceArtifact:c({artifactPath:r().trim().min(1).max(2e3),jsonPointer:r().trim().min(1).max(1e3)}).strict().nullable().default(null),latencyMs:u().int().nonnegative().nullable().default(null),failureClass:tv.nullable()}).strict()).max(1e5),usage:c({policy:ur.nullable(),judge:ur.nullable(),observedSpendUsd:u().nonnegative().nullable(),evaluationGpuSeconds:u().nonnegative().nullable().default(null)}).strict(),managedServing:c({jobId:T,terminalState:b(["completed","cancelled","failed","budget_exhausted"]),sourcePolicyVersion:u().int().nonnegative(),sourceAdapterSha256:J.nullable(),servedPolicyVersion:u().int().nonnegative().nullable(),servedAdapterSha256:J.nullable(),accruedSpendUsd:u().nonnegative(),cleanupAttestationHash:J,resourceCount:u().int().nonnegative(),activeResourceCount:S(0)}).strict().nullable().default(null),evidenceSnapshot:c({id:T,contentHash:J,artifactPath:r().trim().min(1).max(2e3)}).strict(),completedAt:Oe,contentHash:J}).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."})}),bF=c({benchmarkId:S("harness-refiner"),model:cn,upstreamModel:c({providerId:T,modelId:r().trim().min(1).max(300),revision:r().trim().min(1).max(300),pricing:c({version:r().trim().min(1).max(300),source:r().trim().min(1).max(300),effectiveAt:Oe,inputUsdPerMillionTokens:u().nonnegative(),cachedInputUsdPerMillionTokens:u().nonnegative(),outputUsdPerMillionTokens:u().nonnegative()}).strict().optional()}).strict(),reasoningEffort:r().trim().min(1).max(100).nullable(),seeds:p(u().int()).min(1).max(100),repetitions:u().int().positive().max(20),maximumSpendUsd:u().nonnegative(),attemptPlan:p(c({stage:b(["baseline","adaptation","candidate_adaptation","candidate"]),split:r().trim().min(1).max(100),taskIds:p(T).min(1).max(1e5),attemptCount:u().int().positive()}).strict()).length(4)}).strict(),yF=c({benchmarkId:S("model-comparison"),target:c({kind:b(["base_model","model_version","external_reference"]),label:r().trim().min(1).max(300),modelVersionId:T.nullable(),model:cn.nullable()}).strict(),grader:Z,judge:c({model:cn,release:Z,rubricRelease:Z,calibrationRelease:Z,referenceLabel:r().trim().min(1).max(300)}).strict().nullable(),seeds:p(u().int()).min(1).max(100),repetitions:u().int().positive().max(20),maximumSpendUsd:u().nonnegative(),series:c({id:T,protocol:c({id:T,revision:u().int().positive(),contentHash:J}).strict()}).strict().nullable().default(null),panel:c({id:T,role:b(["correction","sibling_verification","cumulative_known","development","retained","frozen_final"]),passLabel:T.nullable()}).strict().nullable().default(null),comparisonPair:c({entryId:T,parent:CI,candidateModelVersionId:T}).strict().nullable().default(null),attemptPlan:p(c({stage:S("comparison"),split:r().trim().min(1).max(100),taskIds:p(T).min(1).max(1e5),attemptCount:u().int().positive()}).strict()).length(1)}).strict(),SF=Dt([bF,yF]),xF=c({schemaVersion:S("openpond.modelRun.v1"),id:T,modelId:T,modelVersionId:T.nullable(),profileId:T,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:T.nullable(),taskset:Vt,comparisonSeriesEntry:vs.nullable().optional(),evaluationTasksetRef:Vt.nullable().optional(),harnessRelease:Z.nullable().optional(),quote:c({maximumSpendUsd:u().nonnegative(),hourlyCostUsd:u().nonnegative().nullable()}).strict().nullable(),evaluation:SF.nullable().default(null),evaluationProgress:c({stage:b(["baseline","adaptation","refiner","candidate_adaptation","candidate","comparison"]),completedAttempts:u().int().nonnegative(),totalAttempts:u().int().positive(),accounting:pF.nullable().default(null),evidenceSnapshot:fF.nullable().default(null)}).strict().nullable().default(null),reward:c({raw:u(),components:re(r(),u())}).strict().nullable(),receipt:Dt([mF,hF,gF,vF]).nullable(),adapterArtifactLineageId:T.nullable(),failure:r().trim().min(1).max(5e3).nullable(),startedAt:Oe,completedAt:Oe.nullable(),updatedAt:Oe}).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 gQ(e){const t=new Map;for(const _ of e.attempts){const P=`${_.phase}\0${_.taskId}`,M=t.get(P);(!M||_.startedAt>M.startedAt||_.startedAt===M.startedAt&&_.attemptId>M.attemptId)&&t.set(P,_)}const n=[...t.values()],a=[["adaptation","adaptation","candidate_adaptation"],["held_out","baseline","candidate"]].flatMap(([_,P,M])=>{const C=new Map(n.filter(N=>N.phase===M).map(N=>[N.taskId,N]));return n.filter(N=>N.phase===P).flatMap(N=>{const $=C.get(N.taskId);return $?[{cohort:_,taskId:N.taskId,baseline:N,refined:$,tokenDelta:$.totalTokens-N.totalTokens}]:[]})}),o=new Set(n.filter(_=>_.phase==="baseline"||_.phase==="adaptation").map(_=>_.taskId)).size,i=e.targetTaskCount??o;if(!Number.isInteger(i)||i<0)throw new Error("Benchmark task-efficiency target must be a non-negative integer.");const s={adaptation:new Set(n.filter(_=>_.phase==="adaptation").map(_=>_.taskId)).size,held_out:new Set(n.filter(_=>_.phase==="baseline").map(_=>_.taskId)).size},l=(_,P)=>({targetTaskCount:P,comparedTaskCount:_.length,passedTaskCount:_.filter(M=>M.tokenDelta<0).length,failedTaskCount:_.filter(M=>M.tokenDelta>=0).length,lowerTaskCount:_.filter(M=>M.tokenDelta<0).length,higherTaskCount:_.filter(M=>M.tokenDelta>0).length,unchangedTaskCount:_.filter(M=>M.tokenDelta===0).length}),m=l(a,i),d=a.reduce((_,P)=>_+P.baseline.totalTokens,0),h=a.reduce((_,P)=>_+P.refined.totalTokens,0),g=h-d,y=a.length===i;return{summary:PI.parse({target:"all_tasks_lower",...m,baselineTokens:d,refinedTokens:h,tokenDelta:g,tokenDeltaPercent:d>0?g/d*100:null,complete:y,passed:y&&m.passedTaskCount===i,cohorts:{adaptation:l(a.filter(_=>_.cohort==="adaptation"),s.adaptation),heldOut:l(a.filter(_=>_.cohort==="held_out"),s.held_out)}}),pairs:a}}const kF=b(["measuring","up_to_date","needs_attention"]),wF=b(["fixed","retained","regressed","unresolved","unavailable"]),Dy=c({evaluationRunId:T,attemptKey:T,artifactPath:r().trim().min(1).max(2e3),jsonPointer:r().trim().min(1).max(1e3),transcriptHash:J.nullable(),traceHash:J.nullable()}).strict(),Zf=c({level:S(.95),lower:u().finite(),upper:u().finite()}).strict(),IF=c({panelId:T,panelRole:Nu,passLabel:T.nullable(),taskset:Vt,attempted:u().int().nonnegative(),available:u().int().nonnegative(),passed:u().int().nonnegative(),strictSuccess:u().min(0).max(1).nullable(),strictSuccessCi95:Zf.nullable(),judgeScore:u().min(0).max(100).nullable(),judgeScoreCi95:Zf.nullable()}).strict(),_F=c({schemaVersion:S("openpond.modelCurrencySnapshot.v1"),id:T,contentHash:J,seriesId:T,protocol:c({id:T,revision:u().int().positive(),contentHash:J}).strict(),entryId:T,passLabel:T,parent:It("kind",[c({kind:S("base_model"),id:T,revision:r().trim().min(1).max(500)}).strict(),c({kind:S("model_version"),id:T,contentHash:J}).strict()]),candidate:c({kind:S("model_version"),id:T,contentHash:J}).strict(),sources:c({evaluationRunIds:p(T).max(1e5),attemptIds:p(T).max(1e6),tasksets:p(Vt).max(1e4),grader:Z,judge:Z.nullable(),calibration:Z.nullable()}).strict(),matches:p(c({key:T,panelId:T,panelRole:Nu,taskId:T,issueFamilyId:T,seed:u().int(),repetition:u().int().nonnegative(),classification:wF,parentPassed:A().nullable(),candidatePassed:A().nullable(),parentAttempt:Dy.nullable(),candidateAttempt:Dy.nullable()}).strict()).max(1e6),taskIds:c({fixed:p(T).max(1e6),retained:p(T).max(1e6),regressed:p(T).max(1e6),unresolved:p(T).max(1e6),unavailable:p(T).max(1e6)}).strict(),panels:p(IF).max(1e4),metrics:c({knownIssueCoverage:u().min(0).max(1).nullable(),issueFamilyGeneralization:u().min(0).max(1).nullable(),behavioralRetention:u().min(0).max(1).nullable(),currentAcquisitionDelta:u().finite().nullable(),retainedDeltaPoints:u().finite().nullable(),frontierStrictDelta:u().finite().nullable(),pairedPValue:u().min(0).max(1).nullable(),wins:u().int().nonnegative(),ties:u().int().nonnegative(),losses:u().int().nonnegative()}).strict(),statistics:c({matchedAttemptCount:u().int().nonnegative(),strictDelta:u().finite().nullable(),strictDeltaCi95:Zf.nullable(),exactPairedBinaryPValue:u().min(0).max(1).nullable(),pairedBootstrapSamples:u().int().positive()}).strict(),criteria:c({allRequiredAttemptsTerminal:A(),criticalCorrectionPassRate:u().min(0).max(1).nullable(),siblingPassRate:u().min(0).max(1).nullable(),behavioralRetentionRate:u().min(0).max(1).nullable(),retainedRegressionPoints:u().finite().nullable(),criticalPriorRegressionCount:u().int().nonnegative(),thresholdRelease:Z}).strict(),efficiency:c({inputTokens:u().int().nonnegative(),outputTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative(),costUsd:u().nonnegative().nullable(),latencyMs:u().int().nonnegative(),tokensPerSuccess:u().nonnegative().nullable(),throughputPerHour:u().nonnegative().nullable(),gpuSeconds:u().nonnegative().nullable()}).strict(),invariants:c({systemPromptHash:J,toolSchema:Z,application:Z,harness:Z,runtime:Z,grader:Z,autoRefinerEnabled:A()}).strict(),evidenceState:kF,evidenceReasons:p(T).max(100),projectedAt:Oe}).strict(),pd=It("kind",[c({kind:S("base_model"),id:T,revision:r().trim().min(1).max(500),label:r().trim().min(1).max(300)}).strict(),c({kind:S("model_version"),id:T,label:r().trim().min(1).max(300)}).strict(),c({kind:S("captured_model"),id:T,label:r().trim().min(1).max(300)}).strict()]),yl=Dt([c({source:S("evaluation_run").default("evaluation_run"),evaluationRunId:T,attemptId:T,modelLabel:r().trim().min(1).max(300).nullable().default(null),modelVersionId:T.nullable().default(null),reward:u().finite().nullable(),components:re(r(),u().finite()).default({})}).strict(),c({source:S("imported_response"),modelLabel:r().trim().min(1).max(300),modelVersionId:T.nullable().default(null),response:ce().refine(e=>e!==void 0,"An imported model response is required."),reward:u().finite().nullable().default(null),components:re(r(),u().finite()).default({})}).strict()]),CF=Dt([c({taskId:T,target:pd,attempt:yl}).strict(),c({taskId:T,target:b(["base","current"]).default("current"),attempt:yl}).strict(),c({taskId:T,target:b(["base","current"]).default("current"),evaluationRunId:T,attemptId:T,reward:u().finite().nullable(),components:re(r(),u().finite()).default({})}).strict().transform(({taskId:e,target:t,...n})=>({taskId:e,target:t,attempt:{source:"evaluation_run",modelLabel:null,modelVersionId:null,...n}}))]);c({schemaVersion:S("openpond.continualLearningDailyBatchManifest.v1"),id:T,seriesId:T,scheduleEntryId:T,dayOrdinal:u().int().positive().max(1e4),sourceTaskset:Vt,taskIds:p(T).min(1).max(1e3),observedAttempts:p(CF).max(1e3).default([]),sourceFileName:r().trim().min(1).max(500).nullable().default(null),availableAt:Oe}).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}:${AF(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 RF=c({schemaVersion:S("openpond.continualLearningDailyBatch.v1"),id:T,seriesId:T,scheduleEntryId:T,dayOrdinal:u().int().positive().max(1e4),label:r().trim().min(1).max(100),runMode:b(["automatic","manual"]).optional(),source:b(["json_upload","sealed_fixture"]),sourceFileName:r().trim().min(1).max(500).nullable(),sourceTaskset:Vt,tasks:p(c({taskId:T,taskContentHash:J,familyKey:T,disposition:b(["include","defer","exclude"]).nullable(),oracleReview:b(["pending","confirmed","needs_correction"]),note:r().trim().max(2e3),observedAttempt:yl.nullable(),baselineAttempt:yl.nullable().default(null),responses:p(c({target:pd,attempt:yl}).strict()).max(100).default([]),stagedAt:Oe.nullable().default(null),queuedEntry:vs.nullable().default(null)}).strict()).min(1).max(1e3),intakeEvaluation:c({status:b(["awaiting","running","ready","failed"]),requestedTargets:p(b(["base","current"])).max(2).default(["base","current"]),requestedPolicies:p(pd).max(100).default([]),runs:p(c({target:pd,runId:T}).strict()).max(100).default([]),baselineRunId:T.nullable(),currentRunId:T.nullable(),currentPolicy:It("kind",[c({kind:S("base_model"),id:T}).strict(),c({kind:S("model_version"),id:T}).strict()]).nullable(),failure:r().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:vs.nullable(),reviewedBy:T.nullable(),reviewedAt:Oe.nullable(),availableAt:Oe,revision:u().int().positive(),createdAt:Oe,updatedAt:Oe}).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,o]of e.tasks.entries()){const i=o.responses.map(s=>AI(s.target));new Set(i).size!==i.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."})}),PF=c({schemaVersion:S("openpond.continualBenchIssueReview.v1"),id:T,seriesId:T,scheduleEntryId:T,passLabel:T,packet:qB,splitManifest:c({id:T,contentHash:J}).strict(),decisions:p(c({taskId:T,disposition:b(["include","defer","exclude"]).nullable(),note:r().trim().max(2e3)}).strict()).min(2).max(1e4),status:b(["pending","reviewed","queued"]),queuedEntry:vs.nullable(),reviewedBy:T.nullable(),reviewedAt:Oe.nullable(),revision:u().int().positive(),createdAt:Oe,updatedAt:Oe}).strict().superRefine((e,t)=>{const n=[...e.packet.cases.map(i=>i.taskId)].sort(),a=[...e.decisions.map(i=>i.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 o=e.decisions.every(i=>i.disposition!==null&&i.note.length>0);e.status!=="pending"&&!o&&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 AI(e){return`${e.kind}:${e.id}`}function AF(e){return typeof e=="string"?e:AI(e)}const Da=r().trim().min(1).max(240),va=r().trim().min(8).max(256),TI=b(["grpo","dapo","gspo-token"]),Ll=c({id:Da,revision:r().trim().min(1).max(256),tokenizerRevision:r().trim().min(1).max(256),chatTemplateHash:va}),TF=c({maxRollouts:u().int().positive().max(1e6),maxEnvironmentExecutions:u().int().positive().max(1e6),maxInputTokens:u().int().positive(),maxOutputTokens:u().int().positive(),maxOptimizerSteps:u().int().positive().max(1e6),wallTimeMs:u().int().positive(),maximumCostUsd:u().nonnegative().nullable()}),EF=c({method:S("grpo"),groupSize:u().int().min(2).max(128),normalization:S("group_standardized"),advantageEpsilon:u().positive().max(.01).default(1e-8),loss:TI,clipRange:u().positive().max(1).default(.2),iterations:u().int().min(2).max(16).default(2),microbatchSize:u().int().positive().max(128).default(1),gradientAccumulationSteps:u().int().positive().max(128).default(1),adamw:bI}),EI=c({method:S("ppo"),valueModel:Ll,gamma:u().min(0).max(1),gaeLambda:u().min(0).max(1),policyClip:u().positive().max(1),valueClip:u().positive().max(10),valueLossCoefficient:u().nonnegative().max(10),ppoEpochs:u().int().positive().max(100),minibatchSize:u().int().positive().max(1e5)}),MF=It("method",[EF,EI]),MI=c({rewardModelVersion:c({id:Da,contentHash:va}).strict(),qualificationReport:c({id:Da,contentHash:va}).strict().nullable().default(null),evaluationReferences:p(c({id:Da,contentHash:va}).strict()).max(1e3).default([]),checkpoint:c({id:Da,contentHash:va,objectRef:r().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/),files:p(c({path:r().trim().min(1).max(512),sizeBytes:u().int().positive(),sha256:va}).strict()).min(4).max(128)}).strict(),runtime:RI,processorRelease:c({id:Da,contentHash:va}).strict(),rewardComposerRelease:c({id:Da,contentHash:va}).strict(),executionReceipt:c({id:Da,contentHash:va}).strict()}).strict(),jI=c({schemaVersion:S("openpond.policyOptimization.v1"),policyModel:Ll,referenceModel:Ll,dataset:c({tasksetId:Da,tasksetHash:va,split:S("train"),selectionStrategy:b(["stable_hash_top_n","rft_easy_curriculum_v1"]),selectionSeed:u().int(),maxExamples:u().int().positive().max(1e5)}),sampler:c({temperature:u().min(0).max(2),topP:u().min(0).max(1),maxOutputTokens:u().int().positive().max(32768),maxTurns:u().int().positive().max(1e3),concurrency:u().int().positive().max(1e3)}),environment:c({id:Da,version:r().trim().min(1).max(256),toolContractHash:va}),reward:c({graderId:Da,graderHash:va,learnedPreference:MI.nullable().default(null)}),kl:c({coefficient:u().nonnegative().nullable(),referenceConstraint:S("fixed_reference")}),budgets:TF,checkpointEverySteps:u().int().positive(),seed:u().int(),evaluationSplit:S("frozen_eval"),optimizer:MF}),Te=r().trim().min(1).max(240),Pt=r().trim().min(1),mt=r().trim().min(8).max(256),cc=re(r(),ce()).default({}),OI=c({schemaVersion:S("openpond.localModelChatConfiguration.v1").default("openpond.localModelChatConfiguration.v1"),profile:b(["efficient","full_harness","custom"]).default("efficient"),systemPromptMode:b(["lean","full_harness","custom"]).default("lean"),customSystemPrompt:r().max(2e4).nullable().default(null),contextWindowTokens:u().int().min(128).max(32768).default(1024),maxOutputTokens:u().int().min(1).max(512).default(64),temperature:u().min(0).max(2).default(0),repetitionPenalty:u().min(.5).max(2).default(1.1),noRepeatNgramSize:u().int().min(0).max(10).default(3),compaction:b(["off","when_needed"]).default("when_needed"),keepWarmSeconds:u().int().min(0).max(3600).default(300),updatedAt:Pt.nullable().default(null)}),jF=OI.parse({}),OF=c({schemaVersion:S("openpond.managedAdapterServingProjection.v1"),teamId:Te.nullable().default(null),source:S("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:A().default(!1),artifactContentHash:mt.nullable().default(null),baseProfileId:Te.nullable().default(null),publishedAt:Pt.nullable(),lastSyncedAt:Pt,lastError:r().trim().min(1).max(5e3).nullable()});function vQ(e){const t=e.managedServing;return!!(t?.source==="sandbox_managed_rl"&&t.canonicalArtifactState==="promotable"&&t.customerBindingAllowed)}function $I(e){return e.state==="ready"&&e.canonicalArtifactState==="promotable"&&e.canonicalDeploymentState==="ready"&&e.customerBindingAllowed&&!!e.teamId&&!!e.canonicalArtifactId&&!!e.canonicalDeploymentId}function bQ(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"&&$I(t)&&t.canonicalArtifactId&&t.canonicalDeploymentId?{kind:"sandbox_customer_binding",evaluationArtifactId:null,canonicalArtifactId:t.canonicalArtifactId,canonicalDeploymentId:t.canonicalDeploymentId}:null}function yQ(e){const t=e.managedServing;return t?$I(t)&&t.canonicalArtifactId&&t.canonicalDeploymentId?{kind:"sandbox_serving",canonicalArtifactId:t.canonicalArtifactId,canonicalDeploymentId:t.canonicalDeploymentId}:null:{kind:"source_artifact",canonicalArtifactId:null,canonicalDeploymentId:null}}const ov="openpond.crossSystemOperations.v1",SQ="1.0.0",NI="openpond.crossSystemTools.v1",$F=["search_crm","query_billing","search_support","run_python"],NF=b(["train","validation","frozen_eval"]),DF=b(["easy","medium","hard"]),LF=b(["renewal_risk_v2"]);b(["renewal_exposure","collections_prioritization","invoice_reconciliation","sla_escalation","contract_billing_mismatch"]);c({seed:u().int().nonnegative(),split:NF,difficulty:DF,scenarioProfile:LF.optional()});const zp={anyOf:[{type:"string",minLength:1,maxLength:256},{type:"null"}],default:null},qp={type:"integer",minimum:1,maximum:50,default:25},DI=[{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:zp,limit:qp}}},{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:zp,limit:qp}}},{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:zp,limit:qp}}},{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}}}}],dc=ZF({schemaVersion:NI,tools:DI}),UF=[`Use only the four registered synthetic Cross-System Operations tools. Contract ${dc}.`,"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(" "),HF=15;function zF(e="auto"){return[UF,"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: ${HF}.`,`Registered tool signatures: ${DI.map(qF).join("; ")}`].join(`
|
|
178
|
-
`)}zF();function qF(e){const t=zd(e.parameters),n=zd(t.properties),a=LI(t.required),o=Object.fromEntries(a.map(i=>[i,fd(n[i])]));return`${e.name}(${JSON.stringify(o)})`}function fd(e){const t=zd(e),n=Jf(t.anyOf);if(n.length)return n.map(fd).join("|");const a=Jf(t.enum);if(a.length)return a.join("|");if(t.type==="array")return[fd(t.items)];if(t.type==="object"){const o=zd(t.properties),i=LI(t.required);return Object.fromEntries(i.map(s=>[s,fd(o[s])]))}return typeof t.type=="string"?t.type:"unknown"}function zd(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Jf(e){return Array.isArray(e)?e:[]}function LI(e){return Jf(e).filter(t=>typeof t=="string")}const qd=b($F),BF=It("kind",[c({kind:S("model"),turn:u().int().nonnegative(),content:r().max(1e5)}),c({kind:S("tool_call"),turn:u().int().nonnegative(),callId:r().trim().min(1).max(240),name:qd,arguments:re(r(),ce())}),c({kind:S("tool_result"),turn:u().int().nonnegative(),callId:r().trim().min(1).max(240),name:qd,ok:A(),result:ce(),rows:u().int().nonnegative(),bytes:u().int().nonnegative(),durationMs:u().int().nonnegative(),error:r().trim().min(1).max(2e4).nullable()}),c({kind:S("final"),turn:u().int().nonnegative(),content:r().max(1e5)})]),FF=c({schemaVersion:S(ov),id:r().trim().min(1).max(240),worldId:r().trim().min(1).max(240),taskId:r().trim().min(1).max(240),toolContractHash:S(dc),modelRef:c({providerId:r().trim().min(1),modelId:r().trim().min(1)}).nullable(),status:b(["completed","budget_exhausted","cancelled","infrastructure_failure"]),steps:p(BF).max(1e3),startedAt:r().trim().min(1),completedAt:r().trim().min(1),infrastructureError:r().trim().min(1).max(2e4).nullable(),metadata:re(r(),ce()).default({})}),VF=c({schemaVersion:S(ov),trajectoryId:r().trim().min(1).max(240),outcome:b(["correct","incorrect","parse_failure","budget_exhausted","tool_schema_violation","infrastructure_failure","cancelled"]),reward:u().min(0).max(1.15).nullable(),rewardEligible:A(),exactAnswer:A(),components:c({exactAnswer:u().min(0).max(1),efficiency:u().min(0).max(.1),conciseOutput:u().min(0).max(.05)}),metrics:c({toolCalls:u().int().nonnegative(),rowsRead:u().int().nonnegative(),bytesRead:u().int().nonnegative(),consecutiveRetrievalCalls:u().int().nonnegative(),wallTimeMs:u().int().nonnegative(),parseFailures:u().int().nonnegative(),budgetExhausted:A()}),parsedAnswer:ce().nullable(),feedback:p(r().trim().min(1).max(5e3)).max(100)}),KF=c({id:r().trim().min(1).max(240),type:S("function"),function:c({name:qd,arguments:r().max(2e4)})}),UI=c({role:b(["system","user","assistant","tool"]),content:r().max(2e5).nullable(),tool_call_id:r().trim().min(1).max(240).optional(),tool_calls:p(KF).max(4).optional()});c({schemaVersion:S(ov),id:r().trim().min(1).max(240),taskId:r().trim().min(1).max(240),worldId:r().trim().min(1).max(240),trajectoryId:r().trim().min(1).max(240),toolContractHash:S(dc),approval:c({status:S("approved"),approvedBy:r().trim().min(1).max(240),approvedAt:r().trim().min(1)}),messages:p(UI).min(3).max(1e3)});const WF=c({tasksetTaskId:r().trim().min(1).max(240),environmentTaskId:r().trim().min(1).max(240),family:b(["renewal_exposure","collections_prioritization","invoice_reconciliation","sla_escalation","contract_billing_mismatch"]),prompt:r().trim().min(1).max(1e5),finalAnswer:r().trim().min(1).max(2e5),trajectoryId:r().trim().min(1).max(240),trajectoryHash:r().trim().min(8).max(256),toolNames:p(qd).min(1).max(100),toolCallCount:u().int().positive(),messageCount:u().int().min(3),reward:u().min(0).max(1.15),messages:p(UI).min(3).max(1e3)}),GF=c({status:S("approved"),approvedBy:r().trim().min(1).max(240),approvedAt:r().trim().min(1),previewHash:r().trim().min(8).max(256),trajectoryCount:u().int().positive()});c({schemaVersion:S("openpond.crossSystemExpertBootstrapPreview.v1"),tasksetId:r().trim().min(1).max(240),tasksetHash:r().trim().min(8).max(256),tasksetRevision:u().int().positive(),previewHash:r().trim().min(8).max(256),toolContractHash:S(dc),status:b(["ready_for_review","approved"]),approval:GF.nullable(),tasks:p(WF).min(1).max(100)});function ZF(e){const t=Yf(e);let n=2166136261,a=2654435769;for(let o=0;o<t.length;o+=1){const i=t.charCodeAt(o);n=Math.imul(n^i,16777619),a=Math.imul(a^i,2246822507)}return`${NI}:${Ly(n)}${Ly(a)}`}function Yf(e){return Array.isArray(e)?`[${e.map(Yf).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${Yf(n)}`).join(",")}}`:JSON.stringify(e)}function Ly(e){return(e>>>0).toString(16).padStart(8,"0")}const JF=c({schemaVersion:S("openpond.singleTurnPolicyTrajectory.v1"),id:Te,taskId:Te,status:b(["completed","infrastructure_failure"]),promptHash:mt,responseText:r().max(2e6),infrastructureError:r().trim().min(1).max(1e4).nullable(),startedAt:Pt,completedAt:Pt,metadata:cc}),YF=c({schemaVersion:S("openpond.ppoTrajectory.v1"),id:Te,taskId:Te,policyModelId:Te,referenceModelId:Te,valueModelId:Te,steps:p(c({index:u().int().nonnegative(),observationHash:mt,actionTokenIds:p(u().int().nonnegative()).min(1),terminated:A(),truncated:A(),reward:u(),policyLogProbability:u(),referenceLogProbability:u(),valuePrediction:u(),return:u(),advantage:u(),mask:u().min(0).max(1)})).min(1).max(1e5),createdAt:Pt}),QF=c({schemaVersion:S("openpond.exactAnswerVerifierResult.v1"),outcome:b(["correct","incorrect","parse_failure","infrastructure_failure"]),graderSetHash:mt,score:u().min(0).max(1).nullable(),passed:A(),rewardEligible:A(),expectedAnswerHash:mt,extractedAnswer:r().max(2e4).nullable(),feedback:p(r().trim().min(1).max(2e4)).max(1e3)}),XF=c({schemaVersion:S("openpond.rolloutTrajectoryReceipt.v1"),id:Te,jobId:Te,planId:Te,tasksetId:Te,tasksetHash:mt,taskId:Te,split:S("train"),correlationId:Te,provider:Te,providerTrace:c({invocationId:Te,experimentId:Te,rolloutId:Te,runId:Te,rowId:Te}),optimizerMethod:b(["grpo","ppo"]).default("grpo"),evidenceLevels:c({requested:b(["trajectory","aggregate","provider_reported"]),observed:b(["trajectory","aggregate","provider_reported"]),providerReported:b(["trajectory","aggregate","provider_reported"])}).default({requested:"trajectory",observed:"trajectory",providerReported:"provider_reported"}),budgetUsage:c({rollouts:u().int().nonnegative(),environmentExecutions:u().int().nonnegative(),inputTokens:u().int().nonnegative(),outputTokens:u().int().nonnegative(),optimizerSteps:u().int().nonnegative(),costUsd:u().nonnegative()}).default({rollouts:0,environmentExecutions:0,inputTokens:0,outputTokens:0,optimizerSteps:0,costUsd:0}),environment:c({id:Te,version:r().trim().min(1).max(256),worldId:Te,worldHash:mt,toolContractHash:mt}),policy:c({modelId:Te,checkpointId:Te.nullable(),completionParametersHash:mt}),status:b(["received","running","succeeded","failed"]),failureClass:b(["policy_failure","parse_failure","tool_schema_violation","budget_exhausted","cancelled","environment_failure","infrastructure_failure"]).nullable(),reward:c({eligible:A(),raw:u().min(0).max(1.15).nullable(),normalized:u().min(0).max(1).nullable(),components:re(r(),u())}),trajectory:Dt([FF,JF,YF]).nullable(),verifier:Dt([VF,QF]).nullable(),providerStatus:re(r(),ce()).default({}),receivedAt:Pt,startedAt:Pt.nullable(),completedAt:Pt.nullable(),updatedAt:Pt}),xQ="dataset-exact-answer",kQ="dataset-exact-answer-v1",wQ="no-tools-v1",Ir=b(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),Du=b(["lora","full"]),ci=b(["openpond_managed"]),e4=c({schemaVersion:S("openpond.sftRecipe.v1"),method:S("sft"),parameterization:S("lora"),baseModel:c({id:Te,revision:r().trim().min(1).max(256),tokenizerRevision:r().trim().min(1).max(256),chatTemplateHash:mt}),dataset:c({trainSplit:S("train"),validationSplit:b(["validation","frozen_eval"]),completionOnly:A(),maxSequenceLength:u().int().positive().max(32768),maxExamples:u().int().positive().max(1e5).default(1e3),selectionStrategy:S("stable_hash_top_n").default("stable_hash_top_n"),selectionSeed:u().int().default(17)}),lora:c({rank:u().int().positive().max(256),alpha:u().positive().max(1024),dropout:u().min(0).max(1),targetModules:p(Te).min(1).max(100)}),optimizer:c({learningRate:u().positive(),epochs:u().positive().max(100),maxSteps:u().int().positive().max(1e6),batchSize:u().int().positive().max(1e4),gradientAccumulationSteps:u().int().positive().max(1e4),seed:u().int()}),resourceLimits:c({cpuThreads:u().int().positive().max(256),memoryBytes:u().int().positive(),wallTimeMs:u().int().positive()})});c({id:Te,input:re(r(),ce()),expectedOutput:re(r(),ce()),tags:p(Te).max(100).default([])});c({id:Te,prompt:r().min(1).max(5e5),chosen:r().min(1).max(5e5),rejected:r().min(1).max(5e5),sourceRefs:p(Te).min(1).max(1e4)});c({id:Te,input:re(r(),ce()),tags:p(Te).max(100).default([])});c({schemaVersion:S("openpond.rewardModelRecipe.v1"),method:S("reward_model"),parameterization:S("lora_with_scalar_head"),runScope:b(["synthetic_smoke","human_preference"]),baseModel:c({id:Te,revision:r().trim().min(1).max(256),tokenizerRevision:r().trim().min(1).max(256),processorRevision:r().trim().min(1).max(256),chatTemplateHash:mt}).strict(),tasksetRelease:Z,preferenceDatasetRelease:Z,processorRelease:Z,input:c({kind:S("structured_text"),serialization:b(["scenario_input_and_candidate_json_v1","visible_agent_trajectory_v1"]),maxCharacters:u().int().positive().max(5e5)}).strict().default({kind:"structured_text",serialization:"scenario_input_and_candidate_json_v1",maxCharacters:32e3}),lora:c({rank:u().int().positive().max(256),alpha:u().positive().max(1024),dropout:u().min(0).max(1),targetModules:p(Te).min(1).max(100)}).strict(),heads:c({scalar:S("pooled_hidden_state_linear"),bucket:b(["none","three_class"]).default("three_class")}).strict(),loss:c({ranking:S("bradley_terry"),rankingWeight:u().positive(),bucketWeight:u().nonnegative(),tieWeight:u().nonnegative()}).strict(),optimizer:c({learningRate:u().positive(),maxSteps:u().int().positive().max(1e5),batchSize:u().int().positive().max(1e4),gradientAccumulationSteps:u().int().positive().max(1e4),seed:u().int(),checkpointEverySteps:u().int().positive().max(1e5)}).strict(),resourceLimits:c({wallTimeMs:u().int().positive().max(1440*60*1e3),maxExamples:u().int().positive().max(1e5),maxInputCharacters:u().int().positive().max(5e5).default(32e3),maxImagePixels:u().int().positive().max(1e8).optional(),maximumSpendUsd:u().nonnegative().max(1e5)}).strict()}).superRefine((e,t)=>{e.runScope==="synthetic_smoke"&&(e.optimizer.maxSteps>100||e.resourceLimits.maximumSpendUsd>10)&&t.addIssue({code:"custom",path:["resourceLimits"],message:"Synthetic-smoke Reward Model runs are limited to 100 steps and USD 10."})});const t4=c({schemaVersion:S("openpond.rftRecipe.v1"),method:S("grpo"),parameterization:S("lora"),baseModel:c({id:Te,revision:r().trim().min(1).max(256),tokenizerRevision:r().trim().min(1).max(256),chatTemplateHash:mt}),dataset:c({trainSplit:S("train"),validationSplit:b(["validation","frozen_eval"]),maxPromptTokens:u().int().positive().max(32768),maxExamples:u().int().positive().max(1e5).default(1e3),selectionStrategy:b(["stable_hash_top_n","rft_easy_curriculum_v1"]).default("stable_hash_top_n")}),lora:c({rank:u().int().positive().max(256)}),rollout:c({groupSize:u().int().min(2).max(64),concurrency:u().int().positive().max(32),maxTurns:u().int().positive().max(100),maxOutputTokens:u().int().positive().max(8192),temperature:u().min(0).max(2),topP:u().positive().max(1),seed:u().int()}),optimizer:c({learningRate:u().positive(),maxSteps:u().int().positive().max(1e5),clipRange:u().positive().max(1).default(.2),iterations:u().int().min(2).max(16).default(2),microbatchSize:u().int().positive().max(64).default(1),gradientAccumulationSteps:u().int().positive().max(64).default(1),advantageEpsilon:u().positive().max(.01).default(1e-8),adamw:bI}),loss:c({method:TI.default("grpo"),klBeta:u().min(0).nullable().default(null)}).default({method:"grpo",klBeta:null}),reward:c({graderId:Te,graderHash:mt,environmentId:Te,environmentVersion:r().trim().min(1).max(256),toolContractHash:mt,learnedPreference:MI.nullable().optional()}),resourceLimits:c({wallTimeMs:u().int().positive().max(1440*60*1e3),maxGpuSeconds:u().int().positive().max(10800).optional(),maxRollouts:u().int().positive().max(1e5),maxPayloadBytes:u().int().positive().max(10*1024*1024)}),policyOptimization:jI.nullable().default(null),continuation:c({schemaVersion:S("openpond.crossJobContinuationRequest.v1"),parentArtifact:Z,sourceArtifact:c({jobId:Te,artifactId:Te,checkpointId:Te,contentHash:mt}).strict(),optimizerMode:b(["continue","reset"])}).strict().optional()}),n4=c({schemaVersion:S("openpond.dpoRecipe.v1"),method:S("dpo"),parameterization:S("lora"),policyModel:Ll,referenceModel:Ll,dataset:c({trainSplit:S("train"),validationSplit:b(["validation","frozen_eval"]),maxPairs:u().int().positive().max(1e5),maxPromptTokens:u().int().positive().max(32768),maxCompletionTokens:u().int().positive().max(32768),selectionStrategy:S("stable_hash_top_n"),selectionSeed:u().int()}),lora:c({rank:u().int().positive().max(256),alpha:u().positive().max(1024),dropout:u().min(0).max(1),targetModules:p(Te).min(1).max(100)}),loss:c({variant:S("sigmoid"),beta:u().positive().max(10),labelSmoothing:u().min(0).max(.5).default(0)}),optimizer:c({learningRate:u().positive(),epochs:u().positive().max(100),maxSteps:u().int().positive().max(1e6),batchSize:u().int().positive().max(1e4),gradientAccumulationSteps:u().int().positive().max(1e4),seed:u().int()}),referenceLogprobs:c({cacheSchemaVersion:S("openpond.dpoReferenceLogprobs.v1"),cacheKey:mt,invalidationHash:mt}),resourceLimits:c({cpuThreads:u().int().positive().max(256),memoryBytes:u().int().positive(),wallTimeMs:u().int().positive()})}),a4=c({schemaVersion:S("openpond.ppoRecipe.v1"),method:S("ppo"),parameterization:S("lora"),policyOptimization:jI.extend({optimizer:EI}),lora:c({rank:u().int().positive().max(256),alpha:u().positive().max(1024),dropout:u().min(0).max(1),targetModules:p(Te).min(1).max(100)}),valueHead:c({initialization:S("policy_hidden_state_linear"),optimizerLearningRate:u().positive(),artifactName:S("value_head.safetensors")}),policyLearningRate:u().positive(),resume:c({checkpointId:Te.nullable(),policyHash:mt,referenceHash:mt,valueModelHash:mt,optimizerStateHash:mt.nullable()}),resourceLimits:c({cpuThreads:u().int().positive().max(256),memoryBytes:u().int().positive(),wallTimeMs:u().int().positive()})}),o4=c({schemaVersion:S("openpond.unsupportedRecipe.v1"),method:Ir.exclude(["sft","dpo","grpo","ppo"]),parameterization:Du,unsupportedReason:r().trim().min(1).max(5e3)}),HI=Dt([e4,n4,t4,a4,o4]),r4=c({schemaVersion:S("openpond.trainingDestinationCapabilities.v1"),destinationId:ci,available:A(),methods:p(Ir),parameterizations:p(Du),modelAllowlist:p(Te).default([]),maxDatasetBytes:u().int().nonnegative().nullable(),environmentPlacements:p(b(["none","local","remote","colocated","provider_native"])),nonProduction:A(),unavailableReason:r().trim().min(1).max(5e3).nullable(),checkedAt:Pt}),i4=c({destinationId:ci,available:A(),methods:p(Ir),parameterizations:p(Du),nonProduction:A(),unavailableReason:r().trim().min(1).max(5e3).nullable()}),s4=c({schemaVersion:S("openpond.baseModelCandidate.v1"),selectionKey:Te,label:r().trim().min(1).max(500),sourceLabel:r().trim().min(1).max(500),preference:lc,available:A(),nonProduction:A(),unavailableReason:r().trim().min(1).max(5e3).nullable(),methods:p(Ir),executionOptions:p(i4).min(1)}),l4=c({code:Te,severity:b(["warning","error"]),path:r().trim().max(2e3).nullable(),message:r().trim().min(1).max(5e3)}),c4=c({schemaVersion:S("openpond.trainingCompatibility.v1"),compatible:A(),destinationId:ci,tasksetId:Te,recipeMethod:Ir,issues:p(l4),checkedAt:Pt}),d4=Dt([rI,b(["destination_unavailable","destination_method_unsupported","destination_model_unsupported","destination_parameterization_unsupported","experimental_destination"])]);c({method:Ir,state:b(["recommended","compatible","needs_dataset_work","destination_unavailable","experimental_destination"]),reasonCodes:p(d4).default([]),reasons:p(r().trim().min(1).max(5e3)).default([]),destinationId:ci.nullable().default(null)});b(["small","standard","custom","small_experiment"]);const u4=c1,zI=c({schemaVersion:S("openpond.trainingPlan.v1"),id:Te,modelId:Te,tasksetId:Te,tasksetHash:mt,comparisonSeriesEntry:vs.nullable().optional(),evaluationTasksetRef:Vt.nullable().optional(),harnessRelease:Z.nullable().optional(),modelImprovementQualification:Z.nullable().optional(),destinationId:ci,recipe:HI,environmentPlacement:b(["none","local","remote","colocated","provider_native"]),compatibility:c4,dataPolicy:c({exportApproved:A(),approvedSourceIds:p(Te),retentionDays:u().int().nonnegative().nullable(),region:r().trim().min(1).max(200).nullable()}),estimatedCostUsd:u().nonnegative().nullable(),createdAt:Pt,contentHash:mt}),m4=c({path:r().trim().min(1).max(2e3),sha256:mt,sizeBytes:u().int().nonnegative(),role:b(["manifest","task_data","grader","environment","recipe","policy","provenance"])}),rv=c({schemaVersion:S("openpond.trainingBundle.v1"),id:Te,planId:Te,tasksetId:Te,tasksetHash:mt,recipeHash:mt,files:p(m4).min(1).max(1e6),totalSizeBytes:u().int().nonnegative(),sourceIds:p(Te),excludedSourceIds:p(Te),containsRawChats:S(!1),containsSecrets:S(!1),containsHiddenGraderAssets:S(!1),createdAt:Pt,contentHash:mt});c({schemaVersion:S("openpond.trainingBundleExport.v1"),manifest:rv,files:p(c({path:r().trim().min(1).max(2e3),sha256:mt,sizeBytes:u().int().nonnegative(),encoding:S("base64"),content:r()})).min(1),contentHash:mt});c({schemaVersion:S("openpond.trainingPreparedStart.v1"),plan:zI,bundle:rv,approvalActor:Te.nullable(),preparedAt:Pt});c({schemaVersion:S("openpond.trainingApproval.v1"),evaluationTasksetRef:Vt.nullable().optional(),id:Te,planId:Te,bundleHash:mt,harnessRelease:Z.nullable().optional(),modelImprovementQualification:Z.nullable().optional(),destinationId:ci,modelId:Te,method:Ir,parameterization:Du,maximumCostUsd:u().nonnegative().nullable(),approvedBy:Te,approvedAt:Pt});c({schemaVersion:S("openpond.trainingJobSourceSnapshot.v1"),evaluationTasksetRef:Vt.nullable().optional(),modelProjectId:Te,sourceProjectRevision:u().int().positive(),profileId:Te,taskset:c({id:Te,revision:u().int().positive(),contentHash:mt}).strict(),tasksetRelease:Z,harnessRelease:Z,baseModel:lc,method:Ir}).strict();const p4=b(["queued","starting","running","cancelling","cancelled","succeeded","failed","reconciling"]),qI=c({schemaVersion:S("openpond.trainingJob.v1"),id:Te,planId:Te,bundleHash:mt,approvalId:Te,destinationId:ci,status:p4,nonProduction:A(),workerPid:u().int().positive().nullable(),startedAt:Pt.nullable(),completedAt:Pt.nullable(),error:r().trim().min(1).max(2e4).nullable(),createdAt:Pt,updatedAt:Pt,metadata:cc}),f4=c({schemaVersion:S("openpond.trainingJobEvent.v1"),id:Te,jobId:Te,sequence:u().int().nonnegative(),type:b(["queued","start","progress","metric","checkpoint","cancel","complete","failure","reconcile"]),timestamp:Pt,payload:cc}),h4=c({schemaVersion:S("openpond.sftStepMetric.v1"),step:u().int().nonnegative(),maxSteps:u().int().positive(),timestamp:Pt,epoch:u().nonnegative().nullable(),loss:u().nullable(),learningRate:u().nonnegative().nullable(),gradientNorm:u().nonnegative().nullable(),entropy:u().nonnegative().nullable(),meanTokenAccuracy:u().min(0).max(1).nullable(),preferenceAccuracy:u().min(0).max(1).nullable().default(null),preferenceMargin:u().nullable().default(null),chosenReward:u().nullable().default(null),rejectedReward:u().nullable().default(null),chosenLogProbability:u().nullable().default(null),rejectedLogProbability:u().nullable().default(null),reward:u().nullable().default(null),policyLoss:u().nullable().default(null),advantageLoss:u().nullable().default(null),inputTokensSeen:u().int().nonnegative().nullable(),memoryBytes:u().int().nonnegative().nullable(),elapsedSeconds:u().nonnegative().nullable()}),g4=c({schemaVersion:S("openpond.policyOptimizationMetric.v1"),method:b(["grpo","ppo"]),step:u().int().nonnegative(),timestamp:Pt,learningRate:u().nonnegative().nullable().default(null),policyLoss:u().nullable(),valueLoss:u().nullable(),gradientNorm:u().nonnegative().nullable().default(null),meanReward:u().nullable(),meanReturn:u().nullable(),kl:u().nullable(),behaviorPolicyKlPreUpdate:u().nonnegative().nullable().default(null),entropy:u().nullable(),policyClipFraction:u().min(0).max(1).nullable(),behaviorPolicyClipFractionPreUpdate:u().min(0).max(1).nullable().default(null),valueClipFraction:u().min(0).max(1).nullable(),explainedVariance:u().nullable(),rolloutLearnerLag:u().int().nonnegative().nullable(),inputTokens:u().int().nonnegative(),outputTokens:u().int().nonnegative(),environmentExecutions:u().int().nonnegative(),trajectoryCount:u().int().nonnegative().nullable().default(null),costUsd:u().nonnegative().nullable()}),v4=c({schemaVersion:S("openpond.managedTrainingRunEvidence.v2"),provider:Te,providerRunId:Te,state:Te,progress:c({targetOptimizerSteps:u().int().nonnegative(),committedOptimizerSteps:u().int().nonnegative(),skippedOptimizerSteps:u().int().nonnegative()}),reward:c({finalMean:u().nullable(),variance:u().nonnegative().nullable(),minimum:u().nullable(),maximum:u().nullable(),distinctValueCount:u().int().nonnegative(),noSignalGroupCount:u().int().nonnegative(),trajectoryCount:u().int().nonnegative(),eligibleTrajectoryCount:u().int().nonnegative()}),usage:c({inputTokens:u().int().nonnegative(),outputTokens:u().int().nonnegative(),environmentExecutions:u().int().nonnegative()}),resource:c({provider:Te,gpuType:r().trim().min(1).max(300).nullable(),gpuCount:u().int().nonnegative().nullable(),hourlyCostUsd:u().nonnegative().nullable(),durationSeconds:u().nonnegative().nullable(),gpuSeconds:u().nonnegative().nullable()}),cost:c({totalUsd:u().nonnegative().nullable()}),checkpoint:c({id:Te,policyVersion:u().int().nonnegative(),sha256:mt.nullable(),sizeBytes:u().int().nonnegative().nullable()}).nullable(),movement:c({adapterDeltaNorm:u().nonnegative().nullable()}),evaluations:p(c({reference:c({id:Te,contentHash:mt}).nullable().optional(),kind:b(["baseline","candidate"]),policyVersion:u().int().nonnegative(),taskCount:u().int().nonnegative().nullable().optional(),targetTaskCount:u().int().nonnegative().nullable().optional(),score:u().nullable(),threshold:u().nullable(),passed:A().nullable()})),canonicalPublication:c({state:Te.nullable(),artifactId:Te.nullable()}),syncedAt:Pt}),Uy=c({count:u().int().nonnegative(),scoredCount:u().int().nonnegative(),meanScore:u().min(0).max(1).nullable(),passedCount:u().int().nonnegative(),passRate:u().min(0).max(1).nullable()}),Hy=c({status:b(["scored","unavailable"]),score:u().min(0).max(1).nullable(),passed:A(),rewardEligible:A(),failureClass:b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),feedback:p(r().trim().min(1).max(2e4)).max(1e3),components:p(c({graderId:Te,score:u().min(0).max(1).nullable(),passed:A(),feedback:r().trim().max(2e4).nullable()})).max(1e3)}),b4=c({taskId:Te,input:re(r(),ce()),baseOutput:re(r(),ce()).nullable(),trainedOutput:re(r(),ce()).nullable(),baseGrade:Hy.nullable(),trainedGrade:Hy.nullable()}),y4=c({schemaVersion:S("openpond.trainingEvaluationSummary.v1"),jobId:Te,tasksetId:Te,base:Uy,trained:Uy,meanScoreDelta:u().min(-1).max(1).nullable(),examples:p(b4).max(1e6)});c({schemaVersion:S("openpond.trainingRunDetail.v1"),job:qI,events:p(f4),stepMetrics:p(h4),policyMetrics:p(g4).default([]),managedEvidence:v4.nullable().default(null),evaluation:y4.nullable(),generatedAt:Pt});const S4=c({schemaVersion:S("openpond.trainingArtifact.v1"),id:Te,jobId:Te,kind:b(["adapter","checkpoint","metrics","log","manifest","evaluation"]),path:r().trim().min(1).max(4e3),sha256:mt,sizeBytes:u().int().nonnegative(),baseModelId:Te.nullable(),baseModelRevision:r().trim().min(1).max(256).nullable(),tokenizerRevision:r().trim().min(1).max(256).nullable(),chatTemplateHash:mt.nullable(),nonProduction:A(),createdAt:Pt,metadata:cc}),x4=c({schemaVersion:S("openpond.modelArtifactLineage.v1"),id:Te,modelId:Te,artifactId:Te,jobId:Te,tasksetId:Te,tasksetHash:mt,graderHash:mt,planHash:mt,bundleHash:mt,recipeHash:mt,workerVersion:r().trim().min(1).max(256),trainerVersion:r().trim().min(1).max(256),importedAt:Pt,frozenEvaluationArtifactId:Te.nullable(),promotable:A(),pinned:A().default(!1),status:b(["imported","rejected"]).default("imported"),rejectedAt:Pt.nullable().default(null),rejectionReason:r().trim().min(1).max(5e3).nullable().default(null),chatConfiguration:OI.default(jF),managedServing:OF.nullable().default(null)}),k4=b(["chat_manual","agent","extension","authoring_optimizer"]),w4=c({schemaVersion:S("openpond.modelBinding.v1"),id:Te,profileId:Te,role:k4,roleTargetId:Te,modelArtifactLineageId:Te,tasksetId:Te,evaluationArtifactId:Te.nullable(),status:b(["active","rolled_back"]),priorBindingId:Te.nullable(),rollbackTargetBindingId:Te.nullable(),promotedBy:Te,promotedAt:Pt,rolledBackAt:Pt.nullable(),metadata:cc});c({schemaVersion:S("openpond.trainingActivity.v1"),profileId:Te,active:A(),activeCounts:c({jobs:u().int().nonnegative(),creations:u().int().nonnegative(),minerRuns:u().int().nonnegative(),datasetImports:u().int().nonnegative()}),revision:mt,generatedAt:Pt});c({schemaVersion:S("openpond.tasksetOperationalState.v1"),tasksetId:Te,attempts:p(yB),artifacts:p(SB),grades:p(kB),evaluationResults:p(dH).default([]),generatedAt:Pt});const I4=c({schemaVersion:S("openpond.trainingState.v1"),profileId:Te,sources:p(F1),creations:p(yI),tasksetDrafts:p(uo).default([]),tasksets:p(Py),benchmarkRuns:p(cp()).default([]),benchmarkComparisons:p(cp()).default([]),datasetImports:p(NB).default([]),datasetArtifacts:p(Wz).default([]),graderAuditReports:p(wB),evaluationResults:p(cp()).default([]),candidates:p(vI),minerConfig:$u,minerRuns:p(iB).default([]),modelProjects:p(u4).default([]),modelVersions:p(lF).default([]),modelRuns:p(xF).default([]),comparisonSeries:p(eF).default([]),comparisonSeriesEntries:p(iF).default([]),modelCurrencySnapshots:p(_F).default([]),continualBenchIssueReviews:p(PF).default([]),continualLearningDailyBatches:p(RF).default([]),rewardModelVersions:p(cF).default([]),rewardModelRuns:p(uF).default([]),modelTasksets:p(Py).default([]),plans:p(zI),bundles:p(rv),jobs:p(qI),artifacts:p(S4),models:p(x4),rolloutReceipts:p(XF).default([]),modelBindings:p(w4).default([]),destinations:p(r4),baseModelCandidates:p(s4).default([]),activityRevision:mt.optional(),generatedAt:Pt}),_4=b(["trajectory","reward","demonstration","preference","correction","critique","targeted_feedback","grader_evidence","infrastructure_failure"]),C4=c({datasetRelease:Z,harnessRelease:Z,evidenceSetRelease:Z.nullable(),profileRelease:Z.nullable(),model:c({source:r().trim().min(1).max(200),revision:r().trim().min(1).max(500),artifactHash:J.nullable()}).strict(),environmentHash:J,graderHash:J,toolContractHash:J,verificationReceiptHash:J.nullable()}).strict(),Zo=c({schemaVersion:S("openpond.learningSignal.v1"),id:T,taskId:T.nullable(),episodeId:T.nullable(),policyVersion:u().int().nonnegative().nullable(),lineage:C4,approved:A(),verifier:b(["deterministic","model_judge","human","none"]),createdAt:Oe,contentHash:J,metadata:re(r(),ce()).default({})}).strict(),R4=Zo.extend({kind:S("trajectory"),payload:c({traceRef:r().trim().min(1).max(2e3),traceHash:J,terminal:A(),failureClass:b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),optimizerSample:S1.nullable().optional()}).strict()}).strict(),P4=Zo.extend({kind:S("reward"),payload:c({reward:u().finite(),components:re(r(),u().finite()),eligible:A(),graderEvidenceRefs:p(T).max(1e3)}).strict()}).strict(),A4=Zo.extend({kind:S("demonstration"),payload:c({prompt:r().max(5e5),response:r().max(1e6)}).strict()}).strict(),T4=Zo.extend({kind:S("preference"),payload:c({prompt:r().max(5e5),chosen:r().max(1e6),rejected:r().max(1e6),rationale:r().max(5e5).nullable()}).strict()}).strict(),E4=Zo.extend({kind:S("correction"),payload:c({original:r().max(1e6),corrected:r().max(1e6),rationale:r().max(5e5).nullable()}).strict()}).strict(),M4=Zo.extend({kind:S("critique"),payload:c({response:r().max(1e6),critique:r().max(5e5),severity:b(["note","warning","error"])}).strict()}).strict(),j4=Zo.extend({kind:S("targeted_feedback"),payload:c({turnIndex:u().int().nonnegative(),target:b(["reasoning","tool","answer","policy"]),feedback:r().max(5e5)}).strict()}).strict(),O4=Zo.extend({kind:S("grader_evidence"),payload:c({graderId:T,score:u().finite().nullable(),passed:A(),privilegedArtifactRefs:p(r().trim().min(1).max(2e3))}).strict()}).strict(),$4=Zo.extend({kind:S("infrastructure_failure"),approved:S(!1),verifier:S("none"),payload:c({code:T,phase:T,retryable:A(),rewardEligible:S(!1)}).strict()}).strict(),BI=It("kind",[R4,P4,A4,T4,E4,M4,j4,O4,$4]);c({schemaVersion:S("openpond.learningSignalBatch.v1"),manifestId:T,manifestHash:J,sequence:u().int().nonnegative(),signals:p(BI).min(1).max(1e5),contentHash:J}).strict();const N4=c({id:T,turn:u().int().nonnegative(),kind:b(["message","tool_call","terminal"]),name:T.nullable(),arguments:re(r(),ce()),content:r().max(1e6).nullable(),contentHash:J}).strict(),D4=c({actionId:T,turn:u().int().nonnegative(),terminal:A(),output:re(r(),ce()),artifactRefs:p(r().trim().min(1).max(2e3)),contentHash:J}).strict(),L4=c({sequence:u().int().nonnegative(),type:b(["created","reset","action","observation","terminal","graded","feedback","failure","collected","destroyed"]),timestamp:Oe,payloadHash:J,metadata:re(r(),ce()).default({})}).strict(),zy=c({graderId:T,graderVersion:r().trim().min(1).max(200),score:u().finite().nullable(),passed:A(),rewardEligible:A(),failureClass:b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),feedback:p(r().max(5e5)),visibleEvidenceRefs:p(r().trim().min(1).max(2e3)),privilegedEvidenceRefs:p(r().trim().min(1).max(2e3)),contentHash:J}).strict();c({schemaVersion:S("openpond.harnessRunTrace.v1"),manifest:Z,taskId:T,seed:r().trim().min(1).max(500),events:p(L4).max(1e6),actions:p(N4).max(1e5),observations:p(D4).max(1e5),graderEvidence:p(zy).max(1e4),learningSignals:p(BI).max(1e5),terminal:A(),failureClass:zy.shape.failureClass,artifactHash:J,contentHash:J}).strict();const U4=r().trim().min(1).max(2e3).refine(e=>{const t=e.replaceAll("\\","/");return!t.startsWith("/")&&!t.includes("\0")&&!t.split("/").some(n=>!n||n==="."||n==="..")},"path must be a safe relative path"),H4=b(["instruction","skill","skill_resource","agent","workflow","dependency_lock","program","asset"]),z4=c({id:T,kind:H4,path:U4,parentId:T.nullable(),mediaType:r().trim().min(1).max(200),visibility:b(["policy","verifier","host_private"]),portability:b(["portable","local_only"])}).strict().superRefine((e,t)=>{e.kind==="skill_resource"!=(e.parentId!==null)&&t.addIssue({code:"custom",message:"only Skill resources require parentId",path:["parentId"]})});c({schemaVersion:S("openpond.harnessSourceManifest.v1"),name:r().trim().min(1).max(240),files:p(z4).min(2).max(1e5),toolDeclarations:p(ec).max(200),capabilityRequirements:p(cg).max(200),lifecycle:Ek,graderInterface:Mk,runtimeProtocol:r().trim().min(1).max(500),metadata:re(r(),ce()).default({})}).strict().superRefine((e,t)=>{const n=new Set,a=new Map,o=new Set;for(const[i,s]of e.files.entries())n.has(s.id)&&t.addIssue({code:"custom",message:"file ids must be unique",path:["files",i,"id"]}),o.has(s.path)&&t.addIssue({code:"custom",message:"file paths must be unique",path:["files",i,"path"]}),n.add(s.id),a.set(s.id,s.kind),o.add(s.path);for(const[i,s]of e.files.entries())s.parentId&&!n.has(s.parentId)?t.addIssue({code:"custom",message:"parentId must reference a declared Skill",path:["files",i,"parentId"]}):s.parentId&&a.get(s.parentId)!=="skill"&&t.addIssue({code:"custom",message:"parentId must reference a primary Skill file",path:["files",i,"parentId"]});e.files.filter(i=>i.kind==="dependency_lock").length!==1&&t.addIssue({code:"custom",message:"exactly one dependency lock is required",path:["files"]}),e.files.filter(i=>i.kind==="program").length!==1&&t.addIssue({code:"custom",message:"exactly one Harness program is required",path:["files"]})});c({rootPath:r(),sourcePath:r(),binding:g$,currentRelease:ry,releases:p(ry),transitions:p(v$)}).strict();c({profile:$k,activate:A().default(!0),reason:r().trim().min(1).max(1e4),actor:r().trim().min(1).max(240).default("local-user"),authoringSkillHash:r().regex(/^[a-f0-9]{64}$/).nullable().default(null)}).strict();c({release:Z,reason:r().trim().min(1).max(1e4),actor:r().trim().min(1).max(240).default("local-user")}).strict();const q4=c({schemaVersion:S("openpond.trainingEngineCapabilities.v1"),adapterId:T,available:A(),methods:p(r().trim().min(1).max(100)),signalKinds:p(_4),modelFamilies:p(r().trim().min(1).max(200)),precisions:p(b(["fp32","fp16","bf16","tf32","int8","int4"])),topologies:p(r().trim().min(1).max(200)),workerProtocolVersion:r().trim().min(1).max(200),upstreamRevision:r().trim().min(1).max(500),workerImageDigest:r().regex(/^sha256:[a-f0-9]{64}$/).nullable().default(null),capabilityReceipt:J,checkedAt:Oe,unavailableReason:r().trim().min(1).max(5e3).nullable()}).strict(),B4=c({schemaVersion:S("openpond.computeTargetCapabilities.v1"),adapterId:T,kind:b(["local","ssh","managed","custom"]),provider:T.nullable(),available:A(),devices:p(c({id:T,kind:b(["cpu","gpu","accelerator"]),vendor:r().trim().min(1).max(200),name:r().trim().min(1).max(500),memoryBytes:u().int().nonnegative().nullable(),runtime:r().trim().min(1).max(200)}).strict()),supportsWorkerImages:A(),supportsArtifactTransfer:A(),supportsCancellation:A(),capabilityReceipt:J,checkedAt:Oe,unavailableReason:r().trim().min(1).max(5e3).nullable()}).strict(),F4=c({schemaVersion:S("openpond.harnessRuntimeCapabilities.v1"),adapterId:T,available:A(),placements:p(b(["local","remote","colocated","provider_native"])),lifecycle:p(b(["create","reset","step","grade","collect","destroy"])),deterministicReplay:A(),privilegedIsolation:A(),capabilityReceipt:J,checkedAt:Oe,unavailableReason:r().trim().min(1).max(5e3).nullable()}).strict();c({schemaVersion:S("openpond.resolvedTrainingPlan.v1"),manifest:dB,recipe:HI,runtime:Yg,compute:Qg,engine:Xg,execution:c({trainingPlanId:T,approvalId:T}).strict().nullable(),maximumSpendUsd:u().nonnegative().nullable(),approvalHash:J,contentHash:J}).strict().superRefine((e,t)=>{const n=[["runtime",e.runtime,e.manifest.runtimeTarget],["compute",e.compute,e.manifest.computeTarget],["engine",e.engine,e.manifest.engine]];for(const[a,o,i]of n)JSON.stringify(o)!==JSON.stringify(i)&&t.addIssue({code:"custom",path:[a],message:`${a} must exactly match the Harness Run Manifest`});e.recipe.method!==e.manifest.recipe.method&&t.addIssue({code:"custom",path:["recipe","method"],message:"Recipe method must match the Harness Run Manifest"}),e.approvalHash!==e.manifest.approval.approvalHash&&t.addIssue({code:"custom",path:["approvalHash"],message:"Approval hash must match the Harness Run Manifest"}),e.maximumSpendUsd!==e.manifest.approval.maximumSpendUsd&&t.addIssue({code:"custom",path:["maximumSpendUsd"],message:"Maximum spend must match the Harness Run Manifest"})});c({schemaVersion:S("openpond.adapterValidationReceipt.v1"),adapterId:T,valid:A(),issues:p(c({code:T,path:r().trim().max(2e3).nullable(),message:r().trim().min(1).max(5e3)}).strict()),capabilityReceipt:J,planHash:J,createdAt:Oe,contentHash:J}).strict();c({runId:T,adapterId:T,protocolVersion:b(["openpond.training.v2","adapter.native.v1"]).default("adapter.native.v1"),routeFamily:b(["training_v2","adapter_native"]).default("adapter_native"),routeId:T.optional(),providerJobId:r().trim().min(1).max(1e3).nullable(),tenantId:T.optional(),leaseId:T.nullable(),manifestHash:J.optional(),inputBundleHash:J.optional(),createdAt:Oe}).strict();c({runId:T,state:b(["queued","preparing","running","cancelling","cancelled","succeeded","failed"]),phase:r().trim().min(1).max(200),progress:u().min(0).max(1).nullable(),rolloutProgress:c({groupsCompleted:u().int().nonnegative(),groupsTarget:u().int().nonnegative(),optimizerUpdatesApplied:u().int().nonnegative(),optimizerUpdatesSkipped:u().int().nonnegative()}).strict().optional(),updatedAt:Oe,errorCode:T.nullable()}).strict();c({runId:T,manifestHash:J,artifacts:p(c({kind:b(["checkpoint","adapter","metrics","trace","evaluation","receipt"]),objectRef:r().trim().min(1).max(2e3),sha256:J,sizeBytes:u().int().nonnegative(),metadata:re(r(),ce()).optional()}).strict()),contentHash:J}).strict();const Qf=b(["ready","model_download_required","compute_setup_required","provider_managed","unsupported"]),V4=c({id:T,label:r().trim().min(1).max(500),description:r().trim().min(1).max(2e3),destinationId:T,computeAdapterId:T,runtimeAdapterId:T,engineAdapterId:T,methods:p(r().trim().min(1).max(100)),capabilityPills:p(r().trim().min(1).max(100)),executionMode:b(["local_worker","provider_native"]),approvalPolicy:c({providerId:oi,providerLabel:r().trim().min(1).max(200),settingsActionLabel:r().trim().min(1).max(500).nullable(),exportApprovalRequired:A(),exportDescription:r().trim().min(1).max(2e3).nullable(),preparationRequired:A(),minimumSpendUsd:u().nonnegative(),maximumSpendUsd:u().positive(),defaultMaximumSpendUsd:u().positive(),minimumRetentionDays:u().int().positive(),maximumRetentionDays:u().int().positive(),defaultRetentionDays:u().int().positive(),methodRequirement:r().trim().min(1).max(2e3).nullable()}).strict().nullable(),limits:c({maximumSequenceLength:u().int().positive(),maximumOutputTokens:u().int().positive(),maximumTrainingExamples:u().int().positive().nullable()}).strict(),defaults:c({loraRank:u().int().positive(),maxSteps:u().int().positive(),rolloutGroupSize:u().int().min(2).max(32),rolloutConcurrency:u().int().positive().max(32),rolloutOutputTokens:u().int().positive()}).strict(),available:A(),unavailableReason:r().trim().min(1).max(5e3).nullable()}).strict(),K4=c({selectionKey:T,label:r().trim().min(1).max(500),source:b(["local","builtin","huggingface","managed","search"]),modelId:r().trim().min(1).max(1e3),revision:r().trim().min(1).max(500).nullable(),tokenizerRevision:r().trim().min(1).max(500).nullable(),chatTemplateHash:J.nullable(),modelAssetId:T.nullable(),expectedBytes:u().int().nonnegative().nullable(),cached:A(),known:A(),searchResolved:A(),computeAdapterIds:p(T),engineAdapterIds:p(T),preparationState:Qf,reason:r().trim().min(1).max(5e3).nullable(),compatibilities:p(c({targetId:T,methods:p(r().trim().min(1).max(100)),state:Qf,reason:r().trim().min(1).max(5e3).nullable()}).strict())}).strict();c({schemaVersion:S("openpond.trainingCatalog.v1"),models:p(K4).max(1e5),engines:p(q4),compute:p(B4),runtimes:p(F4),targets:p(V4),generatedAt:Oe,contentHash:J}).strict();c({schemaVersion:S("openpond.trainingPreparationPlan.v1"),modelRunId:T,state:Qf,reason:r().trim().min(1).max(5e3).nullable(),runtime:Yg.nullable(),compute:Qg.nullable(),engine:Xg.nullable(),downloads:p(c({kind:S("model"),label:r().trim().min(1).max(500),expectedBytes:u().int().nonnegative(),digest:r().trim().min(8).max(500),cached:A(),state:b(["ready","required","downloading","cancelled","failed"]),progress:u().min(0).max(1).nullable(),cancellable:A(),diskImpactBytes:u().int().nonnegative()}).strict()),dataMovement:p(c({direction:b(["upload","download","none"]),label:r().trim().min(1).max(500),bytes:u().int().nonnegative().nullable()}).strict()),quoteUsd:u().nonnegative().nullable(),maximumSpendUsd:u().nonnegative().nullable(),retentionDays:u().int().nonnegative().nullable(),sideEffectsStarted:S(!1),contentHash:J}).strict();const iv=32e3,W4=b(["steer","message","followup","queued","result"]),G4=b(["pending","included","resolved","cancelled","rejected"]),FI=c({id:r().min(1),sequence:u().int().nonnegative(),sessionId:r().min(1),senderSessionId:r().min(1).nullable(),senderKind:b(["user","task","runtime"]),kind:W4,body:r().trim().min(1).max(iv),payload:re(r(),ce()).default({}),idempotencyKey:r().min(1).max(200),replyTo:r().min(1).nullable(),expectedTurnId:r().min(1).nullable(),turnId:r().min(1).nullable(),requestIds:p(r()),state:G4,revision:u().int().positive(),createdAt:r(),updatedAt:r(),error:r().nullable()}).strict();c({expectedTurnId:r().trim().min(1),idempotencyKey:r().trim().min(1).max(200),prompt:r().trim().min(1).max(iv)}).strict();It("action",[c({action:S("resume"),expectedRevision:u().int().positive()}).strict(),c({action:S("cancel"),expectedRevision:u().int().positive()}).strict(),c({action:S("edit"),expectedRevision:u().int().positive(),body:r().trim().min(1).max(iv)}).strict(),c({action:S("steer"),expectedRevision:u().int().positive(),expectedTurnId:r().trim().min(1)}).strict()]);const Z4=c({id:r().min(1),sessionId:r().min(1),turnId:r().min(1),targetSessionId:r().min(1).nullable(),targetTurnId:r().min(1).nullable(),targetInputId:r().min(1).nullable().default(null),afterSequence:u().int().nonnegative(),deadline:r(),state:b(["waiting","message","completed","failed","interrupted","unavailable","timeout","cancelled"]),createdAt:r(),updatedAt:r()}).strict();c({sessionId:r(),activeTurnId:r().nullable(),acceptingInput:A(),paused:A(),inputs:p(FI),waits:p(Z4)});function J4(e,t,n){const a=new Headers;a.set("Accept","text/event-stream"),a.set("Authorization",`Bearer ${e.token}`);const o=new URL(`${e.serverUrl.replace(/\/$/,"")}/v1/events`);return n!==void 0&&Number.isSafeInteger(n)&&n>0&&o.searchParams.set("afterSequence",String(n)),{url:o.toString(),init:{headers:a,signal:t}}}function Y4(e){return Math.min(500*2**Math.max(0,e),1e4)}async function Q4(e,t,n,a){VI(e);const o=e.body.getReader(),i=new TextDecoder;let s="";for(;!a?.aborted;){const{done:l,value:m}=await o.read();if(l){s+=i.decode();break}s+=i.decode(m,{stream:!0});let d=s.indexOf(`
|
|
179
|
-
|
|
180
|
-
`);for(;d>=0;){const h=s.slice(0,d);s=s.slice(d+2),By(h,t,n),d=s.indexOf(`
|
|
181
|
-
|
|
182
|
-
`)}}!a?.aborted&&s.trim()&&By(s,t,n)}function VI(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 X4(e,t,n,a,o={}){const i=new AbortController,s=o.fetchImpl??fetch,l=o.reconnectDelayMs??Y4;let m=qy(o.afterSequence),d=!1;return(async()=>{let h=0;for(;!i.signal.aborted;)try{const g=J4(e,i.signal,m),y=await s(g.url,g.init);if(VI(y),d=!0,h=0,await Q4(y,w=>{const _=qy(w.sequence);_>0&&_<=m||(_>0&&(m=_),t(w))},a,i.signal),d=!1,i.signal.aborted)break;throw new Error("event stream ended")}catch(g){if(d=!1,i.signal.aborted)break;n(g),await e5(l(h),i.signal),h+=1}})().catch(()=>{}),{close(){i.abort()},isOpen(){return d}}}function qy(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0?e:0}function By(e,t,n){let a="message";const o=[];for(const i of e.split(`
|
|
183
|
-
`))i.startsWith(":")||(i.startsWith("event: ")&&(a=i.slice(7).trim()),i.startsWith("data: ")&&o.push(i.slice(6)));if(a==="ready"){n?.();return}if(!(a!=="runtime"||o.length===0))try{t(JSON.parse(o.join(`
|
|
184
|
-
`)))}catch{}}async function e5(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})})}class t5 extends Error{constructor(t,n){super(t),this.status=n,this.name="ApiRequestError"}status}function Fy(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}const Vy=new WeakMap,Ky=new WeakMap,Wc=new WeakMap;let n5=0;async function q(e,t,n){if(t==="/v1/preferences"&&typeof n?.body=="string"){const o=(Wc.get(e)??Promise.resolve()).catch(()=>{}).then(()=>Wy(e,t,n));Wc.set(e,o);try{return await o}finally{Wc.get(e)===o&&Wc.delete(e)}}return Wy(e,t,n)}async function Wy(e,t,n){const a=++n5;if(t==="/v1/preferences"&&typeof n?.body=="string"){const m=Vy.get(e);if(!m)throw new Error("Reload settings before saving so changes can be checked against the current file.");n={...n,body:JSON.stringify({expectedRevision:m,...JSON.parse(n.body)})}}const o=new Headers(n?.headers);o.set("Content-Type","application/json"),o.set("Authorization",`Bearer ${e.token}`);const i=await fetch(`${e.serverUrl}${t}`,{...n,headers:o});if(!i.ok){const m=await i.json().catch(()=>({})),d=m&&typeof m=="object"&&"error"in m?String(m.error):i.statusText;throw new t5(d,i.status)}if(i.status===204)return;const s=await i.json(),l=s?.configuration?.rawRevision??(t==="/v1/preferences"?s?.rawRevision:void 0);return typeof l=="string"&&a>=(Ky.get(e)??0)&&(Vy.set(e,l),Ky.set(e,a)),s}function IQ(e){const t=new URL("/v1/terminal",e.serverUrl);return t.protocol=t.protocol==="https:"?"wss:":"ws:",t.toString()}function _Q(e){return["openpond-terminal",`openpond-token.${o5(e.token)}`]}function a5(e){const t=new TextEncoder().encode(e);let n="";for(let a=0;a<t.length;a+=32768){const o=t.subarray(a,a+32768);n+=String.fromCharCode(...o)}return btoa(n)}function o5(e){return a5(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function r5(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 i5={teamInvitations:e=>q(e,"/v1/team-invitations"),decideTeamInvitation:(e,t,n)=>q(e,`/v1/team-invitations/${t}`,{method:"POST",body:JSON.stringify({token:n})}),organizations:e=>q(e,"/v1/organizations"),createOrganization:(e,t)=>q(e,"/v1/organizations",{method:"POST",body:JSON.stringify(t)}),updateOrganization:(e,t,n)=>q(e,`/v1/organizations/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),organizationMembers:(e,t)=>q(e,`/v1/organizations/${encodeURIComponent(t)}/members`),upsertOrganizationMember:(e,t,n)=>q(e,`/v1/organizations/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify(n)}),organizationMcpServer:(e,t)=>q(e,`/v1/organizations/${encodeURIComponent(t)}/mcp-server`),generateOrganizationMcpServer:(e,t,n)=>q(e,`/v1/organizations/${encodeURIComponent(t)}/mcp-server`,{method:"POST",body:JSON.stringify(n)}),setOrganizationMcpServerStatus:(e,t,n)=>q(e,`/v1/organizations/${encodeURIComponent(t)}/mcp-server/${n}`,{method:"POST"})},s5={taskInbox:(e,t)=>q(e,`/v1/sessions/${encodeURIComponent(t)}/inbox`),steerTurn:(e,t,n)=>q(e,`/v1/sessions/${encodeURIComponent(t)}/turns/steer`,{method:"POST",body:JSON.stringify(n)}),queueTaskInput:(e,t,n,a)=>q(e,`/v1/sessions/${encodeURIComponent(t)}/inbox`,{method:"POST",body:JSON.stringify({input:n,idempotencyKey:a})}),updateTaskInput:(e,t,n,a)=>q(e,`/v1/sessions/${encodeURIComponent(t)}/inbox/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(a)}),sendTurn:(e,t,n)=>q(e,`/v1/sessions/${t}/turns`,{method:"POST",body:JSON.stringify(n)}),runSessionCommand:(e,t,n)=>q(e,`/v1/sessions/${encodeURIComponent(t)}/commands`,{method:"POST",body:JSON.stringify(n)}),recordPreflightTurnFailure:(e,t,n)=>q(e,`/v1/sessions/${t}/preflight-turns/failure`,{method:"POST",body:JSON.stringify(n)}),listCreateImproveRuns:(e,t={})=>q(e,`/v1/create-improve-runs?${l5(t).toString()}`),getCreateImproveRun:(e,t)=>q(e,`/v1/create-improve-runs/${encodeURIComponent(t)}`),getCreateImproveCandidateDiff:(e,t,n)=>q(e,`/v1/create-improve-runs/${encodeURIComponent(t)}/candidates/${encodeURIComponent(n)}/diff`),applyCreateImproveAction:(e,t,n)=>q(e,`/v1/create-improve-runs/${encodeURIComponent(t)}/actions`,{method:"POST",body:JSON.stringify(n)}),interruptTurn:(e,t,n)=>q(e,`/v1/sessions/${t}/turns/interrupt`,{method:"POST",body:JSON.stringify({reason:n})}),compactSession:(e,t,n={reason:"manual"})=>q(e,`/v1/sessions/${t}/compact`,{method:"POST",body:JSON.stringify(n)}),workspaceTool:(e,t,n)=>q(e,`/v1/sessions/${t}/workspace-tools`,{method:"POST",body:JSON.stringify(n)}),ensureCloudWorkspaceReady:(e,t,n)=>q(e,`/v1/sessions/${encodeURIComponent(t)}/workspace/ensure-ready`,{method:"POST",body:JSON.stringify(n)})};function l5(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 c5={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)),q(e,`/v1/sandboxes/${encodeURIComponent(t)}/files?${a.toString()}`)},sandboxUploadFile:(e,t,n)=>q(e,`/v1/sandboxes/${encodeURIComponent(t)}/files`,{method:"POST",body:JSON.stringify(n)}),preserveSandboxSource:(e,t,n={})=>q(e,`/v1/sandboxes/${encodeURIComponent(t)}/preserve-source`,{method:"POST",body:JSON.stringify(n)}),sandboxDownloadFile:async(e,t,n,a={})=>{const o=new URLSearchParams({path:n});a.offsetBytes!==void 0&&o.set("offsetBytes",String(a.offsetBytes)),a.maxBytes!==void 0&&o.set("maxBytes",String(a.maxBytes));const i=await q(e,`/v1/sandboxes/${encodeURIComponent(t)}/files?${o.toString()}`);return{...i,contents:i.file.isBinary?"":r5(i.file.contentsBase64)}}},d5={sandboxGitStatus:(e,t)=>q(e,`/v1/sandboxes/${encodeURIComponent(t)}/git/status`),sandboxGitDiff:(e,t,n)=>q(e,`/v1/sandboxes/${encodeURIComponent(t)}/git/diff`,{method:"POST",body:JSON.stringify(n)})},u5={connectedAppStatus:(e,t={})=>{const n=Fy(t);return n.set("status",t.status??"all"),q(e,`/v1/connected-apps/status${n.size>0?`?${n.toString()}`:""}`)},integrationConnections:(e,t={})=>{const n=Fy(t);return t.status&&n.set("status",t.status),q(e,`/v1/integrations/connections${n.size>0?`?${n.toString()}`:""}`)},sandboxIntegrationLeases:(e,t)=>q(e,`/v1/sandboxes/${encodeURIComponent(t)}/integrations`),attachSandboxIntegrationConnection:(e,t,n)=>q(e,`/v1/sandboxes/${encodeURIComponent(t)}/integrations`,{method:"POST",body:JSON.stringify(n)}),removeSandboxIntegrationLease:(e,t,n)=>q(e,`/v1/sandboxes/${encodeURIComponent(t)}/integrations`,{method:"DELETE",body:JSON.stringify({leaseId:n})})},m5={listSandboxProjects:(e,t)=>{const n=new URLSearchParams({teamId:t.teamId});return q(e,`/v1/sandbox-projects?${n.toString()}`)},getSandboxProject:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return q(e,`/v1/sandbox-projects/${encodeURIComponent(t)}?${a.toString()}`)},getSandboxProjectWorkspace:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return q(e,`/v1/sandbox-projects/${encodeURIComponent(t)}/workspace?${a.toString()}`)},upsertSandboxProject:(e,t)=>q(e,"/v1/sandbox-projects",{method:"POST",body:JSON.stringify(t)}),syncSandboxProject:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return q(e,`/v1/sandbox-projects/${encodeURIComponent(t)}/sync?${a.toString()}`,{method:"POST"})},uploadSandboxProjectSource:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId}),{teamId:o,...i}=n;return q(e,`/v1/sandbox-projects/${encodeURIComponent(t)}/source?${a.toString()}`,{method:"POST",body:JSON.stringify(i)})},archiveSandboxProject:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return q(e,`/v1/sandbox-projects/${encodeURIComponent(t)}?${a.toString()}`,{method:"DELETE"})},listSandboxAgents:(e,t)=>{const n=new URLSearchParams({teamId:t.teamId});return q(e,`/v1/sandbox-agents?${n.toString()}`)},upsertSandboxAgent:(e,t)=>q(e,"/v1/sandbox-agents",{method:"POST",body:JSON.stringify(t)}),runSandboxAgent:(e,t,n)=>q(e,`/v1/sandbox-agents/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify(n)}),runProfileAction:(e,t)=>q(e,"/v1/profile/run",{method:"POST",body:JSON.stringify(t)})},p5={sandbox:(e,t)=>q(e,`/v1/sandboxes/${encodeURIComponent(t)}`)},f5={...u5,...m5,...p5,...d5,...c5},h5={communities:(e,t)=>{const n=new URLSearchParams;return t&&n.set("cursor",t),q(e,`/v1/communities${n.size?`?${n}`:""}`)},communityPreview:(e,t)=>q(e,`/v1/communities/${encodeURIComponent(t)}/preview`),communityRules:(e,t)=>q(e,`/v1/communities/${encodeURIComponent(t)}/rules/current`),joinCommunity:(e,t,n)=>q(e,`/v1/communities/${encodeURIComponent(t)}/join`,{method:"POST",body:JSON.stringify({acceptedRulesVersionId:n})}),acceptCommunityRules:(e,t,n)=>q(e,`/v1/communities/${encodeURIComponent(t)}/rules/accept`,{method:"POST",body:JSON.stringify({acceptedRulesVersionId:n})}),leaveCommunity:(e,t)=>q(e,`/v1/communities/${encodeURIComponent(t)}/leave`,{method:"POST",body:"{}"}),communityChannels:(e,t)=>q(e,`/v1/communities/${encodeURIComponent(t)}/channels`),communityMessages:(e,t,n,a={})=>{const o=new URLSearchParams;return a.beforeSequence!=null&&o.set("beforeSequence",String(a.beforeSequence)),a.limit!=null&&o.set("limit",String(a.limit)),q(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages${o.size?`?${o}`:""}`)},sendCommunityMessage:(e,t,n,a)=>q(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages`,{method:"POST",body:JSON.stringify(a)}),editCommunityMessage:(e,t,n,a,o)=>q(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages/${encodeURIComponent(a)}`,{method:"PATCH",body:JSON.stringify({body:o})}),deleteCommunityMessage:(e,t,n,a)=>q(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages/${encodeURIComponent(a)}`,{method:"DELETE",body:"{}"}),markCommunityRead:(e,t,n,a)=>q(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/read`,{method:"POST",body:JSON.stringify({sequence:a})}),setCommunityChannelMuted:(e,t,n,a)=>q(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)),q(e,`/v1/communities/${encodeURIComponent(t)}/members/search${a.size?`?${a}`:""}`)},updateCommunityNotifications:(e,t,n)=>q(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)),q(e,`/v1/communities/${encodeURIComponent(t)}/events${a.size?`?${a}`:""}`)},communityRealtimeSession:(e,t)=>q(e,`/v1/communities/${encodeURIComponent(t)}/realtime-session`),uploadCommunityAttachment:(e,t,n,a)=>q(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/attachments/upload`,{method:"POST",body:JSON.stringify({attachment:a})}),communityAttachmentDownload:(e,t,n,a)=>q(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/attachments/${encodeURIComponent(a)}/download`)},sv="openpond-app-server-url",Ul="openpond-app-token",g5=750;function KI(){return window.location.protocol!=="http:"&&window.location.protocol!=="https:"?null:window.location.origin&&window.location.origin!=="null"?window.location.origin:null}function Xf(e){const t=e.getItem(sv)?.trim(),n=e.getItem(Ul)?.trim();return t&&n?{serverUrl:t,token:n}:null}function Bd(e){if(!e)return null;try{const t="__openpond_storage_probe__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return null}}function Di(e,t){e.setItem(sv,t.serverUrl),e.setItem(Ul,t.token)}function Gy(e,t){const n=Xf(e);n?.serverUrl!==t.serverUrl||n.token!==t.token||(e.removeItem(sv),e.removeItem(Ul))}function v5(){const e=window.__OPENPOND_WEB_CONNECTION__,t=e?.serverUrl?.trim(),n=e?.token?.trim();return t&&n?{serverUrl:t,token:n}:null}function b5(){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()||KI();return!a||!n?null:{serverUrl:a,token:n}}function y5(){window.location.hash&&window.history.replaceState(null,"",`${window.location.pathname}${window.location.search}`)}function Gc(e,t){t&&(e.some(n=>n.serverUrl===t.serverUrl&&n.token===t.token)||e.push(t))}function S5(){const e=[],t=Bd(window.sessionStorage),n=Bd(window.localStorage),a=KI(),o=t?.getItem(Ul)??n?.getItem(Ul);return Gc(e,null),Gc(e,a&&o?{serverUrl:a,token:o.trim()}:null),Gc(e,t?Xf(t):null),Gc(e,n?Xf(n):null),e}async function Bp(e){const t=new AbortController,n=window.setTimeout(()=>t.abort(),g5);try{const a=await fetch(`${e}/health`,{signal:t.signal}),o=await a.json().catch(()=>null);return a.ok&&o?.server==="openpond-app-server"}catch{return!1}finally{window.clearTimeout(n)}}async function x5(){if(window.openpond)return window.openpond.getConnection();const e=Bd(window.sessionStorage),t=Bd(window.localStorage),n=b5();if(n&&await Bp(n.serverUrl))return t&&Di(t,n),e&&Di(e,n),y5(),{...n,platform:navigator.platform};const a=v5();if(a&&await Bp(a.serverUrl))return t&&Di(t,a),e&&Di(e,a),{...a,platform:navigator.platform};const o=S5();for(const i of o){if(await Bp(i.serverUrl))return t&&Di(t,i),e&&Di(e,i),{...i,platform:navigator.platform};e&&Gy(e,i),t&&Gy(t,i)}throw new Error("No reachable OpenPond app server. Start `openpond ui` again and open the full printed URL.")}const Q={...h5,bootstrap:e=>q(e,"/v1/bootstrap?refreshCodex=1"),localProjectActions:(e,t)=>q(e,`/v1/projects/${encodeURIComponent(t)}/actions`),extensionCatalog:e=>q(e,"/v1/extensions"),extensionPreview:(e,t)=>q(e,"/v1/extensions/preview",{method:"POST",body:JSON.stringify(t)}),extensionAdd:(e,t)=>q(e,"/v1/extensions",{method:"POST",body:JSON.stringify(t)}),extensionUpdate:(e,t,n={})=>q(e,`/v1/extensions/github/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repo)}/update`,{method:"POST",body:JSON.stringify(n)}),extensionUpdateAll:e=>q(e,"/v1/extensions/update-all",{method:"POST"}),extensionRemove:(e,t)=>q(e,`/v1/extensions/github/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repo)}`,{method:"DELETE"}),skillSourceFile:(e,t,n,a)=>q(e,`/v1/skills/${t}/${encodeURIComponent(n)}/source?path=${encodeURIComponent(a)}`),teamChatMembers:(e,t)=>q(e,`/v1/team-chat/members?teamId=${encodeURIComponent(t)}`),teamChatAgents:(e,t)=>q(e,`/v1/team-chat/agents?teamId=${encodeURIComponent(t)}`),teamChatThreads:(e,t)=>q(e,`/v1/team-chat/threads?teamId=${encodeURIComponent(t)}`),teamChatRealtimeSession:(e,t)=>q(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)),q(e,`/v1/team-chat/events?${a.toString()}`)},teamChatGeneral:(e,t)=>q(e,"/v1/team-chat/threads/general",{method:"POST",body:JSON.stringify({teamId:t})}),teamChatDm:(e,t,n)=>q(e,"/v1/team-chat/threads/dm",{method:"POST",body:JSON.stringify({teamId:t,otherUserId:n})}),teamChatThread:(e,t,n,a={})=>{const o=new URLSearchParams({teamId:t});return a.beforeSequence!=null&&o.set("beforeSequence",String(a.beforeSequence)),a.limit!=null&&o.set("limit",String(a.limit)),q(e,`/v1/team-chat/threads/${encodeURIComponent(n)}?${o.toString()}`)},uploadTeamChatAttachment:(e,t,n)=>q(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/attachments/upload`,{method:"POST",body:JSON.stringify(n)}),teamChatAttachmentDownload:(e,t,n)=>q(e,`/v1/team-chat/attachments/${encodeURIComponent(n)}/download?teamId=${encodeURIComponent(t)}`),sendTeamChatMessage:(e,t,n)=>q(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/messages`,{method:"POST",body:JSON.stringify(n)}),createTeamChatAgentRun:(e,t,n)=>q(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/agent-runs`,{method:"POST",body:JSON.stringify(n)}),teamChatAgentConversation:(e,t,n)=>q(e,`/v1/team-chat/agent-runs/${encodeURIComponent(n)}?teamId=${encodeURIComponent(t)}`),editTeamChatMessage:(e,t,n,a)=>q(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/messages/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(a)}),deleteTeamChatMessage:(e,t,n,a)=>q(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/messages/${encodeURIComponent(n)}`,{method:"DELETE",body:JSON.stringify({teamId:a})}),markTeamChatRead:(e,t,n,a)=>q(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/read`,{method:"POST",body:JSON.stringify({teamId:n,sequence:a})}),setTeamChatThreadMuted:(e,t,n,a)=>q(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/mute`,{method:"POST",body:JSON.stringify({teamId:n,muted:a})}),createTeamChatAiThread:(e,t,n)=>q(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/ai-threads`,{method:"POST",body:JSON.stringify(n)}),teamChatAiThread:(e,t,n)=>q(e,`/v1/team-chat/ai-threads/${encodeURIComponent(n)}?teamId=${encodeURIComponent(t)}`),sendTeamChatAiTurn:(e,t,n)=>q(e,`/v1/team-chat/ai-threads/${encodeURIComponent(t)}/turns`,{method:"POST",body:JSON.stringify(n)}),executeTeamChatAiTurn:(e,t,n)=>q(e,`/v1/team-chat/ai-turns/${encodeURIComponent(t)}/execute`,{method:"POST",body:JSON.stringify({teamId:n})}),cancelTeamChatAiTurnExecution:(e,t,n)=>q(e,`/v1/team-chat/ai-turns/${encodeURIComponent(t)}/execute/cancel`,{method:"POST",body:JSON.stringify({teamId:n})}),usage:(e,t={})=>{const n=Zy(t),a=n.size?`?${n.toString()}`:"";return q(e,`/v1/usage${a}`)},usageRecords:(e,t={})=>{const n=Zy(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 q(e,`/v1/usage/records${a}`)},usageTurnCache:(e,t)=>q(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 q(e,`/v1/events/page${a}`)},workOutputs:e=>q(e,"/v1/work/outputs"),harnessHistory:e=>q(e,"/v1/harness"),refinerHistory:e=>q(e,"/v1/refiner"),updateRefinerProfile:(e,t)=>q(e,"/v1/refiner/update",{method:"POST",body:JSON.stringify(t)}),activateRefinerRelease:(e,t)=>q(e,"/v1/refiner/activate",{method:"POST",body:JSON.stringify(t)}),rollbackRefinerRelease:(e,t)=>q(e,"/v1/refiner/rollback",{method:"POST",body:JSON.stringify(t)}),updateHarnessBackgroundReview:(e,t)=>q(e,"/v1/harness/background-review",{method:"POST",body:JSON.stringify(t)}),reviewHarnessEvaluation:(e,t)=>q(e,"/v1/harness/evaluation-review",{method:"POST",body:JSON.stringify(t)}),updateHarnessEvaluationReviewSchedule:(e,t)=>q(e,"/v1/harness/evaluation-review/settings",{method:"POST",body:JSON.stringify(t)}),harnessReleaseDiff:(e,t)=>q(e,"/v1/harness/diff",{method:"POST",body:JSON.stringify(t)}),rollbackHarness:(e,t)=>q(e,"/v1/harness/rollback",{method:"POST",body:JSON.stringify(t)}),reviewHarnessProposal:(e,t)=>q(e,"/v1/harness/review",{method:"POST",body:JSON.stringify(t)}),runSubagentLifecycleAction:(e,t,n)=>q(e,`/v1/subagents/${encodeURIComponent(t)}/lifecycle`,{method:"POST",body:JSON.stringify(n)}),trainingState:(e,t)=>q(e,`/v1/training?profileId=${encodeURIComponent(t)}`),trainingActivity:(e,t)=>q(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),q(e,`/v1/training/catalog${a.size?`?${a.toString()}`:""}`)},datasetCatalog:(e,t)=>q(e,`/v1/training/datasets?profileId=${encodeURIComponent(t)}`),trainingRunDetail:(e,t,n={})=>q(e,`/v1/training/jobs/${encodeURIComponent(t)}/detail?evaluation=${n.includeEvaluation===!1?"false":"true"}`),candidateReview:(e,t,n=!1,a="models")=>q(e,`/v1/training/${a}/${encodeURIComponent(t)}/candidate-decision?refresh=${n}`),recordCandidateReview:(e,t,n,a="models")=>q(e,`/v1/training/${a}/${encodeURIComponent(t)}/candidate-decision`,{method:"POST",body:JSON.stringify(n)}),candidateReviewHistory:(e,t,n,a="models")=>q(e,`/v1/training/${a}/${encodeURIComponent(t)}/candidate-decision-history?decisionId=${encodeURIComponent(n.id)}&decisionHash=${n.contentHash}`),trainingEvaluationTasks:async(e,t,n,a)=>{const o=new URLSearchParams({limit:"25"});return a&&o.set("cursor",a),q(e,`/v1/training/jobs/${encodeURIComponent(t)}/evaluations/${encodeURIComponent(n.id)}/tasks?${o}`)},trainingRequest:(e,t,n,a="POST")=>q(e,`/v1/training${t}`,{method:a,body:a==="GET"||a==="DELETE"?void 0:JSON.stringify(n)}),datasetStorageState:e=>q(e,"/v1/settings/dataset-storage"),updateDatasetStorage:(e,t)=>q(e,"/v1/settings/dataset-storage",{method:"PATCH",body:JSON.stringify({datasetStorePath:t})}),hostedSavedWork:e=>q(e,"/v1/saved-work"),createHostedSavedWork:(e,t)=>q(e,"/v1/saved-work",{method:"POST",body:JSON.stringify(t)}),updateHostedSavedWork:(e,t,n)=>q(e,`/v1/saved-work/schedules/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),deleteHostedSavedWork:(e,t)=>q(e,`/v1/saved-work/schedules/${encodeURIComponent(t)}`,{method:"DELETE"}),runHostedSavedWork:(e,t,n)=>q(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 q(e,`/v1/chat-workflows${n}`)},createChatWorkflow:(e,t)=>q(e,"/v1/chat-workflows",{method:"POST",body:JSON.stringify(t)}),updateChatWorkflow:(e,t,n)=>q(e,`/v1/chat-workflows/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),deleteChatWorkflow:(e,t)=>q(e,`/v1/chat-workflows/${encodeURIComponent(t)}`,{method:"DELETE"}),runChatWorkflow:(e,t)=>q(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 q(e,`/v1/local-agent-schedules${a}`)},syncLocalAgentSchedules:e=>q(e,"/v1/local-agent-schedules/sync",{method:"POST",body:JSON.stringify({})}),patchLocalAgentSchedule:(e,t,n)=>q(e,`/v1/local-agent-schedules/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),runLocalAgentSchedule:(e,t,n={})=>q(e,`/v1/local-agent-schedules/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify(n)}),localAgentScheduleRuns:(e,t,n={})=>{const a=new URLSearchParams;n.limit!==void 0&&a.set("limit",String(n.limit));const o=a.size?`?${a.toString()}`:"";return q(e,`/v1/local-agent-schedules/${encodeURIComponent(t)}/runs${o}`)},refreshOpenPondAccounts:e=>q(e,"/v1/openpond/accounts/refresh",{method:"POST",body:JSON.stringify({})}),refreshOpenPondAccount:e=>q(e,"/v1/openpond/account?refresh=1"),loadMoreOpenPondApps:(e,t)=>q(e,`/v1/openpond/apps/more?offset=${encodeURIComponent(String(t.offset))}&limit=${encodeURIComponent(String(t.limit))}`),switchOpenPondAccount:(e,t)=>q(e,"/v1/openpond/accounts/switch",{method:"POST",body:JSON.stringify(t)}),removeOpenPondAccount:(e,t)=>q(e,"/v1/openpond/accounts",{method:"DELETE",body:JSON.stringify(t)}),signOutOpenPondAccount:e=>q(e,"/v1/openpond/accounts/logout",{method:"POST",body:JSON.stringify({})}),saveOpenPondAccount:(e,t)=>q(e,"/v1/openpond/accounts/login",{method:"POST",body:JSON.stringify(t)}),updateOpenPondAccountConfig:(e,t)=>q(e,"/v1/openpond/accounts/config",{method:"PATCH",body:JSON.stringify(t)}),savePreferences:(e,t)=>q(e,"/v1/preferences",{method:"PATCH",body:JSON.stringify(t)}),saveProviderSettings:(e,t)=>q(e,"/v1/providers",{method:"PATCH",body:JSON.stringify(t)}),providerSettings:e=>q(e,"/v1/providers"),loadProviderModels:(e,t,n={})=>{const a=new URLSearchParams;n.query?.trim()&&a.set("query",n.query.trim()),n.limit&&a.set("limit",String(n.limit));const o=a.size?`?${a.toString()}`:"";return q(e,`/v1/providers/${encodeURIComponent(t)}/models${o}`)},refreshProviderModels:(e,t,n)=>q(e,`/v1/providers/${encodeURIComponent(t)}/models`,{method:"POST",body:JSON.stringify(n)}),saveProviderCredential:(e,t,n)=>q(e,`/v1/providers/${encodeURIComponent(t)}/credential`,{method:"PUT",body:JSON.stringify(n)}),deleteProviderCredential:(e,t,n)=>q(e,`/v1/providers/${encodeURIComponent(t)}/credential`,{method:"DELETE",body:JSON.stringify(n)}),startOpenAiSubscriptionAuth:(e,t)=>q(e,"/v1/providers/openai/subscription-auth",{method:"POST",body:JSON.stringify(t)}),validateProviderCredential:(e,t,n)=>q(e,`/v1/providers/${encodeURIComponent(t)}/validate`,{method:"POST",body:JSON.stringify(n)}),savePersonalization:(e,t)=>q(e,"/v1/personalization",{method:"PATCH",body:JSON.stringify(t)}),recordClientDiagnostic:(e,t)=>q(e,"/v1/diagnostics/client",{method:"POST",body:JSON.stringify(t)}),profileCurrent:e=>q(e,"/v1/profile"),profileCatalog:e=>q(e,"/v1/profile/catalog"),profileWorkflows:e=>q(e,"/v1/profile/workflows"),profileEvaluations:e=>q(e,"/v1/profile/evaluations"),profileEvaluationPrepare:(e,t)=>q(e,"/v1/profile/evaluations/prepare",{method:"POST",body:JSON.stringify(t)}),profileEvaluationRun:(e,t)=>q(e,"/v1/profile/evaluations/run",{method:"POST",body:JSON.stringify(t)}),profileEvaluationRunSuite:(e,t)=>q(e,"/v1/profile/evaluations/run-suite",{method:"POST",body:JSON.stringify(t)}),profileEvaluationCompare:(e,t)=>q(e,"/v1/profile/evaluations/compare",{method:"POST",body:JSON.stringify({id:`comparison-${crypto.randomUUID()}`,runIds:t})}),profileEvaluationSaveReport:(e,t,n)=>q(e,"/v1/profile/evaluations/reports",{method:"POST",body:JSON.stringify({id:`report-${crypto.randomUUID()}`,evidenceKind:t,evidenceId:n})}),profileSelect:(e,t)=>q(e,"/v1/profile/select",{method:"POST",body:JSON.stringify({ref:t})}),profileRemove:(e,t)=>q(e,"/v1/profile/remove",{method:"POST",body:JSON.stringify({ref:t})}),profilePublicationPreview:(e,t)=>q(e,"/v1/profile/publication/preview",{method:"POST",body:JSON.stringify(t)}),profilePublicationPublish:(e,t)=>q(e,"/v1/profile/publication/publish",{method:"POST",body:JSON.stringify(t)}),profileInstall:(e,t)=>q(e,"/v1/profile/install",{method:"POST",body:JSON.stringify(t)}),profileUpdate:(e,t)=>q(e,"/v1/profile/update",{method:"POST",body:JSON.stringify({ref:t})}),profileInit:(e,t)=>q(e,"/v1/profile/init",{method:"POST",body:JSON.stringify(t)}),profileLoad:(e,t)=>q(e,"/v1/profile/load",{method:"POST",body:JSON.stringify(t)}),profileCheck:(e,t)=>q(e,"/v1/profile/check",{method:"POST",body:JSON.stringify(t)}),profileAgentRename:(e,t,n)=>q(e,`/v1/profile/agents/${encodeURIComponent(t)}/name`,{method:"PATCH",body:JSON.stringify(n)}),profileCommit:(e,t)=>q(e,"/v1/profile/commit",{method:"POST",body:JSON.stringify(t)}),profilePush:(e,t)=>q(e,"/v1/profile/push",{method:"POST",body:JSON.stringify(t)}),workspaceLspSettingsStatus:e=>q(e,"/v1/lsp/settings-status"),workspaceLspRuntimeStatus:e=>q(e,"/v1/lsp/status"),restartWorkspaceLsp:e=>q(e,"/v1/lsp/restart",{method:"POST"}),remoteAccess:e=>q(e,"/v1/remote-access"),enableRemoteAccess:e=>q(e,"/v1/remote-access/enable",{method:"POST"}),disableRemoteAccess:e=>q(e,"/v1/remote-access/disable",{method:"POST"}),voiceTranscriptionStatus:(e,t={})=>q(e,"/v1/audio/transcriptions/status",{signal:t.signal}),transcribeVoice:(e,t,n={})=>q(e,"/v1/audio/transcriptions",{method:"POST",body:JSON.stringify(t),signal:n.signal}),createSession:(e,t)=>q(e,"/v1/sessions",{method:"POST",body:JSON.stringify(t)}),patchSession:(e,t,n)=>q(e,`/v1/sessions/${t}`,{method:"PATCH",body:JSON.stringify(n)}),codexHistoryThread:(e,t,n={})=>{const a=new URLSearchParams;n.limit!==void 0&&a.set("limit",String(n.limit)),n.tail&&a.set("tail","1");const o=a.size?`?${a.toString()}`:"";return q(e,`/v1/codex-history/${encodeURIComponent(t)}${o}`)},codexHistoryThreadIncremental:(e,t,n={})=>{const a=new URLSearchParams({incremental:"1"});return n.afterEventId&&a.set("afterEventId",n.afterEventId),n.limit!==void 0&&a.set("limit",String(n.limit)),n.revision&&a.set("revision",n.revision),n.tail&&a.set("tail","1"),q(e,`/v1/codex-history/${encodeURIComponent(t)}?${a.toString()}`)},sendCodexHistoryTurn:(e,t,n)=>q(e,`/v1/codex-history/${encodeURIComponent(t)}/turns`,{method:"POST",body:JSON.stringify(n)}),interruptCodexHistoryTurn:(e,t)=>q(e,`/v1/codex-history/${encodeURIComponent(t)}/turns/interrupt`,{method:"POST"}),patchSidebarAppPreference:(e,t,n)=>q(e,`/v1/sidebar/apps/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),reorderSidebarApps:(e,t)=>q(e,"/v1/sidebar/apps/reorder",{method:"POST",body:JSON.stringify(t)}),sidebarFiles:e=>q(e,"/v1/sidebar/files"),patchSidebarFile:(e,t)=>q(e,"/v1/sidebar/files",{method:"PATCH",body:JSON.stringify(t)}),workspaceStatus:(e,t,n=!1,a={})=>q(e,`/v1/workspaces/${encodeURIComponent(t)}${n?"?ensure=1":""}`,{signal:a.signal}),createWorkspaceBranch:(e,t,n)=>q(e,`/v1/workspaces/${encodeURIComponent(t)}/branches`,{method:"POST",body:JSON.stringify(n)}),checkoutWorkspaceBranch:(e,t,n)=>q(e,`/v1/workspaces/${encodeURIComponent(t)}/branch`,{method:"PATCH",body:JSON.stringify(n)}),workspaceDiff:(e,t,n={})=>q(e,`/v1/workspaces/${encodeURIComponent(t)}/diff`,{signal:n.signal}),workspaceFile:(e,t,n)=>q(e,`/v1/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}`),saveWorkspaceFile:(e,t,n)=>q(e,`/v1/workspaces/${encodeURIComponent(t)}/file`,{method:"PATCH",body:JSON.stringify(n)}),signWorkspaceImageUrl:(e,t)=>q(e,"/v1/assets/workspace-image-url",{method:"POST",body:JSON.stringify(t)}),signLocalImageUrl:(e,t)=>q(e,"/v1/assets/local-image-url",{method:"POST",body:JSON.stringify(t)}),signLocalVideoUrl:(e,t)=>q(e,"/v1/assets/local-video-url",{method:"POST",body:JSON.stringify(t)}),signChatAttachmentImageUrl:(e,t)=>q(e,"/v1/assets/chat-attachment-image-url",{method:"POST",body:JSON.stringify(t)}),chatAttachmentFile:(e,t)=>q(e,"/v1/assets/chat-attachment-file",{method:"POST",body:JSON.stringify(t)}),workspaceLspTouch:(e,t,n,a={})=>q(e,`/v1/workspaces/${encodeURIComponent(t)}/lsp/touch`,{method:"POST",body:JSON.stringify(n),signal:a.signal}),workspaceLspAction:(e,t,n)=>q(e,`/v1/workspaces/${encodeURIComponent(t)}/lsp/action`,{method:"POST",body:JSON.stringify(n)}),workspaceTemplateConfig:(e,t)=>q(e,`/v1/openpond/apps/${encodeURIComponent(t)}/template-config`),...i5,...f5,createLocalProject:(e,t)=>q(e,"/v1/projects",{method:"POST",body:JSON.stringify(t)}),updateLocalProjectAgentSetup:(e,t,n)=>q(e,`/v1/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),uploadLocalProjectCloudSource:(e,t,n)=>q(e,`/v1/projects/${encodeURIComponent(t)}/cloud-source`,{method:"POST",body:JSON.stringify(n)}),previewLocalProjectCloudSource:(e,t,n={})=>{const a=new URLSearchParams;n.branch?.trim()&&a.set("branch",n.branch.trim());const o=a.toString()?`?${a.toString()}`:"";return q(e,`/v1/projects/${encodeURIComponent(t)}/cloud-source/preview${o}`)},deleteLocalProject:(e,t)=>q(e,`/v1/projects/${encodeURIComponent(t)}`,{method:"DELETE"}),gitAvailability:e=>q(e,"/v1/system/git"),installMacOSCommandLineTools:e=>q(e,"/v1/system/git/install-command-line-tools",{method:"POST",body:JSON.stringify({})}),...s5,resolveApproval:(e,t,n)=>q(e,`/v1/approvals/${t}`,{method:"POST",body:JSON.stringify(n)})};function Zy(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 k5=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),w5=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,a)=>a?a.toUpperCase():n.toLowerCase()),Jy=e=>{const t=w5(e);return t.charAt(0).toUpperCase()+t.slice(1)},WI=(...e)=>e.filter((t,n,a)=>!!t&&t.trim()!==""&&a.indexOf(t)===n).join(" ").trim(),I5=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var _5={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 C5=v.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:a,className:o="",children:i,iconNode:s,...l},m)=>v.createElement("svg",{ref:m,..._5,width:t,height:t,stroke:e,strokeWidth:a?Number(n)*24/Number(t):n,className:WI("lucide",o),...!i&&!I5(l)&&{"aria-hidden":"true"},...l},[...s.map(([d,h])=>v.createElement(d,h)),...Array.isArray(i)?i:[i]]));const dt=(e,t)=>{const n=v.forwardRef(({className:a,...o},i)=>v.createElement(C5,{ref:i,iconNode:t,className:WI(`lucide-${k5(Jy(e))}`,`lucide-${e}`,a),...o}));return n.displayName=Jy(e),n};const R5=[["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"}]],P5=dt("activity",R5);const A5=[["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"}]],T5=dt("archive-restore",A5);const E5=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],M5=dt("arrow-left",E5);const j5=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}]],GI=dt("bookmark",j5);const O5=[["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"}]],ZI=dt("bookmark-x",O5);const $5=[["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"}]],Yy=dt("book-open-text",$5);const N5=[["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"}]],Zc=dt("boxes",N5);const D5=[["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"}]],L5=dt("calendar-clock",D5);const U5=[["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"}]],JI=dt("chart-column-stacked",U5);const H5=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Po=dt("check",H5);const z5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],hd=dt("circle-check",z5);const q5=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Ko=dt("chevron-down",q5);const B5=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],ti=dt("chevron-right",B5);const F5=[["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"}]],V5=dt("circle-alert",F5);const K5=[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]],Lu=dt("cloud",K5);const W5=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],G5=dt("credit-card",W5);const Z5=[["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"}]],J5=dt("download",Z5);const Y5=[["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"}]],Fp=dt("external-link",Y5);const Q5=[["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"}]],X5=dt("file-output",Q5);const e3=[["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"}]],lv=dt("file-text",e3);const t3=[["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"}]],YI=dt("folder",t3);const n3=[["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"}]],QI=dt("folder-git-2",n3);const a3=[["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"}]],o3=dt("git-branch",a3);const r3=[["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"}]],i3=dt("github",r3);const s3=[["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"}]],XI=dt("earth",s3);const l3=[["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"}]],c3=dt("circle-question-mark",l3);const d3=[["path",{d:"M2 5h20",key:"1fs1ex"}],["path",{d:"M6 12h12",key:"8npq4p"}],["path",{d:"M9 19h6",key:"456am0"}]],u3=dt("list-filter",d3);const m3=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],p3=dt("loader-circle",m3);const f3=[["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"}]],h3=dt("maximize-2",f3);const g3=[["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"}]],Uu=dt("message-square",g3);const v3=[["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"}]],uc=dt("ellipsis",v3);const b3=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],e_=dt("panel-left",b3);const y3=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],eh=dt("panel-right",y3);const S3=[["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"}]],cv=dt("pin",S3);const x3=[["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"}]],dv=dt("pin-off",x3);const k3=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],w3=dt("plus",k3);const I3=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],_3=dt("power",I3);const C3=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],R3=dt("search",C3);const P3=[["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"}]],t_=dt("settings",P3);const A3=[["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"}]],n_=dt("shapes",A3);const T3=[["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"}]],Qy=dt("shield",T3);const E3=[["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"}]],Hu=dt("square-pen",E3);const M3=[["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"}]],a_=dt("square-terminal",M3);const j3=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],Xy=dt("user-round",j3);const O3=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],mc=dt("x",O3);function $3({platform:e}){return!zu()||uv(e)?null:k.jsxs("div",{className:"window-controls","aria-label":"Window controls",children:[k.jsx("button",{type:"button",className:"window-control minimize",title:"Minimize",onClick:()=>{Vp("minimize")},children:k.jsx(Ko,{size:14})}),k.jsx("button",{type:"button",className:"window-control maximize",title:"Maximize",onClick:()=>{Vp("toggleMaximize")},children:k.jsx(h3,{size:12})}),k.jsx("button",{type:"button",className:"window-control close",title:"Close",onClick:()=>{Vp("close")},children:k.jsx(mc,{size:13})})]})}function uv(e){const t=e?.toLowerCase()??"";return t==="darwin"||t.includes("mac")}function zu(){if(typeof window>"u")return!1;const e=window.openpond;return!!(e?.minimizeWindow||e?.toggleMaximizeWindow||e?.closeWindow)}async function Vp(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.")}}function N3({value:e,options:t,disabled:n,compact:a,className:o,icon:i,placement:s="bottom",label:l,tooltip:m,searchable:d=!1,floating:h=!1,onChange:g}){const[y,w]=v.useState(!1),[_,P]=v.useState(""),M=v.useRef(null),[C,N]=v.useState();v.useLayoutEffect(()=>{if(!y||!h)return;function R(){const E=M.current?.getBoundingClientRect();if(!E)return;const U=window.innerHeight-E.bottom-12,B=E.top-12,D=U<180&&B>U;N({position:"fixed",left:Math.max(12,E.left),width:Math.min(E.width,window.innerWidth-24),minWidth:0,maxWidth:"calc(100vw - 24px)",right:"auto",top:D?"auto":E.bottom+5,bottom:D?window.innerHeight-E.top+5:"auto",maxHeight:Math.max(80,Math.min(320,D?B-5:U-5)),overflowY:"auto",zIndex:1e3})}return R(),window.addEventListener("resize",R),window.addEventListener("scroll",R,!0),()=>{window.removeEventListener("resize",R),window.removeEventListener("scroll",R,!0)}},[y,h]);const $=t.find(R=>R.value===e)??t[0],j=_.trim().toLowerCase(),x=j?t.filter(R=>[R.label,R.shortLabel,R.description].some(E=>E?.toLowerCase().includes(j))):t;return v.useEffect(()=>{if(!y){P("");return}function R(U){M.current?.contains(U.target)||w(!1)}function E(U){U.key==="Escape"&&w(!1)}return document.addEventListener("pointerdown",R),document.addEventListener("keydown",E),()=>{document.removeEventListener("pointerdown",R),document.removeEventListener("keydown",E)}},[y]),k.jsxs("div",{className:`dropdown-select ${o??""} ${a?"compact":""} ${s==="top"?"open-up":""}`,"data-tooltip":m,ref:M,children:[k.jsxs("button",{type:"button",className:`dropdown-trigger ${y?"active":""}`,disabled:n,"aria-label":l,"aria-haspopup":"menu","aria-expanded":y,onClick:()=>w(R=>!R),children:[i,k.jsx("span",{children:$?.shortLabel??$?.label??e}),k.jsx(Ko,{size:14})]}),y&&k.jsxs("div",{className:"dropdown-menu",role:"menu",style:h?C:void 0,children:[d?k.jsxs("label",{className:"dropdown-search",onClick:R=>R.stopPropagation(),children:[k.jsxs("span",{className:"sr-only",children:["Search ",l]}),k.jsx("input",{autoFocus:!0,placeholder:`Search ${l.toLowerCase()}`,value:_,onChange:R=>P(R.target.value)})]}):null,x.map(R=>k.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":R.value===e,disabled:R.disabled,className:[R.value===e?"selected":"",R.separatorBefore?"separator-before":"",R.icon?"with-icon":""].filter(Boolean).join(" "),onClick:()=>{R.disabled||(g(R.value),P(""),w(!1))},children:[k.jsxs("span",{children:[R.icon==="plus"?k.jsx(w3,{size:13}):null,k.jsx("span",{children:R.label})]}),R.description&&k.jsx("small",{children:R.description})]},R.value)),x.length?null:k.jsx("div",{className:"dropdown-empty",children:"No matches"})]})]})}const D3=[{destination:"walkthroughs",icon:Yy,label:"Walkthroughs"},{destination:"external",icon:Yy,label:"Docs",url:"https://openpond.ai/docs"},{destination:"external",icon:lv,label:"Blog",url:"https://openpond.ai/blog"},{destination:"external",icon:G5,label:"Pricing",url:"https://openpond.ai/pricing"},{destination:"external",icon:XI,label:"Web app",url:"https://openpond.ai/sandboxes"},{destination:"external",icon:i3,label:"GitHub",url:"https://github.com/openpond/openpond"},{destination:"external",icon:Uu,label:"Submit issue",url:"https://github.com/openpond/openpond/issues/new/choose"}];function L3({onOpenWalkthroughs:e,walkthroughsActive:t}){const[n,a]=v.useState(!1),o=v.useRef(null);return v.useEffect(()=>{if(!n)return;function i(l){o.current?.contains(l.target)||a(!1)}function s(l){l.key==="Escape"&&a(!1)}return document.addEventListener("pointerdown",i),document.addEventListener("keydown",s),()=>{document.removeEventListener("pointerdown",i),document.removeEventListener("keydown",s)}},[n]),k.jsxs("div",{className:"sidebar-help-menu",ref:o,children:[k.jsx("button",{"aria-expanded":n,"aria-haspopup":"menu","aria-label":"Open docs and help menu",className:`sidebar-icon sidebar-help-trigger ${t?"active":""}`,"data-tooltip":"Help",onClick:()=>a(i=>!i),type:"button",children:k.jsx(c3,{size:17})}),n?k.jsx("div",{className:"sidebar-help-popover",role:"menu","aria-label":"Help",children:D3.map(i=>{const s=i.icon,l=k.jsxs(k.Fragment,{children:[k.jsx(s,{size:15}),k.jsx("span",{children:i.label})]});return i.destination==="walkthroughs"?k.jsx("button",{"aria-current":t?"page":void 0,className:"sidebar-help-item",onClick:()=>{a(!1),e()},role:"menuitem",type:"button",children:l},i.label):k.jsx("a",{className:"sidebar-help-item",href:i.url,onClick:m=>{m.preventDefault(),a(!1),U3(i.url)},rel:"noreferrer",role:"menuitem",target:"_blank",children:l},i.label)})}):null]})}async function U3(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-help",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const CQ=[{value:"chat",label:"Chat"},{value:"work",label:"Work"}],Kp=[{value:"chat",label:"Chat",description:"Chat and complete tasks"},{value:"models",label:"Models",description:"Evaluate, train, and serve models"},{value:"console",label:"Console",description:"Manage models and workspace resources"}];function o_(e){return e==="chat"?"New chat":"New task"}const th=["get-started","models","datasets","graders","experiments","tasks","tasksets","labeling","rewards","evaluations","runs","versions","serving"],H3={"get-started":"Get started",models:"Models",datasets:"Datasets",graders:"Graders",experiments:"Experiments",tasks:"Tasks",tasksets:"Tasksets",labeling:"Labeling",rewards:"Rewards",evaluations:"Runs",runs:"Runs",versions:"Versions",serving:"Serving"},z3={experiments:["history"],tasks:["drafts"],tasksets:["drafts","formats","batches"],rewards:["scorers","combined"],evaluations:["results","review","comparisons"],runs:["series","new"]},q3={datasets:["tasks","experiments","graders","versions"],graders:["overview","checks","usage","versions"],experiments:["overview","cases","compare","configuration"],tasksets:["overview","tasks","reward","attempts","releases"],rewards:["definition","usage","evidence"],evaluations:["overview","comparison","activity"],runs:["details","metrics","evaluation","rollouts","activity","artifacts"],versions:["overview","metrics","evaluation","rollouts","activity","artifacts"]};function za(e="models",t=null,n={}){return e==="evaluations"&&n.collection==="review"?za("labeling",t,{...n,collection:"default"}):{page:e,modelId:["get-started","datasets","graders","experiments"].includes(e)?null:t,collection:e==="evaluations"?"results":"default",resourceId:null,detailTab:null,query:"",after:null,...n}}function mv(e){const t=e.pathname.split("/").filter(Boolean);if(t[0]!=="models"&&t[0]!=="console")return null;let n;try{n=t.slice(1).map(decodeURIComponent)}catch{return null}if(n.some(R=>!R.trim()||R.length>2e3||R.includes("\0")))return null;const a=n[0]&&!th.includes(n[0])?n.shift():null;if(a&&(a.length>500||["projects","scorers"].includes(a)))return null;n[0]==="runs"&&n[1]==="evaluations"&&n.splice(0,2,"evaluations","results"),n[0]==="runs"&&n[1]==="comparisons"&&n.splice(0,2,"evaluations","comparisons");const o=n.shift(),i=o??"models";if(!th.includes(i)||o==="models"||a&&i==="get-started")return null;let s=i==="evaluations"?"results":"default";if(z3[i]?.includes(n[0]))s=n.shift();else if(i==="evaluations"&&n.length)return null;const l=n.shift()??null,m=n.shift()??null;if(n.length||m&&!l||(i==="models"||i==="get-started")&&l||s==="history"&&(l||m))return null;if(s==="drafts"||s==="new"){if(!l||m)return null}else if(s!=="series"){if(["review","formats","batches","comparisons","scorers","combined"].includes(s)){if(m)return null}else if(m&&!q3[i]?.includes(m))return null}if(i==="serving"&&m)return null;const d=new URLSearchParams(e.search??"");if([...d.keys()].some(R=>!["model","q","after","source","project","execution","pass","dataset","revision","hash","sort"].includes(R))||[...d.keys()].some(R=>d.getAll(R).length!==1))return null;const h=d.get("sort");if(h!==null&&(i!=="datasets"||!["id","name","updated"].includes(h)))return null;const g=d.has("revision")?Number(d.get("revision")):void 0,y=d.get("hash")??void 0;if((g!==void 0||y!==void 0)&&(!l||!["datasets","graders"].includes(i)||!Number.isSafeInteger(g)||g<=0||!/^[a-f0-9]{64}$/.test(y??"")))return null;const w=d.get("source");if(w!==null&&(i!=="labeling"&&(i!=="evaluations"||s!=="review")||!w.trim()||w.length>500)||d.has("dataset")&&(i!=="datasets"||!l||d.get("dataset")!=="release"))return null;const _=["datasets","graders","experiments"].includes(i);if(t[0]==="console"&&!_)return null;const P=d.get("project")==="all"?null:d.get("project"),M=d.get("execution"),C=d.get("pass");if([P,M,C].some(R=>R!==null&&(!R.trim()||R.length>240))||!_&&(P||M||C)||i!=="experiments"&&(M||C)||_&&a||s==="history"&&(M||C))return null;const N=d.get("model");if(_&&N!==null||a&&N&&a!==N)return null;const $=a??N;if(i==="get-started"&&d.size!==0)return null;const j=d.get("q")??"",x=d.get("after");return $!==null&&(!$.trim()||$.length>500)||j.length>1e3||x!==null&&(!x.trim()||x.length>2e3)?null:za(i,$,{collection:s,resourceId:l,detailTab:m,query:j,after:x,...h?{sort:h}:{},...g!==void 0?{revision:g,contentHash:y}:{},...d.get("dataset")==="release"?{datasetKind:"release"}:{},...t[0]==="console"?{area:"console"}:{},..._?{...d.has("project")?{projectId:P}:{},...d.has("execution")?{executionId:M}:{},...d.has("pass")?{passId:C}:{}}:{},...w!==null?{sourceId:w}:{}})}function qu(e){const t=[e.area==="console"?"/console":"/models"];if(e.modelId&&t.push(encodeURIComponent(e.modelId)),e.page==="evaluations"&&e.collection==="review")return qu(za("labeling",e.modelId,{collection:"default",resourceId:e.resourceId,sourceId:e.sourceId,query:e.query,after:e.after}));e.page==="evaluations"?t.push("runs",e.collection==="comparisons"?"comparisons":"evaluations"):(e.page!=="models"&&t.push(e.page),e.collection!=="default"&&t.push(e.collection)),e.resourceId&&t.push(encodeURIComponent(e.resourceId)),e.resourceId&&e.detailTab&&t.push(encodeURIComponent(e.detailTab));const n=new URLSearchParams;return e.projectId?n.set("project",e.projectId):e.projectId===null&&["datasets","graders","experiments"].includes(e.page)&&n.set("project","all"),e.page==="datasets"&&e.resourceId&&e.datasetKind==="release"&&n.set("dataset","release"),e.page==="datasets"&&e.sort&&n.set("sort",e.sort),e.revision!==void 0&&e.contentHash&&e.resourceId&&["datasets","graders"].includes(e.page)&&(n.set("revision",String(e.revision)),n.set("hash",e.contentHash)),e.executionId&&n.set("execution",e.executionId),e.passId&&n.set("pass",e.passId),e.query&&n.set("q",e.query),e.after&&n.set("after",e.after),(e.page==="labeling"||e.page==="evaluations"&&e.collection==="review")&&e.sourceId&&n.set("source",e.sourceId),`${t.join("/")}${n.size?`?${n}`:""}`}function B3(e,t){return za(e.page,t,{...e.area?{area:e.area}:{},...["datasets","graders","experiments"].includes(e.page)&&e.projectId!==void 0?{projectId:e.projectId}:{},collection:e.collection==="new"||e.collection==="drafts"?"default":e.collection})}function RQ(e,t,n=null){return{...e,resourceId:t,detailTab:n,after:null,...t!==e.resourceId?{revision:void 0,contentHash:void 0}:{}}}const Fd=new Set,nh=new Set,F3=new Set(["account","notifications","harness","harness-refiner","harness-continuous-review","harness-contents","harness-releases","profile","skills","configuration","context","training","subagents","editor","providers","dataset-storage","remote","usage","personalization","diagnostics"]),ah={apps:"/apps",outputs:"/outputs",projects:"/projects",scheduled:"/workflows","get-started":"/get-started"};let oh=!1,rh="",gd=null,r_=null,Hl="",La=0,al=null,Sl=!1,Wp=null,vd=!1;function pv(e){const t=mv(e);if(t)return{kind:"models",route:t};const n=e.pathname.split("/").filter(Boolean);if(n[0]==="models"||n[0]==="console")return{kind:"models_unavailable",pathname:e.pathname,search:e.search??""};if(n[0]==="settings"&&n.length===2&&F3.has(n[1])){const o=fv(new URLSearchParams(e.search??"").get("returnTo"));return{kind:"settings",section:n[1],...o?{returnTo:o}:{}}}if(n[0]==="chat"&&n.length<=2)try{return{kind:"chat",sessionId:n[1]&&n[1]!=="new"?decodeURIComponent(n[1]):null}}catch{return null}const a=Object.keys(ah).find(o=>ah[o]===e.pathname);return a?{kind:"view",view:a}:null}function i_(e){if(e.kind==="models")return qu(e.route);if(e.kind==="models_unavailable")return`${e.pathname}${e.search}`;if(e.kind==="settings"){const t=fv(e.returnTo??null);return`/settings/${e.section}${t?`?${new URLSearchParams({returnTo:t})}`:""}`}return e.kind==="chat"?e.sessionId?`/chat/${encodeURIComponent(e.sessionId)}`:"/chat/new":ah[e.view]}function V3(e){const t=e?.kind==="settings"?fv(e.returnTo??null):null;if(t){const n=new URL(t,"https://local.openpond.invalid"),a=mv(n);if(a)return{kind:"models",route:a}}return{kind:"chat",sessionId:null}}function fv(e){if(!e||e.length>6e3||!["/models","/console"].some(a=>e.startsWith(a))||e.startsWith("//"))return null;const t=new URL(e,"https://local.openpond.invalid");if(t.origin!=="https://local.openpond.invalid"||t.hash)return null;const n=mv(t);return n?qu(n):null}function pc(){return`${window.location.pathname}${window.location.search}`}function hv(){if(typeof window>"u")return;const e=oh?Hl:pc();e!==rh&&(rh=e,gd=pv(new URL(e,window.location.origin)),r_=gd?.kind==="models"?gd.route:null)}function s_(){rh="",hv();for(const e of nh)e()}async function gv(e){if(vd)return!1;vd=!0;try{for(const t of[...Fd].reverse())if(!await t(e))return!1;return!0}finally{vd=!1}}function vv(e){return{...window.history.state,openpondNavigationIndex:e}}async function K3(){const e=pc(),t=typeof window.history.state?.openpondNavigationIndex=="number"?window.history.state.openpondNavigationIndex:La-1;if(al&&t===La){const a=al;al=null,a();return}if(Wp===t||Fd.size===0){Wp=null,Hl=e,La=t,window.history.replaceState(vv(La),"",e),s_();return}if(t===La)return;if(Sl||vd){al??=()=>{},window.history.go(La-t);return}Sl=!0;const n=t-La;try{await new Promise(a=>{al=a,window.history.go(-n)}),await gv(e)&&(Wp=t,window.history.go(n))}finally{Sl=!1}}function bv(){if(oh||typeof window>"u")return;const e=pv(window.location);Hl=e?i_(e):pc(),La=typeof window.history.state?.openpondNavigationIndex=="number"?window.history.state.openpondNavigationIndex:0,window.history.replaceState(vv(La),"",Hl),window.addEventListener("popstate",K3),oh=!0}function l_(e){return nh.add(e),bv(),()=>{nh.delete(e)}}function PQ(e){return Fd.add(e),bv(),()=>{Fd.delete(e)}}async function AQ(e){!Sl&&await gv(pc())&&e()}function W3(){return v.useSyncExternalStore(l_,()=>(hv(),r_),()=>null)}function G3(){return v.useSyncExternalStore(l_,()=>(hv(),gd),()=>null)}async function Qt(e,t="push"){if(typeof window>"u"||(bv(),Sl))return!1;if(e.kind==="settings"&&!e.returnTo){const a=pv(window.location),o=a?.kind==="models"?qu(a.route):a?.kind==="settings"?a.returnTo:void 0;o&&(e={...e,returnTo:o})}const n=i_(e);return pc()===n?!0:await gv(n)?(t==="push"&&La++,window.history[t==="replace"?"replaceState":"pushState"](vv(La),"",n),Hl=n,s_(),!0):!1}function rs(e,t="push"){return Qt({kind:"models",route:e},t)}function Z3({experience:e="work",beginNewChat:t}){return k.jsx("div",{className:"sidebar-new-task",children:k.jsxs("button",{className:"nav-command nav-command-new-task",type:"button",onClick:()=>{Qt({kind:"chat",sessionId:null}),t(null)},children:[k.jsx(Hu,{size:18}),k.jsx("span",{children:o_(e)})]})})}function J3({productArea:e="chat",setSectionMenuOpen:t,setSelectedAppId:n,setSelectedProjectId:a,setSelectedSessionId:o,setView:i,view:s,modelProjects:l=[],modelTrainingActivityByProjectId:m={}}){const d=W3(),h=d?.modelId??null,g=d?.page??"models";function y(){n(null),a(null),o(null),t(null)}async function w(C){await rs(za(C,["datasets","graders","experiments"].includes(C)?null:h,{...e==="console"?{area:"console"}:{},...d?.projectId!==void 0?{projectId:d.projectId}:{}}))&&(y(),i("labs"))}async function _(C){await rs(B3(d??za(),C||null))&&(y(),i("labs"))}async function P(C){await Qt({kind:"view",view:C})&&(y(),i(C))}const M=h?m[h]??null:null;return k.jsxs("nav",{className:"sidebar-nav","aria-label":"Primary",children:[e!=="chat"?k.jsxs(k.Fragment,{children:[["datasets","graders","experiments"].includes(g)?null:k.jsxs("div",{className:"sidebar-model-project-picker",children:[k.jsx("span",{className:"sidebar-nav-group-label",children:"Model"}),k.jsx(N3,{label:"Model",searchable:l.length>8,value:h??"",options:[{value:"",label:"All models"},...h&&!l.some(C=>C.id===h)?[{value:h,label:"Unavailable model",disabled:!0}]:[],...l.map(C=>({value:C.id,label:C.name}))],onChange:C=>{_(C)}})]}),th.filter(C=>e==="console"?["datasets","graders","experiments"].includes(C):C!=="tasksets"&&C!=="evaluations").map(C=>{const N={"get-started":Zc,models:P5,datasets:Zc,graders:Qy,experiments:hd,tasks:Zc,tasksets:Zc,labeling:hd,rewards:Qy,evaluations:hd,runs:JI,versions:o3,serving:Lu}[C];return k.jsxs("button",{className:`nav-command ${s==="labs"&&(g===C||C==="runs"&&g==="evaluations")?"active":""}`,"aria-current":s==="labs"&&(g===C||C==="runs"&&g==="evaluations")?"page":void 0,type:"button",onClick:()=>{w(C)},children:[k.jsx(N,{size:16}),k.jsx("span",{children:H3[C]}),C==="runs"&&M?k.jsx("span",{className:"sidebar-running-dot","aria-label":M.label}):null]},C)})]}):null,e==="chat"?k.jsxs(k.Fragment,{children:[k.jsxs("button",{className:`nav-command nav-command-prominent ${s==="scheduled"?"active":""}`,"aria-label":"Workflows",type:"button",onClick:()=>{P("scheduled")},children:[k.jsx(L5,{size:18}),k.jsx("span",{children:"Workflows"})]}),k.jsxs("button",{className:`nav-command nav-command-prominent ${s==="outputs"?"active":""}`,"aria-label":"Outputs",type:"button",onClick:()=>{P("outputs")},children:[k.jsx(X5,{size:18}),k.jsx("span",{children:"Outputs"})]}),k.jsxs("button",{className:`nav-command nav-command-prominent ${s==="apps"?"active":""}`,"aria-label":"Apps",type:"button",onClick:()=>{P("apps")},children:[k.jsx(n_,{size:18}),k.jsx("span",{children:"Apps"})]}),k.jsxs("button",{className:`nav-command nav-command-prominent ${s==="projects"?"active":""}`,"aria-label":"Projects",type:"button",onClick:()=>{P("projects")},children:[k.jsx(QI,{size:18}),k.jsx("span",{children:"Projects"})]})]}):null]})}function Y3({setSectionMenuOpen:e,setSelectedAppId:t,setSelectedProjectId:n,setSelectedSessionId:a,setView:o,view:i}){function s(){t(null),n(null),a(null),e(null),o("get-started"),Qt({kind:"view",view:"get-started"})}return k.jsx("nav",{className:"sidebar-utility-nav","aria-label":"Resources",children:k.jsx(L3,{onOpenWalkthroughs:s,walkthroughsActive:i==="get-started"})})}const c_=lp({chatMode:b(["chat","work"]).optional(),notificationMode:b(["all","direct_mentions","none"]).optional(),learningNoticeDismissed:A().optional(),sidebarVisibility:lp({showCodexChats:A(),onlyRunningTasks:A()}).optional(),scheduledWorkView:b(["calendar","list"]).optional(),editorControlsVisible:A().optional(),voiceNoticeAcknowledged:A().optional(),lessonProgress:re(r().min(1).max(200),lp({completed:A(),currentTime:u().finite().nonnegative(),duration:u().finite().positive(),updatedAt:u().finite().nonnegative()})).refine(e=>Object.keys(e).length<=200,"Too many lessons").optional()}),ih={"openpond:last-chat-task-mode":"chatMode","openpond.team-chat.notification-mode":"notificationMode","openpond.sidebar.continuous-learning.dismissed.v1":"learningNoticeDismissed","openpond.sidebar-task-visibility.v1":"sidebarVisibility","openpond.scheduled-work.view.v1":"scheduledWorkView","openpond.workspace.editorControlsVisible":"editorControlsVisible","openpond.voice.setupNoticeAcknowledged":"voiceNoticeAcknowledged","openpond.post-training-progress.v1":"lessonProgress"},sh=new Set;let xl=null,qo=null,Ha={},zl={},Gp=!1,bd=0,is=null,e0=0;const Q3="openpond-client-choices-changed";function yv(){sh.forEach(e=>e()),typeof window<"u"&&window.dispatchEvent(new Event(Q3))}function X3(){return is}function e6(e){return sh.add(e),()=>{sh.delete(e)}}function fc(e){const t=v.useRef(e);t.current=e,v.useEffect(()=>e6(()=>t.current()),[])}async function t0(e){const t=++e0,n=await q(e,"/v1/configuration");if(n.clientState?.revision===null){const o=t6();if(Object.keys(o.patch).length){n.clientState=await q(e,"/v1/configuration",{method:"POST",body:JSON.stringify({action:"client-state",owner:n.clientState.owner,patch:o.patch,importOnly:!0})});for(const i of o.keys)try{window.localStorage.removeItem(i)}catch{}}}if(t!==e0)return;const a=xl?.serverUrl!==e.serverUrl||xl?.token!==e.token||qo?.owner!==n.clientState?.owner;a&&(bd++,Ha={},zl={},is=null),xl=e,(a||(n.clientState?.revision??0)>=(qo?.revision??0))&&(qo=n.clientState),yv()}async function Sv(){if(Gp||!xl||!qo||!Object.keys(Ha).length)return;Gp=!0;const e=Ha,t=xl,n=qo.owner,a=bd;Ha={},zl=e;try{const o=await q(t,"/v1/configuration",{method:"POST",body:JSON.stringify({action:"client-state",owner:n,patch:e})});a===bd&&(qo=o,is=null)}catch(o){a===bd&&(Ha={...e,...Ha},is=`Preference changes have not been saved. ${o instanceof Error?o.message:String(o)}`)}finally{zl={},Gp=!1,yv(),!is&&Object.keys(Ha).length&&Sv()}}function TQ(){is=null,Sv()}const hc={getItem(e){const t=ih[e];if(!t)return null;const n={...qo?.value,...zl,...Ha}[t];return n===void 0?null:typeof n=="string"?n:JSON.stringify(n)},setItem(e,t){if(!qo)return;const n=ih[e];if(!n)throw new Error("Unregistered client preference.");let a;try{a=JSON.parse(t)}catch{a=t}const o=c_.parse({[n]:a});JSON.stringify({...qo.value,...zl,...Ha}[n])!==JSON.stringify(o[n])&&(Ha={...Ha,...o},yv(),Sv())}};function t6(){const e={},t=[];if(typeof window>"u")return{patch:e,keys:t};for(const[n,a]of Object.entries(ih))try{const o=window.localStorage.getItem(n);if(o===null)continue;let i;try{i=JSON.parse(o)}catch{i=o}const s=c_.safeParse({[a]:i});s.success&&(Object.assign(e,s.data),t.push(n))}catch{}return{patch:e,keys:t}}const yd=5,Pn=15,lh=10,Tt={defaultChatProvider:Qr,subagents:yj(),codexPermissionMode:ng,codexReasoningEffort:ag,openPondCommandAccessMode:du,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:""}}}},EQ={activeTemplateId:"default",customized:!1,soul:"",soulPath:null,updatedAt:null,templates:[]},d_=[{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"}],Zp=[{value:"openpond",label:"OpenPond Chat"},{value:"codex",label:"OpenAI Codex",description:"Codex login"}],n6=["openai","xai","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],a6=["openpond","codex",...n6],u_=new Set(a6),m_=[{value:tg,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"}],MQ=[{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."}],ch=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"xhigh",label:"Extra High",shortLabel:"Extra High"}],o6=[{value:"off",label:"Off"},...ch,{value:"max",label:"Max"}],jQ=[{value:"ask",label:"Ask",description:"Ask before running shell commands."},{value:"full-access",label:"Full access",description:"Run shell commands without approval prompts."}],OQ=[{value:"auto",label:"Auto",description:"Use installed language servers when available."},{value:"off",label:"Off",description:"Disable editor language servers."}],$Q=[{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 xv(e){return e.kind==="local"}function r6(e){return e.kind==="cloud"}function yt(e,t){return`${e}:${t}`}function p_(e){const t=e?.trim();if(!t)return null;const n=t.indexOf(":");if(n<=0)return{kind:"local",id:t};const a=t.slice(0,n),o=t.slice(n+1);return(a==="local"||a==="cloud")&&o?{kind:a,id:o}:{kind:"local",id:t}}function Wr(e){return`${e.type}:${e.id}`}function Vd(e){const t=e.currentTarget.getBoundingClientRect();return e.clientY<t.top+t.height/2?"before":"after"}function Kd(e,t,n,a="before"){if(t===n)return e;const o=e.filter(s=>s!==t),i=o.indexOf(n);return i===-1?e:(o.splice(a==="after"?i+1:i,0,t),o)}function n0(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function i6(e,t){if(!t)return e;const n=new Map(e.map(i=>[i.key,i])),a=t.map(i=>n.get(i)).filter(i=>!!i),o=new Set(a.map(i=>i.key));return[...a,...e.filter(i=>!o.has(i.key))]}function kv(e,t){return e?.statuses?.[t]??null}function f_(e,t){return e?.providers?.[t]??null}function wv(e,t){return e?.modelCaches?.[t]??null}function s6(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 l6(e){return e==="openpond"?d_:e==="codex"||e==="openai"?m_:[]}function c6(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 NQ(e){return u_.has(e)}function dh(e,t={}){if(!e)return t.localOnly,Zp;const n=t.includeUnavailable??!1,a=t.enabledOnly??!1,o=[];for(const i of Fh){if(!u_.has(i)||t.localOnly&&i==="openpond")continue;const s=kv(e,i);s&&(!n&&(i==="codex"&&!s.available&&!s.credential.connected||i!=="openpond"&&i!=="codex"&&!s.enabled)||a&&i!=="openpond"&&!s.enabled||a&&i==="codex"&&!s.available&&!s.credential.connected||o.push({value:i,label:i==="openpond"?"OpenPond Chat":s.displayName,description:i==="openpond"?void 0:s.available?"Connected":s.credential.connected?"Configured":s.routing.localByok?"Set up key":s.enabled?"Enabled":void 0}))}return o.length>0?o:Zp}function ql(e,t){const a=(wv(t,e)?.models??[]).filter(l=>e!=="openpond"||l.id!==us).map(s6),o=f_(t,e),i=[...o?.modelOverrides??[],o?.defaultModel].filter(l=>!!l?.trim()&&(e!=="openpond"||l!==us)).map(l=>({value:l,label:l})),s=e==="openpond"&&a.length>0?[]:l6(e);return c6([...a,...i,...s])}function h_(e,t,n){if(e!=="openpond")return ch;const a=wv(n,e)?.models.find(i=>i.id===t)?.capabilities;if(!a?.reasoningEfforts.length)return ch;const o=new Set(a.reasoningEfforts);return o6.filter(i=>o.has(i.value))}function d6(e,t,n){const a=h_(e,t,n),o=e==="openpond"&&(t==="gpt-6-luna"||t==="gpt-6-sol"||t==="claude-opus-5-5")?"medium":"high";return a.some(i=>i.value===o)?o:a[0]?.value??"high"}function u6(e,t,n,a){return h_(e,t,a).some(o=>o.value===n)?n:d6(e,t,a)}function m6(e,t,n){if(e==="codex"||e==="openai")return!0;const a=t.trim();if(!a)return!1;const o=wv(n,e)?.models.find(i=>i.id===a);return o?!!o.capabilities.reasoning:ql(e,n).some(i=>i.value===a&&/\breasoning\b/i.test(i.description??""))}function Wd(e,t){const n=f_(t,e)?.defaultModel?.trim();if(n)return n;const a=kv(t,e)?.defaultModel?.trim();if(a)return a;const o=ql(e,t)[0]?.value?.trim();return o||(e==="codex"?tg:e==="openpond"?us:"")}function _r(e,t,n){const a=t?.trim();if(e==="codex"&&(a==="codex-default"||a==="gpt-5.5"))return tg;const o=ql(e,n);return a&&o.some(i=>i.value===a)||a&&e!=="codex"&&o.length===0&&!n?a:Wd(e,n)}function g_(e,t){const n=e.modelRef?.providerId??e.provider;return{provider:n,model:_r(n,e.modelRef?.modelId,t)}}function Iv(e,t,n){return _r(e,t,n)||void 0}function Na(e,t,n){const a=Iv(e,t,n);return a?{providerId:e,modelId:a}:void 0}function a0(e){return e==="full-access"?{approvalPolicy:"never",sandbox:"danger-full-access"}:{approvalPolicy:"on-request",sandbox:"workspace-write"}}function ba(e){const t=e?.defaultChatProvider??Tt.defaultChatProvider;return{defaultChatProvider:t,defaultChatModel:_r(t,e?.defaultChatModel),subagents:Cl.parse(e?.subagents??Tt.subagents),codexPermissionMode:e?.codexPermissionMode??Tt.codexPermissionMode,codexReasoningEffort:e?.codexReasoningEffort??Tt.codexReasoningEffort,openPondCommandAccessMode:e?.openPondCommandAccessMode??Tt.openPondCommandAccessMode,defaultBranchPrefix:v_(e?.defaultBranchPrefix),defaultNewProjectDirectory:e?.defaultNewProjectDirectory??Tt.defaultNewProjectDirectory,defaultTeamId:e?.defaultTeamId?.trim()||null,advancedWorkspaceControls:e?.advancedWorkspaceControls??Tt.advancedWorkspaceControls,steerActiveResponses:e?.steerActiveResponses??Tt.steerActiveResponses,contextCompaction:{autoEnabled:e?.contextCompaction?.autoEnabled??Tt.contextCompaction.autoEnabled,triggerPercent:e?.contextCompaction?.triggerPercent??Tt.contextCompaction.triggerPercent,summaryModel:e?.contextCompaction?.summaryModel??Tt.contextCompaction.summaryModel},training:{defaultModelRef:e?.training?.defaultModelRef??Tt.training.defaultModelRef,creationMode:e?.training?.creationMode??Tt.training.creationMode,autoApproveEvidence:e?.training?.autoApproveEvidence??Tt.training.autoApproveEvidence},sidebarWidth:e?.sidebarWidth??Tt.sidebarWidth,diffPanelWidth:e?.diffPanelWidth??Tt.diffPanelWidth,sidebarSectionsCollapsed:{pinned:e?.sidebarSectionsCollapsed?.pinned??Tt.sidebarSectionsCollapsed.pinned,projects:e?.sidebarSectionsCollapsed?.projects??Tt.sidebarSectionsCollapsed.projects,cloudProjects:e?.sidebarSectionsCollapsed?.cloudProjects??Tt.sidebarSectionsCollapsed.cloudProjects,chats:e?.sidebarSectionsCollapsed?.chats??Tt.sidebarSectionsCollapsed.chats,savedForLater:e?.sidebarSectionsCollapsed?.savedForLater??Tt.sidebarSectionsCollapsed.savedForLater},editor:{languageServers:e?.editor?.languageServers??Tt.editor.languageServers,diagnosticsWhileEditing:e?.editor?.diagnosticsWhileEditing??Tt.editor.diagnosticsWhileEditing,checkOnSave:e?.editor?.checkOnSave??Tt.editor.checkOnSave,languages:{typescript:{mode:e?.editor?.languages?.typescript?.mode??Tt.editor.languages.typescript.mode,customCommand:e?.editor?.languages?.typescript?.customCommand??Tt.editor.languages.typescript.customCommand},python:{mode:e?.editor?.languages?.python?.mode??Tt.editor.languages.python.mode,customCommand:e?.editor?.languages?.python?.customCommand??Tt.editor.languages.python.customCommand},rust:{mode:e?.editor?.languages?.rust?.mode??Tt.editor.languages.rust.mode,customCommand:e?.editor?.languages?.rust?.customCommand??Tt.editor.languages.rust.customCommand}}}}}function v_(e){const t=e?.trim()??Tt.defaultBranchPrefix;if(!t)return"";const a=t.toLowerCase().replace(/[^a-z0-9._/-]+/g,"-").replace(/\/{2,}/g,"/").replace(/^-+/,"").slice(0,48).split("/").map(o=>o.replace(/^-+|-+$/g,"")).filter(Boolean).join("/");return a?`${a}/`:""}function DQ(e,t){return e==="openpond"?"OpenPond Chat":kv(t,e)?.displayName??(e==="codex"?"OpenAI Codex":e)}function LQ(e,t,n){if(n){const a=ql(n,t).find(o=>o.value===e);if(a)return a.label}if(t)for(const a of Fh){const o=ql(a,t).find(i=>i.value===e);if(o)return o.label}return[...d_,...m_].find(a=>a.value===e)?.label??e}function p6(e,t){return t==="chat"?e.filter(n=>n.experience==="chat"):e.filter(n=>n.experience==="work"||n.experience==="development")}function f6(e){return e.experience==="chat"?"Chat":"Work"}const _v="taskDraft";function b_(e){if(e?.experience!=="work")return null;const t=e.metadata?.[_v];if(!t||typeof t!="object"||Array.isArray(t))return null;const n=t.prompt;return typeof n=="string"&&n.trim()?n:null}function Bl(e){return b_(e)!==null}function h6(e){return(e.split(/\r?\n/u).map(n=>n.trim()).find(Boolean)||"Task draft").slice(0,64)}function Jp(e,t,n=new Date().toISOString()){const a={version:1,prompt:t,savedAt:n};return{...e??{},[_v]:a}}function g6(e){const t={...e??{}};return delete t[_v],t}function Ji(e){const t=Jc(e.metadata?.trainingTasksetId)??Jc(e.metadata?.tasksetId);return t?{id:t,name:Jc(e.metadata?.trainingTasksetName)??Jc(e.metadata?.tasksetName)??v6(t)}:null}function v6(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 Jc(e){return typeof e=="string"&&e.trim()?e.trim():null}const b6="codex_history_";function Ht(e){return!!e?.startsWith(b6)}function y_(e){const t=[],n=new Set;for(const a of e)for(const o of[a.workspacePath,a.path]){const i=Bu(o);if(!i)continue;const s=`${a.id}:${i}`;n.has(s)||(n.add(s),t.push({projectId:a.id,path:i}))}return t.sort((a,o)=>o.path.length-a.path.length)}function y6(e,t,n,a=new Set){if(e.localProjectId&&t.has(e.localProjectId))return e.localProjectId;if(e.workspaceKind==="local_project"&&e.workspaceId&&t.has(e.workspaceId))return e.workspaceId;if(e.metadata?.workspaceTarget==="hybrid"&&e.cwd){const i=S_(e.cwd,n);if(i)return i}if(e.cloudProjectId&&a.has(e.cloudProjectId))return e.cloudProjectId;if(!e.cwd||e.workspaceKind==="sandbox"||e.workspaceKind==="sandbox_template"||e.workspaceKind==="sandbox_app"||!x_(e))return null;const o=Bu(e.cwd);if(!o)return null;for(const i of n)if(Cv(o,i.path))return i.projectId;return null}function o0(e,t,n,a=new Set){if(e.localProjectId&&t.has(e.localProjectId))return yt("local",e.localProjectId);if(e.workspaceKind==="local_project"&&e.workspaceId&&t.has(e.workspaceId))return yt("local",e.workspaceId);if(e.metadata?.workspaceTarget==="hybrid"&&e.cwd){const i=S_(e.cwd,n);if(i)return yt("local",i)}if(e.cloudProjectId&&a.has(e.cloudProjectId))return yt("cloud",e.cloudProjectId);if(!e.cwd||e.workspaceKind==="sandbox"||e.workspaceKind==="sandbox_template"||e.workspaceKind==="sandbox_app"||!x_(e))return null;const o=Bu(e.cwd);if(!o)return null;for(const i of n)if(Cv(o,i.path))return yt("local",i.projectId);return null}function S_(e,t){const n=Bu(e);if(!n)return null;for(const a of t)if(Cv(n,a.path))return a.projectId;return null}function x_(e){return e.workspaceKind==="local_project"||e.provider==="codex"||Ht(e.id)}function Bu(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 Cv(e,t){const n=r0(e),a=r0(t);return n===a||n.startsWith(`${a}/`)}function r0(e){return/^[A-Z]:\//.test(e)?e.toLowerCase():e}const i0=[{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"}],S6=[{value:"recent",label:"Recent first"},{value:"manual",label:"Manual order"}];function s0(e){const t=[];if(e.filter==="done")t.push(...e.doneSessions.filter(o=>!Ji(o)));else if(e.filter==="all")t.push(...e.activeSessions.filter(o=>!Ji(o)),...e.doneSessions.filter(o=>!Ji(o)));else if(e.filter==="tasksets")t.push(...e.activeSessions.filter(o=>l0(o,e.selectedTasksetId)),...e.doneSessions.filter(o=>l0(o,e.selectedTasksetId)));else for(const o of e.activeSessions)Ji(o)||(e.filter==="active"?o.savedForLater||t.push(o):e.filter==="in_progress"?!o.savedForLater&&e.inProgressSessionIds.has(o.id)&&t.push(o):e.filter==="pinned"?o.pinned&&!o.savedForLater&&t.push(o):e.filter==="saved_for_later"&&o.savedForLater&&t.push(o));const n=t.filter(o=>Sd(o,{inProgressSessionIds:e.inProgressSessionIds,onlyRunningTasks:e.onlyRunningTasks,showCodexChats:e.showCodexChats})),a=e.previewSessionIds?new Map(e.previewSessionIds.map((o,i)=>[o,i])):null;return e.sort==="recent"?n.sort((o,i)=>d0(o,i,a)):n.sort((o,i)=>{const s=a?.get(o.id),l=a?.get(i.id);if(s!==void 0||l!==void 0){if(s===void 0)return 1;if(l===void 0)return-1;if(s!==l)return s-l}return o.order!==i.order?o.order-i.order:d0(o,i)})}function Sd(e,t){return t.showCodexChats===!1&&(e.provider==="codex"||Ht(e.id))?!1:!t.onlyRunningTasks||t.inProgressSessionIds.has(e.id)}function l0(e,t){const n=Ji(e);return!!(n&&(!t||n.id===t))}function x6(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 c0(e,t,n){const a=new Set(t);let o=0;return e.map(i=>{if(!a.has(i))return i;const s=n[o];return o+=1,s??i})}function d0(e,t,n=null){const a=kl(e),o=kl(t);if(a!==o)return a?-1:1;if(a&&o){const s=n?.get(e.id),l=n?.get(t.id);if(s!==void 0||l!==void 0){if(s===void 0)return 1;if(l===void 0)return-1;if(s!==l)return s-l}if(e.order!==t.order)return e.order-t.order}const i=Date.parse(t.updatedAt)-Date.parse(e.updatedAt);return i!==0?i:e.title.localeCompare(t.title)}function kl(e){return e.pinned&&!e.savedForLater&&!e.archived}const Yc={showCodexChats:!0,onlyRunningTasks:!1},k_="openpond.sidebar-task-visibility.v1";function u0(e=w_()){try{const t=e?.getItem(k_);if(!t)return Yc;const n=JSON.parse(t);return{showCodexChats:typeof n.showCodexChats=="boolean"?n.showCodexChats:Yc.showCodexChats,onlyRunningTasks:typeof n.onlyRunningTasks=="boolean"?n.onlyRunningTasks:Yc.onlyRunningTasks}}catch{return Yc}}function m0(e,t=w_()){try{t?.setItem(k_,JSON.stringify(e))}catch{}}function w_(){return typeof window>"u"?null:hc}function I_(e){return`${e.kind}:${e.id}`}function Fl(e,t){return!!(e&&t&&e.kind===t.kind&&e.id===t.id)}function k6(e){return{kind:"session",id:e}}function w6(e){return{kind:"project",id:e}}function I6(e){return{kind:"draft",id:e}}function _6(e){return e.selectedSessionId?k6(e.selectedSessionId):e.selectedProjectId?w6(e.selectedProjectId):I6(e.selectedAppId?`app:${e.selectedAppId}`:"new-chat")}function C6(e){if(!e.previousScope||e.previousScope.kind!=="draft"||e.activeScope.kind!=="session")return[...e.tabs];if(Fl(e.previousScope,e.activeScope))return[...e.tabs];const t=e.now??Date.now();return e.tabs.map(n=>Fl(n.scope,e.previousScope)?{...n,scope:e.activeScope,updatedAt:t}:n)}function UQ(e,t){return e.filter(n=>Fl(n.scope,t))}function HQ(e,t){return!!(e&&Fl(e.scope,t))}function R6(e){const t={};for(const n of e){const a=I_(n.scope),o=t[a]??{scope:n.scope,tabCount:0,runningCount:0,failedCount:0,lastExitCode:null,status:"none"};o.tabCount+=1,n.commandStatus==="running"&&(o.runningCount+=1),(n.commandStatus==="failed"||n.status==="error")&&(o.failedCount+=1),n.lastExitCode!==null&&(o.lastExitCode=n.lastExitCode),o.status=A6(o.status,n.status,n.commandStatus),t[a]=o}return t}function P6(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 A6(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 __(e,t){if(!e)return t?.path??"Use files on this machine";if(e.error)return"status unavailable";if(!e.initialized)return"not checked out";const a=[e.currentBranch??t?.branch??e.defaultBranch??"no branch"],o=E6(e),i=t?.linkedCloudSourceKnown===!1&&!!e.headCommit;return o?a.push(o):i?a.push("upload required"):e.diverged?(e.ahead>0&&a.push(br("ahead",e.ahead)),e.behind>0&&a.push(br("behind",e.behind)),a.push("diverged")):(e.ahead>0&&a.push(br("ahead",e.ahead)),e.behind>0&&a.push(br("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 C_(e,t,n,a={}){const o=e?.linkedSandboxProject??null;if(!o?.projectId&&!t)return"upload required";if(o?.projectId&&a.cloudLinkTrusted===!1)return"uploaded to a different account";const i=o?.defaultBranch??t?.defaultBranch??"main",s=o?.manifestHash??null,l=e?.sandboxTemplate?.manifestHash??null,m=o?.syncedAt??t?.syncedAt??null,d=!!(s&&l&&s!==l),h=!!(o?.projectId&&n?.headCommit&&!o.lastUploadedCommit),g=M6(n);return g?`${i} / ${g}`:h?`${i} / upload required`:`${i} / ${d||!m?"needs sync":"setup ready"}`}function T6(e,t,n={}){if(!e)return"select a local project";if(e.linkedSandboxProject?.projectId&&n.cloudLinkTrusted===!1)return"sync to this account";if(!t)return e.linkedSandboxProject?"sync source to cloud":"push local source to cloud";if(t.error)return"repo status unavailable";if(!t.initialized)return"local repo unavailable";const a=[],o=t.aheadOfLinkedSource>0?t.aheadOfLinkedSource:t.ahead;return e.linkedSandboxProject?.projectId||a.push("upload required"),e.linkedSandboxProject?.projectId&&t.headCommit&&!e.linkedSandboxProject.lastUploadedCommit&&a.push("upload required"),o>0&&a.push(R_(o)),t.linkedSourceHeadCommit&&t.headCommit&&t.linkedSourceHeadCommit!==t.headCommit&&t.linkedSourceComparisonError&&o===0&&a.push("source changed"),t.changedFilesCount>0&&a.push(`${t.changedFilesCount} changed file${t.changedFilesCount===1?"":"s"}`),t.untrackedFilesCount>0&&a.push(`${t.untrackedFilesCount} untracked skipped`),a.length>0?a.join(" / "):"nothing to upload"}function E6(e){return e.linkedSourceHeadCommit?e.divergedFromLinkedSource?"diverged":e.aheadOfLinkedSource>0?br("local ahead",e.aheadOfLinkedSource):e.behindLinkedSource>0?br("cloud ahead",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"sync unknown":null:null}function M6(e){return e?.linkedSourceHeadCommit?e.dirty?"local dirty files not in cloud":e.divergedFromLinkedSource?"diverged from local":e.aheadOfLinkedSource>0?br("cloud behind local",e.aheadOfLinkedSource):e.behindLinkedSource>0?br("cloud ahead local",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"source check unavailable":"synced":null}function br(e,t){return`${e} by ${R_(t)}`}function R_(e){return`${e} commit${e===1?"":"s"}`}function j6({size:e=14,className:t}){return k.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:[k.jsx("path",{d:"M12 13v8"}),k.jsx("path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242"}),k.jsx("path",{d:"m8 17 4-4 4 4"})]})}function P_({kind:e,linkedCloud:t=!1,open:n=!1,className:a,baseSize:o=15}){const i=e==="cloud"?"cloud":n?"folder-open":"folder";return k.jsx("span",{className:["project-kind-icon",e,t?"linked-cloud":"",a??""].filter(Boolean).join(" "),"aria-hidden":"true",children:k.jsxs("svg",{className:`lucide lucide-${i} project-kind-icon-svg`,xmlns:"http://www.w3.org/2000/svg",width:o,height:o,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e==="cloud"?k.jsx(N6,{}):n?k.jsx($6,{}):k.jsx(O6,{}),t&&e==="local"?k.jsx(D6,{}):null]})})}function O6(){return k.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 $6(){return k.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 N6(){return k.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 D6(){return k.jsxs("g",{className:"project-kind-icon-cloud-badge",children:[k.jsx("circle",{cx:"18",cy:"17",r:"5"}),k.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"})]})}var uh=bR();function L6({title:e,pinned:t,savedForLater:n,archived:a,onRename:o,onTogglePin:i,onToggleSaveForLater:s,onDockRight:l,onArchive:m}){const d=v.useRef(null),h=v.useRef(null),[g,y]=v.useState(null),w=[...o?[{label:"Rename",Icon:Hu,action:o}]:[],{label:t?"Unpin":"Pin",Icon:t?dv:cv,action:i},...s?[{label:n?"Return to active":"Save for later",Icon:n?ZI:GI,action:s}]:[],...l?[{label:"Open in right panel",Icon:eh,action:l}]:[],{label:a?"Reopen":"Mark done",Icon:a?T5:Po,action:m}];function _(P=!1){y(null),P&&d.current?.focus()}return v.useEffect(()=>{if(!g)return;h.current?.querySelector("button")?.focus();const P=C=>{!h.current?.contains(C.target)&&!d.current?.contains(C.target)&&y(null)},M=()=>y(null);return document.addEventListener("pointerdown",P),window.addEventListener("resize",M),()=>{document.removeEventListener("pointerdown",P),window.removeEventListener("resize",M)}},[g]),k.jsxs(k.Fragment,{children:[k.jsx("div",{className:`sidebar-row-actions sidebar-task-menu-trigger${g?" is-open":""}`,children:k.jsx("button",{ref:d,type:"button",className:"sidebar-row-action","aria-label":`More actions for task ${e}`,"aria-haspopup":"menu","aria-expanded":!!g,draggable:!1,onDoubleClick:P=>P.stopPropagation(),onClick:P=>{if(P.stopPropagation(),g){_(!0);return}const M=P.currentTarget.getBoundingClientRect();y({left:Math.max(8,Math.min(M.right-192,window.innerWidth-200)),top:Math.max(8,Math.min(M.bottom+4,window.innerHeight-(w.length*32+17)))})},children:k.jsx(uc,{size:16})})}),g&&uh.createPortal(k.jsx("div",{ref:h,role:"menu","aria-label":`Actions for ${e}`,className:"sidebar-task-menu",style:g,onClick:P=>P.stopPropagation(),onDoubleClick:P=>P.stopPropagation(),onBlur:P=>{P.currentTarget.contains(P.relatedTarget)||_()},onKeyDown:P=>{P.stopPropagation();const M=Array.from(P.currentTarget.querySelectorAll("button")),C=M.indexOf(document.activeElement);if(P.key==="Escape"&&(P.preventDefault(),_(!0)),["ArrowDown","ArrowUp","Home","End"].includes(P.key)){P.preventDefault();const N=P.key==="Home"?0:P.key==="End"?M.length-1:(C+(P.key==="ArrowDown"?1:-1)+M.length)%M.length;M[N]?.focus()}},children:w.map(({label:P,Icon:M,action:C},N)=>k.jsxs("button",{type:"button",role:"menuitem",className:N===w.length-1?"task-menu-done":void 0,onClick:()=>{_(!0),C()},children:[k.jsx(M,{size:15}),P]},P))}),document.body)]})}function U6({session:e,onSave:t,onClose:n}){const[a,o]=v.useState(e.title),i=v.useRef(null);v.useEffect(()=>{const m=i.current;m&&(m.focus(),m.select())},[]),v.useEffect(()=>{function m(d){d.key==="Escape"&&n()}return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[n]);function s(){const m=a.trim();m&&(t(m),n())}function l(m){m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),s())}return k.jsx("div",{className:"git-dialog-backdrop rename-chat-backdrop",role:"presentation",onMouseDown:n,children:k.jsxs("section",{className:"git-dialog rename-chat-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"rename-chat-title",onMouseDown:m=>m.stopPropagation(),children:[k.jsx("h2",{id:"rename-chat-title",children:"Rename chat"}),k.jsx("textarea",{ref:i,className:"rename-chat-input",value:a,rows:1,maxLength:200,onChange:m=>o(m.target.value),onKeyDown:l,"aria-label":"Chat title"}),k.jsxs("div",{className:"git-dialog-footer",children:[k.jsx("button",{type:"button",className:"git-dialog-secondary",onClick:n,children:"Cancel"}),k.jsx("button",{type:"button",className:"git-dialog-primary",autoFocus:!0,onClick:s,disabled:!a.trim(),children:"Save"})]})]})})}const H6=24;function z6({title:e}){const t=v.useRef(e),[n,a]=v.useState(e);return v.useEffect(()=>{const o=t.current;if(t.current=e,!e){a("");return}if(o||window.matchMedia("(prefers-reduced-motion: reduce)").matches){a(e);return}const i=Array.from(e);let s=0;a("");const l=window.setInterval(()=>{s+=1,a(i.slice(0,s).join("")),s>=i.length&&window.clearInterval(l)},H6);return()=>window.clearInterval(l)},[e]),k.jsx("span",{className:"sidebar-task-title-text","aria-label":e||"New task",children:n||"New task"})}const q6=2650,B6=304,F6=260,V6=new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric"}),K6=new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit"}),W6=new Intl.DateTimeFormat("en-US",{dateStyle:"medium",timeStyle:"short"});function G6(){return{animationDelay:`${-(Date.now()%q6)}ms`}}function Z6(e){const t=e.currentTarget,n=t.firstElementChild;if(!(n instanceof HTMLElement))return;const a=Math.max(0,n.scrollWidth-t.clientWidth),o=a>2;t.dataset.overflowing=String(o),t.style.setProperty("--sidebar-title-ticker-distance",`${-a}px`),t.style.setProperty("--sidebar-title-ticker-duration",`${Math.min(6.5,Math.max(2.8,a/42+2.4))}s`)}function Yp({label:e,actions:t,actionsVisible:n=!1,className:a,titleAccessory:o,children:i,collapsed:s=!1,titleActive:l=!1,onTitleClick:m,onToggleCollapsed:d}){return k.jsxs("section",{className:["sidebar-section",a,n?"actions-visible":""].filter(Boolean).join(" "),children:[k.jsxs("div",{className:"section-header",children:[k.jsxs("div",{className:"section-title-row",children:[m?k.jsxs("div",{className:"section-title-combo",children:[k.jsx("button",{type:"button",className:`section-title-link${l?" active":""}`,onClick:m,children:k.jsx("span",{children:e})}),d&&k.jsx("button",{type:"button",className:"section-chevron-button","aria-label":`${s?"Expand":"Collapse"} ${e}`,"aria-expanded":!s,onClick:d,children:s?k.jsx(ti,{size:13}):k.jsx(Ko,{size:13})})]}):d?k.jsxs("button",{type:"button",className:"section-title-button","aria-label":`${s?"Expand":"Collapse"} ${e}`,"aria-expanded":!s,onClick:d,children:[k.jsx("span",{children:e}),s?k.jsx(ti,{size:13}):k.jsx(Ko,{size:13})]}):k.jsx("span",{children:e}),o]}),t&&k.jsx("div",{className:"section-actions",children:t})]}),!s&&k.jsx("div",{className:"sidebar-section-body",children:i})]})}function p0({children:e,expanded:t=!1,onClick:n}){return k.jsx("button",{type:"button",className:"sidebar-show-more",onClick:n,children:e??(t?"Show less":"Show more")})}function Qp({session:e,selected:t,icon:n,archived:a=!1,hideIcon:o=!1,nested:i=!1,dragging:s,placeholder:l,running:m,goalRuntime:d,subagentRuntime:h,terminalIndicator:g,projectLabel:y,ariaDescribedBy:w,childSessionCount:_=0,childSessionsExpanded:P=!1,onSelect:M,onToggleChildSessions:C,onTogglePin:N,onToggleSaveForLater:$,onDockRight:j,onArchive:x,onDragStart:R,onDragEnd:E,onDragOver:U,onDrop:B,onRename:D}){const[W,se]=v.useState(!1),de=d?.status==="queued",Me=d?.tone==="active"&&!de,ke=(h?.activeCount??0)>0,te=_>0&&!!C,Ee=o&&!te,ye=ke||Me||!de&&(m??e.status==="active"),ne=ke&&h?h.label:Me&&d?Y6(d):"Running",be=["sidebar-task-row",Bl(e)?"is-draft":"",ye?"has-running-dot":""].filter(Boolean).join(" "),ae=v.useMemo(G6,[]),ue=k.jsx(L6,{title:e.title,pinned:!!e.pinned,savedForLater:!!e.savedForLater,archived:a,onRename:D?()=>se(!0):void 0,onTogglePin:N,onToggleSaveForLater:$,onDockRight:j,onArchive:x}),xe=k.jsxs(Rv,{selected:t,dataSessionId:e.id,dragging:s,iconless:Ee,nested:i,placeholder:l,className:be||void 0,ariaExpanded:te?P:void 0,ariaDescribedBy:w,onSelect:M,onDragStart:R,onDragEnd:E,onDragOver:U,onDrop:B,onDoubleClick:D?()=>se(!0):void 0,children:[Ee?null:te?k.jsx("button",{type:"button",className:"sidebar-child-toggle","data-tooltip":P?"Hide subagent conversations":"Show subagent conversations","aria-label":`${P?"Hide":"Show"} ${_} subagent ${_===1?"conversation":"conversations"}`,"aria-expanded":P,onClick:we=>{we.stopPropagation(),C?.()},children:P?k.jsx(Ko,{size:13}):k.jsx(ti,{size:13})}):n??k.jsx(Uu,{size:15}),k.jsx("span",{className:"row-label-shell",title:y||void 0,children:k.jsx("span",{className:"sidebar-session-title-line",children:k.jsx("span",{className:"row-label sidebar-task-title","data-overflowing":"false",onPointerEnter:Z6,children:k.jsx(z6,{title:e.title})})})}),k.jsxs("div",{className:"row-meta",children:[k.jsxs("span",{className:"row-meta-status",children:[g?k.jsx(A_,{indicator:g}):null,ye?k.jsx("span",{className:`sidebar-running-dot${ke?" subagent":Me?" goal":""}`,style:ae,"aria-label":ne}):null]}),ue]})]}),De=W&&D?k.jsx(U6,{session:e,onSave:we=>D(e,we),onClose:()=>se(!1)}):null;return k.jsxs(k.Fragment,{children:[xe,De]})}function J6({file:e,selected:t=!1,placeholder:n,onSelect:a,onTogglePin:o,onToggleSaveForLater:i,onDragStart:s,onDragEnd:l,onDragOver:m,onDrop:d}){const h=e.path.split("/").at(-1)??e.path,g=`${e.workspaceName} · ${e.path}`;return k.jsxs(Rv,{selected:t,placeholder:n,className:`sidebar-file-row actions-2${e.available?"":" unavailable"}`,onSelect:a,onDragStart:s,onDragEnd:l,onDragOver:m,onDrop:d,children:[e.available?k.jsx(lv,{size:15}):k.jsx(V5,{size:15}),k.jsx("span",{className:"row-label-shell",title:g,children:k.jsx("span",{className:"row-label",children:h})}),k.jsx("div",{className:"row-meta",children:k.jsxs("div",{className:"sidebar-row-actions",children:[k.jsx(Gd,{label:e.status==="pinned"?"Unpin file":"Pin file",onClick:o,children:e.status==="pinned"?k.jsx(dv,{size:13}):k.jsx(cv,{size:13})}),k.jsx(Gd,{label:e.status==="saved_for_later"?"Remove from Save for later":"Save file for later",onClick:i,children:e.status==="saved_for_later"?k.jsx(ZI,{size:13}):k.jsx(GI,{size:13})})]})})]})}function Y6(e){return e.actionLabel}function Q6({kind:e="local",project:t,pinned:n=!1,selected:a,expanded:o=!1,disclosure:i=!0,workspaceState:s,cloudLinkTrusted:l=!0,cloudLinkWarning:m=null,placeholder:d,terminalIndicator:h,onSelect:g,onNewChat:y,onMoveToCloud:w,onWorkspaceTargetSelect:_,onTogglePin:P,onRemove:M,onDragStart:C,onDragEnd:N,onDragOver:$,onDrop:j}){const[x,R]=v.useState(!1),E=v.useRef(null),[U,B]=v.useState({}),D=!!w||!!M,W=e==="local"&&l!==!1&&!!t.linkedSandboxProject?.projectId,se=v.useCallback(()=>{if(typeof window>"u")return;const ke=E.current?.getBoundingClientRect();if(!ke)return;const te=Math.max(12,window.innerWidth-B6-12),Ee=Math.max(12,window.innerHeight-F6),ye=Math.max(12,Math.min(ke.right+10,te)),ne=Math.max(12,Math.min(ke.top-4,Ee)),be={"--sidebar-project-locations-left":`${Math.round(ye)}px`,"--sidebar-project-locations-top":`${Math.round(ne)}px`};B(ae=>ae["--sidebar-project-locations-left"]===be["--sidebar-project-locations-left"]&&ae["--sidebar-project-locations-top"]===be["--sidebar-project-locations-top"]?ae:be)},[]),de=v.useCallback(()=>{se(),g()},[g,se]);function Me(){R(!1)}return k.jsxs("div",{ref:E,className:["sidebar-project-row-shell",x?"project-menu-open":""].filter(Boolean).join(" "),onFocusCapture:se,onPointerEnter:se,children:[k.jsxs(Rv,{selected:a,placeholder:d,className:["sidebar-project-row",x?"project-menu-open":""].filter(Boolean).join(" "),ariaExpanded:i?o:void 0,onSelect:de,onDragStart:C,onDragEnd:N,onDragOver:$,onDrop:j,children:[k.jsx(P_,{kind:e,linkedCloud:W,open:e==="local"&&o,className:"sidebar-row-icon",baseSize:15}),k.jsx("span",{className:"row-label-shell",children:k.jsxs("span",{className:"sidebar-project-title-line",children:[k.jsx("span",{className:"row-label",children:t.name}),k.jsx(X6,{value:t.updatedAt}),i?k.jsx("span",{className:"sidebar-project-caret","aria-hidden":"true",children:o?k.jsx(Ko,{size:13}):k.jsx(ti,{size:13})}):null]})}),k.jsxs("div",{className:"row-meta",children:[k.jsx("span",{className:"row-meta-status",children:h?k.jsx(A_,{indicator:h}):null}),k.jsxs("div",{className:"sidebar-row-actions",children:[k.jsx(Gd,{label:n?"Unpin project":"Pin project",onClick:P,children:n?k.jsx(dv,{size:13}):k.jsx(cv,{size:13})}),D&&k.jsx(pV,{open:x,onToggleOpen:()=>R(ke=>!ke)}),k.jsx(Gd,{label:"New task",onClick:y,children:k.jsx(Hu,{size:13})})]})]})]}),k.jsx(tV,{kind:e,project:t,workspaceState:s,cloudLinkTrusted:l,cloudLinkWarning:m,onWorkspaceTargetSelect:_,style:U}),x&&k.jsx(fV,{onClose:Me,onMoveToCloud:w?()=>{Me(),w()}:void 0,onRemove:()=>{Me(),M()}})]})}function X6({value:e}){const t=eV(e);if(!t||!e)return null;const n=new Date(e);return k.jsx("time",{className:"sidebar-row-updated-at",dateTime:e,title:`Last updated ${W6.format(n)}`,children:t})}function eV(e,t=new Date){if(!e)return null;const n=new Date(e);if(Number.isNaN(n.getTime()))return null;const a=K6.format(n);return n.getFullYear()===t.getFullYear()&&n.getMonth()===t.getMonth()&&n.getDate()===t.getDate()?a:`${V6.format(n)} ${a}`}function A_({indicator:e}){return k.jsx("span",{className:`sidebar-terminal-indicator ${e.status}`,"data-tooltip":e.label,"aria-label":e.label,title:e.label,children:k.jsx(a_,{size:13})})}function tV({kind:e,project:t,workspaceState:n,cloudLinkTrusted:a,cloudLinkWarning:o,onWorkspaceTargetSelect:i,style:s}){const l=oV(e,t,n,a,o);return k.jsxs("aside",{className:"sidebar-project-locations-popover","aria-label":`${t.name} status`,style:s,children:[k.jsx("div",{className:"sidebar-project-locations-title",children:t.name}),k.jsx("div",{className:"sidebar-project-location-list",children:l.map(m=>{const d=["sidebar-project-location-row",m.tone??"",m.actionTarget?"clickable":""].filter(Boolean).join(" "),h=k.jsxs(k.Fragment,{children:[k.jsx("span",{className:["sidebar-project-location-icon",m.key].filter(Boolean).join(" "),"aria-hidden":"true",children:m.icon}),k.jsx("span",{className:"sidebar-project-location-copy",children:k.jsx(nV,{value:m.value})})]});return m.actionTarget?k.jsx("button",{type:"button",className:d,"data-workspace-target":m.actionTarget,disabled:m.disabled||!i,title:m.disabledReason??void 0,onClick:g=>{g.stopPropagation(),!m.disabled&&i?.(m.actionTarget)},children:h},m.key):k.jsx("div",{className:d,children:h},m.key)})})]})}function nV({value:e}){const t=aV(e);return k.jsxs("span",{className:"sidebar-project-location-value","aria-label":e,children:[t.branch?k.jsxs(k.Fragment,{children:[k.jsx("span",{className:"sidebar-project-location-branch",children:t.branch}),k.jsx("span",{className:"sidebar-project-location-separator","aria-hidden":"true",children:"/"})]}):null,k.jsx("span",{className:"sidebar-project-location-status",children:t.status})]})}function aV(e){const n=e.indexOf(" / ");return n===-1?{branch:null,status:e}:{branch:e.slice(0,n),status:e.slice(n+3)}}function oV(e,t,n,a=!0,o=null){return e==="cloud"?iV(t):rV(t,n,a,o)}function rV(e,t,n=!0,a=null){const o=sV(e,t,n),i=lV(t),s=dV(e,n),l=n===!1&&a;return[{key:"local",value:o,tone:i?"attention":"local",icon:e.source==="git"?k.jsx(QI,{size:13}):k.jsx(YI,{size:13}),actionTarget:"local"},{key:"cloud",value:l||(s?uV(e,t,n):"not in cloud"),tone:l?"attention":"cloud",icon:k.jsx(Lu,{size:13}),actionTarget:s?"cloud":"upload_cloud"}]}function iV(e){return[{key:"cloud",value:mV(e),tone:e.syncedAt?"cloud":"attention",icon:k.jsx(Lu,{size:13}),actionTarget:"cloud"}]}function sV(e,t,n){const a=cV(e,t);return t?t.error?`${a} / status unavailable`:t.initialized?__(t,{branch:e.linkedSandboxProject?.defaultBranch??null,linkedCloudSourceKnown:e.linkedSandboxProject?.projectId&&n?!!e.linkedSandboxProject.lastUploadedCommit||!t.headCommit:!0}):`${a} / not checked out`:`${a} / available`}function lV(e){return!!(e?.dirty||(e?.changedFilesCount??0)>0||(e?.untrackedFilesCount??0)>0)}function cV(e,t){return t?.currentBranch??t?.defaultBranch??e.linkedSandboxProject?.defaultBranch??"local"}function dV(e,t=!0){return!!(t&&e.linkedSandboxProject?.projectId||e.linkedOpenPondApp?.appId)}function uV(e,t,n){return C_(e,null,t,{cloudLinkTrusted:n})}function mV(e){const t=e.defaultBranch??"main",n=e.syncedAt?"setup ready":"needs setup";return`${t} / ${n}`}function pV({open:e,onToggleOpen:t}){return k.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:k.jsx(uc,{size:13})})}function fV({onClose:e,onMoveToCloud:t,onRemove:n}){return k.jsxs(k.Fragment,{children:[k.jsx("button",{type:"button",className:"sidebar-project-menu-backdrop","aria-label":"Close project actions",onClick:a=>{a.stopPropagation(),e()}}),k.jsxs("div",{className:"section-menu-popover sidebar-project-row-popover",role:"menu",children:[t&&k.jsxs("button",{type:"button",role:"menuitem",onClick:a=>{a.stopPropagation(),t()},children:[k.jsx(j6,{size:13}),k.jsx("span",{children:"Move to Cloud"})]}),k.jsxs("button",{type:"button",role:"menuitem",onClick:a=>{a.stopPropagation(),n()},children:[k.jsx(mc,{size:13}),k.jsx("span",{children:"Remove from Projects"})]})]})]})}function Rv({children:e,className:t,dataSessionId:n,dragging:a,iconless:o=!1,nested:i=!1,placeholder:s=!1,selected:l,ariaExpanded:m,ariaDescribedBy:d,onSelect:h,onDragStart:g,onDragEnd:y,onDragOver:w,onDrop:_,onDoubleClick:P}){const M=!!g;return k.jsx("div",{className:["sidebar-row",t??"",l?"selected":"",a?"dragging":"",o?"iconless":"",i?"nested":"",s?"placeholder":""].filter(Boolean).join(" "),draggable:M,"data-session-id":n,role:"button",tabIndex:0,"aria-expanded":m,"aria-describedby":d,onClick:h,onDoubleClick:P,onKeyDown:C=>{C.target===C.currentTarget&&(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),h())},onDragStart:g,onDragEnd:y,onDragEnter:C=>{w&&(C.preventDefault(),C.dataTransfer.dropEffect="move",w(C))},onDragOver:C=>{w&&(C.preventDefault(),C.dataTransfer.dropEffect="move",w(C))},onDrop:C=>{_&&(C.preventDefault(),_(C))},children:e})}function Gd({children:e,label:t,onClick:n}){return k.jsx("button",{type:"button",className:"sidebar-row-action","data-tooltip":t,"aria-label":t,onClick:a=>{a.stopPropagation(),n()},children:e})}function hV({filter:e,groupByProject:t,noun:n,onFilterChange:a,onGroupByProjectChange:o,onOnlyRunningTasksChange:i,onShowCodexChatsChange:s,onTasksetChange:l,onSortChange:m,onlyRunningTasks:d,openMenu:h,setOpenMenu:g,showCodexChats:y,sort:w,selectedTasksetId:_,tasksets:P}){const M=v.useRef(null),[C,N]=v.useState(!1),j=P.find(E=>E.id===_)?.name??i0.find(E=>E.value===e)?.label??"Active",x=h==="tasks-filter",R=h==="chats";return v.useEffect(()=>{if(!x&&!R)return;function E(U){M.current?.contains(U.target)||g(null)}return document.addEventListener("pointerdown",E),()=>document.removeEventListener("pointerdown",E)},[x,g,R]),k.jsxs("div",{className:"sidebar-task-list-controls",ref:M,children:[k.jsxs("div",{className:"section-menu",children:[k.jsx("button",{type:"button",className:`section-icon ${R?"active":""}`,"aria-label":`${n==="tasks"?"Task":"Chat"} list options`,"aria-haspopup":"menu","aria-expanded":R,onClick:()=>g(E=>E==="chats"?null:"chats"),children:k.jsx(uc,{size:14})}),R?k.jsxs("div",{className:"section-menu-popover",role:"menu","aria-label":`${n==="tasks"?"Task":"Chat"} list options`,children:[k.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":y,onClick:()=>s(!y),children:[k.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:y?k.jsx(Po,{size:13}):null}),k.jsx("span",{children:"Show Codex chats, including pinned"})]}),k.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":d,onClick:()=>i(!d),children:[k.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:d?k.jsx(Po,{size:13}):null}),k.jsxs("span",{children:["Only running ",n,", including pinned"]})]}),n==="tasks"?k.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":t,onClick:()=>o(!t),children:[k.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:t?k.jsx(Po,{size:13}):null}),k.jsx("span",{children:"Group by project"})]}):null,S6.map(E=>k.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":w===E.value,onClick:()=>{m(E.value),g(null)},children:[k.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:w===E.value?k.jsx(Po,{size:13}):null}),k.jsx("span",{children:E.label})]},E.value))]}):null]}),k.jsxs("div",{className:"section-menu",children:[k.jsx("button",{type:"button",className:`section-icon ${x?"active":""}`,"aria-label":`Filter ${n}: ${j}`,"aria-haspopup":"menu","aria-expanded":x,onClick:()=>g(E=>E==="tasks-filter"?null:"tasks-filter"),children:k.jsx(u3,{size:14})}),x?k.jsx("div",{className:"section-menu-popover",role:"menu","aria-label":`Filter ${n}`,children:i0.map(E=>k.jsxs(v.Fragment,{children:[E.value==="tasksets"?k.jsxs("button",{type:"button",role:"menuitem","aria-expanded":C,onClick:()=>N(U=>!U),children:[k.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:C?k.jsx(Ko,{size:13}):k.jsx(ti,{size:13})}),k.jsx("span",{children:E.label})]}):k.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":e===E.value,onClick:()=>{a(E.value),g(null)},children:[k.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e===E.value?k.jsx(Po,{size:13}):null}),k.jsx("span",{children:E.label})]}),E.value==="tasksets"&&C?k.jsxs(k.Fragment,{children:[k.jsxs("button",{className:"section-menu-taskset-option",type:"button",role:"menuitemradio","aria-checked":e==="tasksets"&&!_,onClick:()=>{l(null),g(null)},children:[k.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&!_?k.jsx(Po,{size:13}):null}),k.jsx("span",{children:"All Tasksets"})]}),P.map(U=>k.jsxs("button",{className:"section-menu-taskset-option",type:"button",role:"menuitemradio","aria-checked":e==="tasksets"&&_===U.id,onClick:()=>{l(U.id),g(null)},children:[k.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&_===U.id?k.jsx(Po,{size:13}):null}),k.jsx("span",{children:U.name}),k.jsx("span",{className:"section-menu-option-count","aria-hidden":"true",children:U.chatCount})]},U.id))]}):null]},E.value))}):null]})]})}function gV({onAddProject:e,onViewProjects:t}){const[n,a]=v.useState(!1),o=v.useRef(null),i=v.useRef(null);return v.useEffect(()=>{if(!n)return;o.current?.querySelector('[role="menuitem"]')?.focus();const s=l=>{o.current?.contains(l.target)||a(!1)};return document.addEventListener("pointerdown",s),()=>document.removeEventListener("pointerdown",s)},[n]),k.jsxs(k.Fragment,{children:[k.jsxs("div",{className:"section-menu",ref:o,onKeyDown:s=>{s.key==="Escape"&&(s.stopPropagation(),a(!1),i.current?.focus())},children:[k.jsx("button",{ref:i,type:"button",className:`section-icon${n?" active":""}`,"aria-label":"Project options","aria-haspopup":"menu","aria-expanded":n,onClick:()=>a(s=>!s),children:k.jsx(uc,{size:14})}),n?k.jsxs("div",{className:"section-menu-popover",role:"menu","aria-label":"Project options",children:[k.jsx("button",{type:"button",role:"menuitem",onClick:()=>{a(!1),t()},children:"View all projects"}),k.jsx("button",{type:"button",role:"menuitem",onClick:()=>{a(!1),e()},children:"Add project"})]}):null]}),k.jsx("button",{type:"button",className:"section-icon",onClick:e,"aria-label":"Add project",title:"Add project",children:"+"})]})}const vV=240,bV=36;function yV(e,t,n=!1){const a=Math.max(12,t.width-vV-12),o=Math.max(12,t.height-bV-(n?22:0)-12);return{"--sidebar-task-detail-left":`${Math.round(Math.max(12,Math.min(e.right+10,a)))}px`,"--sidebar-task-detail-top":`${Math.round(Math.max(12,Math.min(e.top-4,o)))}px`}}function SV({detail:e,onClose:t}){if(v.useEffect(()=>{if(!e||typeof window>"u")return;const o=l=>{l.key==="Escape"&&t()};let i=!1;const s=window.requestAnimationFrame(()=>{window.addEventListener("scroll",t,!0),i=!0});return window.addEventListener("keydown",o),()=>{window.cancelAnimationFrame(s),window.removeEventListener("keydown",o),i&&window.removeEventListener("scroll",t,!0)}},[e,t]),!e)return null;const n=new Date(e.updatedAt),a=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(n);return k.jsxs("aside",{id:e.descriptionId,className:"sidebar-task-detail-popover",style:e.style,role:"tooltip","aria-label":`Last updated for ${e.title}`,children:[k.jsx("time",{dateTime:e.updatedAt,children:a}),e.folderName?k.jsxs("div",{className:"sidebar-task-detail-folder",children:[k.jsx(YI,{size:13,"aria-hidden":"true"}),k.jsx("span",{children:e.folderName})]}):null]})}function xV({children:e,expanded:t,groupKey:n,kind:a,label:o,onToggle:i,onNewTask:s,onOpenProject:l,onRemoveProject:m,project:d}){const h=`sidebar-task-group-${n.replace(/[^a-zA-Z0-9_-]/g,"-")}`,g=a==="draft"?lv:Uu,[y,w]=v.useState(!1),_=!!(s||l||m);return k.jsxs("section",{className:"sidebar-task-project-group",children:[k.jsxs("div",{className:`sidebar-task-project-group-header-shell${y?" menu-open":""}`,children:[k.jsxs("button",{type:"button",className:"sidebar-task-project-group-header","aria-controls":h,"aria-expanded":t,onClick:()=>{w(!1),i()},children:[d?k.jsx(P_,{kind:d.kind,linkedCloud:!!(d.kind==="local"&&d.project.linkedSandboxProject?.projectId),open:d.kind==="local"&&t,className:"sidebar-task-project-group-icon",baseSize:14}):k.jsx(g,{className:"sidebar-task-project-group-icon",size:14,"aria-hidden":"true"}),k.jsx("span",{className:"sidebar-task-project-group-name",children:o}),k.jsx("span",{className:"sidebar-task-project-group-caret","aria-hidden":"true",children:t?k.jsx(Ko,{size:13}):k.jsx(ti,{size:13})})]}),d&&_?k.jsxs("div",{className:"sidebar-task-project-group-actions",children:[l||m?k.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(P=>!P),children:k.jsx(uc,{size:13})}):null,s?k.jsx("button",{type:"button",className:"sidebar-row-action","data-tooltip":"New task","aria-label":"New task",onClick:s,children:k.jsx(Hu,{size:13})}):null]}):null,y?k.jsxs(k.Fragment,{children:[k.jsx("button",{type:"button",className:"sidebar-task-project-group-menu-backdrop","aria-label":"Close project actions",onClick:()=>w(!1)}),k.jsxs("div",{className:"section-menu-popover sidebar-task-project-group-menu",role:"menu",children:[l?k.jsx("button",{type:"button",role:"menuitem",onClick:()=>{w(!1),l()},children:k.jsx("span",{children:"Open project"})}):null,m?k.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{w(!1),m()},children:[k.jsx(mc,{size:13}),k.jsx("span",{children:"Remove from Projects"})]}):null]})]}):null]}),t?k.jsx("div",{id:h,className:"sidebar-task-project-group-content",children:e}):null]})}const kV={},wV=new Map,IV=new Map;function _V(e,t){return Math.min(Math.max(e,Pn)+lh,t)}function CV(e,t){const n=Math.max(Pn,Math.min(e,t));if(n<=Pn)return Pn;const a=Math.ceil((n-Pn)/lh);return Math.max(Pn,Pn+(a-1)*lh)}function RV(e,t){const n=new Map;for(const a of e){const o=t(a),i=n.get(o.key);i?i.sessions.push(a):n.set(o.key,{...o,sessions:[a]})}return[...n.values()]}function PV({activeSessions:e,archiveSession:t,archivedSessions:n,chatRowsVisibleCount:a,childSessionRowsByParentId:o={},cloudProjectRows:i,beginProjectChat:s,onAddProject:l,commitTaskDrop:m,commitTaskPreviewDrop:d,dockSessionRight:h,experience:g="work",goalRuntimeBySessionId:y=wV,localProjectRows:w,openSidebarFile:_,pinnedCollapsed:P,pinnedRows:M,previewTaskDrop:C,previewPinnedDrop:N,projectRows:$,renameSession:j,restoreSession:x,runningSessionIds:R,sectionMenuOpen:E,selectedProjectId:U,selectedSessionId:B,setChatRowsVisibleCount:D,setSectionMenuOpen:W,setSelectedAppId:se,setSelectedProjectId:de,setSelectedSessionId:Me,setView:ke,sidebarProjectIdBySessionId:te,startTaskDrag:Ee,startPinnedDrag:ye,subagentRuntimeBySessionId:ne=IV,taskDragSessionId:be,taskPreviewSessionIds:ae,terminalSummaries:ue=kV,toggleSessionPinned:xe,toggleSessionSavedForLater:De,view:we,clearTaskDrag:oe,removeProject:Se,toggleProjectPinned:He,onTogglePinnedCollapsed:Ze,setSidebarFileStatus:Ke,commitPinnedDrop:tt,commitPinnedPreviewDrop:qe,clearSidebarDrag:Ge,dragItem:ze}){const[L,O]=v.useState("active"),[z,X]=v.useState("recent"),[me,$e]=v.useState(!0);v.useEffect(()=>{g!=="chat"&&$e(!0)},[g]);const[Le,nt]=v.useState({work:!1,chat:!0}),[at,lt]=v.useState({work:!1,chat:!1}),pt=g==="chat"?"chat":"work",je=Le[pt],[Ye,f]=v.useState(u0);fc(()=>f(u0()));const{onlyRunningTasks:H,showCodexChats:Y}=Ye,[he,ie]=v.useState(null),[K,I]=v.useState(()=>new Set),[V,ee]=v.useState(()=>new Map),[G,le]=v.useState(null);v.useEffect(()=>{U&&nt(F=>F[pt]?{...F,[pt]:!1}:F)},[pt,U]);const pe=g==="chat"?"chats":"tasks",fe=$??[...w,...i],Pe=v.useMemo(()=>new Map(fe.map(F=>[F.id,F.project.name])),[fe]),_e=v.useMemo(()=>new Map(fe.map(F=>[F.id,F])),[fe]),Ne=v.useMemo(()=>{const F=new Set(R);for(const Ue of e){const Ie=y.get(Ue.id),Be=ne.get(Ue.id);(Ie?.tone==="active"&&Ie.status!=="queued"||(Be?.activeCount??0)>0||jt(Ue.id)?.status==="running")&&F.add(Ue.id)}return F},[e,y,R,ne,ue]),Re=v.useMemo(()=>s0({activeSessions:e,doneSessions:n,filter:"all",inProgressSessionIds:Ne,sort:"manual"}),[e,n,Ne]),Xe=v.useMemo(()=>s0({activeSessions:e,doneSessions:n,filter:L,inProgressSessionIds:Ne,onlyRunningTasks:H,selectedTasksetId:he,previewSessionIds:ae,showCodexChats:Y,sort:z}),[e,n,Ne,H,he,Y,L,ae,z]),st=v.useMemo(()=>{const F=new Map;for(const Ue of[...e,...n]){if(!Sd(Ue,{inProgressSessionIds:Ne,onlyRunningTasks:H,showCodexChats:Y}))continue;const Ie=Ji(Ue);if(!Ie)continue;const Be=F.get(Ie.id);Be?Be.chatCount+=1:F.set(Ie.id,{...Ie,chatCount:1})}return[...F.values()].sort((Ue,Ie)=>Ue.name.localeCompare(Ie.name))},[e,n,Ne,H,Y]),on=v.useMemo(()=>M.filter(F=>F.type!=="session"||Sd(F.session,{inProgressSessionIds:Ne,onlyRunningTasks:H,showCodexChats:Y})),[Ne,H,M,Y]),At=v.useMemo(()=>Xe.filter(F=>!kl(F)),[Xe]),tn=v.useMemo(()=>At.slice(0,Math.max(Pn,a)),[a,At]),dn=v.useMemo(()=>{const F=RV(tn,Ue=>{if(Bl(Ue))return{key:"draft",label:"Drafts",projectId:null,project:null,kind:"draft"};const Ie=te[Ue.id],Be=ht(Ue)??"Work";return{key:Ie?`project:${Ie}`:`projectless:${Be}`,label:Be,projectId:Ie??null,project:Ie?_e.get(Ie)??null:null,kind:Ie?"project":"projectless"}});for(const Ue of fe)F.some(Ie=>Ie.projectId===Ue.id)||F.push({key:`project:${Ue.id}`,label:Ue.project.name,projectId:Ue.id,project:Ue,kind:"project",sessions:[]});return F},[fe,Pe,_e,te,tn]),un=tn.length<At.length,Kt=tn.length>Pn,Aa=v.useMemo(()=>new Set(dn.filter(F=>F.sessions.some(Ue=>Ue.id===B||Ne.has(Ue.id))).map(F=>F.key)),[dn,Ne,B]),la=Re.filter(F=>!kl(F)).map(F=>F.id),Mn=tn.map(F=>F.id),_n=JSON.stringify(Object.entries(o).filter(([F,Ue])=>Ue.length>0&&(ne.get(F)?.activeCount??0)>0).flatMap(([F,Ue])=>Ue.map(Ie=>[F,Ie.id])).sort(([F,Ue],[Ie,Be])=>F.localeCompare(Ie)||Ue.localeCompare(Be)));v.useEffect(()=>{const F=JSON.parse(_n);if(F.length===0)return;const Ue=new Set(F.map(([Ie])=>Ie));I(Ie=>[...Ue].every(Be=>Ie.has(Be))?Ie:new Set([...Ie,...Ue]))},[_n]);function jt(F){return P6(ue[I_({kind:"session",id:F})])}function ht(F){if(Bl(F))return"Draft";const Ue=te[F.id];return Ue?Pe.get(Ue)??F.workspaceName??"Project":f6(F)}function mn(F){Qt({kind:"chat",sessionId:F.id}),Me(F.id);const Ue=te[F.id]??null;se(Ue?null:F.appId),de(Ue),ke("chat")}function vt(F){return(o[F.id]??[]).filter(Ue=>Sd(Ue,{inProgressSessionIds:Ne,onlyRunningTasks:H,showCodexChats:Y}))}function Et(F,Ue){return K.has(F.id)||Ue.some(Ie=>Ie.id===B)}function ca(F){I(Ue=>{const Ie=new Set(Ue);return Ie.has(F)?Ie.delete(F):Ie.add(F),Ie})}function Ut(F){const Ue=vt(F);return Ue.length===0||!Et(F,Ue)?null:k.jsx("div",{className:"sidebar-child-session-group",children:Ue.map(Ie=>k.jsx(Qp,{session:Ie,selected:we==="chat"&&B===Ie.id,hideIcon:!0,nested:!0,running:Ne.has(Ie.id),goalRuntime:y.get(Ie.id)??null,subagentRuntime:ne.get(Ie.id)??null,terminalIndicator:jt(Ie.id),projectLabel:ht(F),onSelect:()=>mn(Ie),onTogglePin:()=>xe(Ie),onToggleSaveForLater:()=>De(Ie),onDockRight:()=>h(Ie),onArchive:()=>Ie.archived?x(Ie):t(Ie),onRename:j},Ie.id))})}function pn(F,Ue){if(typeof window>"u")return;const Ie=kl(F)?ht(F):null;le({descriptionId:`sidebar-task-detail-${F.id}`,sessionId:F.id,title:F.title,updatedAt:F.updatedAt,folderName:Ie,style:yV(Ue.getBoundingClientRect(),{width:window.innerWidth,height:window.innerHeight},!!Ie)})}function rt(F,Ue={}){const Ie=F.archived,Be=be===F.id,bt=vt(F),Bn="sidebar-session-group",fn=z==="manual"?{onDragStart:We=>Ee(We,{allSessionIds:la,visibleSessionIds:Mn,sessionId:F.id}),onDragEnd:oe,onDragOver:We=>{Be||C(We,F.id)},onDrop:We=>{Be?d():m(We,F.id)}}:{};return k.jsxs("div",{className:Bn,onPointerEnter:We=>pn(F,We.currentTarget),onPointerLeave:()=>le(null),onFocusCapture:We=>pn(F,We.currentTarget),onBlurCapture:We=>{We.currentTarget.contains(We.relatedTarget)||le(null)},children:[k.jsx(Qp,{session:F,selected:!Ie&&we==="chat"&&B===F.id,archived:Ie,hideIcon:!0,placeholder:Be,running:Ne.has(F.id),goalRuntime:y.get(F.id)??null,subagentRuntime:ne.get(F.id)??null,terminalIndicator:jt(F.id),projectLabel:Ue.projectLabel===void 0?ht(F):Ue.projectLabel,metadataPresentation:Ue.metadataPresentation,ariaDescribedBy:G?.sessionId===F.id?G.descriptionId:void 0,childSessionCount:bt.length,childSessionsExpanded:Et(F,bt),onToggleChildSessions:()=>ca(F.id),onSelect:()=>{le(null),Ie&&x(F),mn(F)},onTogglePin:()=>xe(F),onToggleSaveForLater:()=>De(F),onDockRight:()=>h(F),onArchive:()=>Ie?x(F):t(F),onRename:j,...fn}),Be?null:Ut(F)]},F.id)}function kn(F){F!=="tasksets"&&ie(null),O(F),D(Pn)}function Wa(F){ie(F),O("tasksets"),D(Pn)}function Ga(F){X(F),D(Pn)}function ea(){D(F=>_V(F,At.length))}function da(){D(F=>CV(F,At.length))}function jn(F){const Ue={id:F.id,type:F.type};return{onDragStart:Ie=>ye(Ie,Ue),onDragEnd:Ge,onDragOver:Ie=>N(Ie,Ue),onDrop:Ie=>{ze?.id===F.id&&ze.type===F.type?qe():tt(Ie,Ue)}}}function go(F){const Ue=jn(F),Ie=ze?.id===F.id&&ze.type===F.type;if(F.type==="project"){const bt=F.item;return k.jsx(Q6,{kind:bt.kind,project:bt.project,pinned:!0,selected:we==="chat"&&U===bt.id,expanded:!1,disclosure:!1,placeholder:Ie,onSelect:()=>{se(null),de(bt.id),Me(null),ke("chat")},onNewChat:()=>s(bt.id),onTogglePin:()=>He(bt),onRemove:()=>Se(bt),...Ue},F.key)}if(F.type==="file")return k.jsx(J6,{file:F.file,placeholder:Ie,onSelect:()=>_(F.file),onTogglePin:()=>Ke(F.file,"none"),onToggleSaveForLater:()=>Ke(F.file,"saved_for_later"),...Ue},F.key);const Be=F.session;return k.jsx("div",{onPointerEnter:bt=>pn(Be,bt.currentTarget),onPointerLeave:()=>le(null),onFocusCapture:bt=>pn(Be,bt.currentTarget),onBlurCapture:bt=>{bt.currentTarget.contains(bt.relatedTarget)||le(null)},children:k.jsx(Qp,{ariaDescribedBy:G?.sessionId===Be.id?G.descriptionId:void 0,session:Be,selected:we==="chat"&&B===Be.id,hideIcon:!0,placeholder:Ie,running:Ne.has(Be.id),goalRuntime:y.get(Be.id)??null,subagentRuntime:ne.get(Be.id)??null,terminalIndicator:jt(Be.id),projectLabel:ht(Be),metadataPresentation:"flyout",onSelect:()=>{le(null),mn(Be)},onTogglePin:()=>xe(Be),onToggleSaveForLater:()=>De(Be),onDockRight:()=>h(Be),onArchive:()=>t(Be),onRename:j,...Ue})},F.key)}function Ta(F){const Ue=Aa.has(F.key)||V.get(F.key)!==!1;return k.jsx(xV,{expanded:Ue,groupKey:F.key,kind:F.kind,label:F.label,onToggle:()=>{ee(Ie=>{const Be=new Map(Ie);return Be.set(F.key,!Ue),Be})},onNewTask:F.project?()=>s(F.project.id):void 0,onOpenProject:F.project?()=>{se(null),de(F.project.id),Me(null),ke("chat")}:void 0,onRemoveProject:F.project?()=>Se(F.project):void 0,project:F.project,children:F.sessions.map(Ie=>rt(Ie,{metadataPresentation:"flyout",projectLabel:F.label}))},F.key)}return k.jsxs("div",{className:"sidebar-sections",children:[on.length>0?k.jsx(Yp,{label:"Pinned",className:"sidebar-pinned-section",collapsed:P,onToggleCollapsed:Ze,children:on.map(go)}):null,k.jsx(Yp,{label:"Projects",className:`sidebar-projects-section${g!=="chat"?" development":""}`,collapsed:je,onToggleCollapsed:()=>nt(F=>({...F,[pt]:!F[pt]})),actions:k.jsx(gV,{onAddProject:l,onViewProjects:()=>{(async()=>await Qt({kind:"view",view:"projects"})&&(se(null),de(null),Me(null),ke("projects")))()}}),children:dn.filter(F=>F.kind==="project").map(F=>Ta(g==="chat"||!me?{...F,sessions:[]}:F))}),k.jsxs(Yp,{label:g==="chat"?"Chat":"Work",className:"sidebar-task-section sidebar-ordinary-section",collapsed:at[pt],onToggleCollapsed:()=>lt(F=>({...F,[pt]:!F[pt]})),actionsVisible:E==="chats"||E==="tasks-filter"||L!=="active"||H||!Y,actions:k.jsx(hV,{filter:L,groupByProject:me,noun:pe,onFilterChange:kn,onGroupByProjectChange:$e,onOnlyRunningTasksChange:F=>{f(Ue=>{const Ie={...Ue,onlyRunningTasks:F};return m0(Ie),Ie}),D(Pn)},onShowCodexChatsChange:F=>{f(Ue=>{const Ie={...Ue,showCodexChats:F};return m0(Ie),Ie}),D(Pn)},onTasksetChange:Wa,onSortChange:Ga,onlyRunningTasks:H,openMenu:E,setOpenMenu:W,showCodexChats:Y,sort:z,selectedTasksetId:he,tasksets:st}),children:[(g==="chat"||!me?tn:tn.filter(F=>!te[F.id])).map(F=>rt(F)),At.length===0&&on.length===0?k.jsx("div",{className:"empty-row",children:x6(L,pe)}):null,At.length>Pn&&(un||Kt)?k.jsxs("div",{className:"sidebar-pagination-controls","aria-label":`Showing ${tn.length} of ${At.length} ${pe}`,children:[un?k.jsx(p0,{onClick:ea,children:"Show more"}):null,Kt?k.jsx(p0,{onClick:da,children:"Show less"}):null]}):null]}),k.jsx(SV,{detail:G,onClose:()=>le(null)})]})}const AV="/";function Jn(e){return`${AV}${e.replace(/^\.?\//,"")}`}const TV=Jn("openpond-icon.png"),EV=Jn("openpond-wordlogo-white.png"),zQ=Jn("tutorials/what-is-an-openpond-agent-poster.png"),qQ=Jn("tutorials/what-is-an-openpond-agent.vtt"),BQ=Jn("tutorials/how-to-make-an-agent-poster.png"),FQ=Jn("tutorials/how-to-make-an-agent.vtt");function VQ(e){return Jn(`tutorials/how-to-make-an-agent-${e}-poster.png`)}function KQ(e){return Jn(`tutorials/how-to-make-an-agent-${e}.vtt`)}const f0={github:Jn("connected-apps/github.svg"),google:Jn("connected-apps/google.svg"),microsoft_teams:Jn("connected-apps/microsoft.svg"),mcp:Jn("connected-apps/openpond-mcp.svg"),slack:Jn("connected-apps/slack.svg"),x:Jn("connected-apps/x.svg")};function WQ(e){return f0[e]??f0.mcp}function MV({value:e,onChange:t}){const[n,a]=v.useState(!1),o=v.useRef(null),i=v.useRef(null),s=v.useRef(null),l=v.useRef(null),m=Kp.find(y=>y.value===e)??Kp[0];v.useEffect(()=>{if(!n)return;const y=_=>{_.target instanceof Node&&!o.current?.contains(_.target)&&a(!1)},w=()=>a(!1);return window.addEventListener("pointerdown",y),window.addEventListener("blur",w),()=>{window.removeEventListener("pointerdown",y),window.removeEventListener("blur",w)}},[n]),v.useLayoutEffect(()=>{n&&l.current&&h0(s.current,l.current),l.current=null},[n]);const d=y=>{if(n){h0(s.current,y);return}l.current=y,a(!0)},h=y=>{y.key==="ArrowDown"?(y.preventDefault(),d("first")):y.key==="ArrowUp"&&(y.preventDefault(),d("last"))},g=y=>{const w=T_(s.current),_=w.findIndex(C=>C===document.activeElement);if(y.key==="Escape"){y.preventDefault(),a(!1),i.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 P=y.key==="ArrowDown"?1:-1,M=_<0?0:(_+P+w.length)%w.length;w[M]?.focus()};return k.jsxs("div",{className:"sidebar-experience-menu",ref:o,children:[k.jsxs("button",{ref:i,type:"button",className:"sidebar-wordmark-button sidebar-experience-trigger","aria-label":`OpenPond product: ${m.label}`,"aria-haspopup":"menu","aria-expanded":n,onClick:()=>{l.current=null,a(y=>!y)},onKeyDown:h,children:[k.jsx("img",{className:"sidebar-wordmark",src:EV,alt:""}),k.jsx("span",{className:"sidebar-experience-label",children:m.label}),k.jsx(Ko,{size:13,"aria-hidden":"true"})]}),n?k.jsx("div",{ref:s,className:"sidebar-experience-popover",role:"menu","aria-label":"Choose product",onKeyDown:g,children:Kp.map(y=>{const w=y.value===e;return k.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:[k.jsxs("span",{children:[k.jsx("strong",{children:y.label}),k.jsx("small",{children:y.description})]}),w?k.jsx(Po,{size:14,"aria-hidden":"true"}):null]},y.value)})}):null]})}function T_(e){return e?Array.from(e.querySelectorAll('[role="menuitemradio"]')):[]}function h0(e,t){const n=T_(e);(t==="first"?n[0]:n.at(-1))?.focus()}function jV(...e){for(const t of e){const n=t?.trim();if(n)return n}return null}function OV(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"?jV(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 $V({account:e,open:t,organizations:n,selectedTeamId:a,onOpenActivity:o,onOpenChange:i,onOpenSettings:s,onSelectTeam:l,onLogOut:m}){const[d,h]=v.useState(null),[g,y]=v.useState(!1),w=v.useRef(null),_=v.useMemo(()=>OV(e),[e]),P=_.label.trim().slice(0,1).toUpperCase(),M=n.find(C=>C.teamId===a)??n[0]??null;return v.useEffect(()=>{if(!t)return;function C($){w.current?.contains($.target)||i(!1)}function N($){$.key==="Escape"&&i(!1)}return document.addEventListener("pointerdown",C),document.addEventListener("keydown",N),()=>{document.removeEventListener("pointerdown",C),document.removeEventListener("keydown",N)}},[i,t]),k.jsxs("div",{className:"user-auth-footer",ref:w,children:[k.jsxs("button",{type:"button",className:`user-auth-trigger ${t?"active":""}`,"aria-haspopup":"menu","aria-expanded":t,"aria-label":`${_.label} account menu`,onClick:()=>i(!t),children:[k.jsx("span",{className:"user-auth-avatar","aria-hidden":"true",children:_.image?k.jsx("img",{src:_.image,alt:""}):P?k.jsx("span",{children:P}):k.jsx(Xy,{size:16})}),k.jsx("span",{className:"user-auth-name",children:_.label})]}),t?k.jsxs("div",{className:"user-auth-menu",role:"menu","aria-label":"Account",children:[k.jsxs("div",{className:"user-auth-menu-header",children:[k.jsx("span",{className:"user-auth-menu-avatar","aria-hidden":"true",children:_.image?k.jsx("img",{src:_.image,alt:""}):P?k.jsx("span",{children:P}):k.jsx(Xy,{size:17})}),k.jsx("span",{className:"user-auth-menu-identity",children:k.jsx("strong",{children:_.label})})]}),n.length>0&&l?k.jsxs("label",{className:"user-auth-team-picker",children:[k.jsx(n_,{size:15,"aria-hidden":"true"}),k.jsx("span",{className:"user-auth-team-picker-label",children:"Team"}),k.jsx("select",{"aria-label":"Active team",disabled:d!==null,value:M?.teamId??"",onChange:async C=>{const N=C.currentTarget.value;h(N);try{await l(N)}catch{}finally{h(null)}},children:n.map(C=>k.jsx("option",{value:C.teamId,children:C.displayName},C.teamId))})]}):null,k.jsx("div",{className:"user-auth-menu-divider"}),o?k.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",onClick:()=>{i(!1),o()},children:[k.jsx(JI,{size:15}),k.jsx("span",{children:"Activity"})]}):null,k.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",onClick:()=>{i(!1),s()},children:[k.jsx(t_,{size:15}),k.jsx("span",{children:"Settings"})]}),e?.state==="signed_in"&&m?k.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",disabled:g,onClick:async()=>{y(!0);try{await m(),i(!1)}catch{}finally{y(!1)}},children:[k.jsx(_3,{size:15}),k.jsx("span",{children:g?"Logging out…":"Log out"})]}):null]}):null]})}function g0(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 NV(e,t){const n=g0(e),a=g0(t);if(!n||!a)return!1;for(let o=0;o<a.length;o+=1){if(a[o]>n[o])return!0;if(a[o]<n[o])return!1}return!1}function E_(e){const t=e?.toLowerCase()??"";return t==="darwin"||t.includes("mac")?"mac":t==="linux"||t.includes("linux")?"linux":null}function DV(e){const t=e?.toLowerCase()??"";return t==="arm64"||t==="aarch64"?"arm64":t==="x64"||t==="x86_64"||t==="amd64"?"x64":null}function LV(e,t,n){const a=E_(t),o=DV(n);if(a==="mac"){const i=e.filter(s=>/-mac-.*\.zip$/i.test(s.name));return o==="arm64"?i.find(s=>/-mac-arm64\.zip$/i.test(s.name))??null:o==="x64"?i.find(s=>/-mac-x64\.zip$/i.test(s.name))??i.find(s=>/-mac-universal\.zip$/i.test(s.name))??null:i.find(s=>/-mac-universal\.zip$/i.test(s.name))??i.find(s=>/-mac-arm64\.zip$/i.test(s.name))??i[0]??null}if(a==="linux"){const i=e.filter(s=>/\.AppImage$/i.test(s.name));return o==="arm64"?i.find(s=>/(?:arm64|aarch64).*\.AppImage$/i.test(s.name))??null:o==="x64"?i.find(s=>/(?:x86_64|x64|amd64).*\.AppImage$/i.test(s.name))??i[0]??null:i[0]??null}return null}function UV(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(!NV(e.currentVersion,a))return null;const o=typeof t.html_url=="string"?t.html_url:"",s=(Array.isArray(t.assets)?t.assets:[]).flatMap(m=>{if(!m||typeof m!="object")return[];const d=m;return typeof d.name!="string"||typeof d.browser_download_url!="string"?[]:[{name:d.name,downloadUrl:d.browser_download_url}]}),l=LV(s,e.platform,e.arch);return!l||!o?null:{version:a,releaseUrl:o,assetName:l.name,downloadUrl:l.downloadUrl}}const HV=3600*1e3,zV="https://api.github.com/repos/openpond/openpond/releases/latest";function qV(e){const[t,n]=v.useState({status:"idle",update:null,lastCheckedAt:null}),a=e.currentVersion?.trim()??"",o=e.platform??"",i=e.arch??"",s=e.enabled&&!!a&&!!E_(o);return v.useEffect(()=>{if(!s){n({status:"idle",update:null,lastCheckedAt:null});return}let l=!1;async function m(){n(h=>({...h,status:h.update?"available":"checking"}));try{const h=await fetch(zV,{headers:{Accept:"application/vnd.github+json"}});if(!h.ok)throw new Error(`GitHub release check failed: ${h.status}`);const g=await h.json(),y=UV({payload:g,currentVersion:a,platform:o,arch:i});if(l)return;n({status:y?"available":"current",update:y,lastCheckedAt:Date.now()})}catch{if(l)return;n(h=>({status:h.update?"available":"error",update:h.update,lastCheckedAt:Date.now()}))}}m();const d=window.setInterval(()=>{m()},HV);return()=>{l=!0,window.clearInterval(d)}},[i,a,s,o]),t}const M_="openpond.sidebar.continuous-learning.dismissed.v1";function v0(e=j_()){if(!e)return!1;try{return e.getItem(M_)==="true"}catch{return!1}}function BV(e=j_()){if(e)try{e.setItem(M_,"true")}catch{}}function j_(){return typeof window>"u"?null:hc}function FV({connection:e,onOpenSettings:t}){const[n,a]=v.useState(null),[o,i]=v.useState(v0);fc(()=>i(v0()));const s=v.useCallback(async()=>{if(!e){a(null);return}try{a(await Q.harnessHistory(e))}catch{a(null)}},[e]);if(v.useEffect(()=>{s()},[s]),o||!e||!n?.workspace)return null;const l=n.evaluationReviewSchedule,m=l.activityEnabled?`${l.activityBatchSize} outcomes${l.enabled?` + ${l.cadence}`:""}`:l.enabled?l.cadence:"Manual";return k.jsxs("section",{className:"sidebar-learning-notice","aria-label":"Continuous learning",children:[k.jsxs("header",{children:[k.jsx("strong",{children:"Continuous learning"}),k.jsxs("div",{className:"sidebar-learning-notice-actions",children:[k.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Open Continuous learning settings",onClick:t,type:"button",children:k.jsx(t_,{size:14})}),k.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Close continuous learning",onClick:()=>{i(!0),BV()},type:"button",children:k.jsx(mc,{size:14})})]})]}),k.jsxs("div",{className:"sidebar-learning-status",children:[k.jsx("strong",{children:"Refiner"}),k.jsx("span",{children:n.backgroundReview.enabled?"On":"Off"})]}),k.jsxs("div",{className:"sidebar-learning-status",children:[k.jsx("strong",{children:"Continuous Review"}),k.jsx("span",{children:m})]})]})}function VV(e){const[t,n]=v.useState(!1),{beginNewChat:a,arch:o,currentVersion:i,experience:s,productArea:l,onProductAreaChange:m,onSidebarResizeStart:d,platform:h,setSectionMenuOpen:g,setSelectedAppId:y,setSelectedProjectId:w,setSelectedSessionId:_,setSidebarOpen:P,setView:M,view:C,modelProjects:N,modelTrainingActivityByProjectId:$}=e,j=v.useCallback(U=>{n(!1),g(U)},[g]),x=v.useCallback(U=>{n(U),U&&g(null)},[g]),R=qV({currentVersion:i,platform:h,arch:o,enabled:zu()}),E=R.status==="available"?R.update:null;return k.jsxs("aside",{className:"sidebar",children:[k.jsxs("div",{className:"sidebar-toolbar",children:[k.jsx("button",{className:"sidebar-icon","aria-label":"Hide sidebar",onClick:()=>P(!1),children:k.jsx(e_,{size:16})}),k.jsx(MV,{value:l,onChange:m}),E&&k.jsxs("button",{type:"button",className:"sidebar-update-pill",title:`Download OpenPond ${E.version}: ${E.assetName}`,"aria-label":`Download OpenPond ${E.version}`,onClick:()=>{KV(E.downloadUrl)},children:[k.jsx(J5,{size:14}),k.jsx("span",{children:"Update"})]})]}),l!=="chat"?null:k.jsx(Z3,{experience:s,beginNewChat:a}),k.jsxs("div",{className:"sidebar-scroll",children:[l==="chat"&&e.account?.activeProfile&&e.onOpenPonder?k.jsxs("button",{type:"button",className:"sidebar-ponder-entry",onClick:e.onOpenPonder,children:[k.jsx("span",{"aria-hidden":"true",children:"✦"})," Ponder Pal"]}):null,k.jsx(J3,{productArea:l,setSectionMenuOpen:j,setSelectedAppId:y,setSelectedProjectId:w,setSelectedSessionId:_,setView:M,view:C,modelProjects:N,modelTrainingActivityByProjectId:$}),l!=="chat"?null:k.jsx(PV,{...e,setSectionMenuOpen:j})]}),k.jsxs("div",{className:"sidebar-bottom-stack",children:[l!=="chat"?null:k.jsx(FV,{connection:e.connection,onOpenSettings:()=>{g(null),Qt({kind:"settings",section:"harness"})}}),k.jsxs("div",{className:"sidebar-footer-row",children:[k.jsx($V,{account:e.account,open:t,organizations:e.organizations,selectedTeamId:e.teamChatOrganization?.teamId??null,onOpenChange:x,onOpenActivity:()=>{g(null),Qt({kind:"settings",section:"usage"})},onOpenSettings:()=>{g(null),Qt({kind:"settings",section:"account"})},onSelectTeam:e.onSelectTeam,onLogOut:e.onLogOut}),k.jsx(Y3,{setSectionMenuOpen:j,setSelectedAppId:y,setSelectedProjectId:w,setSelectedSessionId:_,setView:M,view:C})]})]}),k.jsx("div",{className:"sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",onPointerDown:d})]})}async function KV(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-update",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const WV=[/^(?:(?:type)?error:\s*)?failed to fetch\.?$/i,/^networkerror when attempting to fetch resource\.?$/i,/^load failed\.?$/i];function O_(e,t="Something went wrong."){const a=(e instanceof Error?e.message:String(e??"")).trim();return a?$_(a)?"Couldn’t connect to OpenPond.":a:t}function $_(e){const t=e.trim();return WV.some(n=>n.test(t))}const N_=v.createContext(null);function b0({children:e,showToast:t}){return k.jsx(N_.Provider,{value:t,children:e})}function GV(){return v.useContext(N_)}function y0(e,t={}){const n=GV(),a=v.useRef(null),o=t.enabled??!0,i=t.fallback??"Something went wrong.",s=t.prefix?.trim()??"",l=e==null||e===""?null:`${s}${s?": ":""}${O_(e,i)}`;v.useEffect(()=>{if(!o||!l){a.current=null;return}a.current!==l&&(a.current=l,n?.(l,"error"))},[o,l,n])}function ZV({state:e,onClose:t,onOpenBrowserUrl:n,onStart:a}){if(y0(e?.previewError,{prefix:"Upload preview"}),y0(e?.error,{prefix:"Cloud setup"}),!e)return null;const o=e.status==="uploading",i=e.status==="ready",s=e.status==="error",l=e.projectKind==="cloud",m=e.preview??null;return k.jsx("div",{className:"git-dialog-backdrop",role:"presentation",children:k.jsxs("section",{className:"git-dialog cloud-setup-dialog",role:"dialog","aria-modal":"true","aria-label":"Set up Cloud coding",children:[k.jsx("button",{className:"git-dialog-close",disabled:o,type:"button",onClick:t,"aria-label":"Close Cloud setup",title:"Close",children:k.jsx(mc,{size:14})}),k.jsx("div",{className:"git-dialog-icon",children:i?k.jsx(hd,{size:18}):k.jsx(Lu,{size:18})}),k.jsx("h2",{children:i?"Cloud repo ready":"Set up Cloud coding"}),k.jsx("p",{children:i?"Your source is ready in OpenPond Git. Finish by creating the Cloud sandbox environment.":l?"This Cloud Project is ready for a sandbox environment.":"OpenPond will upload tracked and unignored files into OpenPond Git, then send you to the Cloud sandbox setup page."}),k.jsxs("div",{className:"cloud-setup-summary",children:[k.jsxs("div",{className:"git-dialog-row",children:[k.jsx("span",{children:"Project"}),k.jsx("strong",{children:e.projectName})]}),k.jsxs("div",{className:"git-dialog-row",children:[k.jsx("span",{children:"Source"}),k.jsx("strong",{children:l?"OpenPond Git":"Local project upload"})]}),k.jsxs("div",{className:"git-dialog-row",children:[k.jsx("span",{children:"Branch"}),k.jsx("strong",{children:m?.branch??e.branch??"main"})]}),!l&&k.jsxs("div",{className:"git-dialog-row",children:[k.jsx("span",{children:"Cloud project"}),k.jsx("strong",{children:m?.targetProjectId??e.cloudProjectId??"New on upload"})]})]}),!i&&!l&&k.jsx("div",{className:"cloud-setup-upload-preview",role:"status","aria-live":"polite",children:e.previewLoading?k.jsxs(k.Fragment,{children:[k.jsx("strong",{children:"Calculating upload preview"}),k.jsx("span",{children:"Checking tracked and unignored files before anything is pushed."})]}):e.previewError?k.jsxs(k.Fragment,{children:[k.jsx("strong",{children:"Preview unavailable"}),k.jsx("span",{children:"Close and reopen setup to try the preview again."})]}):m?k.jsxs(k.Fragment,{children:[k.jsx("strong",{children:m.initializedEmptyProject?"Will initialize an empty project":`Will upload ${m.fileCount} files`}),k.jsx("span",{children:S0({byteCount:m.byteCount,skippedCount:m.skippedCount,headCommit:m.headCommit,targetProjectName:m.targetProjectName})})]}):k.jsxs(k.Fragment,{children:[k.jsx("strong",{children:"Upload preview pending"}),k.jsx("span",{children:"File count, byte count, and skipped files will appear here before upload."})]})}),o&&k.jsxs("div",{className:"cloud-setup-progress",role:"status","aria-live":"polite",children:[k.jsx(p3,{className:"cloud-setup-spinner",size:16}),k.jsx("span",{children:"Uploading source to OpenPond Git..."})]}),i&&e.upload&&k.jsxs("div",{className:"cloud-setup-upload-result",children:[k.jsx("strong",{children:e.upload.initializedEmptyProject?"Initialized empty project":`Uploaded ${e.upload.fileCount} files`}),k.jsx("span",{children:S0({byteCount:e.upload.byteCount,skippedCount:e.upload.skippedCount,headCommit:e.upload.headCommit,targetProjectName:e.upload.branch})})]}),i&&e.setupUrl&&k.jsxs("div",{className:"cloud-setup-next",children:[e.projectUrl?k.jsxs("span",{children:["Your repo is ready here:"," ",k.jsxs("a",{href:e.projectUrl,target:"_blank",rel:"noreferrer",onClick:d=>Xp(d,e.projectUrl,n,{newTab:!0}),children:["Project page",k.jsx(Fp,{size:13})]})]}):k.jsx("span",{children:"Your repo is ready. Next step:"}),k.jsxs("a",{href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:d=>Xp(d,e.setupUrl,n),children:["Setup the Cloud sandbox",k.jsx(Fp,{size:13})]})]}),k.jsxs("div",{className:"git-dialog-footer",children:[k.jsx("button",{className:"git-dialog-secondary",disabled:o,type:"button",onClick:t,children:i?"Done":"Cancel"}),i?e.setupUrl?k.jsxs("a",{className:"git-dialog-primary cloud-setup-primary-link",href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:d=>Xp(d,e.setupUrl,n),children:["Open setup",k.jsx(Fp,{size:13})]}):null:k.jsx("button",{className:"git-dialog-primary",disabled:o,type:"button",onClick:a,children:o?"Uploading":s?"Try again":l?"Show setup link":"Upload source"})]})]})})}function Xp(e,t,n,a={}){!t||!n||(e.preventDefault(),n(t,a))}function JV(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 S0({byteCount:e,skippedCount:t,headCommit:n,targetProjectName:a}){const o=[JV(e),`${t} skipped`],i=YV(n);return i&&o.push(`local ${i}`),o.push(a),o.join(" · ")}function YV(e){const t=e?.trim();return t?t.slice(0,7):null}const QV=v.lazy(()=>ni(()=>import("./CommandMenu-Cs5S8t-Q.js"),__vite__mapDeps([0,1,2,3]),import.meta.url).then(e=>({default:e.CommandMenu}))),XV=v.lazy(()=>ni(()=>import("./SettingsView-BZrOUPZb.js"),__vite__mapDeps([4,1,2,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21]),import.meta.url).then(e=>({default:e.SettingsView}))),eK=v.lazy(()=>ni(()=>import("./NewProjectDialog-hlAzFK2Y.js"),__vite__mapDeps([22,1,2,8,13,23]),import.meta.url).then(e=>({default:e.NewProjectDialog}))),tK=v.lazy(()=>ni(()=>import("./WorkspaceGitDialogs-B3xtasTt.js"),__vite__mapDeps([24,1,2,11,12,25,21]),import.meta.url).then(e=>({default:e.CommitDialog}))),nK=v.lazy(()=>ni(()=>import("./WorkspaceGitDialogs-B3xtasTt.js"),__vite__mapDeps([24,1,2,11,12,25,21]),import.meta.url).then(e=>({default:e.BranchDialog})));function aK({payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:o,onError:i,onToast:s,onBack:l,onOpenSourceSession:m,onStartRefinerAuthoring:d,onAcceptEvaluationReview:h,onOpenSkill:g,onOpenExtension:y,teamChatCurrentUserId:w,teamChatEnabled:_,teamChatNotificationMode:P,teamChatThreads:M,onTeamChatNotificationModeChange:C,onTeamChatThreadMuteChange:N,diffPanelWidth:$,diffPanelResizing:j,diffPanelExpanded:x,onDiffPanelResizeStart:R,onDiffPanelExpandedChange:E}){return k.jsx(v.Suspense,{fallback:null,children:k.jsx(XV,{payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:o,onError:i,onToast:s,onBack:l,onOpenSourceSession:m,onStartRefinerAuthoring:d,onAcceptEvaluationReview:h,onOpenSkill:g,onOpenExtension:y,teamChatCurrentUserId:w,teamChatEnabled:_,teamChatNotificationMode:P,teamChatThreads:M,onTeamChatNotificationModeChange:C,onTeamChatThreadMuteChange:N,diffPanelWidth:$,diffPanelResizing:j,diffPanelExpanded:x,onDiffPanelResizeStart:R,onDiffPanelExpandedChange:E})})}function oK({activeSessions:e,branchDialogName:t,branchDialogOpen:n,commitDialogOpen:a,commitDraft:o,commitIncludeUnstaged:i,commitMessage:s,commitNextStep:l,canPublishOpenPondProject:m,expandProject:d,newProjectBusy:h,newProjectDialogOpen:g,newProjectDirectory:y,newProjectMode:w,newProjectName:_,newProjectPath:P,projectRows:M,query:C,searchOpen:N,visibleWorkspaceDiff:$,visibleWorkspaceState:j,workspaceBusy:x,appDispatch:R,beginNewChat:E,openDefaultsSettingsFromBranchDialog:U,setBranchDialogName:B,setBranchDialogOpen:D,setCommitDialogOpen:W,setCommitDraft:se,setCommitIncludeUnstaged:de,setCommitMessage:Me,setCommitNextStep:ke,setNewProjectDialogOpen:te,setNewProjectName:Ee,setNewProjectPath:ye,setQuery:ne,setSearchOpen:be,submitCommitDialog:ae,submitCreateWorkspaceBranch:ue,submitNewProjectDialog:xe}){return k.jsxs(k.Fragment,{children:[N&&k.jsx(v.Suspense,{fallback:null,children:k.jsx(QV,{open:N,query:C,projects:M,sessions:e,onQueryChange:ne,onClose:()=>{be(!1),ne("")},onNewChat:()=>{be(!1),ne(""),E()},onOpenProject:De=>{R({type:"selectProject",projectId:De.id}),R({type:"patch",patch:{searchOpen:!1,query:""}}),d(De.id)},onOpenSession:De=>{R({type:"selectSession",sessionId:De.id,appId:De.appId,projectId:De.workspaceKind==="local_project"&&De.workspaceId?yt("local",De.workspaceId):null}),R({type:"patch",patch:{searchOpen:!1,query:""}})}})}),g&&k.jsx(v.Suspense,{fallback:null,children:k.jsx(eK,{open:g,mode:w,name:_,path:P,directory:y,busy:h,onNameChange:Ee,onPathChange:ye,onClose:()=>{h||te(!1)},onSubmit:xe})}),a&&k.jsx(v.Suspense,{fallback:null,children:k.jsx(tK,{open:a,branch:j?.currentBranch??null,filesChanged:$?.filesChanged??j?.changedFilesCount??0,additions:$?.additions??0,deletions:$?.deletions??0,message:s,includeUnstaged:i,nextStep:l,draft:o,busy:x,canPush:!!j?.remoteUrl,canPublish:m,onMessageChange:Me,onIncludeUnstagedChange:de,onNextStepChange:ke,onDraftChange:se,onClose:()=>{x||W(!1)},onSubmit:ae})}),n&&k.jsx(v.Suspense,{fallback:null,children:k.jsx(nK,{open:n,branchName:t,busy:x,onBranchNameChange:B,onSetPrefix:U,onClose:()=>{x||D(!1)},onSubmit:ue})})]})}function D_({toast:e,onDismiss:t}){if(!e)return null;const n=!!(e.actionLabel&&e.onAction);return k.jsxs("div",{className:`app-toast ${e.tone} ${e.placement??"bottom-right"}`,role:e.tone==="error"?"alert":"status","aria-live":"polite",children:[k.jsx("span",{className:"app-toast-message",children:e.message}),n&&k.jsx("div",{className:"app-toast-actions",children:k.jsx("button",{type:"button","aria-label":e.actionLabel,onClick:()=>{t(),e.onAction?.()},children:e.actionLabel})})]})}const gc=v.createContext(null);function rK({children:e}){const[t,n]=v.useState(null),[a,o]=v.useState(null),i=v.useMemo(()=>({title:t,actions:a,setTitle:n,setActions:o}),[t,a]);return k.jsx(gc.Provider,{value:i,children:e})}function GQ({children:e}){return k.jsx(gc.Provider,{value:null,children:e})}function iK({children:e,className:t=""}){const n=v.useContext(gc);return k.jsx("div",{ref:n?.setTitle,className:`page-chrome-title-target ${t}`,children:e?k.jsx("div",{className:"page-chrome-fallback",children:e}):null})}function sK({className:e=""}){const t=v.useContext(gc);return k.jsx("div",{ref:t?.setActions,className:e})}function ZQ({title:e,actions:t,fallback:n,children:a}){const o=v.useContext(gc);return o?k.jsxs(k.Fragment,{children:[o.title?uh.createPortal(k.jsx("div",{className:"page-chrome-title",children:e}),o.title):null,o.actions&&t?uh.createPortal(t,o.actions):null,a]}):n??k.jsxs("header",{children:[e,t]})}async function lK(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 cK({activeView:e,onDiscoverCommunities:t,onOpenTeamChat:n}){return k.jsxs("div",{className:"titlebar-collaboration-actions",children:[k.jsx("button",{type:"button",className:`titlebar-icon${e==="team"?" active":""}`,"aria-label":"Team chat",title:"Team chat",onClick:n,children:k.jsx(Uu,{size:16})}),k.jsx("button",{type:"button",className:`titlebar-icon${e==="community"?" active":""}`,"aria-label":"Discover communities",title:"Discover communities",onClick:t,children:k.jsx(XI,{size:16})})]})}const dK=v.lazy(()=>ni(()=>import("./WorkspaceEnvironmentMenu-CJB-z2tS.js"),__vite__mapDeps([26,1,2,17,23,5,12,27,25,28]),import.meta.url).then(e=>({default:e.WorkspaceEnvironmentMenu})));function uK({sidebarOpen:e,title:t,conversationId:n,breadcrumbs:a,backAction:o,workspaceName:i,workspaceId:s,busy:l,workspaceState:m,workspaceKind:d,selectedApp:h,selectedProject:g,workspaceDiff:y,managedWorkspace:w,workspaceBusy:_,defaultTeamId:P,showDiffControls:M,diffPanelOpen:C,terminalOpen:N,rightSidebarAvailable:$=!1,rightSidebarOpen:j=!1,onToggleDiffPanel:x,onToggleRightSidebar:R,onOpenSearch:E,onToggleTerminal:U,onRunTerminalCommand:B,onWorkspaceToolAction:D,onOpenCommitDialog:W,onWorkspaceBranchChange:se,onWorkspaceBranchCreate:de,connection:Me,onBootstrap:ke,onOpenSandboxWorkspace:te,onShowSidebar:Ee,onOpenTeamChat:ye,onDiscoverCommunities:ne,collaborationView:be=null,platform:ae,showWorkspaceControls:ue=!0}){const xe=y?.filesChanged??0,De=zu()&&!uv(ae),we=!!(ye||ne)||ue||$||De,[oe,Se]=v.useState(null);v.useEffect(()=>{if(!oe)return;const Ke=()=>Se(null);return window.addEventListener("pointerdown",Ke),window.addEventListener("blur",Ke),window.addEventListener("resize",Ke),()=>{window.removeEventListener("pointerdown",Ke),window.removeEventListener("blur",Ke),window.removeEventListener("resize",Ke)}},[oe]);const He=Ke=>{Ke.preventDefault(),Ke.stopPropagation();const tt=190,qe=n?76:42;Se({x:Math.min(Ke.clientX,window.innerWidth-tt-8),y:Math.min(Ke.clientY,window.innerHeight-qe-8)})},Ze=Ke=>{lK(Ke),Se(null)};return k.jsxs("header",{className:"app-titlebar",children:[k.jsxs("div",{className:"titlebar-left",children:[!e&&k.jsx("button",{className:"titlebar-icon",title:"Show sidebar",onClick:Ee,children:k.jsx(e_,{size:16})}),o?k.jsx("button",{className:"titlebar-icon",type:"button","aria-label":o.label,title:o.label,onClick:o.onSelect,children:k.jsx(M5,{size:16})}):null,k.jsx(iK,{children:a?.length?k.jsx("nav",{className:"titlebar-breadcrumbs","aria-label":"Breadcrumb",children:a.map((Ke,tt)=>{const qe=tt===a.length-1;return k.jsxs("div",{className:"titlebar-breadcrumb-item",children:[Ke.onSelect&&!qe?k.jsx("button",{type:"button",onClick:Ke.onSelect,children:Ke.label}):k.jsx("strong",{children:Ke.label}),!qe&&k.jsx(ti,{size:14})]},`${Ke.label}-${tt}`)})}):k.jsxs("div",{className:"titlebar-title",children:[k.jsx("strong",{className:"titlebar-copy-target",title:"Double-click to select; right-click for copy options",onContextMenu:He,children:t}),i&&k.jsx("span",{children:i})]})})]}),we&&k.jsxs("div",{className:"titlebar-right",children:[k.jsx(sK,{className:"page-chrome-actions"}),k.jsx(cK,{activeView:be,onDiscoverCommunities:ne,onOpenTeamChat:ye}),ue&&k.jsxs("div",{className:"titlebar-actions",children:[k.jsx(v.Suspense,{fallback:null,children:k.jsx(dK,{mode:"topbar",busy:l,workspaceState:m,workspaceId:s,workspaceKind:d,selectedApp:h,selectedProject:g,workspaceBusy:_,defaultTeamId:P,workspaceDiff:y,managedWorkspace:w,showDiffControls:M,diffPanelOpen:C,onToggleDiffPanel:x,onRunTerminalCommand:B,onWorkspaceToolAction:D,onOpenCommitDialog:W,onWorkspaceBranchChange:se,onWorkspaceBranchCreate:de,connection:Me,onBootstrap:ke,onOpenSandboxWorkspace:te})}),k.jsx("button",{type:"button",className:"titlebar-icon",title:"Search chats and projects","aria-label":"Search chats and projects",onClick:E,children:k.jsx(R3,{size:16})}),k.jsx("button",{type:"button",className:`titlebar-icon ${N?"active":""}`,title:`${N?"Hide":"Show"} terminal`,"aria-label":`${N?"Hide":"Show"} terminal`,"aria-pressed":N,onClick:U,children:k.jsx(a_,{size:16})}),M&&k.jsx("button",{type:"button",className:`topbar-diff-button ${j?"active":""}`,title:`${j?"Hide":"Show"} sidebar${xe?`, ${xe} changed files`:""}`,"aria-label":`${j?"Hide":"Show"} sidebar`,"aria-pressed":j,onClick:x,children:k.jsx(eh,{size:16})})]}),$&&R&&!M?k.jsx("div",{className:"titlebar-actions",children:k.jsx("button",{type:"button",className:`topbar-diff-button ${j?"active":""}`,title:`${j?"Hide":"Show"} sidebar`,"aria-label":`${j?"Hide":"Show"} sidebar`,"aria-pressed":j,onClick:R,children:k.jsx(eh,{size:16})})}):null,k.jsx($3,{platform:ae})]}),oe&&k.jsxs("div",{className:"titlebar-copy-menu",role:"menu","aria-label":"Conversation title actions",style:{left:oe.x,top:oe.y},onPointerDown:Ke=>Ke.stopPropagation(),children:[k.jsx("button",{type:"button",role:"menuitem",onClick:()=>Ze(t),children:"Copy title"}),n&&k.jsx("button",{type:"button",role:"menuitem",onClick:()=>Ze(n),children:"Copy conversation ID"})]})]})}function mK(){const[e,t]=v.useState(null),n=v.useRef(null),a=v.useCallback(i=>new Promise(s=>{n.current?.resolve(!1);const l={...i,cancelLabel:i.cancelLabel??"Cancel",tone:i.tone??"default",resolve:s};n.current=l,t(l)}),[]),o=v.useCallback(i=>{const s=n.current;n.current=null,t(null),s?.resolve(i)},[]);return{confirmAction:a,confirmDialog:e,resolveConfirmDialog:o}}function pK({state:e,onResolve:t}){const n=v.useId(),a=v.useId();if(v.useEffect(()=>{if(!e)return;function i(s){s.key==="Escape"&&t(!1)}return document.addEventListener("keydown",i),()=>document.removeEventListener("keydown",i)},[t,e]),!e)return null;const o=e.tone==="danger"?"git-dialog-primary danger":"git-dialog-primary";return k.jsx("div",{className:"git-dialog-backdrop",role:"presentation",onMouseDown:()=>t(!1),children:k.jsxs("section",{className:"git-dialog project-confirm-dialog",role:"alertdialog","aria-modal":"true","aria-labelledby":n,"aria-describedby":a,onMouseDown:i=>i.stopPropagation(),children:[k.jsx("h2",{id:n,children:e.title}),k.jsx("p",{id:a,children:e.body}),k.jsxs("div",{className:"git-dialog-footer",children:[k.jsx("button",{type:"button",className:"git-dialog-secondary",onClick:()=>t(!1),children:e.cancelLabel}),k.jsx("button",{type:"button",className:o,autoFocus:!0,onClick:()=>t(!0),children:e.confirmLabel})]})]})})}function fK(){const{confirmAction:e,confirmDialog:t,resolveConfirmDialog:n}=mK();return{confirmProjectAction:v.useCallback(o=>e({tone:"danger",...o}),[e]),projectConfirmDialog:t,resolveProjectConfirmDialog:n}}function hK({state:e,onResolve:t}){return k.jsx(pK,{state:e,onResolve:t})}const Zd=new Map,gK=(e,t,n)=>{const a=Zd.get(e)??{commits:0,maxActualDurationMs:0,totalActualDurationMs:0};a.commits+=1,a.maxActualDurationMs=Math.max(a.maxActualDurationMs,n),a.totalActualDurationMs+=n,Zd.set(e,a)};function vK({children:e,id:t}){return k.jsx(v.Profiler,{id:t,onRender:gK,children:e})}typeof window<"u"&&(window.__OPENPOND_RENDER_COMMITS__={get:()=>Object.fromEntries([...Zd.entries()].map(([e,t])=>[e,{...t}])),reset:()=>Zd.clear()});const bK=v.lazy(()=>ni(()=>import("./MainPane-gPkr0OWu.js").then(e=>e.o),__vite__mapDeps([29,1,2,11,30,7,27,8,5]),import.meta.url).then(e=>({default:e.MainPane})));function yK({className:e,style:t,sidebar:n,topBar:a,mainPane:o,cloudSetup:i,projectConfirm:s,lazyPanels:l,toast:m}){return k.jsx(rK,{children:k.jsxs("div",{className:e,style:t,children:[k.jsx(vK,{id:"sidebar",children:k.jsx(VV,{...n})}),k.jsxs("div",{className:"content-shell",children:[k.jsx(uK,{...a}),k.jsx(v.Suspense,{fallback:k.jsx("main",{className:"main-pane","aria-busy":"true","aria-label":"Loading workspace"}),children:k.jsx(bK,{...o})})]}),k.jsx(ZV,{...i}),k.jsx(hK,{...s}),k.jsx(oK,{...l}),k.jsx(D_,{...m})]})})}function SK({settings:e,toast:t}){return k.jsxs(k.Fragment,{children:[k.jsx(aK,{...e}),k.jsx(D_,{...t})]})}const xd="OpenPond".split("");function xK({visibleLetterCount:e=xd.length}){const t=xd.slice(0,Math.max(0,Math.min(e,xd.length)));return k.jsxs("div",{className:"app-splash-lockup",children:[k.jsx("div",{className:"app-splash-mark",children:k.jsx("img",{alt:"OpenPond",className:"app-splash-logo",decoding:"async",src:TV})}),k.jsx("span",{"aria-hidden":"true",className:`app-splash-wordmark${t.length>0?" is-visible":""}`,children:t.map((n,a)=>k.jsx("span",{className:"app-splash-letter",children:n},`${n}-${a}`))})]})}const ef=xd.length,kK=520,wK=240;function x0(){return typeof window>"u"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function IK({startup:e}){const[t,n]=v.useState(()=>x0()?ef:0);return v.useEffect(()=>{if(x0()){n(ef);return}const a=Array.from({length:ef},(o,i)=>window.setTimeout(()=>n(i+1),kK+wK*i));return()=>{a.forEach(o=>window.clearTimeout(o))}},[]),k.jsxs("main",{className:"app-splash","aria-busy":"true","aria-label":e.label,role:"status",children:[k.jsx(xK,{visibleLetterCount:t}),k.jsx("span",{className:"app-splash-status",children:e.label})]})}const Pv=5e3;function Eo(e,t){if(e.length===0)return t;if(t.length===0)return e;const n=new Set,a=[];for(const o of[...e,...t])n.has(o.id)||(n.add(o.id),a.push(o));return a}function Ao(e,t,n=Pv){return kd(Eo(e,t),n)}function kd(e,t=Pv){return e.length<=t?e:e.slice(e.length-t)}function _K(e,t,n){return n.length===0?e:{...e,[t]:Eo(e[t]??[],n)}}function CK(e,t){if(t.length===0)return kd(e);if(e.length===0)return kd(t);const n=new Map;let a=0;for(const o of[...e,...t])n.has(o.id)||n.set(o.id,{event:o,index:a}),a+=1;return kd([...n.values()].sort((o,i)=>PK(o,i)).map(({event:o})=>o))}function Jd(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 RK(e){let t=null;for(const n of e)n.sequence!==void 0&&(t===null||n.sequence<t)&&(t=n.sequence);return t}function PK(e,t){const n=e.event.sequence,a=t.event.sequence;if(typeof n=="number"&&typeof a=="number"){const s=n-a;if(s!==0)return s}const o=Date.parse(e.event.timestamp),i=Date.parse(t.event.timestamp);if(Number.isFinite(o)&&Number.isFinite(i)){const s=o-i;if(s!==0)return s}return e.index-t.index}function k0(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 AK(e){return e===null?"unknown":e>=85?"high":e>=65?"medium":"low"}function w0(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 TK(e){return e==="codex"}function EK(e){return e==="openpond"}function L_(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="session.context.updated")continue;const a=QO.safeParse(n.data);if(a.success)return a.data}return null}function U_(e){if(e.snapshot&&e.snapshot.provider===e.provider){const n=e.snapshot.usedTokens,a=e.snapshot.maxContextTokens,o=Math.min(100,Math.round(e.snapshot.percentFull)),i=`${o}% full`,s=`${k0(n)} / ${k0(a)} tokens used`;return{usedTokens:n,maxTokens:a,percent:o,summary:i,tokensLabel:s,detail:w0(e.preferences,o),tooltip:`Context window: ${i} ${s}. ${w0(e.preferences,o)}`,tone:AK(o)}}if(TK(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(!EK(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 Av(e){let t=!1;const n=H_(e);for(let a=e.length-1;a>=0;a-=1){const o=e[a];if(MK(o)){t=!0;continue}const i=bs(o?.data);if(!(o?.name!=="diagnostic"||!i)){if(i.kind==="thread_goal_cleared")return null;if(i.kind==="thread_goal"){const s=Tv(bs(i.goal),Wn(i.provider),n);if(s){const l=Vl(s);return t&&l.tone==="active"?null:l}}if(i.kind==="goal_context"){const s=q_(o.output??"",Wn(i.provider)??"codex",n);if(s){const l=Vl(s);return t&&l.tone==="active"?null:l}}}}return null}function Yd(e){const t=H_(e);for(let n=e.length-1;n>=0;n-=1){const a=e[n],o=bs(a?.data);if(!(a?.name!=="diagnostic"||!o)){if(o.kind==="thread_goal_cleared"&&o.synthetic!==!0)return null;if(o.kind==="thread_goal"){const i=Tv(bs(o.goal),Wn(o.provider),t);if(!i)continue;const s=Vl(i);return s.tone==="active"?s:null}if(o.kind==="goal_context"){const i=q_(a.output??"",Wn(o.provider)??"codex",t);if(!i)continue;const s=Vl(i);return s.tone==="active"?s:null}}}return null}function tf(e){const t=bs(bs(e)?.codexGoalRuntime),n=Tv(t,Wn(t?.provider)??"codex");if(!n)return null;const a=Vl(n);return a.tone==="active"?a:null}function MK(e){return e?.name==="turn.completed"||e?.name==="turn.interrupted"||e?.name==="turn.failed"}function Vl(e){const t=B_(e.status),n=K_(e.timeUsedSeconds),a=`Goal ${n}`,o=e.tokensUsed===null?null:e.tokenBudget===null?`${nf(e.tokensUsed)} tokens`:`${nf(e.tokensUsed)} / ${nf(e.tokenBudget)} tokens`,i=o?`${e.statusLabel} · ${o}`:e.statusLabel;return{objective:e.objective,status:e.status,timeUsedSeconds:e.timeUsedSeconds,tokensUsed:e.tokensUsed,tokenBudget:e.tokenBudget,actionLabel:t.actionLabel,timeLabel:n,label:a,detail:i,tooltip:`Goal runtime: ${W_(e.timeUsedSeconds)}. ${i}. ${e.objective}`,tone:t.tone,observedAt:e.observedAt}}function jK(e,t){if(!e||e.tone!=="active"||!e.observedAt)return e;const n=z_(e.observedAt,t);if(n<=0)return e;const a=e.timeUsedSeconds+n,o=K_(a);return{...e,timeUsedSeconds:a,timeLabel:o,label:`Goal ${o}`,tooltip:`Goal runtime: ${W_(a)}. ${e.detail}. ${e.objective}`,observedAt:t}}function Tv(e,t=null,n=null){if(!e)return null;const a=Wn(e.objective)??"Active goal",o=Wn(e.status)??"active";if((mh(t)??mh(Wn(e.provider)))!=="codex")return null;const s=n??Wn(e.updatedAt)??Wn(e.updated_at)??null,l=Li(e.timeUsedSeconds)??Li(e.time_used_seconds)??0,m=Wn(e.activeSinceAt)??Wn(e.active_since_at),d=B_(o).tone==="active"?z_(m??Wn(e.createdAt)??Wn(e.created_at),s):0,h=m?l+d:Math.max(l,d),g=Li(e.tokensUsed)??Li(e.tokens_used),y=Li(e.tokenBudget)??Li(e.token_budget);return{objective:a,status:o,statusLabel:V_(o),timeUsedSeconds:Math.max(0,Math.floor(h)),tokensUsed:g===null?null:Math.max(0,Math.floor(g)),tokenBudget:y===null?null:Math.max(0,Math.floor(y)),observedAt:s}}function H_(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 z_(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 q_(e,t=null,n=null){if(!e.trim()||mh(t)!=="codex")return null;const a=F_(e,"Status")??"active",o=ol(e,"Tokens used"),i=ol(e,"Token budget"),s=ol(e,"Time used seconds")??ol(e,"Time spent pursuing goal")??ol(e,"Elapsed seconds")??0;return{objective:I0(e,"objective")??I0(e,"untrusted_objective")??"Active goal",status:a,statusLabel:V_(a),timeUsedSeconds:Math.max(0,Math.floor(s)),tokensUsed:o,tokenBudget:i,observedAt:n}}function B_(e){switch(OK(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 OK(e){return e.trim().toLowerCase().replace(/[-\s]+/g,"_")}function F_(e,t){const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^\\s*-?\\s*${n}:\\s*(.+?)\\s*$`,"im").exec(e)?.[1]?.trim()||null}function ol(e,t){const n=F_(e,t);if(!n)return null;const a=n.replace(/,/g,""),o=/-?\d+(?:\.\d+)?/.exec(a);if(!o)return null;const i=Number(o[0]);return Number.isFinite(i)?i:null}function I0(e,t){return new RegExp(`<${t}>\\s*([\\s\\S]*?)\\s*<\\/${t}>`,"i").exec(e)?.[1]?.trim()||null}function V_(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function K_(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 W_(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 nf(e){if(e<1e3)return String(e);if(e>=1e6){const n=e/1e6;return n<10?`${_0(n,2)}M`:n<100?`${_0(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 _0(e,t){return e.toFixed(t).replace(/\.?0+$/,"")}function bs(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Wn(e){return typeof e=="string"&&e.trim()?e.trim():null}function mh(e){return e?.trim().toLowerCase()||null}function Li(e){return typeof e=="number"&&Number.isFinite(e)?e:null}const $K=new Set(["planning","applying_source","running_checks","evaluating","pushing_hosted","running_hosted_checks"]),NK=new Set(["awaiting_questions","awaiting_plan_approval","paused"]);function ph(e){const t=G_(e);return t?HK(t):null}function G_(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="create_improve.updated")continue;const a=UK(VK(n.data));if(a)return a}return null}function DK(e){if(e.events)return G_(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 LK(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 UK(e){const t=Xl.safeParse(e?.createImproveRun);return t.success?t.data:null}function HK(e){const t=zK(e);if(!t)return null;const n=qK(e.createdAt,e.updatedAt),a=e.blockedReason??BK(e.state);return{objective:e.objective,status:e.state,timeUsedSeconds:n,tokensUsed:null,tokenBudget:null,actionLabel:t.actionLabel,timeLabel:FK(n),label:t.actionLabel,detail:a,tooltip:`${t.actionLabel}: ${a}. ${e.objective}`,tone:t.tone}}function zK(e){const t=e.state,n=e.target.kind==="agent"?"Agent":"Work";return $K.has(t)?{tone:"active",actionLabel:`${n} running`}:NK.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 qK(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 BK(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function FK(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 VK(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Z_(e,t){if(!t)return null;const n=new Map,a=[];for(const j of e){if(!j.name.startsWith("subagent."))continue;const x=GK(j);x&&a.push(x);const R=WK(j);R?.parentSessionId===t&&n.set(R.id,R)}if(n.size===0)return null;const o=[...n.values()].sort((j,x)=>Hi(x).localeCompare(Hi(j))),i=o.filter(j=>j.status==="queued"||j.status==="running"),s=o.filter(j=>j.status==="completed"),l=o.filter(j=>j.status==="failed"),m=o.filter(j=>j.status==="cancelled"),d=o.filter(j=>j.status==="needs_resume"),h=[...s,...l,...m].sort((j,x)=>Hi(x).localeCompare(Hi(j))),g=o.reduce((j,x)=>{const R=ys(x.metadata?.usage);return j.totalTokens+=Xc(R?.totalTokens),j.promptTokens+=Xc(R?.promptTokens),j.completionTokens+=Xc(R?.completionTokens),j.requestCount+=Xc(R?.requestCount),j},{totalTokens:0,promptTokens:0,completionTokens:0,requestCount:0}),y=o.flatMap(j=>J_([...j.report?.blockers??[],j.error,j.progress.currentBlocker]).map(x=>({runId:j.id,roleId:j.roleId,status:j.status,message:x}))),w=o.flatMap(j=>Y_([...j.report?.artifacts??[],j.report?.patchRef,j.report?.diffRef,...j.progress.patchRefs]).map(x=>({...x,runId:j.id,roleId:j.roleId}))),_=h.map(j=>KK(j,a)),P=o[0]??null,M=P?{runId:P.id,roleId:P.roleId,status:P.status,message:P.progress.latestMeaningfulActivity||P.report?.summary||P.objective,updatedAt:Hi(P)}:null,C=i.length>0?`${i.length} ${i.length===1?"child":"children"} running`:`${h.length} ${h.length===1?"child":"children"} finished`,N=[i.length?`${i.length} active`:null,s.length?`${s.length} completed`:null,l.length?`${l.length} failed`:null,m.length?`${m.length} cancelled`:null,d.length?`${d.length} paused`:null].filter(Boolean).join(" · "),$=M?`${YK(M.roleId)}: ${M.message}`:"";return{sessionId:t,runs:o,activeRuns:i,completedRuns:s,failedRuns:l,cancelledRuns:m,needsResumeRuns:d,terminalRuns:h,latestRun:P,latestMeaningfulUpdate:M,activeCount:i.length,completedCount:s.length,failedCount:l.length,cancelledCount:m.length,needsResumeCount:d.length,terminalCount:h.length,usage:g,blockers:y,evidenceRefs:w,finalResults:_,testsRunCount:o.reduce((j,x)=>j+x.progress.validationAttempts.length,0),label:C,tooltip:[N,$].filter(Boolean).join(". ")}}function KK(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:Y_([...e.report?.artifacts??[],e.report?.patchRef,e.report?.diffRef]),testsRun:e.report?.testsRun??[],validationAttempts:e.progress.validationAttempts.map(n=>n.command),blockers:J_([...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:ZK(e),updatedAt:Hi(e)}}function WK(e){const t=ys(e.data),n=[t?.run,ys(t?.message)?.run];for(const a of n){const o=Hx.safeParse(a);if(o.success)return o.data}return null}function GK(e){const t=bj.safeParse(ys(e.data)?.message);return t.success?t.data:null}function ZK(e){const t=ys(ys(e.metadata?.workspaceHandoff)?.workspaceRetention);return t?.status!=="retained"?null:{status:"retained",reason:Qc(t.reason),retainedAt:Qc(t.retainedAt),expiresAt:Qc(t.expiresAt),retentionDays:JK(t.retentionDays),trigger:Qc(t.trigger),cleanupAfterExpiry:t.cleanupAfterExpiry===!0}}function Hi(e){return e.updatedAt??e.completedAt??e.startedAt??e.createdAt}function J_(e){return[...new Set(e.map(t=>t?.trim()).filter(t=>!!t))]}function Y_(e){const t=new Map;for(const n of e)n&&t.set(`${n.kind}:${n.id}`,n);return[...t.values()]}function ys(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Qc(e){return typeof e=="string"&&e.trim()?e.trim():null}function Xc(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function JK(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function YK(e){return e.slice(0,1).toUpperCase()+e.slice(1).replace(/[-_]+/g," ")}const fh=[];function hh(e,t){return Q_(e,t,null)}function Q_(e,t,n){const a=n&&n9(n.events,e)?XK(n.indexes,n.events.length,e):QK(e),o=t9(t);return{...a,...o}}function QK(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 e9(t)}function XK(e,t,n){const a=new Map(e.eventsBySessionId),o=new Map(e.latestContextUsageBySessionId),i=new Map(e.latestGoalRuntimeBySessionId),s=new Map(e.latestSubagentRuntimeBySessionId),l=new Set(e.activeGoalSessionIds),m=new Set(e.activeSubagentSessionIds),d=new Set;for(let h=t;h<n.length;h+=1){const g=n[h];if(!g.sessionId)continue;if(d.has(g.sessionId)){a.get(g.sessionId).push(g);continue}const y=a.get(g.sessionId);a.set(g.sessionId,y?[...y,g]:[g]),d.add(g.sessionId)}for(const h of d){const g=a.get(h)??fh,y=L_(g);y?o.set(h,y):o.delete(h);const w=eC(g);w?(i.set(h,w),w.tone==="active"?l.add(h):l.delete(h)):(i.delete(h),l.delete(h));const _=Z_(g,h);_?(s.set(h,_),X_({sessionEvents:g,sessionId:h,latestGoalRuntimeBySessionId:i,activeGoalSessionIds:l}),_.activeCount>0?m.add(h):m.delete(h)):(s.delete(h),m.delete(h))}return{eventsBySessionId:a,latestContextUsageBySessionId:o,latestGoalRuntimeBySessionId:i,latestSubagentRuntimeBySessionId:s,activeGoalSessionIds:l,activeSubagentSessionIds:m}}function e9(e){const t=new Map,n=new Map,a=new Map,o=new Set,i=new Set;for(const[s,l]of e){const m=L_(l);m&&t.set(s,m);const d=eC(l);d&&(n.set(s,d),d.tone==="active"&&o.add(s))}for(const[s,l]of e){const m=Z_(l,s);m&&(a.set(s,m),X_({sessionEvents:l,sessionId:s,latestGoalRuntimeBySessionId:n,activeGoalSessionIds:o}),m.activeCount>0&&i.add(s))}return{eventsBySessionId:e,latestContextUsageBySessionId:t,latestGoalRuntimeBySessionId:n,latestSubagentRuntimeBySessionId:a,activeGoalSessionIds:o,activeSubagentSessionIds:i}}function X_(e){if(e.latestGoalRuntimeBySessionId.has(e.sessionId))return;const t=Yd(e.sessionEvents);t&&(e.latestGoalRuntimeBySessionId.set(e.sessionId,t),t.tone==="active"&&e.activeGoalSessionIds.add(e.sessionId))}function eC(e){return ph(e)??Av(e)??Yd(e)}function t9(e){const t=new Map,n=new Map,a=new Map,o=new Map;for(const i of e){t.set(i.id,i);const s=n.get(i.status);if(s?s.push(i):n.set(i.status,[i]),i.status!=="pending")continue;const l=a.get(i.sessionId);l?l.push(i):a.set(i.sessionId,[i]);const m=o.get(i.sessionId);(!m||C0(i.createdAt)>C0(m.createdAt))&&o.set(i.sessionId,i)}return{approvalsById:t,approvalsByStatus:n,pendingApprovalsBySessionId:a,latestPendingApprovalBySessionId:o}}function n9(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 vc(e,t){return t?e.eventsBySessionId.get(t)??fh:fh}function tC(e,t){return t?e.latestContextUsageBySessionId.get(t)??null:null}function nC(e,t){return t?e.latestGoalRuntimeBySessionId.get(t)??null:null}function a9(e,t){return t?e.latestSubagentRuntimeBySessionId.get(t)??null:null}function o9(e,t){return t?e.latestPendingApprovalBySessionId.get(t)??null:null}function C0(e){const t=Date.parse(e);return Number.isFinite(t)?t:Number.NEGATIVE_INFINITY}function r9(e,t){return e?.conversationId===t}function i9(e,t){return e?.id===t?null:e}function s9(e){const t=new Set;if(e.readmePath){const n=e.readmePath.replaceAll("\\","/").split("/").at(-1);n&&t.add(n)}for(const n of e.skills){t.add(n.relativePath);const a=n.relativePath.lastIndexOf("/"),o=a>=0?n.relativePath.slice(0,a):"";for(const i of n.resourceFiles)t.add(o?`${o}/${i}`:i)}return{name:`${e.owner}/${e.repo}`,description:`${e.skills.length} installed skill${e.skills.length===1?"":"s"} from GitHub.`,scope:"extension",packagePath:e.sourcePath,files:[...t]}}function l9(e){return JSON.stringify([e.source,e.repositoryId,e.profileId])}function JQ(e,t){return e.profiles.find(n=>l9(n.ref)===t)?.ref??null}function c9(e,t){return!!(e&&t&&e.source===t.source&&e.repositoryId===t.repositoryId&&e.profileId===t.profileId)}function YQ(e,t){return e.profiles.find(n=>c9(n.ref,t))?.state??null}function d9(e,t){const n=new Map(BN.map(a=>[a.name,{...a,validationMessages:[...a.validationMessages],resourceFiles:[...a.resourceFiles]}]));for(const a of e?.skills??[])n.has(a.name)||n.set(a.name,a);for(const a of t?.extensions??[])if(a.validationStatus==="valid")for(const o of a.skills)o.validationStatus!=="valid"||n.has(o.name)||n.set(o.name,{name:o.name,description:o.description,path:o.relativePath,scope:"profile",enabled:!0,sourcePath:a.sourcePath,charCount:o.charCount,sourceHash:o.sourceHash,validationStatus:"valid",validationMessages:[],resourceFiles:o.resourceFiles});return[...n.values()].sort((a,o)=>a.name.localeCompare(o.name))}function u9(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 QQ(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 aC="openpond:last-chat-task-mode";function m9(e,t){return e==="labs"?"models":"chat"}function p9(e){try{return e.getItem(aC)==="work"?"work":"chat"}catch{return"chat"}}function Ev(){if(typeof window>"u")return"chat";try{return p9(hc)}catch{return"chat"}}function f9(e,t){try{e.setItem(aC,t==="chat"?"chat":"work")}catch{}}function h9(e){if(!(typeof window>"u"))try{f9(hc,e)}catch{}}const g9="uploaded to a different account";function oC(e,t){const n=e?.linkedSandboxProject??null;if(!n?.projectId||!n.teamId)return{state:"none",linked:null,cloudProject:null};const a=t?.find(o=>o.id===n.projectId&&o.teamId===n.teamId)??null;return a?{state:"confirmed",linked:n,cloudProject:a}:{state:"different_account",linked:n,cloudProject:null}}function Ca(e,t){const n=oC(e,t);return n.state==="confirmed"?n.cloudProject:null}function v9(e,t){return oC(e,t).state==="different_account"?g9:null}function po(e){return e==="sandbox"||e==="sandbox_template"||e==="sandbox_app"}function rC(e={}){return{...e,workspaceTarget:"hybrid"}}function b9(e={}){return{...e,workspaceTarget:"local"}}function fo(e){return e?.metadata?.workspaceTarget==="hybrid"}function y9(e){return!!(e&&e.provider==="openpond"&&e.workspaceKind==="local_project"&&e.cloudProjectId&&e.title.trim().endsWith(" Cloud"))}function iC({cloudProjects:e,selectedCloudProject:t,selectedProject:n}){const a=n?.linkedSandboxProject??null,o=e?Ca(n,e):null,i=t?.id??o?.id??(e?null:a?.projectId??null),s=t?.teamId??o?.teamId??(e?null:a?.teamId??null);return!i||!s?{kind:"missing_cloud_project",message:"Upload/sync this Project to Cloud before using Hybrid."}:{kind:"ready",cloudProjectId:i,cloudTeamId:s,cwd:n?.workspacePath??null,localProjectId:n?.id??null,workspaceName:t?.name??o?.name??a?.projectName??n?.name??"Hybrid workspace"}}function sC({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:rC(),cwd:n.cwd,title:a}}function S9(e){return v.useEffect(()=>{const t=b_(e.selectedSession);!t||e.composerDraftStore.getSnapshot()||e.composerDraftStore.set(t)},[e.composerDraftStore,e.selectedSession?.id]),v.useCallback(async t=>{const n=t.trim();if(!e.connection||!n||e.activeExperience==="chat")return!1;const a=h6(n);try{let o;const i=e.selectedSession;if(i&&Bl(i))o=await Q.patchSession(e.connection,i.id,{title:a,metadata:Jp(i.metadata,n)}),e.setSessions(s=>s.map(l=>l.id===o.id?o:l));else{const s=i?.metadata?.workspaceTarget==="hybrid"?"hybrid":i?.metadata?.workspaceTarget==="local"?"local":null,l=i?.provider??(e.selectedCloudProject?"openpond":e.activeProvider),m=i?.modelRef??(l==="openpond"?{providerId:"openpond",modelId:us}:{providerId:l,modelId:e.activeModel}),d=s?{workspaceTarget:s}:!i&&e.workspaceTarget==="local"?{workspaceTarget:"local"}:{};let h;if(!i&&e.workspaceTarget==="hybrid"){const g=iC({cloudProjects:e.cloudProjects,selectedCloudProject:e.selectedCloudProject,selectedProject:e.selectedProject});if(g.kind!=="ready")throw new Error(g.message);const y=sC({modelRef:m,provider:l,target:g,title:a});h={...y,experience:"work",metadata:Jp(y.metadata,n)}}else h={experience:"work",provider:l,modelRef:m,openPondCommandAccessMode:i?.openPondCommandAccessMode??e.activeOpenPondCommandAccessMode,appId:i?.appId??null,appName:i?.appName??null,workspaceKind:i?.workspaceKind??(e.selectedCloudProject?"sandbox":e.selectedProject?"local_project":void 0),workspaceId:i?.workspaceId??e.selectedCloudProject?.id??e.selectedProject?.id??null,workspaceName:i?.workspaceName??e.selectedCloudProject?.name??e.selectedProject?.name??null,localProjectId:i?.localProjectId??e.selectedProject?.id??null,cloudProjectId:i?.cloudProjectId??e.selectedCloudProject?.id??null,cloudTeamId:i?.cloudTeamId??e.selectedCloudProject?.teamId??null,cwd:i?.cwd??e.selectedProject?.workspacePath??null,metadata:Jp(d,n),title:a};o=await Q.createSession(e.connection,h),e.setSessions(g=>[o,...g])}return e.composerDraftStore.set(""),e.setMentionedAppId(null),e.setSelectedSessionId(null),e.setView("chat"),e.requestComposerFocus(),e.showToast("Task draft saved.","success"),!0}catch(o){return e.showToast(o instanceof Error?o.message:"Could not save task draft.","error"),!1}},[e.activeExperience,e.activeModel,e.activeOpenPondCommandAccessMode,e.activeProvider,e.cloudProjects,e.composerDraftStore,e.connection,e.requestComposerFocus,e.selectedCloudProject,e.selectedProject,e.selectedSession,e.setMentionedAppId,e.setSelectedSessionId,e.setSessions,e.setView,e.showToast,e.workspaceTarget])}const x9=[];function k9({primary:e,secondary:t}){const[n,a]=v.useState(null),o=v.useRef(new Set),[i,s]=v.useState(!1),[l,m]=v.useState(null),d=G3(),h=d?.kind==="models"&&["datasets","graders","experiments"].includes(d.route.page),{composerDraftStore:g,appDispatch:y,pendingTerminalCommand:w,setPendingTerminalCommand:_,terminalTabs:P,setTerminalTabs:M,trainingDetailTasksetId:C,setTrainingDetailTasksetId:N,mentionedAppId:$,setMentionedAppId:j,cloudSetupDialog:x,setCloudSetupDialog:R,rightPanelTabRequest:E,workspaceDiffPanelViewState:U,mainComposerFocusRequestId:B,requestMainComposerFocus:D,projectConfirmDialog:W,resolveProjectConfirmDialog:se,query:de,searchOpen:Me,archivedChatsOpen:ke,sectionMenuOpen:te,cloudProjectsExpanded:Ee,sidebarOpen:ye,view:ne,selectedAppId:be,selectedProjectId:ae,selectedSessionId:ue,codexPermissionMode:xe,codexReasoningEffort:De,busy:we,diffPanelOpen:oe,diffPanelExpanded:Se,rightPanelMode:He,activeExperience:Ze,changeNewExperience:Ke,terminalOpen:tt,settingsSection:qe,newProjectDialogOpen:Ge,newProjectMode:ze,newProjectName:L,newProjectPath:O,newProjectBusy:z,commitDialogOpen:X,commitMessage:me,commitIncludeUnstaged:$e,commitNextStep:Le,commitDraft:nt,branchDialogOpen:at,branchDialogName:lt,toast:pt,labDetailNavigation:je,setQuery:Ye,setSearchOpen:f,setArchivedChatsOpen:H,setSectionMenuOpen:Y,setCloudProjectsExpanded:he,setChatRowsVisibleCount:ie,setSidebarOpen:K,setView:I,setSelectedAppId:V,setSelectedProjectId:ee,setSelectedSessionId:G,setPrompt:le,setDraftProvider:pe,setDraftModel:fe,setDraftExperience:Pe,setDiffPanelOpen:_e,setDiffPanelExpanded:Ne,setRightPanelMode:Re,setTerminalOpen:Xe,setSettingsSection:st,setNewProjectDialogOpen:on,setNewProjectName:At,setNewProjectPath:tn,setCommitDialogOpen:dn,setCommitMessage:un,setCommitIncludeUnstaged:Kt,setCommitNextStep:Aa,setCommitDraft:la,setBranchDialogOpen:Mn,setBranchDialogName:_n,setError:jt,showToast:ht,applyBootstrapPayload:mn,bootstrap:vt,connection:Et,startup:ca,training:Ut,pinnedCollapsed:pn,cloudProjectsCollapsed:rt,chatsCollapsed:kn,savedForLaterCollapsed:Wa,sidebarWidth:Ga,sidebarResizing:ea,diffPanelWidth:da,diffPanelResizing:jn,togglePinnedCollapsed:go,toggleCloudProjectsCollapsed:Ta,toggleChatsCollapsed:F,toggleSavedForLaterCollapsed:Ue,startSidebarResize:Ie,startDiffPanelResize:Be,selectedApp:bt,selectedCloudProject:Bn,selectedProject:fn,selectedProjectLinkedApp:We,selectedSession:vn,sidebarSessions:ut,runtimeIndexes:Cn,runtimeEventStore:Ea,chatMentionApps:Jo,connectedAppMentions:ua,pendingApproval:Yo,pendingChatUserMessages:Rr,account:vo,activeModel:On,activeProvider:ma,appDefaults:Fn,startMessage:Qo,organizations:Pr,teamChatOrganization:Xo,teamChatTeamId:er,teamChat:St,publishTeamProfileAgent:Ts,communitySidebar:Ar,communityView:Es,teamAiThreadId:di,toggleTeamAiSidebar:Ms,activeOpenPondCommandAccessMode:bo,viewWorkspaceAppId:js,viewWorkspaceId:ui,viewWorkspaceKind:mi,viewWorkspaceName:pi,selectedActionCatalog:Os,expandedProjectIds:$s,expandProject:Za,toggleProjectExpanded:Ns,changeCodexPermissionMode:fi,changeCodexReasoningEffort:hi,changeOpenPondCommandAccessMode:tr,resolveApproval:gi,beginNewChat:ta,beginNewChatWithTrainingModel:Ds,dismissTrainingChatHandoff:Tr,trainingChatHandoff:yo,selectTrainingChatTaskForComposer:Vn,chatHistoryLoadStates:Ls,loadMoreSelectedChatHistory:Us,selectedPagedSessionEvents:bn,activeSessions:nr,archivedSessions:pa,pinnedSessions:Ma,savedForLaterSessions:Er,savedForLaterFiles:ar,sidebarFileBookmarks:Hs,setSidebarFileStatus:vi,setSessions:Mr,projectRows:So,localProjectRows:or,cloudProjectRows:rr,projectSessionRowsByProjectId:bi,childSessionRowsByParentId:yi,sidebarProjectIdBySessionId:fa,chatRows:ha,visibleChatRows:Si,chatRowsVisibleCount:jr,sessionEvents:Ja,goalRuntime:Or,subagentRuntime:xo,visibleChatMessages:xi,activeTerminalScope:ki,terminalSummaries:wi,runningSessionIds:zs,selectedSessionRunning:Ii,sidebarGoalRuntimeBySessionId:_i,sidebarSubagentRuntimeBySessionId:qs,taskDragSessionId:ir,taskPreviewSessionIds:Ci,startTaskDrag:$r,clearTaskDrag:Ya,previewTaskDrop:Bs,commitTaskDrop:Fs,commitTaskPreviewDrop:Vs,dragItem:Ks,startPinnedDrag:Qa,clearSidebarDrag:Ri,previewPinnedDrop:Ws,commitPinnedDrop:Gs,commitPinnedPreviewDrop:Zs,commandProjectRows:na,contextWindowStatus:Pi,pinnedRows:Js,workspaceBusy:ct,diffBusy:Jt,visibleWorkspaceState:Kn,visibleWorkspaceDiff:rn,refreshVisibleWorkspaceDiff:Rn,managedWorkspace:aa,canSyncActiveWorkspace:Yu,canPublishOpenPondProject:Qu,projectTarget:Xu,workspaceTarget:yc}=e,{title:em,browserConversationId:Nr,handleWorkspaceDiffPanelViewStateChange:Sc,openSessionInChat:Ai,changeProjectTarget:tm,submitNewProjectDialog:nm,changeWorkspaceBranch:am,openCommitDialog:om,openCreateWorkspaceBranchDialog:rm,openDefaultsSettingsFromBranchDialog:im,runWorkspaceTool:sm,submitCommitDialog:lm,submitCreateWorkspaceBranch:cm,syncWorkspaceLocally:dm,answerCreateImproveQuestion:xc,applyCreateImproveCandidate:um,approveCreateImproveRun:mm,cancelCreateImproveRun:pm,changeDraftProvider:Ys,openCreateImprovePullRequest:kc,reconcileCreateImprovePullRequest:fm,rejectCreateImproveCandidate:hm,pauseCreateImproveRun:wc,resumeCreateImproveRun:Ic,reviseCreateImproveRun:gm,stopTurn:Ti,archiveSession:vm,restoreSession:_c,renameSession:bm,toggleSessionPinned:Qs,toggleProjectPinned:Cc,toggleSessionSavedForLater:Rc,moveProjectToCloud:ym,startCloudSetupUpload:Pc,changeWorkspaceTarget:Sm,sendPromptFromMainComposer:xm,openSandboxWorkspace:Ac,openCloudProjectDialog:km,openExistingProjectPathDialog:Tc,openUrlInBrowserPanel:wm,showBrowserPanel:Im,showChangesPanel:_m,showGoalSidebarTab:sr,rightChatTrainingLaunchRequest:Ec,setRightChatTrainingLaunchRequest:Cm,closeRightChatPanel:Rm,openRightChatPanel:Xs,rightChatPanelViews:Pm,showRightChatPanel:Am,showRightPanelDiffTab:Tm,submitRightChatPrompt:Em,activateRightChatPanel:Mm,updateRightChatModel:jm,updateRightChatPrompt:Om,updateRightChatProvider:$m,updateRightChatScrollState:Nm,openProfileSettings:Dm,diagnosticEvents:Lm,toggleRightSidebar:Mc,removeProject:Um}=t,ja=vt?.account.activeProfile&&vt?.preferences.defaultTeamId?`${vt.account.activeProfile.handle}:${vt.preferences.defaultTeamId}`:null;v.useEffect(()=>{if(!(!ja||ne!=="chat"||d?.kind!=="chat"||d.sessionId||ue||o.current.has(ja))){o.current.add(ja);try{const Ae=localStorage.getItem(`openpond:ponder-mode:v1:${ja}`);(Ae==="clean"||Ae==="activity")&&a(Ae)}catch{}}},[ja,d,ne,ue]),v.useEffect(()=>{if(!(!ja||!o.current.has(ja)))try{localStorage.setItem(`openpond:ponder-mode:v1:${ja}`,n??"off")}catch{}},[ja,n]);const Ei=v.useCallback(Ae=>{V(null),ee(Ae),G(null),I("chat"),Za(Ae),D()},[Za,D,V,ee,G,I]),Hm=v.useCallback((Ae=null)=>{a(null);const it=ue?fa[ue]??null:null;if(!Ae&&it){Ei(it);return}ta(Ae)},[ta,Ei,ue,fa]),zm=v.useCallback(async Ae=>{if(!(!Et||!vt))try{const it=await Q.savePreferences(Et,{defaultTeamId:Ae});mn({...vt,preferences:it.preferences})}catch(it){const Ot=it instanceof Error?it.message:String(it);throw jt(Ot),ht("Could not switch teams","error"),it}},[mn,vt,Et,jt,ht]),qm=v.useCallback(async()=>{if(Et)try{const Ae=await Q.signOutOpenPondAccount(Et);mn(Ae);const it=await Q.savePreferences(Et,{defaultTeamId:null});mn({...Ae,preferences:it.preferences}),ht("Logged out","success")}catch(Ae){const it=Ae instanceof Error?Ae.message:String(Ae);throw jt(it),ht("Could not log out","error"),Ae}},[mn,Et,jt,ht]),el=er??Fn.defaultTeamId??null,Bm=v.useMemo(()=>So.filter(Ae=>Ae.kind==="local"||el!==null&&Ae.project.teamId===el),[So,el]),Fm=v.useMemo(()=>{const Ae={};for(const it of nr){const Ot=fa[it.id];Ot&&(Ae[Ot]=(Ae[Ot]??0)+1)}for(const it of or){if(it.kind!=="local")continue;const Ot=it.project.linkedSandboxProject?.projectId;if(!Ot||!it.cloudLinkTrusted)continue;const ga=yt("cloud",Ot);Ae[it.id]=(Ae[it.id]??0)+(Ae[ga]??0)}return Ae},[nr,or,fa]),[jc,ko]=v.useState(null),[Mi,ji]=v.useState(null),Vm=d9(vt?.profile,vt?.extensionCatalog),[Dr,tl]=v.useState(null),[Oi,nl]=v.useState(null),[Xa,Oc]=v.useState(null),Km=v.useCallback(()=>{V(null),ee(null),G(null),Y(null),I("team")},[Y,V,ee,G,I]),Wm=v.useCallback(()=>{V(null),ee(null),G(null),Y(null),Ar.discoverCommunities()},[Ar.discoverCommunities,Y,V,ee,G]),Gm=S9({activeExperience:Ze,activeModel:On,activeOpenPondCommandAccessMode:bo,activeProvider:ma,cloudProjects:vt?.cloudProjects??x9,composerDraftStore:g,connection:Et,requestComposerFocus:D,selectedCloudProject:Bn,selectedProject:fn,selectedSession:vn,setMentionedAppId:j,setSelectedSessionId:G,setSessions:Mr,setView:I,showToast:ht,workspaceTarget:yc.value}),Zm=v.useCallback(async Ae=>{if(!Et)throw new Error("OpenPond is not connected.");let it=ma,Ot=On;it==="codex"&&(it=dh(vt?.providers,{enabledOnly:!0}).find(yn=>yn.value!=="codex")?.value??Qr,Ot=Wd(it,vt?.providers)??Pl);const ga=ut.find(yn=>yn.id===Ae.sourceSessionId),wo=await Q.createSession(Et,{experience:Ae.target,provider:it,modelRef:{providerId:it,modelId:Ot},openPondCommandAccessMode:bo,appId:null,appName:null,workspaceId:null,workspaceName:null,localProjectId:null,cloudProjectId:null,cloudTeamId:null,cwd:null,title:`Continue ${ga?.title??"task"}`.slice(0,120),metadata:{experienceHandoff:u9({sourceTaskId:Ae.sourceSessionId,sourceExperience:ga?.experience??null,targetExperience:Ae.target,sourceMessageIds:Ae.sourceMessageIds??[],sourceContext:Ae.sourceContext,output:Ae.output})}});return Mr(yn=>[wo,...yn]),Pe(Ae.target),pe(it),fe(Ot),g.set(Ae.prompt),Qt({kind:"chat",sessionId:wo.id}),y({type:"selectSession",sessionId:wo.id,appId:null,projectId:null}),V(null),ee(null),Xe(!1),I("chat"),Re("home"),_e(Ae.target==="work"),Ne(!1),wo},[On,bo,ma,y,vt?.providers,g,Et,Ne,_e,Pe,fe,pe,Re,V,ee,Mr,Xe,I,ut]),Jm=v.useCallback(Ae=>{tl(Ae),nl(null),ta(null),K(!0)},[ta,K]),Ym=v.useCallback(Ae=>{ta(null),Pe("work"),g.set(`$openpond-refiner-authoring ${Ae}`),I("chat"),K(!0)},[ta,g,Pe,K,I]),$c=v.useCallback(Ae=>{nl(s9(Ae)),tl(null),ta(null),K(!0)},[ta,K]);v.useEffect(()=>{!Dr&&!Oi||ne!=="chat"||ue||ae||be||(ko(Dr),ji(Oi),tl(null),nl(null),Re("home"),Ne(!1),_e(!0))},[Dr,Oi,be,ae,ue,Ne,_e,Re,ne]),v.useEffect(()=>{!jc&&!Mi||ne==="chat"&&oe&&He==="home"||(ko(null),ji(null))},[oe,Mi,jc,He,ne]);const Nc=v.useCallback(()=>{ko(null),ji(null),Ne(!1),_e(!1)},[Ne,_e]),Qm=v.useCallback(Ae=>{let it;if(Ae.workspaceKind==="local"){const Ot=yt("local",Ae.workspaceId);it=`draft:${Ot}`,V(null),ee(Ot),G(null),Za(Ot),I("chat")}else{const Ot=ut.find(ga=>ga.id===Ae.sourceSessionId||ga.workspaceId===Ae.workspaceId);if(!Ot){ht("This saved file's cloud chat is no longer available.","error");return}it=Ot.id,Ai(Ot.id)}Re("changes"),_e(!0),Oc({id:Date.now(),conversationId:it,file:Ae}),Ae.available||ht(`File unavailable: ${Ae.path}`,"error")},[Za,Ai,_e,Re,V,ee,G,I,ht,ut]);v.useEffect(()=>{if(!r9(Xa,Nr))return;const Ae=window.setTimeout(()=>{Re("changes"),_e(!0),Oc(it=>i9(it,Xa.id))},0);return()=>window.clearTimeout(Ae)},[Nr,_e,Re,Xa]);const Xm=d?.kind==="models"&&d.route.area==="console"?"console":m9(ne);v.useEffect(()=>{if(d){if(d.kind==="models"||d.kind==="models_unavailable"){ne!=="labs"&&I("labs");return}if(d.kind==="settings"){V(null),ee(null),G(null),st(d.section),ne!=="settings"&&I("settings");return}if(d.kind==="view"){V(null),ee(null),G(null),ne!==d.view&&I(d.view);return}d.sessionId!==null&&(a(null),V(null),ee(null)),G(d.sessionId),ne!=="chat"&&I("chat")}},[d,V,ee,G,st,I,ne]);const ep=v.useCallback(Ae=>{if(Y(null),V(null),ee(null),G(null),Ae==="models"||Ae==="console"){rs(Ae==="console"?za("datasets",null,{area:"console"}):za()),I("labs");return}Ae==="chat"&&Qt({kind:"chat",sessionId:null}),Ke(Ev())},[Ke,Qt,Y,V,ee,G,I]),tp=v.useCallback(async(Ae,it)=>{const Ot=await Ut.actions.acceptHarnessReview(Ae,it,{providerId:ma,modelId:On},De);return Ot?(N(Ot.materializedTasksetId??null),rs(za()),I("labs"),!0):(ht("Taskset review could not be opened.","error"),!1)},[On,ma,De,rs,za,N,I,ht,Ut.actions]);if(!ca.ready)return k.jsx(IK,{startup:ca});if(ne==="settings")return k.jsx(b0,{showToast:ht,children:k.jsx(SK,{settings:{payload:vt,connection:Et,diagnostics:Lm,initialSection:qe,onPayload:mn,onError:jt,onToast:ht,onOpenSourceSession:Ai,onStartRefinerAuthoring:Ym,onAcceptEvaluationReview:tp,onOpenSkill:Jm,onOpenExtension:$c,teamChatCurrentUserId:St.currentUserId,teamChatEnabled:er!==null,teamChatNotificationMode:St.notificationMode,teamChatThreads:St.threads,onTeamChatNotificationModeChange:St.setNotificationMode,onTeamChatThreadMuteChange:St.setThreadMuted,diffPanelWidth:da,diffPanelResizing:jn,diffPanelExpanded:Se,onDiffPanelResizeStart:Be,onDiffPanelExpandedChange:Ne,onBack:()=>{const Ae=V3(d);Qt(Ae),I(Ae.kind==="models"?"labs":"chat"),K(!0)}},toast:{toast:pt,onDismiss:()=>y({type:"field",key:"toast",value:null})}})});const ot=zu(),zt=Et?.platform??navigator.platform,qt=ot&&uv(zt),Bt=ki,Oa=Kn?.initialized?Kn.repoPath:vn?.cwd??null,np={"--sidebar-width":`${Ga}px`,"--diff-panel-width":`${da}px`},uR=ne==="chat"&&Ze!=="chat"||ne==="labs"||ne==="scheduled"&&i||ne==="team"&&!!di,mR=["app-shell",qt?"platform-macos":"",ye?"sidebar-open":"sidebar-closed",ea?"sidebar-resizing":"",jn?"diff-panel-resizing":""].filter(Boolean).join(" "),ap=ue?Ls[ue]:null,pR=ue?ap?.cursorSequence??RK(Ao(bn,vc(Cn,ue))):null,fR=!!ue&&!!Et&&(Ht(ue)?!0:!!vt?.eventWindow?.hasMoreBefore&&!!pR)&&(ap?.hasMore??!0),hR=!!ap?.loading,gR=(()=>{const Ae=Ut.payload;if(!Ae)return{};const it=new Map(Ae.plans.map(yn=>[yn.id,yn])),Ot=new Set(["queued","starting","running","cancelling","reconciling"]),ga={queued:"Queued",starting:"Starting",running:"Running",cancelling:"Cancelling",reconciling:"Reconciling"},wo={};for(const yn of[...Ae.modelRuns].sort(($a,$i)=>$i.updatedAt.localeCompare($a.updatedAt))){if(yn.kind==="evaluation"||!["prepared","running"].includes(yn.status))continue;const $a=Ae.jobs.filter(op=>op.metadata.modelRunId===yn.id).sort((op,vR)=>vR.updatedAt.localeCompare(op.updatedAt))[0];if($a&&!Ot.has($a.status))continue;const $i=$a?.status??(yn.status==="prepared"?"starting":"running");wo[yn.modelId]={label:ga[$i]??"Running",status:$i}}for(const yn of[...Ae.jobs].sort(($a,$i)=>$i.updatedAt.localeCompare($a.updatedAt))){if(!Ot.has(yn.status))continue;const $a=it.get(yn.planId)?.modelId;!$a||wo[$a]||(wo[$a]={label:ga[yn.status]??"Active",status:yn.status})}return wo})();return k.jsx(b0,{showToast:ht,children:k.jsx(yK,{className:mR,style:np,sidebar:{onOpenPonder:()=>{Qt({kind:"chat",sessionId:null}),G(null),I("chat"),a("activity")},productArea:Xm,modelProjects:(Ut.payload?.modelProjects??[]).filter(Ae=>Ae.hosted===null||Ae.hosted.teamId===(Fn.defaultTeamId?.trim()??null)),modelTrainingActivityByProjectId:gR,onProductAreaChange:ep,experience:Ze,view:ne,selectedAppId:be,selectedProjectId:ae,selectedSessionId:ue,selectedTeamThreadId:St.selectedThreadId,teamChatEnabled:er!==null,organizations:Pr,teamChatOrganization:Xo,teamChatLoading:St.loading,currentUserId:St.currentUserId,teamMembers:St.members,teamThreads:St.threads,...Ar,account:vo,connection:Et,profile:vt?.profile,pinnedCollapsed:pn,cloudProjectsCollapsed:rt,chatsCollapsed:kn,savedForLaterCollapsed:Wa,archivedChatsOpen:ke,cloudProjectsExpanded:Ee,sectionMenuOpen:te,dragItem:Ks,taskDragSessionId:ir,taskPreviewSessionIds:Ci,activeSessions:nr,archivedSessions:pa,pinnedRows:Js,pinnedSessions:Ma,savedForLaterSessions:Er,savedForLaterFiles:ar,projectRows:So,localProjectRows:or,cloudProjectRows:rr,projectSessionRowsByProjectId:bi,childSessionRowsByParentId:yi,sidebarProjectIdBySessionId:fa,terminalSummaries:wi,runningSessionIds:zs,goalRuntimeBySessionId:_i,subagentRuntimeBySessionId:qs,visibleChatRows:Si,chatRows:ha,chatRowsVisibleCount:jr,expandedProjectIds:$s,currentVersion:vt?.server.version??null,platform:zt,arch:Et?.arch??null,onSidebarResizeStart:Ie,setSidebarOpen:K,setView:I,setSelectedAppId:V,setSelectedProjectId:ee,setSelectedSessionId:G,setSearchOpen:f,setSectionMenuOpen:Y,setSettingsSection:st,onSelectTeam:zm,onLogOut:qm,onTogglePinnedCollapsed:go,onToggleCloudProjectsCollapsed:Ta,onToggleChatsCollapsed:F,onToggleSavedForLaterCollapsed:Ue,setArchivedChatsOpen:H,setCloudProjectsExpanded:he,setChatRowsVisibleCount:ie,beginNewChat:Hm,beginProjectChat:Ei,onAddProject:Tc,dockSessionRight:Xs,selectTeamThread:Ae=>{I("team"),St.selectThread(Ae)},openTeamDm:Ae=>{I("team"),St.openDm(Ae)},toggleSessionPinned:Qs,toggleProjectPinned:Cc,toggleSessionSavedForLater:Rc,openSidebarFile:Qm,setSidebarFileStatus:(Ae,it)=>{vi(Ae,it)},archiveSession:vm,restoreSession:_c,renameSession:bm,removeProject:Um,expandProject:Za,toggleProjectExpanded:Ns,startPinnedDrag:Qa,clearSidebarDrag:Ri,previewPinnedDrop:Ws,commitPinnedDrop:Gs,commitPinnedPreviewDrop:Zs,startTaskDrag:$r,clearTaskDrag:Ya,previewTaskDrop:Bs,commitTaskDrop:Fs,commitTaskPreviewDrop:Vs},topBar:{sidebarOpen:ye,title:ne==="chat"&&n?"Ponder Pal":em,backAction:je.backAction,breadcrumbs:je.breadcrumbs,conversationId:ne==="chat"?ue:null,workspaceName:pi,workspaceId:ui,busy:we,workspaceState:Kn,workspaceKind:mi,selectedApp:We??bt,selectedProject:fn,workspaceDiff:rn,managedWorkspace:aa,workspaceBusy:ct,defaultTeamId:Fn.defaultTeamId,showDiffControls:ne==="chat"&&Ze==="development",diffPanelOpen:oe,terminalOpen:tt,rightSidebarAvailable:uR,rightSidebarOpen:ne==="labs"&&h?l?.open??!1:ne==="scheduled"?i:oe,onToggleDiffPanel:Mc,onToggleRightSidebar:ne==="labs"&&h?l?.toggle:ne==="scheduled"?()=>s(Ae=>!Ae):ne==="team"&&di?Ms:Mc,onOpenSearch:()=>{Y(null),f(!0)},onToggleTerminal:()=>Xe(Ae=>!Ae),onRunTerminalCommand:Ae=>{_({id:Date.now(),scope:Bt,command:Ae}),Xe(!0)},onWorkspaceToolAction:sm,onOpenCommitDialog:om,onWorkspaceBranchChange:am,onWorkspaceBranchCreate:rm,connection:Et,onBootstrap:mn,onOpenSandboxWorkspace:Ac,onShowSidebar:()=>K(!0),onOpenTeamChat:Km,onDiscoverCommunities:Wm,collaborationView:ne==="team"||ne==="community"?ne:null,platform:zt,showWorkspaceControls:ne!=="team"&&ne!=="community"&&ne!=="labs"&&ne!=="scheduled"&&ne!=="outputs"&&ne!=="projects"&&(Ze==="development"||Ze==="work"&&!!(fn||vn?.localProjectId||vn?.cloudProjectId||vn?.workspaceKind==="local_project"))},mainPane:{ponderMode:n,onPonderModeChange:a,experience:Ze,onNewExperienceChange:Ke,view:ne,teamChat:{currentUserId:St.currentUserId,members:St.members,agents:St.agents,profile:vt?.profile??null,teamId:er,teamName:Xo?.displayName??null,detail:St.detail,aiThread:St.aiThread,agentConversation:St.agentConversation,loading:St.loading,busy:St.busy,error:St.error,connection:Et,providerSettings:vt?.providers??null,provider:ma,model:On,codexPermissionMode:xe,codexReasoningEffort:De,openPondCommandAccessMode:bo,contextWindowStatus:Pi,showToast:ht,onProviderChange:Ys,onModelChange:fe,onCodexPermissionModeChange:fi,onCodexReasoningEffortChange:hi,onOpenPondCommandAccessModeChange:tr,onOpenProviderSettings:()=>{st("providers"),I("settings"),Qt({kind:"settings",section:"providers"})},onSendMessage:St.sendMessage,onPublishProfileAgent:Ts,onOpenAiThread:async Ae=>{await St.openAiThread(Ae),Re("chat"),_e(!0)},onOpenAgentConversation:async Ae=>{await St.openAgentConversation(Ae),Re("chat"),_e(!0)},onCloseAiThread:()=>_e(!1),onCloseAgentConversation:()=>{St.closeAgentConversation(),_e(!1)},onSendAgentTurn:St.sendAgentTurn,onSendAiTurn:St.sendAiTurn,onStopAiTurn:St.stopAiTurn,onEditMessage:St.editMessage,onDeleteMessage:St.deleteMessage,onRetryMessage:St.retryMessage,onDismissFailedMessage:St.dismissFailedMessage,onLoadMoreMessages:St.loadMoreMessages,onRetryLoad:St.refresh},community:Es,bootstrap:vt,runtimeEvents:Ja,chatMessages:xi,pendingUserMessage:ue?Rr[ue]??null:null,contextWindowStatus:Pi,goalRuntime:Or,subagentRuntime:xo,selectedSessionId:ue,composerDraftStore:g,mainComposerFocusRequestId:B,labCloseDetailRequestId:je.closeDetailRequestId,labCloseDetailKind:je.closeDetailKind,sideChatTrainingLaunchRequest:Ec,onSideChatTrainingLaunchHandled:Ae=>Cm(it=>it?.id===Ae?null:it),mentionApps:Jo,connectedAppMentions:ua,profileSkills:Vm,selectedMentionAppId:$,busy:we,turnRunning:Ii,activeProvider:ma,activeModel:On,codexPermissionMode:xe,codexReasoningEffort:De,openPondCommandAccessMode:bo,pendingApproval:Yo,activeWorkspaceAppId:js,activeWorkspaceId:ui,activeWorkspaceKind:mi,projectTarget:Xu,actionCatalog:Os,workspaceTarget:yc,connection:Et,workspaceName:pi,workspaceState:Kn,workspaceDiff:rn,workspaceBusy:ct,diffBusy:Jt,forceChatThread:!!ue,diffPanelOpen:oe,diffPanelExpanded:Se,rightPanelMode:He,rightPanelTabRequest:E,rightChatPanels:Pm,runtimeEventStore:Ea,nativeSkillSidebar:jc,extensionSkillSidebar:Mi,workspaceDiffPanelViewState:U,sidebarFileOpenRequest:Xa,sidebarFileBookmarks:Hs,onSetSidebarFileStatus:(Ae,it)=>{vi(Ae,it)},browserConversationId:Nr,terminalScope:Bt,terminalTabs:P,terminalCwd:Oa,pendingTerminalCommand:w,terminalOpen:tt,onToggleTerminal:()=>Xe(Ae=>!Ae),onWorkspaceDiffPanelViewStateChange:Sc,training:Ut,trainingSessions:ut,trainingChatHandoff:yo,trainingDetailTasksetId:C,onTrainingDetailTasksetIdChange:N,onTrainingChatTaskSelect:Vn,onTrainingChatHandoffDismiss:Tr,onOpenSession:Ai,onExperienceHandoff:Zm,cloudProjects:vt?.cloudProjects??[],projects:Bm,projectsAccountBaseUrl:vo?.baseUrl??vo?.activeProfile?.baseUrl??null,projectsTeamName:Xo?.displayName??null,projectTaskCounts:Fm,onNewCloudProject:km,onNewLocalProject:Tc,onNewProjectTask:Ae=>Ei(Ae.id),onToggleProjectPinned:Cc,onUploadLocalProject:ym,chatHistoryHasMore:fR,chatHistoryLoading:hR,onDiffPanelResizeStart:Be,onToggleDiffPanelExpanded:()=>Ne(Ae=>!Ae),onShowDiffPanel:_m,onShowBrowserPanel:Im,onShowFilesPanel:()=>Tm("files"),onShowGoalSidebarTab:sr,onShowTrainingDraftPanel:()=>{Re("training"),_e(!0)},onShowRightChatPanel:Am,onAddRightChat:()=>Xs(null),onOpenRightChatForSession:(Ae,it)=>{const Ot=it??ut.find(ga=>ga.id===Ae)??null;Ot&&Xs(Ot,{preserveView:!0})},onLabDetailOpenChange:je.onDetailOpenChange,evaluationSidebarActive:ne==="labs"&&h,onEvaluationSidebarControl:m,scheduledDetailOpen:i,onScheduledDetailOpenChange:s,onTerminalTabsChange:M,onCloseRightChatPanel:Rm,onCloseNativeSkillSidebar:Nc,onActivateRightChatPanel:Mm,onRightChatModelChange:jm,onRightChatPromptChange:Om,onRightChatScrollStateChange:Nm,onRightChatProviderChange:$m,onSubmitRightChat:Em,onStopRightChat:Ae=>Ti(Ae),onCloseTerminal:()=>Xe(!1),onLoadMoreChatHistory:Us,canSyncWorkspace:Yu,startMessage:Qo,onPayload:mn,onError:jt,setView:I,onOpenProfileSettings:Dm,onOpenProviderSettings:()=>{Qt({kind:"settings",section:"providers"})},onOpenTrainingSettings:()=>{Qt({kind:"settings",section:"training"})},onOpenDatasetStorageSettings:()=>{Qt({kind:"settings",section:"dataset-storage"})},changeDraftProvider:Ys,changeProjectTarget:tm,changeWorkspaceTarget:Sm,setDraftProvider:pe,setDraftModel:fe,onBeginNewChatWithModel:Ds,changeCodexPermissionMode:fi,changeCodexReasoningEffort:hi,changeOpenPondCommandAccessMode:tr,resolveApproval:gi,answerCreateImproveQuestion:xc,applyCreateImproveCandidate:um,approveCreateImproveRun:mm,cancelCreateImproveRun:pm,openCreateImprovePullRequest:kc,reconcileCreateImprovePullRequest:fm,rejectCreateImproveCandidate:hm,pauseCreateImproveRun:wc,resumeCreateImproveRun:Ic,reviseCreateImproveRun:gm,setMentionedAppId:j,showToast:ht,onSaveTaskDraft:Gm,sendPrompt:xm,stopTurn:Ae=>Ti(void 0,Ae),syncWorkspaceLocally:dm,refreshWorkspaceDiff:Rn},cloudSetup:{state:x,onClose:()=>R(null),onOpenBrowserUrl:wm,onStart:()=>{Pc()}},projectConfirm:{state:W,onResolve:se},lazyPanels:{activeSessions:nr,branchDialogName:lt,branchDialogOpen:at,commitDialogOpen:X,commitDraft:nt,commitIncludeUnstaged:$e,commitMessage:me,commitNextStep:Le,canPublishOpenPondProject:Qu,connection:Et,expandProject:Za,newProjectBusy:z,newProjectDialogOpen:Ge,newProjectDirectory:Fn.defaultNewProjectDirectory,newProjectMode:ze,newProjectName:L,newProjectPath:O,projectRows:na,query:de,searchOpen:Me,visibleWorkspaceDiff:rn,visibleWorkspaceState:Kn,workspaceBusy:ct,appDispatch:y,beginNewChat:()=>ta(null),openDefaultsSettingsFromBranchDialog:im,setBranchDialogName:_n,setBranchDialogOpen:Mn,setCommitDialogOpen:dn,setCommitDraft:la,setCommitIncludeUnstaged:Kt,setCommitMessage:un,setCommitNextStep:Aa,setNewProjectDialogOpen:on,setNewProjectName:At,setNewProjectPath:tn,setPrompt:le,setQuery:Ye,setSearchOpen:f,submitCommitDialog:lm,submitCreateWorkspaceBranch:cm,submitNewProjectDialog:nm},toast:{toast:pt,onDismiss:()=>y({type:"field",key:"toast",value:null})}})})}const Yi=new Map,wd=new Map;function gh(e){if(!e||e.state!=="signed_in")return null;const t=e.accounts.find(o=>o.isActive)??null,n=e.activeProfile?.handle?.trim()||t?.handle?.trim()||e.label.trim()||"signed_in",a=e.activeProfile?.baseUrl??t?.baseUrl??e.baseUrl??"";return[n,a,e.apiBaseUrl??"",e.chatApiBaseUrl??""].join("|")}function w9(e){const t=e?.trim();if(!t)return null;const n=Yi.get(t);return n?.updatedAt?n.organizations:null}function I9(e,t){const n=e?.trim();if(n){Yi.set(n,{organizations:t,promise:null,updatedAt:Date.now()});for(const a of wd.get(n)??[])a()}}function _9(e,t){const n=e?.trim();if(!n)return()=>{};const a=wd.get(n)??new Set;return a.add(t),wd.set(n,a),()=>{a.delete(t),a.size===0&&wd.delete(n)}}function R0(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(o=>(I9(t,o),o)).catch(o=>{const i=Yi.get(t);throw i?.promise===a&&Yi.set(t,{organizations:i.organizations,promise:null,updatedAt:i.updatedAt}),o});return Yi.set(t,{organizations:n?.organizations??[],promise:a,updatedAt:n?.updatedAt??0}),a}const XQ="openpond.config.json";function eX(e,t,n){return t<=0?-1:n==="Home"?0:n==="End"?t-1:n==="ArrowRight"?(e+1)%t:(e-1+t)%t}function lC(){return{activeTab:"files",openFilePaths:[],selectedPath:null}}function af(e){return{activeTab:e.activeTab,openFilePaths:[...e.openFilePaths],selectedPath:e.selectedPath}}function tX(e,t=null){const n=R9(e.openFilePaths.map(o=>A0(o,t)).filter(Boolean)),a=e.selectedPath&&A0(e.selectedPath,t)||null;return{activeTab:e.activeTab==="file"&&!a?"files":e.activeTab,openFilePaths:n,selectedPath:a}}function P0(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 A0(e,t=null){let n=C9(e);const a=t?.trim().replace(/\\/g,"/").replace(/\/+$/,"");if(!a)return n;if(n===a)return"";n.startsWith(`${a}/`)&&(n=n.slice(a.length+1));const o=a.split("/").filter(Boolean).at(-1);return o&&n.startsWith(`${o}/`)&&(n=n.slice(o.length+1)),n}function nX(e){return e.startsWith("/")||/^[A-Za-z]:\//.test(e)}function aX(e){return{path:e,status:"unchanged",additions:0,deletions:0,patch:"",content:null}}function oX(e,t){const n=T0(e.path);return!n||e.path.endsWith("/")||e.content==null&&/Could not access .+\/null['"]?/.test(e.patch)?!0:t.some(a=>{const o=T0(a);return!!(o&&o.startsWith(`${n}/`))})}function rX(e){return/\.(?:md|markdown|mdx)$/i.test(e)||/(?:^|\/)readme$/i.test(e)}function iX(e){return/\.(?:doc|docx|pdf)$/i.test(e)}function C9(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 R9(e){return Array.from(new Set(e))}function T0(e){const n=e.replace(/\\/g,"/").replace(/^\.\/+/,"").split("/").filter(Boolean);return n.length===0?null:n.join("/")}function P9(e){if(!e||e.state!=="signed_in")return null;const t=e.accounts.find(l=>l.isActive)??null,n=e.profile?.id?.trim()??"",a=e.activeProfile?.handle?.trim()||t?.handle?.trim()||e.label.trim()||"signed_in",o=e.activeProfile?.baseUrl??t?.baseUrl??e.baseUrl??"",i=e.apiBaseUrl??t?.apiBaseUrl??"",s=e.chatApiBaseUrl??t?.chatApiBaseUrl??"";return[n?`profile:${n}`:"profile:unknown",a,o,i,s].join("|")}function cC(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"cloud-project"}function A9(e){const t=new TextEncoder().encode(e);let n="";for(const a of t)n+=String.fromCharCode(a);return btoa(n)}function Fu(e){const t=e,n=t.teamId||t.id||"";if(!n)return null;const a=t.displayName||t.name||n,o=t.workspaceKind==="personal"||t.isPersonalDefault===!0||t.kind==="personal_default"||t.name?.trim().toLowerCase()==="personal";return{teamId:n,slug:t.slug||cC(a),name:t.name||a,displayName:a,role:t.role==="owner"||t.role==="admin"||t.role==="member"?t.role:"member",workspaceKind:t.workspaceKind==="personal"||t.workspaceKind==="shared"?t.workspaceKind:o?"personal":"shared",status:t.status==="disabled"||t.status==="archived"?t.status:"active",kind:t.kind==="personal_default"||t.kind==="managed_client"||t.kind==="team"?t.kind:void 0,isPersonalDefault:o,isManagedClient:t.isManagedClient===!0||t.kind==="managed_client",primaryContactEmail:t.primaryContactEmail??null,customDomain:t.customDomain??null,planKey:typeof t.planKey=="string"?t.planKey:null,effectiveAccessState:t.effectiveAccessState==="checkout_pending"||t.effectiveAccessState==="active"||t.effectiveAccessState==="grace"||t.effectiveAccessState==="suspended"||t.effectiveAccessState==="cancelling"||t.effectiveAccessState==="cancelled"?t.effectiveAccessState:null,canManageBilling:t.canManageBilling===!0||t.role==="owner",createdAt:t.createdAt??"",updatedAt:t.updatedAt??""}}function T9(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 E9(e,t){const n=e.filter(o=>o.status==="active"&&o.workspaceKind==="shared"),a=t?.trim()??"";if(a){const o=n.find(i=>i.teamId===a);if(o)return o}return n.find(o=>o.role==="owner")??n.find(o=>o.role==="admin")??n[0]??null}function M9(...e){for(const t of e){const n=t?.trim();if(n)return n}return""}function j9({draftProvider:e,hasSelectedCloudProject:t,selectedSessionHybridWorkspace:n}){return t&&!n?"openpond":e}const O9=[{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 $9(...e){return M9(...e.map(t=>{const n=t?.trim();return n&&!n.includes("@")?n:null}))}function N9(e){if(e?.state!=="signed_in")return"";const t=e.accounts.find(n=>n.isActive)??null;return $9(e.profile?.name,e.label,t?.displayLabel,e.profile?.handle,t?.handle,e.activeProfile?.handle)}function D9({bootstrap:e,draftModel:t,draftProvider:n,selectedApp:a,selectedAppId:o,selectedCloudProject:i,selectedProject:s,selectedSession:l,selectedSessionId:m,selectedSessionLinkedProject:d}){const h=l?.workspaceKind==="local_project"?l.workspaceId??null:d?.id??null,g=Ht(m)&&!l,y=l?po(l.workspaceKind):!1,w=fo(l),_=l?y9(l):!1,P=l?.cwd&&(!y||w)?pk(l.cwd):null,M=e?.providers??null,C=Ca(s,e?.cloudProjects??[]),N=j9({draftProvider:n,hasSelectedCloudProject:!!i,selectedSessionHybridWorkspace:w}),$=_r(N,t,M),j=ba(e?.preferences),x=g?null:l?y?l.workspaceKind??"sandbox":_?"sandbox":h?"local_project":l.workspaceKind??(l.appId?"sandbox_app":P?"local_project":null):i?"sandbox":s?"local_project":o?"sandbox_app":null,R=g?null:l?y&&!w||_?null:h||(l.workspaceId??l.appId??P):i?null:s?.id??o,E=g?null:l?y?l.workspaceId??null:_?null:h??l.workspaceId??l.appId??P:i?null:s?.id??o,U=e?.account??null,B=!e||U?.state==="loading"||U?.state==="switching",D=!B&&U?.state==="signed_out",W=B?null:D?"Sign in":U?.label??U?.activeProfile?.handle??"Account",se=N9(U),de=se?`Welcome, ${se}`:"Welcome",Me=l?.workspaceName??l?.appName??i?.name??s?.name??a?.name??null,ke=po(x)?"cloud":"local",te=s?.name??d?.name??(l?.workspaceKind==="local_project"?l.workspaceName:null)??"Local workspace",Ee=(ke==="cloud"?Me:null)??i?.name??C?.name??s?.name??"Cloud workspace",ye=!!(i?.id||C?.id||l?.cloudProjectId||ke==="cloud");return{account:U,accountLabel:W,accountPending:B,accountSignedOut:D,activeModel:$,activeProvider:N,activeWorkspaceAppId:R,activeWorkspaceId:E,activeWorkspaceKind:x,activeWorkspaceLocation:ke,appDefaults:j,cloudLinked:ye,cloudTargetName:Ee,localTargetName:te,selectedCodexHistoryPending:g,selectedSessionCloudWorkspace:y,selectedSessionLocalPathWorkspaceId:P,selectedSessionPendingCloudStart:_,selectedSessionProjectId:h,startMessage:de,workspaceName:Me}}function L9({accountPending:e,accountSignedOut:t,activeWorkspaceLocation:n,bootstrap:a,busy:o,cloudLinked:i,selectedCloudProject:s,selectedProject:l,selectedSession:m,pendingWorkspaceTarget:d,workspaceStates:h,workspaceBusy:g}){const y=Ca(l,a?.cloudProjects??[]),_=!!!l?.linkedSandboxProject?.projectId||!!y,P=v.useMemo(()=>{const E=(a?.localProjects??[]).map(W=>({value:`local:${W.id}`,label:W.name,detail:W.workspacePath,kind:"local"})),U=(a?.cloudProjects??[]).map(W=>({value:`cloud:${W.id}`,label:W.name,detail:W.organizationName??W.sourceLabel??"OpenPond Cloud",kind:"cloud"})),B=l?`local:${l.id}`:s?`cloud:${s.id}`:"none",D=[...E,...U].find(W=>W.value===B)??null;return{value:B,label:D?.label??"Select Project",detail:D?.detail??"Choose a project for local or cloud work",busy:g||o,options:[...E,...U,...O9,{value:"none",label:"Don't work in a project",detail:"General chat without project files",kind:"none"}]}},[a?.cloudProjects,a?.localProjects,o,s,l,g]),M=!!(i||l),C=!!(s?.id||y?.id||m?.cloudProjectId||fo(m)),N=l?h[l.id]??null:null,$=__(N,{branch:l?.linkedSandboxProject?.defaultBranch??null,path:l?.workspacePath??m?.cwd??null,linkedCloudSourceKnown:l?.linkedSandboxProject?.projectId&&_?!!l.linkedSandboxProject.lastUploadedCommit||!N?.headCommit:!0}),j=C_(l,s??y,N,{cloudLinkTrusted:_}),x=T6(l,N,{cloudLinkTrusted:_}),R=v.useMemo(()=>{const E={value:"local",label:l?"Local checkout":"Local",detail:l?"Use the selected checkout on this machine.":"Use an app-managed task workspace on this machine.",stateNote:l?$:"App-managed local task workspace",disabled:!1,disabledReason:null},U={value:"hybrid",label:"Hybrid",detail:"Use your selected model with hosted sandbox edits.",stateNote:C?j:"upload required",disabled:e||t||!C,disabledReason:t?"Add an OpenPond account before using Hybrid.":"Upload/sync this Project to Cloud before using Hybrid."},B={value:"cloud",label:"Hosted",detail:"Run with hosted compute, with or without a Project.",stateNote:l||s?j:"Projectless hosted task",disabled:e||t,disabledReason:t?"Add an OpenPond account before using Cloud.":e?"Checking OpenPond account.":null},D={value:"upload_cloud",label:"Upload/sync to cloud",detail:"Push local source to OpenPond Git before cloud work.",stateNote:x,disabled:e||t||!l,disabledReason:t?"Add an OpenPond account before uploading source.":"Select a local Project before uploading source."},W=n==="cloud"?"local":"cloud",se=W==="local"?E:B;let de=n==="cloud"?B:E;return d==="cloud"?de=B:d==="local"?de=E:(fo(m)||d==="hybrid")&&(de=U),{value:de.value,label:de.label,detail:de.stateNote||de.detail,busy:g,action:{...se,label:W==="cloud"?"Hosted":l?"Local checkout":"Check out locally"},uploadAction:l?D:null,options:[E,U,B]}},[n,e,t,i,M,j,C,$,d,l,m,x,g]);return{projectTarget:P,workspaceTarget:R}}function Dn(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")}function dC(e){return Dn(e.name||e.gitRepo||e.id)}function sX(e){return`@${dC(e)}`}function uC(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>Dn(t[1]??"")).filter(Boolean)}function U9(e,t){const n=uC(e);if(n.length===0)return!1;const a=new Set([Dn(t.id),dC(t),t.gitRepo?Dn(t.gitRepo):""].filter(Boolean));return n.some(o=>a.has(o))}function mC(e){return e.filter(t=>t.sandbox)}function H9(e,t){const n=uC(e);if(n.length===0)return null;const a=new Map;for(const o of n){const i=t.find(s=>{const l=Dn(s.id),m=Dn(s.name),d=s.gitRepo?Dn(s.gitRepo):"";return o===l||o===m||o===d});i&&a.set(i.id,i)}return a.size===1?Array.from(a.values())[0]??null:null}function lX(e,t){const n=e.slice(0,t),a=n.match(/(?:^|\s)@([A-Za-z0-9_-]*)$/);if(!a||typeof a.index!="number")return null;const o=n.slice(a.index).indexOf("@");return o<0?null:{query:Dn(a[1]??""),start:a.index+o}}function z9(e){return new Set(e.map(t=>t.id))}function E0(e,t){const n=e?.linkedOpenPondApp??null;return n?.appId&&t.has(n.appId)?n:null}function q9({bootstrap:e,codexHistorySessions:t,selectedProjectId:n,selectedSessionId:a,selectedAppId:o,sessions:i}){const s=v.useMemo(()=>e?.apps.find(D=>D.id===o)??null,[e?.apps,o]),l=v.useMemo(()=>new Map((e?.localProjects??[]).map(D=>[D.id,D])),[e?.localProjects]),m=v.useMemo(()=>new Map((e?.cloudProjects??[]).map(D=>[D.id,D])),[e?.cloudProjects]),d=v.useMemo(()=>p_(n),[n]),h=v.useMemo(()=>d?.kind==="local"?l.get(d.id)??null:null,[l,d]),g=v.useMemo(()=>d?.kind==="cloud"?m.get(d.id)??null:null,[m,d]),y=v.useMemo(()=>z9(e?.apps??[]),[e?.apps]),w=v.useMemo(()=>mC(e?.apps??[]),[e?.apps]),_=v.useMemo(()=>{const D=[];for(const W of e?.localProjects??[]){const se=E0(W,y);se&&D.push([se.appId,W.id])}return new Map(D)},[e?.localProjects,y]),P=v.useMemo(()=>new Set((e?.localProjects??[]).map(D=>D.id)),[e?.localProjects]),M=v.useMemo(()=>y_(e?.localProjects??[]),[e?.localProjects]),C=v.useRef([]),N=v.useMemo(()=>B9(i,t,C.current),[t,i]),$=v.useMemo(()=>N.find(D=>D.id===a)??null,[N,a]),j=v.useMemo(()=>{if(!$)return null;if($.localProjectId)return l.get($.localProjectId)??null;if($.workspaceKind==="local_project")return $.workspaceId?l.get($.workspaceId)??null:null;const D=y6($,P,M);if(D)return l.get(D)??null;if(!$.appId)return null;const W=_.get($.appId);return W?l.get(W)??null:null},[_,l,P,M,$]),x=v.useMemo(()=>$?.cloudProjectId?m.get($.cloudProjectId)??null:null,[m,$]),R=h??j,E=g??x,U=v.useMemo(()=>E0(R,y),[y,R]),B=v.useMemo(()=>U?e?.apps.find(D=>D.id===U.appId)??null:null,[e?.apps,U]);return{cloudProjectById:m,currentAppIds:y,linkedProjectByAppId:_,localProjectById:l,mentionableSandboxApps:w,selectedApp:s,selectedCloudProject:E,selectedProject:R,selectedProjectLinkedApp:B,selectedProjectLinkedOpenPondApp:U,selectedSession:$,selectedSessionLinkedProject:j,sidebarSessions:N}}function B9(e,t,n){const a=new Map;for(const d of e){const h=M0(d);a.set(h,d)}for(const d of t){const h=M0(d),g=a.get(h);a.set(h,g?F9(g,d):d)}const o=Array.from(a.entries());if(!n)return o.sort((d,h)=>j0(d[1],h[1])).map(d=>d[1]);const i=[],s=new Set;for(const d of n){const h=a.get(d);h&&(i.push([d,h]),s.add(d))}const m=[...o.filter(([d])=>!s.has(d)).sort((d,h)=>j0(d[1],h[1])),...i];return n.splice(0,n.length,...m.map(([d])=>d)),m.map(d=>d[1])}function F9(e,t){return{...e,metadata:V9(e.metadata,t.metadata),status:e.status==="active"||t.status==="active"?"active":e.status,updatedAt:K9(e.updatedAt,t.updatedAt)}}function M0(e){return e.codexThreadId?`codex:${e.codexThreadId}`:`session:${e.id}`}function j0(e,t){const n=O0(t)-O0(e);return n!==0?n:e.title.localeCompare(t.title)}function V9(e,t){const n={...e??{},...t??{}};return Object.keys(n).length>0?n:void 0}function K9(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 O0(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 W9(e){return!!(e&&po(e.workspaceKind)&&!fo(e)&&e.provider!=="openpond")}function G9(e,t){const n=g_(e,t);return`${e.id}\0${n.provider}\0${n.model}`}function Z9({activeWorkspaceId:e,activeWorkspaceKind:t,appDispatch:n,connection:a,expandProject:o,linkedProjectByAppId:i,providerSettings:s,selectedAppId:l,selectedSession:m,selectedSessionId:d,selectedSessionProjectId:h,setDiffPanelExpanded:g,setDraftModel:y,setDraftProvider:w,setError:_,setSelectedAppId:P,setSelectedProjectId:M,setSessions:C,setTerminalOpen:N,toast:$}){const j=v.useRef(null);v.useEffect(()=>{if(!l)return;const x=h??(d?null:i.get(l)??null);if(!x)return;const R=yt("local",x);P(null),M(R),o(R)},[o,i,l,d,h,P,M]),v.useEffect(()=>{if(!$||$.persistent)return;const x=window.setTimeout(()=>{n({type:"clearToast",toastId:$.id})},$.durationMs??($.tone==="error"?7e3:3500));return()=>window.clearTimeout(x)},[n,$]),v.useEffect(()=>{function x(R){(R.metaKey||R.ctrlKey)&&R.key==="`"&&(R.preventDefault(),N(E=>!E))}return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[N]),v.useEffect(()=>{g(!1)},[e,t,g]),v.useEffect(()=>{if(!d){j.current=null;return}if(!m||m.id!==d)return;const x=G9(m,s);if(j.current===x)return;j.current=x;const R=g_(m,s);w(R.provider),y(R.model)},[s,m,d,y,w]),v.useEffect(()=>{!a||!m||!W9(m)||Q.patchSession(a,m.id,{provider:"openpond"}).then(x=>{C(R=>R.map(E=>E.id===x.id?x:E)),w("openpond"),y(R=>_r("openpond",R))}).catch(x=>{_(x instanceof Error?x.message:String(x))})},[a,m,y,w,_,C])}function J9({connection:e,setError:t}){return v.useCallback(async(n,a)=>{if(!e){const o=new Error("OpenPond App server is not connected.");throw t(o.message),o}t(null);try{await Q.resolveApproval(e,n,{decision:a})}catch(o){const i=o instanceof Error?o.message:String(o);throw t(i),o}},[e,t])}function Y9({activeProvider:e,contextCompaction:t,contextUsage:n,pinnedItems:a,pinnedPreviewKeys:o,pinnedProjects:i,projectRows:s,visibleProjectRows:l}){const m=v.useMemo(()=>i6(a,o),[a,o]),d=v.useMemo(()=>U_({provider:e,snapshot:n,preferences:t}),[e,t,n]),h=v.useMemo(()=>Array.from(new Set([...i,...l].filter(xv).map(y=>y.project.id))),[i,l]);return{commandProjectRows:v.useMemo(()=>s,[s]),contextWindowStatus:d,pinnedRows:m,sidebarWorkspaceAppIds:h}}function Q9({appDispatch:e,expandProject:t,linkedProjectByAppId:n,requestComposerFocus:a,onBeginNewChat:o,setMentionedAppId:i}){return v.useCallback((s=null)=>{o?.();const l=s?.id?n.get(s.id)??null:null;if(l){const m=yt("local",l);i(null),e({type:"selectProject",projectId:m}),t(m),a();return}i(null),e({type:"beginNewChat",appId:s?.id??null}),a()},[e,t,n,o,a,i])}const pC={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 cX(e){return`@${e.token}`}function X9(e){return`@${oW(e)}`}function eW(e){const t=new Map;for(const n of e){if(!n.connected||n.statusSource!=="integration_connection")continue;const a=t.get(n.providerFamily)??[];a.push(n),t.set(n.providerFamily,a)}return Array.from(t.entries()).map(([n,a])=>{const o=a[0],i=zi(a.flatMap(g=>g.capabilities.map(y=>y.id))),s=zi(a.flatMap(g=>g.capabilityLabels)),l=zi(a.flatMap(g=>g.connections.map(y=>y.id).filter(iW))),m=zi(a.map(g=>g.id)),d=zi(a.map(g=>g.setupSurface)),h=aW(n);return{provider:n,label:o.providerLabel,detail:s.length>0?s.slice(0,4).join(", "):o.description,token:h,tokens:nW(a),ref:{kind:"integration",provider:n,appIds:m,setupSurfaces:d,...l.length>0?{connectionIds:l}:{},...i.length>0?{capabilities:i}:{}}}})}function dX(e,t){const n=Dn(t);return e.filter(a=>n?a.tokens.some(o=>o.includes(n)):!0).slice(0,8)}function tW(e,t){const n=rW(e);if(n.length===0)return[];const a=new Map;for(const o of n){const i=t.find(s=>s.tokens.includes(o));i&&a.set(i.provider,i)}return Array.from(a.values())}function uX(e,t){if(t.length===0)return[];const n=[];for(const a of e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)){const o=a[1]??"",i=Dn(o);if(!i)continue;const s=t.find(g=>g.tokens.includes(i));if(!s)continue;const m=(a[0]??"").indexOf("@");if(m<0||typeof a.index!="number")continue;const d=a.index+m,h=`@${o}`;n.push({detail:s.detail,displayText:X9(s),end:d+h.length,label:s.label,provider:s.provider,start:d,text:h})}return n}function nW(e){return zi(e.flatMap(t=>[...pC[t.providerFamily],t.providerFamily,t.id,t.label,t.shortLabel]).map(Dn).filter(Boolean))}function aW(e){return Dn(pC[e][0]??e)}function oW(e){return e.provider==="github"?"GitHub":e.provider==="x"?"X":e.provider==="mcp"?"MCP":e.label}function rW(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>Dn(t[1]??"")).filter(Boolean)}function zi(e){return Array.from(new Set(e))}function iW(e){return typeof e=="string"&&e.length>0}function sW({bootstrap:e,connectedAppRows:t,mentionableSandboxApps:n,runtimeIndexes:a,selectedApp:o,selectedCloudProject:i,selectedProject:s,selectedSession:l,selectedSessionId:m}){const d=v.useMemo(()=>{const _=new Map;for(const P of e?.cloudProjects??[]){const M=_.get(P.teamId)??[];M.push(P.id),_.set(P.teamId,M)}return _},[e?.cloudProjects]),g=!!(l||o||s||i)?[]:n,y=v.useMemo(()=>eW(t),[t]),w=v.useMemo(()=>o9(a,m),[a,m]);return{chatMentionApps:g,cloudProjectIdsByTeam:d,connectedAppMentions:y,pendingApproval:w}}function lW({connection:e,setBootstrap:t,setCodexPermissionMode:n,setCodexReasoningEffort:a,setError:o}){const i=v.useCallback(l=>{if(!e){o("Connect to OpenPond before saving preferences.");return}Q.savePreferences(e,{codexPermissionMode:l}).then(m=>{n(m.preferences.codexPermissionMode),a(m.preferences.codexReasoningEffort),t(d=>d&&{...d,preferences:m.preferences})}).catch(m=>{o(m instanceof Error?m.message:String(m))})},[e,t,n,a,o]),s=v.useCallback(l=>{if(!e){o("Connect to OpenPond before saving preferences.");return}Q.savePreferences(e,{codexReasoningEffort:l}).then(m=>{n(m.preferences.codexPermissionMode),a(m.preferences.codexReasoningEffort),t(d=>d&&{...d,preferences:m.preferences})}).catch(m=>{o(m instanceof Error?m.message:String(m))})},[e,t,n,a,o]);return{changeCodexPermissionMode:i,changeCodexReasoningEffort:s}}const cW=6e4;function Mv(e,t){if(!e)return t;const n=uW(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 hC(e,n)?e:n}function dW(e,t){const n=Mv(e,t),a=e?{...n,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order,updatedAt:e.updatedAt}:n;return e&&hC(e,a)?e:a}function fl(e,t){let n=!1,a=!1;const o=e.map(i=>{if(i.id!==t.id)return i;n=!0;const s=Mv(i,t);return s!==i&&(a=!0),s});return n?a?o:e:[t,...e]}function Vu(e,t){let n=!1,a=!1;const o=e.map(i=>{if(i.id!==t.id)return i;n=!0;const s=dW(i,t);return s!==i&&(a=!0),s});return n?a?o:e:[t,...e]}function vh(e,t,n,a=Date.now()){const o=new Map(e.map(i=>[i.id,i]));return t.map(i=>{const s=o.get(i.id);if(s&&n){const l=pW(s,i,n,a);if(l)return l}return Mv(s,i)})}function $0(e,t,n,a=Date.now()){const o=new Map(e.map(d=>[d.id,d])),i=new Map(vh(e,t,n,a).map(d=>[d.id,d])),s=new Set(o.keys()),l=t.filter(d=>!s.has(d.id)).map(d=>i.get(d.id)??d),m=e.map(d=>{const h=i.get(d.id);return h||(fC(d,t)?d:null)}).filter(d=>!!d);return[...l,...m]}function fC(e,t){const n=Date.parse(e.updatedAt);if(!Number.isFinite(n))return!1;const a=mW(t);return a===null||n>=a}function N0(e,t,n,a=Date.now()){const o=new Map(t.map(i=>[i.id,i]));for(const i of n){const s=o.get(i.id);s&&(gC(s,i)||(e[i.id]=a))}}function uW(e,t){const n=Date.parse(e),a=Date.parse(t);return Number.isFinite(n)&&Number.isFinite(a)&&n>a}function hC(e,t){return JSON.stringify(e)===JSON.stringify(t)}function mW(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 pW(e,t,n,a){const o=n[t.id];return o===void 0?null:a-o>cW||gC(e,t)?(delete n[t.id],null):{...t,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order}}function gC(e,t){return e.pinned===t.pinned&&e.savedForLater===t.savedForLater&&e.archived===t.archived&&e.order===t.order}const vC=800,fW=5e3,D0=5e4,hW=16,gW=3e4,Zn=new Map;function vW(e,t){return Zn.get(yC(e,t))?.payload??null}async function bC(e,t,n={}){const a=yC(e,t),o=Zn.get(a),i=n.limit??vC,s=n.tail??!0;if(o?.promise)return o.promise;if(!n.force&&s&&o?.payload&&Date.now()-o.fetchedAt<=gW)return L0(a,o),o.payload;const l=!!(n.force&&s&&o?.payload),m=l?o?.payload?.events.at(-1)?.id:void 0,d=Q.codexHistoryThreadIncremental(e,t,{afterEventId:m,limit:i,revision:l?o?.revision:void 0,tail:s}).then(h=>{const g=Zn.get(a)?.payload??o?.payload;if(h.unchanged){if(!g)throw new Error("Codex history revision matched without a cached thread.");return Zn.set(a,{fetchedAt:Date.now(),payload:g,revision:h.revision}),L0(a,Zn.get(a)),g}const y={session:h.session,events:h.events},w=s&&g&&!h.reset?{...y,events:bW(g.events,y.events)}:y;return Zn.set(a,{fetchedAt:Date.now(),payload:w,revision:h.revision}),U0(),w}).catch(h=>{throw Zn.get(a)?.promise===d&&Zn.delete(a),h});return Zn.set(a,{fetchedAt:o?.fetchedAt??0,payload:o?.payload,promise:d,revision:o?.revision}),U0(),d}function yC(e,t){return`${e.serverUrl}
|
|
185
|
-
${e.token}
|
|
186
|
-
${t}`}function L0(e,t){Zn.delete(e),Zn.set(e,t)}function U0(){for(;Zn.size>hW;){const e=Zn.keys().next().value;if(!e)return;Zn.delete(e)}}function bW(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 yW=500,SW=2500,xW=15e3;function kW(e){return e.active?yW:e.surface==="thread"?SW:xW}function jv(e,t){return!t||e.session.status==="active"?e:{...e,session:{...e.session,status:"active"}}}function wW(e={}){const t={cachedPayload:e.cachedPayload??vW,clearTimer:e.clearTimer??(d=>globalThis.clearTimeout(d)),loadPayload:e.loadPayload??bC,now:e.now??Date.now,setTimer:e.setTimer??((d,h)=>globalThis.setTimeout(d,h))},n=new Map;let a=1;function o(d){const h=_W(d.connection,d.sessionId);let g=n.get(h);g||(g={connection:d.connection,disposed:!1,inFlight:null,latestPayload:t.cachedPayload(d.connection,d.sessionId),nextRefreshAt:null,sessionId:d.sessionId,subscribers:new Map,timer:null},n.set(h,g));const y=a++;return g.subscribers.set(y,d),g.latestPayload&&d.onPayload(g.latestPayload),i(g,0),()=>{const w=n.get(h);if(w){if(w.subscribers.delete(y),w.subscribers.size>0){i(w,l(w));return}w.disposed=!0,m(w),n.delete(h)}}}function i(d,h){if(d.disposed||d.subscribers.size===0||d.inFlight)return;const g=t.now()+Math.max(0,h);d.timer&&d.nextRefreshAt!==null&&d.nextRefreshAt<=g||(m(d),d.nextRefreshAt=g,d.timer=t.setTimer(()=>{d.timer=null,d.nextRefreshAt=null,s(d)},Math.max(0,h)))}async function s(d){if(d.disposed||d.subscribers.size===0||d.inFlight)return;const h=t.loadPayload(d.connection,d.sessionId,{force:!!d.latestPayload});d.inFlight=h;try{const g=await h;if(d.disposed||g===d.latestPayload)return;d.latestPayload=g;for(const y of d.subscribers.values())y.onPayload(g)}catch(g){if(d.disposed)return;for(const y of d.subscribers.values())y.onError?.(g)}finally{d.inFlight===h&&(d.inFlight=null),d.disposed||i(d,l(d))}}function l(d){const h=[...d.subscribers.values()],g=h.some(w=>w.locallyActive||w.reportedActive)||d.latestPayload?.session.status==="active"||Av(d.latestPayload?.events??[])?.tone==="active",y=h.some(w=>w.surface==="thread")?"thread":"sidebar";return kW({active:g,surface:y})}function m(d){d.timer&&t.clearTimer(d.timer),d.timer=null,d.nextRefreshAt=null}return{subscribe:o}}const IW=wW();function Ov(e){return IW.subscribe(e)}function _W(e,t){return`${e.serverUrl}
|
|
187
|
-
${e.token}
|
|
188
|
-
${t}`}function CW({connection:e,selectedSessionId:t,selectedSessionLocallyActive:n,selectedSessionStatus:a,setCodexHistorySessions:o,setError:i}){const[s,l]=v.useState({events:[],sessionId:null}),m=Ht(t)?t:null,d=m&&s.sessionId===m?s.events:[],h=v.useCallback(g=>{l(y=>{if(!m)return{events:[],sessionId:null};const w=y.sessionId===m?y.events:[];return{events:typeof g=="function"?g(w):g,sessionId:m}})},[m]);return v.useEffect(()=>{if(!e||!m){l(w=>w.sessionId===null&&w.events.length===0?w:{events:[],sessionId:null});return}i(w=>w==="Session not found"?null:w);const g=n;return Ov({connection:e,locallyActive:g,onError:w=>i(w instanceof Error?w.message:String(w)),onPayload:w=>{const _=jv(w,g);l(P=>P.sessionId!==m?{events:_.events,sessionId:m}:{events:Ao(P.events,_.events),sessionId:m}),i(P=>P==="Session not found"?null:P),o(P=>Vu(P,_.session))},reportedActive:a==="active",sessionId:m,surface:"thread"})},[e,m,n,a,o,i]),{codexHistoryEvents:d,setCodexHistoryEvents:h}}function SC(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 RW({connection:e,appPreferences:t,sessions:n,pinnedItems:a,setAppPreferences:o,setCodexHistorySessions:i,setSessions:s,sidebarFileBookmarks:l,setSidebarFileBookmarks:m,setError:d}){const[h,g]=v.useState(null),[y,w]=v.useState(null),_=v.useRef(null),P=v.useRef(null);function M(R,E){R.dataTransfer.effectAllowed="move",R.dataTransfer.setData("text/plain",`${E.type}:${E.id}`),SC(R);const U=a.map(B=>B.key);_.current=E,P.current=U,g(E),w(U)}function C(){_.current=null,P.current=null,g(null),w(null)}function N(R,E){const U=_.current;if(!U)return;const B=Vd(R),D=P.current??a.map(se=>se.key),W=Kd(D,Wr(U),Wr(E),B);n0(D,W)||(P.current=W,w(W))}function $(R){if(!e)return;const E=a.map(ke=>ke.key),U=new Set(E),B=[...R.filter(ke=>U.has(ke)),...E.filter(ke=>!R.includes(ke))];if(n0(E,B))return;const D=t,W=new Map(n.map(ke=>[ke.id,ke])),se=l,de=new Map(a.map(ke=>[ke.key,ke]));o(ke=>{const te={...ke};return B.forEach((Ee,ye)=>{const ne=de.get(Ee);ne?.type==="project"&&(te[ne.id]={...te[ne.id]??{},pinned:!0,archived:!1,order:ye})}),te});const Me=ke=>{const te=new Map(ke.map(ne=>[ne.id,ne])),Ee=B.map((ne,be)=>{const ae=de.get(ne),ue=ae?.type==="session"?te.get(ae.id):null;return ue?{...ue,order:be}:null}).filter(ne=>!!ne),ye=new Map(Ee.map(ne=>[ne.id,ne]));return ke.map(ne=>ye.get(ne.id)??ne)};s(Me),i(Me),m(ke=>{const te=new Map;return B.forEach((Ee,ye)=>{const ne=de.get(Ee);ne?.type==="file"&&te.set(ne.id,ye)}),ke.map(Ee=>{const ye=te.get(Ee.id);return ye===void 0?Ee:{...Ee,order:ye}})}),Promise.all(B.map((ke,te)=>{const Ee=de.get(ke);return Ee?Ee.type==="project"?Q.patchSidebarAppPreference(e,Ee.id,{pinned:!0,archived:!1,order:te}):Ee.type==="session"?Q.patchSession(e,Ee.id,{order:te}):Q.patchSidebarFile(e,{workspaceKind:Ee.file.workspaceKind,workspaceId:Ee.file.workspaceId,workspaceName:Ee.file.workspaceName,path:Ee.file.path,status:"pinned",order:te,sourceSessionId:Ee.file.sourceSessionId}):Promise.resolve(null)})).catch(ke=>{d(ke instanceof Error?ke.message:String(ke)),o(D);const te=Ee=>Ee.map(ye=>W.get(ye.id)??ye);s(te),i(te),m(se)})}function j(R,E){const U=_.current;if(U){const B=P.current??a.map(W=>W.key),D=Kd(B,Wr(U),Wr(E),Vd(R));$(D)}C()}function x(){_.current&&$(P.current??a.map(E=>E.key)),C()}return{dragItem:h,pinnedPreviewKeys:y,startPinnedDrag:M,clearSidebarDrag:C,previewPinnedDrop:N,commitPinnedDrop:j,commitPinnedPreviewDrop:x}}function PW({connection:e,sessions:t,setCodexHistorySessions:n,setError:a,setSessions:o}){const[i,s]=v.useState(null),[l,m]=v.useState(null),d=v.useRef(null),h=v.useRef(null);function g(C,N){C.dataTransfer.effectAllowed="move",C.dataTransfer.setData("text/plain",`session:${N.sessionId}`),SC(C),d.current=N,h.current=N.visibleSessionIds,s(N.sessionId),m(N.visibleSessionIds)}function y(C,N){const $=d.current;if(!$)return;const j=h.current??$.visibleSessionIds,x=Kd(j,$.sessionId,N,Vd(C));AW(j,x)||(h.current=x,m(x))}function w(){d.current=null,h.current=null,s(null),m(null)}function _(C,N){const $=d.current;if(!$){w();return}const j=h.current??$.visibleSessionIds,x=Kd(j,$.sessionId,N,Vd(C));M(c0($.allSessionIds,$.visibleSessionIds,x)),w()}function P(){const C=d.current;C&&M(c0(C.allSessionIds,C.visibleSessionIds,h.current??C.visibleSessionIds)),w()}function M(C){const N=new Map(C.map((R,E)=>[R,E])),$=new Map(t.map(R=>[R.id,R.order])),j=C.filter((R,E)=>$.get(R)!==E);if(j.length===0)return;const x=R=>R.map(E=>{const U=N.get(E.id);return U===void 0||U===E.order?E:{...E,order:U}});o(x),n(x),e&&Promise.all(j.map(R=>Q.patchSession(e,R,{order:N.get(R)}))).catch(R=>{const E=U=>U.map(B=>{const D=$.get(B.id);return D===void 0||D===B.order?B:{...B,order:D}});o(E),n(E),a(R instanceof Error?R.message:String(R))})}return{clearTaskDrag:w,commitTaskDrop:_,commitTaskPreviewDrop:P,previewTaskDrop:y,startTaskDrag:g,taskDragSessionId:i,taskPreviewSessionIds:l}}function AW(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function H0({afterMessageId:e=null,attachments:t,content:n,sessionId:a}){const o=new Date().toISOString(),i=`pending_user_${a}_${o}_${Math.random().toString(36).slice(2,8)}`,s=TW(t);return{id:i,role:"user",content:n,sessionId:a,afterMessageId:e,timestamp:o,turnId:i,...s.length>0?{attachments:s}:{}}}function xC(e,t){return!t||kC(e,t)?e:[...e,t]}function kC(e,t){const n=t.afterMessageId?e.findIndex(i=>i.id===t.afterMessageId):-1,a=n>=0?n+1:0,o=Date.parse(t.timestamp);for(let i=a;i<e.length;i+=1){const s=e[i];if(s.role!=="user"||s.content!==t.content)continue;if(n>=0||!t.afterMessageId)return!0;const l=Date.parse(s.timestamp);if(!Number.isFinite(o)||!Number.isFinite(l)||l>=o)return!0}return!1}function TW(e){return e.map(({contentsBase64:t,text:n,...a})=>a)}function ve(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 Cr(e){const t=e.trim();if(!t||!t.startsWith("{")&&!t.startsWith("["))return null;try{return JSON.parse(t)}catch{return null}}function Ce(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Bo(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];if(t(a))return a}return null}function EW(e,t,n){if(t.name==="workspace_action_result"){const a=Bo(e,o=>o.role==="assistant"&&o.turnId===t.turnId&&o.actionRun?.actionName===n.actionName);if(a?.actionRun){a.id=t.id,a.timestamp=t.timestamp,a.actionRun={...a.actionRun,...n,refs:bh([...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 MW(e){if(e.name!=="workspace_action"&&e.name!=="workspace_action_result")return null;const t=Ce(e.data),n=Ce(e.args),a=ve(n,["actionName"])??ve(Ce(n?.input),["actionName"])??of(t)??of(Ce(t?.run))??of(Ce(t?.agentRun));if(!(e.action==="sandbox_run_action"||e.action==="profile_run_action"||!!a||t?.openPondActionRun===!0||t?.openPondProfileActionRun===!0)||!a)return null;const i=Ce(t?.run)??Ce(t?.agentRun),s=Ce(i?.metadata),l=Ce(t?.actionSummary)??Ce(i?.actionSummary)??Ce(s?.actionSummary),m=Ce(t?.action)??l??Ce(s?.selectedAction)??null,d=Ce(t?.responseSummary)??Ce(i?.responseSummary)??Ce(s?.responseSummary),h=Ce(t?.sourceSummary)??Ce(i?.sourceSummary)??Ce(s?.sourceSummary),g=Ce(t?.traceSummary)??Ce(i?.traceSummary)??Ce(s?.traceSummary),y=Ce(t?.evalSummary)??Ce(i?.evalSummary)??Ce(s?.evalSummary),w=bh([...Co("artifact",t?.artifactRefs,"Artifact"),...Co("artifact",m?.artifactRefs,"Artifact"),...Co("artifact",l?.artifactRefs,"Artifact"),...Co("artifact",d?.artifactRefs,"Artifact"),...Co("trace",t?.traceArtifactRefs,"Trace"),...Co("trace",g?.artifactRefs,"Trace"),...Co("eval",t?.evalResultArtifactRefs,"Eval"),...Co("eval",y?.artifactRefs,"Eval"),...Co("output",t?.outputRefs,"Output")]),_=ve(h,["sourceRef","ref"]);return _&&w.push({id:yh("source",_),kind:"source",label:"Source",target:_}),{actionName:a,title:ve(m,["label","title","name"])??ve(s,["selectedActionLabel"])??LW(a),status:jW(e,d,i),responseText:ve(d,["text","summary","message"])??(e.name==="workspace_action_result"&&e.output?.trim()||null),runId:ve(i,["id","runId"])??ve(t,["runId","agentRunId"])??null,projectId:ve(i,["projectId"])??ve(t,["projectId"])??ve(n,["projectId"])??null,agentId:ve(i,["agentId"])??ve(t,["agentId"])??ve(n,["agentId"])??null,agentName:ve(Ce(m?.implementation),["agentName"])??ve(m,["agentName"])??ve(s,["selectedAgentName"])??null,sandboxId:ve(i,["sandboxId"])??ve(t,["sandboxId"])??ve(Ce(t?.sandbox),["id"])??ve(Ce(t?.createdSandbox),["id"])??ve(n,["sandboxId"])??null,runtimeId:ve(i,["runtimeId"])??ve(t,["runtimeId"])??null,implementationType:ve(t,["implementationType"])??ve(m,["implementationType","type","kind"])??ve(Ce(m?.implementation),["type","kind"])??ve(s,["implementationType"])??(e.action==="profile_run_action"||t?.openPondProfileActionRun===!0?"openpond-profile-action":null),sourceRef:_,manifestHash:ve(h,["manifestHash"])??ve(t,["manifestHash"])??ve(s,["manifestHash"])??null,refs:bh(w),childCalls:$W(t,i,s)}}function of(e){return e?ve(e,["actionName","name"])??ve(Ce(e.action),["actionName","name"])??ve(Ce(e.actionSummary),["actionName","name"])??ve(Ce(e.selectedEntrypoint),["name"]):null}function jW(e,t,n){if(e.status==="failed")return"failed";const a=ve(t,["status"]);if(a==="failed")return"failed";if(a==="running"||a==="pending")return a;if(a==="available"||e.status==="completed")return"completed";const o=ve(n,["status"]);return o==="failed"?"failed":o==="succeeded"||o==="completed"?"completed":o==="queued"||o==="running"||o==="runtime_created"?"running":e.status==="pending"?"pending":e.status==="started"||e.name==="workspace_action"?"running":"unknown"}function Co(e,t,n){return(Array.isArray(t)?t:t?[t]:[]).flatMap(o=>{const i=OW(e,o,n);return i?[i]:[]})}function OW(e,t,n){if(typeof t=="string"&&t.trim()){const s=t.trim();return{id:yh(e,s),kind:e,label:n,target:s}}const a=Ce(t);if(!a)return null;const o=ve(a,["url","webUrl","artifactPath","path","ref"])??ve(Ce(a.artifact),["url","webUrl","path","ref"]);if(!o)return null;const i=ve(a,["label","title","name","type","kind"])??n;return{id:yh(e,o),kind:e,label:i,target:o}}function bh(e){const t=new Set,n=[];for(const a of e){const o=`${a.kind}:${a.target}`;t.has(o)||(t.add(o),n.push(a))}return n}function yh(e,t){return`${e}:${t}`}function $W(e,t,n){return[e?.childCalls,e?.childRuns,e?.implementationCalls,t?.childCalls,t?.childRuns,n?.childCalls,n?.childRuns].flatMap(o=>NW(o)).slice(0,6)}function NW(e){return(Array.isArray(e)?e:e?[e]:[]).flatMap((n,a)=>{const o=Ce(n);if(!o)return[];const i=ve(o,["id","runId","callId"])??`child_${a+1}`,s=ve(o,["label","title","actionName","name","tool"])??ve(Ce(o.action),["label","name"])??"Implementation call",l=ve(o,["detail","summary","runId","sandboxId","runtimeId"])??null;return[{id:i,label:s,status:DW(o),detail:l}]})}function DW(e){const t=ve(e,["status","state"]);return t==="running"||t==="completed"||t==="failed"||t==="pending"?t:t==="succeeded"?"completed":"unknown"}function LW(e){const t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e}const UW=new Set([".avif",".gif",".jpeg",".jpg",".png",".webp"]);function wC(e){if(!e)return!1;const t=e.split("?")[0]?.split("#")[0]??e,n=t.lastIndexOf(".");return n<0?!1:UW.has(t.slice(n).toLowerCase())}function IC(e){return e.split("/").filter(Boolean).pop()??e}function HW(e){if(!xh(e))return;const t=Ce(e.data),a=(typeof t?.openpondImagePreviewPath=="string"?t.openpondImagePreviewPath:null)??Gr(e.data)??Gr(e.args)??Gr(e.output);if(!(!a||!wC(a)))return{path:a,appId:e.appId??null,title:IC(a)}}function zW(e){if(e.name!=="tool.completed"&&e.name!=="workspace_action_result")return[];const t=[],n=new Set;return Sh(e.data,t,n),t.slice(0,12)}function Sh(e,t,n,a=0){if(a>7||e==null)return;if(Array.isArray(e)){for(const l of e)Sh(l,t,n,a+1);return}const o=Ce(e);if(!o)return;const i=ve(o,["path","artifactRef"]),s=ve(o,["contentType","mimeType"]);i&&s&&!n.has(i)&&(n.add(i),t.push({path:i,title:ve(o,["title","name"])??IC(i),contentType:s,sizeBytes:typeof o.sizeBytes=="number"?o.sizeBytes:null}));for(const l of Object.values(o))Sh(l,t,n,a+1)}function xh(e){if(e.name!=="tool.started"&&e.name!=="tool.completed")return!1;const t=Ce(e.data);return typeof t?.openpondImagePreviewPath=="string"&&t.openpondImagePreviewPath.trim()?!0:[e.output,e.action,ve(t,["tool","toolName","tool_name","name","functionName","function_name","command"]),ve(Ce(t?.input),["tool","toolName","tool_name","name"]),ve(Ce(t?.arguments),["tool","toolName","tool_name","name"]),ve(Ce(t?.args),["tool","toolName","tool_name","name"])].filter(a=>!!a).some(a=>a.toLowerCase().includes("view_image"))}function Gr(e,t=0,n=""){if(t>5||e==null)return null;if(typeof e=="string"){if(rf(n)&&wC(e.trim()))return e.trim();const o=Cr(e);if(o!==null){const i=Gr(o,t+1,n);if(i)return i}return qW(e)}if(Array.isArray(e)){for(const o of e){const i=Gr(o,t+1,n);if(i)return i}return null}const a=Ce(e);if(!a)return null;for(const[o,i]of Object.entries(a)){if(!rf(o))continue;const s=Gr(i,t+1,o);if(s)return s}for(const[o,i]of Object.entries(a)){if(rf(o))continue;const s=Gr(i,t+1,o);if(s)return s}return null}function rf(e){return/^(path|filePath|filepath|imagePath|image|localPath|uri|url)$/i.test(e)}function qW(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 BW(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=VW(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 FW(e){if(e.action!=="connected_app_search"&&e.action!=="connected_app_read"&&e.action!=="connected_app_write")return null;const t=_C(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 VW(e){return _C(e).providerLabel}function _C(e){const t=Ce(e.args),n=Ce(e.data),a=Ce(n?.result),o=cu(ve(t,["provider"])??ve(a,["provider"])??ve(n,["provider"])??void 0),i=ve(a,["providerLabel"])??ve(n,["providerLabel"])??(o?eg(o)?.label:null)??"connected app",s=ve(t,["operation"]),l=ve(a,["operation"])??ve(n,["operation"]),m=sf(t?.capabilityIds)||sf(a?.capabilityIds)||sf(n?.capabilityIds);return{providerLabel:i,providerOperation:s,operation:l,capabilityCount:m}}function sf(e){return Array.isArray(e)?e.length:0}function CC(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()||lf(a)}}return t==="<turn_aborted>"?{kind:"turn_aborted",text:lf("turn_aborted")}:t==="<goal_context>"?{kind:"goal_context",text:lf("goal_context")}:null}function lf(e){return e==="turn_aborted"?"The previous turn was interrupted.":"Goal context updated."}function Ku(e){return e.name==="diagnostic"&&Ce(e.data)?.kind==="goal_context"}const KW="Steered by user";function WW(e){return e?.trim().toLowerCase()===KW.toLowerCase()}function GW(e,t){if(!t.turnId)return;XW(e,t.turnId);const n=ZW(t);if(!n)return;const a=QW(e,t.turnId);if(a){a.refinerActivity=n;return}const o={id:`${t.id}:work-refiner`,role:"activity_group",activities:[],timestamp:t.timestamp,turnId:t.turnId,traceState:"completed",traceStartedAt:t.timestamp,traceCompletedAt:t.timestamp,refinerActivity:n},i=e.findIndex(s=>s.role==="assistant"&&s.turnId===t.turnId);i>=0?e.splice(i,0,o):e.push(o)}function ZW(e){const t=Ce(e.data),n=Ce(t?.activity);return n?JW(n,e):YW(e,t)}function mX(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 · ${a8(e.route??"external")} issue routed`;const t=e.result==="applied"?"Applied":"Needs review";return`Refiner · ${e.summary} — ${t}`}function JW(e,t){const n=ro(e.state,["running","completed","failed"]);if(!n)return null;const a=n==="failed"?"failed":ro(e.result,["no_action","routed","applied","retained"]),o=Hn(e.reason)??t.output??t.error??null;return{state:n,visibility:ro(e.visibility,["always","material_only"])??"material_only",result:n==="running"?null:a,workspaceId:Hn(e.workspaceId),decision:ro(e.decision,["no_action","route","propose"]),route:Hn(e.route),operation:ro(e.operation,["create","update","delete"]),target:Hn(e.target),summary:Hn(e.summary)??RC(n,a),expectedOutcome:Hn(e.expectedOutcome),reason:o,evidenceBasis:e8(e.evidenceBasis),critiqueStatus:ro(e.critiqueStatus,["not_applicable","pending","passed","rejected","failed"])??(n==="running"?"pending":"not_applicable"),validationStatus:ro(e.validationStatus,["not_applicable","pending","passed","failed"])??(n==="running"?"pending":"not_applicable"),validations:t8(e.validationReceipts),edits:n8(e.edits),refs:{trigger:oo(e.trigger),outcome:oo(e.outcome),proposal:oo(e.proposal),applyReceipt:oo(e.applyReceipt),advanceReceipt:oo(e.advanceReceipt),inputHarness:oo(e.inputHarness),outputHarness:oo(e.outputHarness)}}}function YW(e,t){if(!e.name.startsWith("harness.refiner."))return null;const n=e.name==="harness.refiner.failed"||e.status==="failed",a=e.name==="harness.refiner.completed",o=Ce(t?.outcome),i=Ce(t?.proposal),s=o?.routed===!0,l=Hn(t?.workspaceAdvance),m=n?"failed":a?i?l==="advanced"||/\bapplied\b/i.test(e.output??"")?"applied":"retained":s?"routed":"no_action":null;return{state:n?"failed":a?"completed":"running",visibility:"material_only",result:m,workspaceId:null,decision:i?"propose":s?"route":a?"no_action":null,route:Hn(o?.route),operation:null,target:null,summary:RC(n?"failed":a?"completed":"running",m),expectedOutcome:null,reason:e.output??e.error??null,evidenceBasis:null,critiqueStatus:i?"passed":"not_applicable",validationStatus:i?"pending":"not_applicable",validations:[],edits:[],refs:{trigger:oo(t?.trigger),outcome:oo(o),proposal:oo(i),applyReceipt:null,advanceReceipt:null,inputHarness:null,outputHarness:null}}}function QW(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];if(a.role==="activity_group"&&a.turnId===t&&!a.activities?.some(o=>o.subagentMessage))return a}return null}function XW(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 e8(e){const t=Ce(e),n=ro(t?.kind,["single_deterministic","recurrent_independent"]);return!t||!n?null:{kind:n,supportingEvidenceIds:z0(t.supportingEvidenceIds),counterevidence:z0(t.counterevidence)}}function t8(e){return Array.isArray(e)?e.flatMap(t=>{const n=Ce(t),a=Hn(n?.id),o=ro(n?.status,["passed","failed","blocked","skipped"]),i=Hn(n?.summary);return a&&o&&i?[{id:a,status:o,summary:i}]:[]}):[]}function n8(e){return Array.isArray(e)?e.flatMap(t=>{const n=Ce(t),a=Hn(n?.id),o=ro(n?.operation,["create","update","delete"]),i=Hn(n?.target),s=Hn(n?.summary);return!a||!o||!i||!s?[]:[{id:a,operation:o,target:i,summary:s,content:typeof n?.content=="string"?n.content:null}]}):[]}function oo(e){const t=Ce(e),n=Hn(t?.id),a=Hn(t?.contentHash);return n&&a?`${n} · ${a.slice(0,12)}`:null}function z0(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()):[]}function Hn(e){return typeof e=="string"&&e.trim()?e.trim():null}function ro(e,t){return typeof e=="string"&&t.includes(e)?e:null}function RC(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 a8(e){return e.length>0?`${e[0].toUpperCase()}${e.slice(1)}`:e}const q0=64*1024,B0=8*1024;function F0(e,t){const n=PC(t);if(n.subagentMessage){e.push({id:t.id,role:"activity_group",activities:[n],timestamp:t.timestamp,turnId:t.turnId});return}const a=o8(e,t.turnId);if(a){a.activities=s8(a.activities??[],t,n),a.timestamp=t.timestamp;return}Id(e,t),e.push({id:t.id,role:"activity_group",activities:[n],timestamp:t.timestamp,turnId:t.turnId,traceState:"running",traceStartedAt:t.timestamp})}function Id(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];a.role!=="activity_group"||a.activities?.some(o=>o.subagentMessage)||a.traceState==="running"&&(a.traceState="settled",a.traceCompletedAt=t.timestamp)}}function o8(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];if(a.turnId!==t||a.role!=="activity_group")return null;if(!a.activities?.some(o=>o.subagentMessage))return a}return null}function kh(e,t,n){if(!t.turnId)return;const a=e.filter(l=>l.role==="activity_group"&&l.turnId===t.turnId&&!l.activities?.some(m=>m.subagentMessage)),o=a.filter(l=>l.traceState==="running"),i=o.length>0?o:a.length>0?[a[a.length-1]]:[];for(const l of i)l.traceState=n;const s=i.at(-1);s&&(s.traceCompletedAt=t.timestamp,s.timestamp=t.timestamp)}function r8(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];if(a?.turnId!==t.turnId||a.role!=="activity_group")continue;const o=a.activities?.filter(i=>i.controlKind!=="turn_aborted")??[];o.length!==a.activities?.length&&(o.length===0?e.splice(n,1):a.activities=o)}kh(e,t,"interrupted"),!WW(t.output)&&e.push({id:t.id,role:"status_divider",content:i8(t),timestamp:t.timestamp,turnId:t.turnId,statusKind:"interruption",statusState:"failed",statusTone:"danger"})}function i8(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 s8(e,t,n=PC(t)){const a=[...e];return v8(a,t,n)||f8(a,t,n)||h8(a,t,n)||g8(a,t,n)?a:[...a,n]}function l8(e){return e.name==="session.compaction.started"||e.name==="session.compaction.completed"||e.name==="session.compaction.failed"}function c8(e,t){const n={id:t.id,role:"status_divider",content:d8(t),timestamp:t.timestamp,turnId:t.turnId,statusKind:"compaction",statusState:u8(t),statusTone:m8(t)};if(t.name!=="session.compaction.started"){const a=Bo(e,o=>o.role==="status_divider"&&o.statusKind==="compaction"&&o.statusState==="running"&&o.turnId===t.turnId);if(a){a.id=n.id,a.content=n.content,a.timestamp=n.timestamp,a.statusState=n.statusState,a.statusTone=n.statusTone;return}}e.push(n)}function d8(e){const t=p8(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 u8(e){return e.name==="session.compaction.started"?"running":e.name==="session.compaction.completed"?"completed":"failed"}function m8(e){return e.name==="session.compaction.failed"?"danger":e.name==="session.compaction.completed"?"success":"info"}function p8(e){return Ce(e.data)?.reason==="auto"?"auto":"manual"}function PC(e){const t=HW(e),n=e.name==="assistant.reasoning.delta"?"reasoning":R8(e),a=P8(e),o=E8(e),i=T8(e),s=M8(e),l=j8(e),m=zW(e);return{id:e.id,label:l?l.direction==="received"?"Child message received":"Child message sent":S8(e),content:l?.summary??k8(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:$v(e)??void 0}:{},...n&&e.name==="command.output"?{detail:wh(e)}:{},...n==="command"?{terminal:U8(e)}:{},...i?{meta:i}:{},...o?{receipt:o}:{},...s?{openSession:s}:{},...l?{subagentMessage:l}:{},state:y8(e),...t?{imagePreview:t}:{},...m.length>0?{artifacts:m}:{}}}function f8(e,t,n){if(t.name==="tool.completed"){const a=V0(e,t);if(!a)return!1;const o=H8(a.timestamp,t.timestamp);a.label=t.status==="failed"?"Failed":"Ran",a.state=n.state,a.timestamp=t.timestamp,a.artifacts=n.artifacts,a.terminal={...a.terminal,...n.terminal,...o!==null?{durationMs:o}:{}};const i=wh(t);return i&&i!==a.content&&(a.detail=Qd(a.detail,i)),!0}if(t.name==="command.output"){const a=V0(e,t);if(!a)return!1;const o=wh(t);return o&&(a.detail=Qd(a.detail,o)),a.terminal={...a.terminal,...n.terminal},a.timestamp=t.timestamp,n.state==="failed"?a.state="failed":a.state!=="completed"&&a.state!=="failed"&&(a.state="running"),!0}return!1}function h8(e,t,n){if(t.name!=="tool.completed"||n.kind==="command")return!1;const a=$v(t),o=Bo(e,s=>s.state==="running"&&s.kind!=="command"&&(a?s.callId===a:!!t.action&&s.action===t.action));if(!o)return!1;const i=n.content.trim();return o.id=n.id,o.label=n.label,o.timestamp=n.timestamp,o.state=n.state,i&&i!==o.content.trim()&&(o.content.trim()===o.action?o.content=i:o.detail=Qd(o.detail,i)),n.detail&&(o.detail=Qd(o.detail,n.detail)),o.meta=n.meta,o.receipt=n.receipt,o.imagePreview=n.imagePreview??o.imagePreview,o.artifacts=n.artifacts,!0}function g8(e,t,n){if(t.name!=="workspace_action_result")return!1;const a=b8(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 v8(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 V0(e,t){const n=$v(t);if(n){const a=Bo(e,o=>o.kind==="command"&&o.callId===n);if(a)return a}return Bo(e,a=>a.kind==="command")}function b8(e,t){const n=t.action??"",a=AC[n]??{started:"Running workspace action"};return Bo(e,o=>o.state==="running"&&o.label===a.started&&o.kind!=="command"&&!o.controlKind)}function y8(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 S8(e){if(e.name==="assistant.reasoning.delta")return ve(Ce(e.data),["kind"])==="commentary"?"Update":"Reasoning";if(Ku(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(xh(e)&&e.name==="tool.started")return"Reading image";if(xh(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=BW(e);if(t)return t;const n=I8(e);if(n)return n;const a=w8(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"?x8(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 AC={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 x8(e){const t=e.action??"",n=AC[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 k8(e,t){if(e.name==="assistant.reasoning.delta")return e.output??"";if(t)return t.path;const n=CC(e.output??"");if(n)return n.text;if(Ku(e)||e.name==="turn.interrupted")return e.output??e.error??"";const a=_8(e);if(a)return a;const o=C8(e);if(o)return o;const i=FW(e);if(i)return i;const s=TC(e);if(s)return s;if(e.name==="command.output")return MC(e.output??"");if(e.name==="tool.started"||e.name==="tool.completed"){const l=e.data;if(l&&typeof l=="object"){const m=l.command;if(typeof m=="string"&&m.trim())return m;const d=l.tool;if(typeof d=="string"&&d.trim())return d;const h=l.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 w8(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 I8(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 _8(e){if(!e.action?.startsWith("openpond_browser_"))return null;const t=Ce(Ce(e.data)?.result),n=ve(t,["output"]);if(n)return n;const a=Ce(Cr(e.output??"")),o=ve(a,["output"]);if(o)return o;const i=Ce(e.args),s=ve(i,["url"]);return s||(e.action==="openpond_browser_type"?"Text redacted":e.error??e.output??e.action)}function C8(e){if(e.action!=="openpond_create_improve")return null;const t=Ce(Ce(e.data)?.result),n=ve(t,["nextStep"]);if(n)return n;const a=Ce(Cr(e.output??"")),o=ve(a,["output"]);if(o)return o;const i=Ce(e.args),s=ve(i,["reason"]);if(s)return s;const l=ve(i,["objective"]);return l||(e.error??null)}function R8(e){if(e.name==="command.output")return"command";if(e.name!=="tool.started"&&e.name!=="tool.completed")return;const t=Ce(e.data),n=ve(t,["type"]),a=ve(t,["tool","toolName","tool_name","name","functionName","function_name"]);if(e.action==="commandExecution"||n==="commandExecution"||TC(e)||a&&/(^|[._-])exec_command$/i.test(a))return"command"}function P8(e){if(e.name==="turn.interrupted")return"turn_aborted";if(Ku(e))return"goal_context"}function TC(e){const t=Ce(e.data),n=ve(t,["type"]),a=ve(t,["tool","toolName","tool_name","name","functionName","function_name"]),o=Ce(t?.result),i=Ce(Cr(e.output??"")),s=Ce(i?.data),l=ve(t,["command","cmd"])??ve(Ce(t?.input),["command","cmd"])??ve(Ce(t?.arguments),["command","cmd"])??ve(Ce(t?.args),["command","cmd"])??A8(ve(t,["arguments","args","input"]))??ve(Ce(e.args),["command","cmd"])??ve(o,["command","cmd"])??ve(s,["command","cmd"]);return l||e.name==="tool.started"&&(e.action==="commandExecution"||n==="commandExecution"||/(^|[._-])exec_command$/i.test(a??""))&&e.output?.trim()||null}function A8(e){if(!e)return null;const t=Cr(e),n=Ce(t);return ve(n,["command","cmd"])}function $v(e){const t=Ce(e.data);return ve(t,["callId","call_id","toolCallId","tool_call_id","id","itemId","item_id"])}function T8(e){const t=Ce(e.data);if(!t)return null;const n=[],a=Ce(t.workspaceToolTiming),o=typeof a?.durationMs=="number"?a.durationMs:null;o!==null&&n.push(N8(o));const i=Ce(t.workspaceExecutionTarget),s=ve(i,["target"]);if(s==="sandbox"){const d=i?.hybrid===!0,h=ve(i,["sandboxId","workspaceId"]);n.push(`${d?"Hybrid ":""}sandbox${h?` ${K0(h)}`:""}`)}else s==="local"&&n.push("local workspace");const l=Ce(t.sourcePreservation);if(l?.attempted===!0)if(l.ok!==!0)n.push("checkpoint failed");else if(l.preserved===!0){const d=ve(l,["preservedSha"]);n.push(d?`checkpoint ${L8(d)}`:"checkpoint saved")}else n.push("checkpoint clean");const m=EC(t);return m&&(n.push(`receipt ${K0(m.id)}`),n.push(`${D8(m.totalUsd)} ${m.status}`)),n.length>0?n.join(" · "):null}function E8(e){const t=EC(Ce(e.data));return t?{id:t.id,status:t.status,totalUsd:t.totalUsd}:void 0}function M8(e){if(!e.name.startsWith("subagent."))return;const t=Ce(e.data),n=Ce(t?.run),a=ve(t,["childSessionId"])??ve(n,["childSessionId"]);if(!a)return;const o=ve(n,["roleId"])??ve(t,["roleId"]),i=ve(n,["status"])??ve(t,["status"]);return{sessionId:a,label:"Open conversation",...o?{roleId:o}:{},...i?{status:i}:{}}}function j8(e){if(e.name!=="subagent.message")return;const t=Ce(e.data),n=Ce(t?.message);if(!n)return;const a=ve(n,["id"]),o=ve(n,["kind"]),i=ve(n,["fromRunId"]),s=ve(n,["body"]);if(!a||!o||!i||!s)return;const l=Ce(t?.delivery??n.delivery),m=Ce(t?.modelRef),d=ve(m,["providerId"]),h=ve(m,["modelId"]),y=ve(l,["deliveredParentSessionId"])===e.sessionId&&!i.startsWith("parent:")?"received":"sent",w=Array.isArray(n.refs)?n.refs.flatMap(_=>{const P=Ce(_),M=ve(P,["kind"]),C=ve(P,["id"]),N=ve(P,["label"]);return M&&C&&N?[{kind:M,id:C,label:N}]:[]}):[];return{direction:y,summary:O8(s),body:s,messageId:a,kind:o,fromRunId:i,toRunId:ve(n,["toRunId"]),toRole:ve(n,["toRole"]),childSessionId:ve(t,["childSessionId"]),roleId:ve(t,["roleId"]),modelRef:d&&h?{providerId:d,modelId:h}:null,deliveryStatus:ve(l,["status"]),wakeReason:ve(l,["wakeParentReason"]),createdAt:ve(n,["createdAt"]),refs:w}}function O8(e){const t=e.replace(/\s+/g," ").trim();if(!t)return"No message body";const n=/^(.*?[.!?])(?:\s|$)/.exec(t)?.[1]??t;return $8(n,96)}function $8(e,t){if(e.length<=t)return e;const n=e.slice(0,t-1),a=n.lastIndexOf(" "),o=a>=Math.floor(t*.55)?a:t-1;return`${n.slice(0,o).trimEnd()}...`}function EC(e){const t=Ce(e?.sandbox),n=Array.isArray(t?.receipts)?t.receipts:[];for(let a=n.length-1;a>=0;a-=1){const o=Ce(n[a]),i=ve(o,["id"]),s=ve(o,["status"]),l=ve(o,["totalUsd","retailTotalUsd"]);if(i&&s&&l)return{id:i,status:s,totalUsd:l}}return null}function N8(e){return e<1e3?`${Math.max(0,Math.round(e))} ms`:e<1e4?`${(e/1e3).toFixed(1)} s`:`${Math.round(e/1e3)} s`}function D8(e){const t=e.trim();return t.startsWith("$")?t:`$${t}`}function L8(e){return e.length>12?e.slice(0,12):e}function K0(e){const t=e.trim();return t.length<=14?t:`${t.slice(0,6)}...${t.slice(-4)}`}function MC(e){let t=e.replace(/\r\n/g,`
|
|
189
|
-
`).trim();if(!t)return"";const n=z8(t);if(n!==null)return ss(n);const a=`
|
|
190
|
-
Output:
|
|
191
|
-
`,o=t.indexOf(a);return o>=0&&q8(t.slice(0,o))&&(t=t.slice(o+a.length).trim()),t=t.replace(/^Total output lines: \d+\n\n/,""),ss(t.trim())}function wh(e){const t=MC(e.output??"");if(t)return t;const n=Ce(Ce(e.data)?.result);return n?ss(jC(n)):""}function U8(e){const t=Ce(e.data),n=Ce(t?.result),a=Ce(Cr(e.output??"")),o=Ce(a?.data),i=Ce(t?.workspaceToolTiming),s=[n?.exitCode,o?.exitCode,t?.exitCode].find(m=>typeof m=="number"),l=i?.durationMs;return{...typeof s=="number"?{exitCode:s}:{},...typeof l=="number"?{durationMs:l}:{}}}function H8(e,t){const n=Date.parse(t)-Date.parse(e);return Number.isFinite(n)&&n>0?n:null}function z8(e){const t=Ce(Cr(e)),n=typeof t?.action=="string"?t.action:"";if(!t||typeof t.ok!="boolean"||!n||typeof t.output!="string")return null;const a=Ce(t.data);return a?jC(a,ve(t,["output"])):typeof t.output=="string"?t.output.trim():""}function jC(e,t=null){const n=ve(e,["stdout"])?.replace(/\r\n/g,`
|
|
192
|
-
`).trimEnd()??"",a=ve(e,["stderr"])?.replace(/\r\n/g,`
|
|
193
|
-
`).trimEnd()??"",o=[n,a].filter(Boolean);return o.length>0?o.join(`
|
|
194
|
-
`):t?.replace(/\r\n/g,`
|
|
195
|
-
`).trim()??""}function q8(e){return/^(Chunk ID|Exit code):/m.test(e)&&/Wall time:/m.test(e)}function Qd(e,t){const n=e??"";if(!n)return ss(t);if(n===t||n.includes(t))return n;if(t.includes(n))return ss(t);const a=n.endsWith(`
|
|
196
|
-
`)||t.startsWith(`
|
|
197
|
-
`)?"":`
|
|
198
|
-
`;return ss(`${n}${a}${t}`)}function ss(e){if(e.length<=q0)return e;const t=`
|
|
199
|
-
|
|
200
|
-
… output omitted from live view; full output remains in task history …
|
|
201
|
-
|
|
202
|
-
`,n=Math.max(0,q0-B0-t.length);return`${e.slice(0,B0)}${t}${e.slice(-n)}`}const B8=/\bopenpond\s+opchat\b/i,F8=/\b(?:50[0-9]|52[0-9]|53[0-9])\b|bad\s+gateway|gateway\s+timeout|service\s+unavailable/i;function OC(e){const t=e?.trim()||"Turn failed";return B8.test(t)&&F8.test(t)?"Server connection lost. Retry your message.":t}function V8(e,t){if((ed(t,"code")??ed(t,"errorCode"))==="opchat_quota_exceeded")return"opchat_quota_exceeded";const a=t&&typeof t=="object"?t.error:null;if(a&&typeof a=="object"&&(ed(a,"code")??ed(a,"errorCode"))==="opchat_quota_exceeded")return"opchat_quota_exceeded";const o=e??"";return/\bopchat_quota_exceeded\b/i.test(o)||/OpChat token allowance is exhausted/i.test(o)?"opchat_quota_exceeded":null}function ed(e,t){if(!e||typeof e!="object")return null;const a=e[t];return typeof a=="string"&&a.trim()?a.trim():null}function K8(e){const t=new Map,n=new Set;for(const a of e)a.turnId&&(a.role==="assistant"&&a.content?.trim()&&t.set(a.turnId,a.content),(a.role==="error"||a.role==="status_divider"&&a.statusState!=="running"||a.role==="activity_group"&&a.traceState!=="running")&&n.add(a.turnId));for(const a of e){if(a.role!=="activity_group"||!a.turnId||a.activities?.some(l=>l.subagentMessage))continue;const o=W8(a.activities??[]);if(o.length===0){a.deliverables=void 0;continue}const i=t.get(a.turnId)??"",s=i?G8(o,i):[];if(s.length>0){a.deliverables=s;continue}a.deliverables=n.has(a.turnId)?[o[o.length-1]]:void 0}}function W8(e){const t=new Set(e.map(a=>a.imagePreview?.path).filter(a=>!!a)),n=new Map;for(const a of e)if(!a.imagePreview)for(const o of a.artifacts??[])t.has(o.path)||(n.delete(o.path),n.set(o.path,o));return[...n.values()]}function G8(e,t){const n=$C(t);return e.filter(a=>Z8(a).some(o=>t.includes(o)||n.includes(o)))}function Z8(e){const t=new Set;for(const n of[e.path,e.title,J8(e.path)]){const a=n.trim();a&&(t.add(a),t.add($C(a)))}return[...t]}function J8(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).at(-1)??e}function $C(e){try{return decodeURIComponent(e)}catch{return e}}const NC=8;function Y8(e){if(e.name!=="tool.completed"||e.status==="failed")return[];if(e.action!=="web_search"&&e.action!=="web_fetch")return[];const t=_h(e.data),n=e.output?_h(Cr(e.output)):null;return Q8(t??n)}function Ih(e,t){if(t.length===0)return e;const n=[],a=new Set;for(const o of[...e??[],...t]){const i=DC(o.url);if(!(!i||a.has(i))&&(a.add(i),n.push(o),n.length>=NC))break}return n.length>0?n:void 0}function _h(e,t=0){if(t>5)return null;const n=Ce(e);if(!n)return null;const a=Array.isArray(n.results)?n.results:Array.isArray(n.items)?n.items:ve(n,["url"])?[n]:null;if(a)return{provider:ve(n,["provider"]),results:a};for(const o of["result","data","output"]){const i=_h(n[o],t+1);if(i)return i}return null}function Q8(e){if(!e)return[];const t=[],n=new Set;for(let a=0;a<e.results.length;a+=1){const o=X8(e.results[a],a,e.provider);if(!o)continue;const i=DC(o.url);if(!(!i||n.has(i))&&(n.add(i),t.push(o),t.length>=NC))break}return t}function X8(e,t,n){const a=Ce(e);if(!a)return null;const o=ve(a,["url","href"]);if(!o||!eG(o))return null;const i=ve(a,["title"])??W0(o)??`Source ${t+1}`;return{id:ve(a,["id"])??`source_${t+1}`,title:i,url:o,sourceName:ve(a,["sourceName","source_name","source"])??W0(o),snippet:ve(a,["snippet","description"]),provider:n,faviconUrl:tG(ve(a,["faviconUrl","favicon_url","iconUrl","icon_url"]))??nG(o),publishedAt:ve(a,["publishedAt","published_at"]),updatedAt:ve(a,["updatedAt","updated_at"])}}function eG(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function DC(e){try{const t=new URL(e);return t.hash="",t.toString()}catch{return null}}function tG(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 nG(e){try{return new URL("/favicon.ico",e).toString()}catch{return null}}function W0(e){try{return new URL(e).hostname.replace(/^www\./i,"")}catch{return null}}const G0=new WeakMap;function Wu(e){const t=G0.get(e);if(t)return t;const n=aG(e);return G0.set(e,n),n}function aG(e){const t=[],n=new Set,a=new Map;for(const o of e){if(o.name==="task.input"){const i=FI.safeParse(Ce(o.data)?.input);i.success&&i.data.senderKind==="user"&&i.data.kind==="steer"&&!n.has(i.data.id)&&(n.add(i.data.id),t.push({id:`task-input:${i.data.id}`,role:"user",content:i.data.body,timestamp:o.timestamp,turnId:i.data.turnId??void 0}));continue}if(o.name==="turn.started"){Id(t,o),oG(t,o);const i=lG(o.args);if(i){const s=CC(i);if(s){F0(t,{...o,name:s.kind==="turn_aborted"?"turn.interrupted":"diagnostic",output:s.text,data:{...Ce(o.data)??{},kind:s.kind}});continue}t.push({id:o.id,role:"user",content:i,attachments:cG(o.args),timestamp:o.timestamp,turnId:o.turnId});const l=J0(o.args);l&&t.push({id:`${o.id}:create-improve`,role:"assistant",timestamp:o.timestamp,turnId:o.turnId,createImproveRun:l})}continue}if(o.name==="create_improve.updated"){const i=J0(o.data);if(!i)continue;const s=Bo(t,l=>l.turnId===o.turnId&&!!l.createImproveRun);s?(s.createImproveRun=i,s.timestamp=o.timestamp):t.push({id:`${o.id}:create-improve`,role:"assistant",timestamp:o.timestamp,turnId:o.turnId,createImproveRun:i});continue}if(o.name==="assistant.delta"){const i=o.output??"";if(!i)continue;Id(t,o);const s=t[t.length-1];if(s?.role==="assistant"&&s.turnId===o.turnId&&!s.createImproveRun)s.content=`${s.content??""}${i}`,s.timestamp=o.timestamp,s.sources=Ih(s.sources,Z0(a,o.turnId)??[]);else{const l=Z0(a,o.turnId);t.push({id:o.id,role:"assistant",content:i,timestamp:o.timestamp,turnId:o.turnId,...l?.length?{sources:l}:{}})}continue}if(o.name==="assistant.reasoning.delta"){const i=o.output??"";if(!i)continue;Id(t,o);const s=t[t.length-1];s?.role==="assistant"&&s.turnId===o.turnId&&s.reasoningContent!==void 0&&!s.createImproveRun?(s.reasoningContent=`${s.reasoningContent}${i}`,s.timestamp=o.timestamp):s?.role==="assistant"&&s.turnId===o.turnId&&!s.reasoningContent&&!s.createImproveRun?(s.reasoningContent=i,s.timestamp=o.timestamp):t.push({id:o.id,role:"assistant",reasoningContent:i,timestamp:o.timestamp,turnId:o.turnId});continue}if(o.name==="user_question.asked"){const i=Ce(o.data),s=wj.safeParse(i?.question);if(!s.success)continue;t.push({id:o.id,role:"assistant",timestamp:o.timestamp,turnId:o.turnId,userQuestion:s.data});continue}if(o.name==="user_question.answered"||o.name==="user_question.dismissed"){const i=Ce(o.data),s=Ij.safeParse(i?.resolution);if(!s.success)continue;const l=Bo(t,m=>m.userQuestion?.id===s.data.questionId);if(!l?.userQuestion||l.userQuestion.status!=="pending")continue;l.userQuestion={...l.userQuestion,status:s.data.action==="answer"?"answered":"dismissed",answer:s.data.action==="answer"?{optionId:s.data.optionId,text:s.data.text}:null,answeredAt:o.timestamp},l.timestamp=o.timestamp;continue}if(o.name==="turn.completed"){kh(t,o,"completed");continue}if(o.name==="turn.failed"){kh(t,o,"failed");const i=o.error??"Turn failed",s=V8(i,o.data);t.push({id:o.id,role:"error",content:OC(i),...s?{errorKind:s}:{},timestamp:o.timestamp,turnId:o.turnId});continue}if(o.name==="turn.interrupted"){r8(t,o);continue}if(l8(o)){c8(t,o);continue}if(o.name.startsWith("harness.refiner.")){GW(t,o);continue}if(o.name==="tool.started"||o.name==="tool.completed"||o.name==="skill.selected"||o.name==="skill.loaded"||o.name==="skill.load_failed"||o.name==="command.output"||o.name==="workspace_action"||o.name==="workspace_action_result"||o.name==="approval.requested"||o.name.startsWith("subagent.")||Ku(o)){if(iG(o))continue;const i=MW(o);if(i){EW(t,o,i);continue}const s=Y8(o);s.length>0&&rG(t,a,o.turnId,s),F0(t,o)}if(o.name==="workspace.diff"){const i=sG(o.data);if(!i||i.filesChanged===0)continue;const s=Bo(t,l=>l.role==="assistant"&&l.turnId===o.turnId);s&&(s.changeSummary=i,s.timestamp=o.timestamp)}}return K8(t),t}function oG(e,t){if(Ce(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 rG(e,t,n,a){if(!n)return;const o=e[e.length-1];if(o?.role!=="assistant"||o.turnId!==n){t.set(n,Ih(t.get(n),a));return}o.sources=Ih(o.sources,a)}function Z0(e,t){if(!t)return;const n=e.get(t);return n&&e.delete(t),n}function iG(e){if(e.name!=="approval.requested")return!1;if(e.action==="create_plan")return!0;const t=Ce(e.data),n=Ce(t?.approval);return t?.kind==="create_plan"||n?.kind==="create_plan"}function sG(e){const t=DO.safeParse(e);return t.success?t.data:null}function lG(e){if(!e||typeof e!="object"||!("prompt"in e))return"";const t=e.prompt;return typeof t=="string"?t:""}function cG(e){if(!e||typeof e!="object"||!("attachments"in e))return;const t=bD.array().safeParse(e.attachments);return t.success&&t.data.length>0?t.data:void 0}function J0(e){const t=Ce(e);if(!t)return null;const n=Xl.safeParse(t.createImproveRun);return n.success?n.data:null}function pX(e){if(!e)return"";const t=new Date(e).getTime();if(Number.isNaN(t))return"";const n=Math.max(0,Math.floor((Date.now()-t)/1e3));if(n<60)return`${n}s`;const a=Math.floor(n/60);if(a<60)return`${a}m`;const o=Math.floor(a/60);return o<48?`${o}h`:`${Math.floor(o/24)}d`}function fX(e){const t=LC(e);return t?t.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):""}function hX(e){const t=LC(e);return t?t.toLocaleString():""}function LC(e){if(!e)return null;const t=new Date(e);return Number.isNaN(t.getTime())?null:t}function dG(e){const{chatMessages:t,runtimeIndexes:n,selectedSessionId:a}=e,[o,i]=v.useState({}),s=v.useCallback(m=>{i(d=>({...d,[m.sessionId]:m}))},[]);v.useEffect(()=>{i(m=>{let d=m;for(const[h,g]of Object.entries(m)){const y=Wu(vc(n,h));kC(y,g)&&(d===m&&(d={...m}),delete d[h])}return d})},[n]);const l=v.useMemo(()=>xC(t,a?o[a]:null),[t,o,a]);return{pendingChatUserMessages:o,recordPendingChatUserMessage:s,visibleChatMessages:l}}function uG({connection:e,selectedSession:t,setBootstrap:n,setError:a,setOpenPondCommandAccessMode:o,setSessions:i}){return{changeOpenPondCommandAccessMode:v.useCallback((l,m=t)=>{if(!e){a("Connect to OpenPond before saving preferences.");return}const d=m?.provider==="codex"?null:m;Q.savePreferences(e,{openPondCommandAccessMode:l}).then(h=>{o(h.preferences.openPondCommandAccessMode),n(g=>g&&{...g,preferences:h.preferences})}).catch(h=>{a(h instanceof Error?h.message:String(h))}),d&&Q.patchSession(e,d.id,{openPondCommandAccessMode:l}).then(h=>{i(g=>g.map(y=>y.id===h.id?h:y))}).catch(h=>{a(h instanceof Error?h.message:String(h))})},[e,t,n,a,o,i])}}function mG({localProjects:e,cloudProjects:t,sessions:n,runtimeIndexes:a,appPreferences:o,selectedSessionId:i,selectedProjectId:s,archivedChatsOpen:l,projectsExpanded:m,chatRowsVisibleCount:d,sidebarFileBookmarks:h=[]}){const g=v.useMemo(()=>e.filter(oe=>!oe.hiddenFromDefaultSidebar),[e]),y=v.useMemo(()=>n.filter(oe=>!oe.archived&&Y0(oe)),[n]),w=v.useMemo(()=>y.filter(oe=>oe.pinned),[y]),_=v.useMemo(()=>y.filter(oe=>!!oe.savedForLater),[y]),P=v.useMemo(()=>n.filter(oe=>oe.archived&&Y0(oe)),[n]),M=v.useMemo(()=>new Set(e.map(oe=>oe.id)),[e]),C=v.useMemo(()=>new Set(t.map(oe=>oe.id)),[t]),N=v.useMemo(()=>y_(e),[e]),$=v.useMemo(()=>{const oe={};for(const Se of[...y,...P]){const He=o0(Se,M,N,C);He&&(oe[Se.id]=He)}return oe},[y,P,C,M,N]),j=v.useMemo(()=>y.filter(oe=>!oe.pinned&&!oe.savedForLater&&!oe.appId&&!$[oe.id]),[y,$]),x=v.useMemo(()=>P.filter(oe=>!oe.appId&&!o0(oe,M,N,C)),[P,C,M,N]),R=v.useMemo(()=>{const oe={};for(const Se of y){if(Se.pinned||Se.savedForLater)continue;const He=$[Se.id];if(!He)continue;const Ze=oe[He];Ze?Ze.push(Se):oe[He]=[Se]}return oe},[y,$]),E=v.useMemo(()=>{const oe={};for(const Se of n){if(Se.archived||!UC(Se))continue;const He=oe[Se.parentSessionId];He?He.push(Se):oe[Se.parentSessionId]=[Se]}for(const Se of Object.values(oe))Se.sort((He,Ze)=>Date.parse(Ze.updatedAt)-Date.parse(He.updatedAt));return oe},[n]),U=v.useMemo(()=>g.map((oe,Se)=>{const He=yt("local",oe.id),Ze=v9(oe,t);return{id:He,kind:"local",project:oe,pinned:!!o[He]?.pinned,order:o[He]?.order??Se,cloudLinkTrusted:!Ze,cloudLinkWarning:Ze}}).sort(cf),[o,t,g]),B=v.useMemo(()=>t.map((oe,Se)=>{const He=yt("cloud",oe.id);return{id:He,kind:"cloud",project:oe,pinned:!!o[He]?.pinned,order:o[He]?.order??Se,cloudLinkTrusted:!0,cloudLinkWarning:null}}).sort(cf),[o,t]),D=v.useMemo(()=>new Set(g.map(oe=>Ca(oe,t)?.id??null).filter(oe=>!!oe)),[t,g]),W=v.useMemo(()=>B.filter(oe=>!D.has(oe.project.id)),[B,D]),se=v.useMemo(()=>[...U,...W].sort(cf),[W,U]),de=v.useMemo(()=>se.filter(oe=>oe.pinned),[se]),Me=v.useMemo(()=>h.filter(oe=>oe.status==="pinned"),[h]),ke=v.useMemo(()=>h.filter(oe=>oe.status==="saved_for_later"),[h]),te=se,Ee=v.useMemo(()=>pG(te,m,s),[te,m,s]),ye=v.useMemo(()=>[...de.map(oe=>({type:"project",key:Wr({type:"project",id:oe.id}),id:oe.id,item:oe,order:oe.order})),...w.map(oe=>({type:"session",key:Wr({type:"session",id:oe.id}),id:oe.id,session:oe,order:oe.order})),...Me.map((oe,Se)=>({type:"file",key:Wr({type:"file",id:oe.id}),id:oe.id,file:oe,order:oe.order??de.length+w.length+Se}))].sort((oe,Se)=>{if(oe.order!==Se.order)return oe.order-Se.order;if(oe.type!==Se.type){const Ke={project:0,session:1,file:2};return Ke[oe.type]-Ke[Se.type]}const He=oe.type==="project"?oe.item.project.name:oe.type==="session"?oe.session.title:oe.file.path,Ze=Se.type==="project"?Se.item.project.name:Se.type==="session"?Se.session.title:Se.file.path;return He.localeCompare(Ze)}),[Me,de,w]),ne=v.useMemo(()=>l?[...j,...x]:j,[l,x,j]),be=v.useMemo(()=>ne.slice(0,Math.max(Pn,d)),[ne,d]),ae=v.useMemo(()=>vc(a,i),[a,i]),ue=v.useMemo(()=>Wu(ae),[ae]),xe=tC(a,i),De=nC(a,i),we=a9(a,i);return{activeSessions:y,pinnedSessions:w,savedForLaterSessions:_,pinnedFiles:Me,savedForLaterFiles:ke,chatSessions:j,archivedSessions:P,pinnedProjects:de,pinnedItems:ye,projectRows:te,localProjectRows:U,visibleProjectRows:Ee,cloudProjectRows:W,projectSessionRowsByProjectId:R,childSessionRowsByParentId:E,sidebarProjectIdBySessionId:$,chatRows:ne,visibleChatRows:be,sessionEvents:ae,chatMessages:ue,contextUsage:xe,goalRuntime:De,subagentRuntime:we}}function Y0(e){return UC(e)?!1:e.hiddenFromDefaultSidebar?e.metadata?.benchmarkRuntime==="desktop_local_work":!0}function UC(e){return!!(e.parentSessionId&&e.subagentRunId)}function cf(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 pG(e,t,n){if(t||e.length<=yd)return e;const a=e.slice(0,yd);if(!n||a.some(i=>i.id===n))return a;const o=e.find(i=>i.id===n);return o?[...a.slice(0,yd-1),o]:a}function fG(e){return e.name==="turn.completed"||e.name==="turn.failed"||e.name==="turn.interrupted"}function HC(e){let t=-1,n=null;for(let a=e.length-1;a>=0;a-=1){const o=e[a];if(o?.name==="turn.started"){t=a,n=o.turnId??null;break}}if(t===-1)return"none";for(let a=e.length-1;a>t;a-=1){const o=e[a];if(!(!o||!fG(o))&&!(n&&o.turnId&&o.turnId!==n))return o.name==="turn.completed"?"completed":"blocked"}return"pending"}function Q0(e,t){if(e.systemKind)return!1;const n=vc(t,e.id);if(n.length===0)return!1;const a=HC(n);return a==="pending"||a==="none"&&zC(n)==="pending"}function X0(e,t){if(e.systemKind||e.status!=="active")return!1;const n=vc(t,e.id);if(n.length===0)return!0;const a=HC(n);return a==="pending"||a==="none"&&zC(n)!=="terminal"}function zC(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 hG({goalRuntime:e,goalRuntimeBySessionId:t,runtimeIndexes:n,selectedSession:a,selectedSessionId:o,sidebarSessions:i,subagentRuntimeBySessionId:s}){const l=v.useMemo(()=>new Map(i.map(y=>[y.id,y])),[i]),m=v.useMemo(()=>{const y=new Set;for(const[w,_]of t??[]){const P=l.get(w);_.tone==="active"&&!P?.systemKind&&y.add(w)}for(const w of n.activeGoalSessionIds)l.get(w)?.systemKind||y.add(w);return o&&!a?.systemKind&&e?.tone==="active"&&y.add(o),y},[e,t,n,a,o,l]),d=v.useMemo(()=>{const y=new Set(m);for(const[w,_]of s??[]){const P=l.get(w);_.activeCount>0&&!P?.systemKind&&y.add(w)}for(const w of n.activeSubagentSessionIds)l.get(w)?.systemKind||y.add(w);for(const w of i)w.systemKind||Q0(w,n)&&y.add(w.id);return a&&Q0(a,n)&&y.add(a.id),y},[m,n,a,i,l,s]),h=v.useMemo(()=>{const y=new Set(d);for(const w of i)X0(w,n)&&y.add(w.id);return a&&X0(a,n)&&y.add(a.id),y},[d,n,a,i]),g=!!(a&&!a.systemKind&&d.has(a.id));return{runningSessionIds:h,selectedSessionRunning:g}}const gG=1e3;function vG(e){const[t,n]=v.useState(()=>new Date().toISOString());return v.useEffect(()=>{if(!e)return;const a=()=>n(new Date().toISOString());a();const o=window.setInterval(a,gG);return()=>window.clearInterval(o)},[e]),t}function bG(e){const{codexHistoryEvents:t,codexHistorySessions:n,connection:a,expandedProjectIds:o,goalRuntime:i,locallyActiveCodexHistorySessionIds:s,pinnedSessions:l,savedForLaterSessions:m,projectSessionRowsByProjectId:d,rightChatHistoryEvents:h,runtimeIndexes:g,selectedSession:y,selectedSessionId:w,serverId:_,setCodexHistorySessions:P,sidebarSessions:M,subagentRuntime:C,visibleChatRows:N,visibleProjectRows:$}=e,[j,x]=v.useState({});v.useEffect(()=>{x({})},[_]);const R=v.useMemo(()=>{const ne=[],be=new Set,ae=xe=>{!xe||xe.id===w||!Ht(xe.id)||be.has(xe.id)||(be.add(xe.id),ne.push(xe.id))};for(const xe of n)(xe.status==="active"||s.has(xe.id))&&ae(xe);const ue=ne.length;for(const xe of $)for(const De of(d[xe.id]??[]).slice(0,2))ae(De);for(const xe of o)for(const De of(d[xe]??[]).slice(0,yd))ae(De);for(const xe of l)ae(xe);for(const xe of m)ae(xe);for(const xe of N)ae(xe);return[...ne.slice(0,ue),...ne.slice(ue,ue+8)].join(`
|
|
203
|
-
`)},[n,o,s,l,m,d,w,N,$]),E=v.useCallback(ne=>{x(be=>be[ne.session.id]===ne.events?be:{...be,[ne.session.id]:ne.events}),P(be=>Vu(be,ne.session))},[P]),U=v.useMemo(()=>{if(!R)return"";const ne=new Set(R.split(`
|
|
204
|
-
`).filter(Boolean));return M.filter(be=>ne.has(be.id)&&be.status==="active").map(be=>be.id).join(`
|
|
205
|
-
`)},[R,M]),B=v.useMemo(()=>R?R.split(`
|
|
206
|
-
`).filter(ne=>s.has(ne)).join(`
|
|
207
|
-
`):"",[R,s]);v.useEffect(()=>{!y||!w||!Ht(w)||t.length===0||E({session:y,events:t})},[E,t,y,w]),v.useEffect(()=>{if(!a||!R)return;const ne=a,be=R.split(`
|
|
208
|
-
`).filter(Boolean),ae=new Set(U.split(`
|
|
209
|
-
`).filter(Boolean)),ue=new Set(B.split(`
|
|
210
|
-
`).filter(Boolean)),xe=be.map(De=>Ov({connection:ne,locallyActive:ue.has(De),onPayload:we=>E(jv(we,ue.has(De))),reportedActive:ae.has(De),sessionId:De,surface:"sidebar"}));return()=>xe.forEach(De=>De())},[E,U,B,R,a]);const D=v.useMemo(()=>new Map(M.map(ne=>[ne.id,ne])),[M]),W=v.useMemo(()=>{const ne=new Map(g.latestGoalRuntimeBySessionId);for(const be of M){const ae=be.status==="active"?tf(be.metadata):null;ae&&ne.set(be.id,ae)}for(const be of[j,h])for(const[ae,ue]of Object.entries(be)){const xe=D.get(ae),De=xe?.status==="active"?tf(xe.metadata):null,we=ph(ue)??Av(ue)??(xe?.status==="active"?Yd(ue)??De:null);we?ne.set(ae,we):ne.delete(ae)}if(w)if(i)ne.set(w,i);else if(y?.status==="active"&&t.length>0){const be=ph(t)??Yd(t)??tf(y.metadata);be?ne.set(w,be):ne.delete(w)}else(!Ht(w)||t.length>0)&&ne.delete(w);return ne},[t.length,j,i,h,g.latestGoalRuntimeBySessionId,y?.status,y?.metadata,w,D,M]),se=v.useMemo(()=>[...W.values()].some(ne=>ne.tone==="active"&&!!ne.observedAt),[W]),de=vG(se),Me=v.useMemo(()=>se?new Map([...W].map(([ne,be])=>[ne,jK(be,de)??be])):W,[W,de,se]),ke=w?Me.get(w)??i:i,te=v.useMemo(()=>{const ne=new Map(g.latestSubagentRuntimeBySessionId);return w&&(C?ne.set(w,C):ne.delete(w)),ne},[g.latestSubagentRuntimeBySessionId,w,C]),{runningSessionIds:Ee,selectedSessionRunning:ye}=hG({goalRuntime:ke,goalRuntimeBySessionId:Me,runtimeIndexes:g,selectedSession:y,selectedSessionId:w,sidebarSessions:M,subagentRuntimeBySessionId:te});return{goalRuntime:ke,runningSessionIds:Ee,selectedSessionRunning:ye,sidebarGoalRuntimeBySessionId:Me,sidebarSubagentRuntimeBySessionId:te}}function yG({searchOpen:e,sectionMenuOpen:t,setSectionMenuOpen:n,setSearchOpen:a,setQuery:o}){v.useEffect(()=>{const i=s=>{if((s.metaKey||s.ctrlKey)&&s.key.toLowerCase()==="k"){s.preventDefault(),n(null),a(l=>!l);return}if(s.key==="Escape"&&e){s.preventDefault(),a(!1),o(""),n(null);return}s.key==="Escape"&&t&&(s.preventDefault(),n(null))};return document.addEventListener("keydown",i),()=>document.removeEventListener("keydown",i)},[e,t,o,a,n])}function SG({afterSequence:e,appendEvents:t,connection:n,setApprovals:a,setSessions:o,setError:i,onDisconnected:s}){v.useEffect(()=>{if(!n?.token||e===null)return;const l=n;let m=null,d=[],h=null,g=null,y=!1;const w=new Map;let _=0;const P=16;function M(){m!==null&&(window.clearTimeout(m),m=null)}function C(){i(D=>D==="Event stream disconnected"?null:D)}function N(){h=null;const D=d;if(d=[],D.length===0)return;_=Date.now(),t(D);const W=xG(D);W.length>0&&o(se=>W.reduce(fl,se)),a(se=>{let de=se;for(const Me of D)if(Me.name==="approval.requested"&&Me.data&&(de=[Me.data,...de]),Me.name==="approval.resolved"&&Me.data&&typeof Me.data=="object"){const ke=Me.data;ke.approvalId&&(de=de.filter(te=>te.id!==ke.approvalId))}return de})}function $(){const D=Date.now()-_;if(D>=P){h!==null&&(window.clearTimeout(h),h=null),N();return}h===null&&(h=window.setTimeout(N,P-D))}function j(D){x(D),d.push(D),$()}function x(D){if(!(!D.sessionId||!D.name.startsWith("harness.refiner."))){if(D.name==="harness.refiner.completed"||D.name==="harness.refiner.failed"){w.delete(D.sessionId);return}(D.name==="harness.refiner.queued"||D.name==="harness.refiner.started")&&(w.set(D.sessionId,typeof D.sequence=="number"?D.sequence:0),R())}}function R(){g!==null||w.size===0||(g=window.setTimeout(()=>{g=null,E()},1e3))}async function E(){if(!(y||w.size===0)){y=!0;try{await Promise.all([...w].map(async([D,W])=>{const se=await Q.runtimeEventsPage(l,{sessionId:D,afterSequence:W,limit:100});for(const de of se.events){const Me=de.event;w.set(D,Math.max(w.get(D)??0,de.sequence)),j(Me)}}))}catch{}finally{y=!1,R()}}}function U(){h!==null&&(window.clearTimeout(h),h=null),N()}document.addEventListener("visibilitychange",U);const B=X4(n,D=>{M(),C(),j(D)},()=>{M(),m=window.setTimeout(()=>{B.isOpen()||(i("Event stream disconnected"),s?.())},2e3)},()=>{M(),C(),window.dispatchEvent(new Event("openpond-runtime-connected"))},{afterSequence:e});return()=>{M(),h!==null&&window.clearTimeout(h),g!==null&&window.clearTimeout(g),h=null,g=null,d=[],document.removeEventListener("visibilitychange",U),B.close()}},[e,t,n,s,a,i,o])}function xG(e){const t=new Map;for(const n of e){const a=n.data;if(!a||typeof a!="object"||Array.isArray(a))continue;const o=n.name==="session.started"||n.name==="session.title.updated"?"session":n.name==="subagent.started"||n.name==="subagent.failed"?"childSession":null;if(!o)continue;const i=El.safeParse(a[o]);i.success&&t.set(i.data.id,i.data)}return[...t.values()]}function df(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function kG(e){return typeof e=="string"&&e.trim()?e.trim():null}function wG(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n.name!=="create_improve.updated")continue;const a=df(n.data),o=df(a?.createImproveRun);if(o?.state!=="ready_local"&&o?.state!=="released"||df(o.adapter)?.kind!=="local")continue;const s=kG(o.id)??n.id;return[n.sessionId??"global",n.turnId??"turn",s].join(":")}return null}const IG=332,eS=244,tS=560,_G=560,nS=320,aS=2400,CG=440;function uf(e){const t=typeof window>"u"?tS:Math.min(tS,Math.max(eS,window.innerWidth-420));return Math.min(t,Math.max(eS,Math.round(e)))}function mf(e){const t=typeof window>"u"?aS:Math.min(aS,Math.max(nS,window.innerWidth-CG));return Math.min(t,Math.max(nS,Math.round(e)))}function RG(e,t){return!!(e&&e.serverUrl===t.serverUrl&&e.token===t.token&&e.platform===t.platform)}const Qi=new Map;function Nv(e,t){const n=e?.trim();return n?`${t?.trim()||"global"}|${n}`:null}function qC(e,t){const n=Nv(e,t);if(!n)return null;const a=Qi.get(n);return a?.updatedAt?a.agents:null}function PG(e,t,n){const a=Nv(e,n);a&&Qi.set(a,{agents:t,promise:null,updatedAt:Date.now()})}function Dv(e){const t=e.teamId?.trim();if(!t)return Promise.resolve([]);const n=Nv(t,e.accountKey);if(!n)return Promise.resolve([]);const a=Qi.get(n);if(!e.force){if(a?.updatedAt)return Promise.resolve(a.agents);if(a?.promise)return a.promise}const o=e.fetchAgents(t).then(i=>(PG(t,i,e.accountKey),i)).catch(i=>{const s=Qi.get(n);throw s?.promise===o&&Qi.set(n,{agents:s.agents,promise:null,updatedAt:s.updatedAt}),i});return Qi.set(n,{agents:a?.agents??[],promise:o,updatedAt:a?.updatedAt??0}),o}const AG=6e4,TG=6e4,EG=6e4,Lv=["pinned","projects","cloudProjects","chats","savedForLater"];function MG(e,t,n,a=Date.now()){for(const o of NG(t,n))BC(t[o],n[o])||(e[o]=a)}function jG(e,t,n,a=Date.now()){const o={...t};for(const[i,s]of Object.entries(n)){if(a-s>AG){delete n[i];continue}const l=LG(e,i),m=e[i];!l||BC(m,t[i])||(o[i]=m)}return o}function OG(e,t,n,a=Date.now()){for(const o of Lv)t[o]!==n[o]&&(e[o]=a)}function $G(e,t,n,a=Date.now()){const o={...t};for(const i of Lv){const s=n[i];if(s!==void 0){if(a-s>TG){delete n[i];continue}if(e[i]===t[i]){delete n[i];continue}o[i]=e[i]}}return DG(e,o)?e:o}function oS(e,t,n=Date.now()){return e===t?null:{value:t,changedAt:n}}function rS(e,t,n=Date.now()){return t?n-t.changedAt>EG?{value:e,localChange:null}:e===t.value?{value:e,localChange:t}:{value:t.value,localChange:t}:{value:e,localChange:null}}function NG(e,t){return new Set([...Object.keys(e),...Object.keys(t)])}function BC(e,t){return e?.pinned===t?.pinned&&e?.archived===t?.archived&&e?.order===t?.order}function DG(e,t){return Lv.every(n=>e[n]===t[n])}function LG(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const UG=5e4,hr="\0openpond-unscoped-runtime-events",ao=[];class HG{perSessionLimit;totalLimit;entries=new Map;eventKeyById=new Map;listenersByKey=new Map;allListeners=new Set;summaryListeners=new Set;retainedKeys=new Set;allEventsSnapshot=ao;summaryEventsSnapshot=ao;clock=0;eventCount=0;constructor(t={}){if(this.perSessionLimit=lS(t.perSessionLimit??Pv,"perSessionLimit"),this.totalLimit=lS(t.totalLimit??UG,"totalLimit"),this.totalLimit<this.perSessionLimit)throw new Error("totalLimit must be greater than or equal to perSessionLimit")}append(t){if(t.length===0)return sS();const n=new Map;let a=0;for(const d of t){if(this.eventKeyById.has(d.id)){a+=1;continue}const h=d.sessionId||hr,g=n.get(h);g?g.push(d):n.set(h,[d]),this.eventKeyById.set(d.id,h)}if(n.size===0)return{...sS(),duplicateEventCount:a};const o=new Set;let i=0,s=0,l=!1;for(const[d,h]of n){h.some(cS)&&(l=!0);const g=this.entries.get(d),y=g?.snapshot.events??ao,w=Math.max(0,Math.min(y.length,this.perSessionLimit-h.length)),_=h.length>this.perSessionLimit?h.slice(h.length-this.perSessionLimit):h,P=w===y.length?y:y.slice(y.length-w),M=P.length===0?_:[...P,..._],C=y.slice(0,y.length-P.length);C.some(cS)&&(l=!0);for(const j of C)this.eventKeyById.delete(j.id);for(const j of h.slice(0,h.length-_.length))this.eventKeyById.delete(j.id);const $={eventIds:new Set(M.map(j=>j.id)),lastTouched:++this.clock,retained:g?.retained??this.retainedKeys.has(d),snapshot:{events:M,latestSequence:Jd(M),revision:(g?.snapshot.revision??0)+1}};this.entries.set(d,$),this.eventCount+=M.length-y.length,i+=_.length,s+=C.length+h.length-_.length,o.add(d)}const m=this.enforceTotalLimit(o);return s+=m,this.publish(o,l||m>0),qG({acceptedEventCount:i,duplicateEventCount:a,evictedEventCount:s,changedKeys:o})}mergeBootstrap(t){const n=zG(t),a=new Set([...this.entries.keys(),...n.keys()]),o=[];for(const i of a){const s=n.get(i)??ao,l=this.entries.get(i)?.snapshot.events??ao;o.push(...CK(s,l))}return this.replace(o)}replace(t){const n=new Set(this.eventKeyById.keys()),a=new Set(this.entries.keys());this.entries.clear(),this.eventKeyById.clear(),this.eventCount=0,this.allEventsSnapshot=ao,this.summaryEventsSnapshot=ao;const o=this.append(t);for(const m of this.retainedKeys){const d=this.entries.get(m);d&&(d.retained=!0)}const i=this.eventKeyById;let s=0;for(const m of n)i.has(m)||(s+=1);const l=new Set([...a].filter(m=>!this.entries.has(m)));return l.size>0&&this.publish(l,!0),{...o,evictedEventCount:o.evictedEventCount+s,changedSessionIds:new Set([...o.changedSessionIds,...[...l].filter(m=>m!==hr)]),unscopedEventsChanged:o.unscopedEventsChanged||l.has(hr)}}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=ao,this.summaryEventsSnapshot=ao,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??iS:iS;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(BG),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!==hr&&a.retained&&(t+=1);return{eventCount:this.eventCount,retainedSessionCount:t,sessionCount:this.entries.size-(this.entries.has(hr)?1:0),perSessionLimit:this.perSessionLimit,totalLimit:this.totalLimit}}subscribeAll=t=>(this.allListeners.add(t),()=>this.allListeners.delete(t));subscribeSummary=t=>(this.summaryListeners.add(t),()=>this.summaryListeners.delete(t));subscribeSession(t,n){let a=this.listenersByKey.get(t);return a||(a=new Set,this.listenersByKey.set(t,a)),a.add(n),()=>{a?.delete(n),a?.size===0&&this.listenersByKey.delete(t)}}enforceTotalLimit(t){let n=0;for(;this.eventCount>this.totalLimit&&this.entries.size>0;){const a=this.oldestEvictionCandidate(!1)??this.oldestEvictionCandidate(!0);if(!a)break;const[o,i]=a,s=this.eventCount-this.totalLimit;if(!i.retained||i.snapshot.events.length<=s){n+=i.snapshot.events.length,this.removeEntry(o),t.add(o);continue}const l=i.snapshot.events.slice(0,s),m=i.snapshot.events.slice(s);for(const d of l)this.eventKeyById.delete(d.id);i.eventIds=new Set(m.map(d=>d.id)),i.snapshot={events:m,latestSequence:Jd(m),revision:i.snapshot.revision+1},this.eventCount-=l.length,n+=l.length,t.add(o)}return n}oldestEvictionCandidate(t){let n=null;for(const a of this.entries)!t&&a[1].retained||(!n||a[1].lastTouched<n[1].lastTouched)&&(n=a);return n}removeEntry(t){const n=this.entries.get(t);if(n){for(const a of n.snapshot.events)this.eventKeyById.delete(a.id);this.eventCount-=n.snapshot.events.length,this.entries.delete(t)}}publish(t,n=!1){if(t.size!==0){this.allEventsSnapshot=null,n&&(this.summaryEventsSnapshot=null);for(const a of t)for(const o of this.listenersByKey.get(a)??[])o();for(const a of this.allListeners)a();if(n)for(const a of this.summaryListeners)a()}}}const iS=Object.freeze({events:ao,latestSequence:null,revision:0});function zG(e){const t=new Map;for(const n of e){const a=n.sessionId||hr,o=t.get(a);o?o.push(n):t.set(a,[n])}return t}function qG(e){return{acceptedEventCount:e.acceptedEventCount,duplicateEventCount:e.duplicateEventCount,evictedEventCount:e.evictedEventCount,changedSessionIds:new Set([...e.changedKeys].filter(t=>t!==hr)),unscopedEventsChanged:e.changedKeys.has(hr)}}function sS(){return{acceptedEventCount:0,duplicateEventCount:0,evictedEventCount:0,changedSessionIds:new Set,unscopedEventsChanged:!1}}function BG(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 lS(e,t){if(!Number.isInteger(e)||e<=0)throw new Error(`${t} must be a positive integer`);return e}function cS(e){return e.name!=="assistant.delta"&&e.name!=="assistant.reasoning.delta"&&e.name!=="command.output"}const FG=256,VG=15e3,KG=5e3,WG=3e4;class GG{constructor(t={}){this.options=t}options;entries=new Map;connection=null;accountScope=null;generation=0;activateConnection(t){ZG(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,JG(this.entries,t,a),a.state==="ready"?a.url:null):null}load(t,n){const a=this.get(t);if(a)return Promise.resolve(a);const o=this.now(),i=this.entries.get(t);if(i?.state==="loading"&&!this.expired(i,o))return i.promise;if(i?.state==="failed"&&!this.expired(i,o))return Promise.resolve(null);const s=this.generation,l=n().then(m=>this.generation!==s?null:(this.entries.set(t,{state:"ready",url:m.url,expiresAt:m.expiresAt,lastAccessedAt:this.now()}),this.prune(),m.url)).catch(()=>{if(this.generation!==s)return null;const m=this.now();return this.entries.set(t,{state:"failed",expiresAt:m+(this.options.failureTtlMs??KG),lastAccessedAt:m}),this.prune(),null});return this.entries.set(t,{state:"loading",promise:l,expiresAt:o+(this.options.loadingTtlMs??WG),lastAccessedAt:o}),this.prune(),l}clear(){this.generation+=1,this.entries.clear()}size(){return this.prune(),this.entries.size}prune(){const t=this.now();for(const[a,o]of this.entries)this.expired(o,t)&&this.entries.delete(a);const n=this.options.maxEntries??FG;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??VG:0;return t.expiresAt<=n+a}now(){return(this.options.now??Date.now)()}}const dS=new GG;function gX(e,t,...n){return[t,e.serverUrl,...n].join("\0")}function ZG(e,t){return e?.serverUrl===t?.serverUrl&&e?.token===t?.token&&e?.platform===t?.platform}function JG(e,t,n){e.delete(t),e.set(t,n)}const YG={connecting:"Connecting to OpenPond",account:"Loading account",team:"Loading default team",ready:"Ready"};function QG(e){return{label:YG[e],ready:e==="ready",stage:e}}const XG=650,e7=1200,t7=6e4;function n7(e){const{setDraftModel:t,setDraftProvider:n,setCodexPermissionMode:a,setCodexReasoningEffort:o,setOpenPondCommandAccessMode:i,setError:s,setSelectedAppId:l,setSelectedProjectId:m,setSelectedSessionId:d}=e,[h,g]=v.useState(null),[y,w]=v.useState(null),[_]=v.useState(()=>new HG),P=v.useSyncExternalStore(_.subscribeSummary,_.getSummaryEvents,_.getSummaryEvents),M=v.useCallback(O=>{const z=_.getAllEvents(),X=typeof O=="function"?O(z):O;X!==z&&_.replace(X)},[_]),C=v.useCallback(O=>{_.append(O)},[_]),[N,$]=v.useState(null),[j,x]=v.useState([]),[R,E]=v.useState([]),[U,B]=v.useState([]),[D,W]=v.useState({}),[se,de]=v.useState("connecting"),Me=gh(y?.account),ke=v.useRef({}),te=v.useRef({}),Ee=v.useRef({}),ye=v.useRef([]),ne=v.useRef([]),be=v.useRef(null),ae=v.useRef(null),ue=v.useRef(!1),xe=v.useRef(Date.now()),De=v.useRef(null),we=v.useRef(null);v.useEffect(()=>{dS.activateConnection(h),dS.activateAccountScope(Me)},[h,Me]);const oe=v.useCallback(O=>{ue.current||de(O)},[]),Se=v.useCallback(O=>{W(z=>{const X=typeof O=="function"?O(z):O;return MG(ke.current,z,X),X})},[]),He=v.useCallback(O=>{x(z=>{const X=typeof O=="function"?O(z):O;return N0(te.current,z,X),ye.current=X,X})},[]),Ze=v.useCallback(O=>{E(z=>{const X=typeof O=="function"?O(z):O;return N0(Ee.current,z,X),ne.current=X,X})},[]),Ke=v.useCallback(()=>{if(ue.current||De.current!==null)return;const O=()=>{De.current=null,!ue.current&&(ue.current=!0,de("ready"))},z=Date.now()-xe.current,X=a7(z);if(X===0){O();return}De.current=window.setTimeout(O,X)},[]);v.useEffect(()=>()=>{De.current!==null&&window.clearTimeout(De.current)},[]);const tt=v.useCallback(O=>{const z=be.current,X=!z||z===O.server.id;be.current=O.server.id,$(me=>me?.serverId===O.server.id?me:{afterSequence:O.eventWindow?.latestSequence??Jd(O.events)??0,serverId:O.server.id}),w(O),X?_.mergeBootstrap(O.events):_.replace(O.events),x(me=>{const $e=X?$0(me,O.sessions,te.current):vh(me,O.sessions,te.current);return ye.current=$e,$e}),E(me=>{const $e=X?$0(me,O.codexHistorySessions??[],Ee.current):vh(me,O.codexHistorySessions??[],Ee.current);return ne.current=$e,$e}),B(O.approvals),W(me=>jG(me,O.sidebarAppPreferences,ke.current)),l(me=>me&&O.apps.some($e=>$e.id===me)?me:null),m(me=>{if(!me)return null;const $e=p_(me);return $e?.kind==="local"&&O.localProjects.some(Le=>Le.id===$e.id)?yt("local",$e.id):$e?.kind==="cloud"&&(O.cloudProjects??[]).some(Le=>Le.id===$e.id)?yt("cloud",$e.id):O.localProjects.some(Le=>Le.id===me)?yt("local",me):(O.cloudProjects??[]).some(Le=>Le.id===me)?yt("cloud",me):null}),d(me=>{if(!me)return null;const $e=[...O.sessions,...O.codexHistorySessions??[]];if($e.some(nt=>nt.id===me&&!nt.archived))return me;if(!X)return null;const Le=ye.current.find(nt=>nt.id===me)??ne.current.find(nt=>nt.id===me)??null;return Le&&!Le.archived&&fC(Le,$e)?me:null})},[_,l,m,d]),qe=v.useCallback(O=>{w(z=>z&&{...z,preferences:O.preferences})},[]);v.useEffect(()=>{const O=ba(y?.preferences);n(O.defaultChatProvider),t(O.defaultChatModel)},[y?.preferences.defaultChatProvider,y?.preferences.defaultChatModel,t,n]),v.useEffect(()=>{a(ba(y?.preferences).codexPermissionMode)},[y?.preferences.codexPermissionMode,a]),v.useEffect(()=>{o(ba(y?.preferences).codexReasoningEffort)},[y?.preferences.codexReasoningEffort,o]),v.useEffect(()=>{i(ba(y?.preferences).openPondCommandAccessMode)},[y?.preferences.openPondCommandAccessMode,i]),v.useEffect(()=>{if(!h||!y){ae.current=null;return}if(y.account.state!=="signed_in"){ae.current=null,Ke();return}const O=gh(y.account);if(!O){ae.current=null,Ke();return}Ke(),oe("team");const z=y.preferences.defaultTeamId?.trim()??"",X=o7(O,z,y.accountMeta.asOf??"initial");if(ae.current===X)return;ae.current=X;let me=!1;const $e=Le=>Dv({teamId:Le,accountKey:O,fetchAgents:async nt=>(await Q.listSandboxAgents(h,{teamId:nt})).agents}).catch(()=>{!me&&ae.current===X&&(ae.current=null)});return R0({accountKey:O,force:!0,fetchOrganizations:()=>uS(h)}).then(async Le=>{if(me)return;if(Le.length===0){Ke();return}if(!!z&&Le.some(lt=>lt.teamId===z)){await $e(z),Ke();return}const at=T9(Le)?.teamId;if(!at){Ke();return}if(z){s("The configured default team is unavailable for this account. Select an available team in account settings."),Ke();return}await $e(at),me||Ke()}).catch(Le=>{me||(ae.current=null,s(Le instanceof Error?Le.message:String(Le)),Ke())}),()=>{me=!0}},[tt,qe,y?.account,y?.accountMeta.asOf,y?.preferences.defaultTeamId,Ke,h,oe,s]),v.useEffect(()=>{if(!h||!Me)return;let O=!1;const z=()=>{O||(O=!0,R0({accountKey:Me,force:!0,fetchOrganizations:()=>uS(h)}).catch(()=>{}).finally(()=>{O=!1}))},X=()=>{document.visibilityState==="visible"&&z()},me=window.setInterval(z,t7);return window.addEventListener("focus",z),document.addEventListener("visibilitychange",X),()=>{window.clearInterval(me),window.removeEventListener("focus",z),document.removeEventListener("visibilitychange",X)}},[h,Me]),fc(()=>{const O=X3();s(O||(z=>z?.startsWith("Preference changes have not been saved.")?null:z))}),v.useEffect(()=>{h&&t0(h).catch(O=>s(String(O)))},[h,Me,s]);const Ge=v.useCallback(async()=>{oe("connecting"),$(null);const O=await x5();g(X=>RG(X,O)?X:O),oe("account");const z=await Q.bootstrap(O);await t0(O),tt(z),Ke(),s(X=>X&&($_(X)||X==="Event stream disconnected")?null:X)},[tt,Ke,oe,s]);v.useEffect(()=>{let O=!1,z=null;const X=async me=>{try{await Ge()}catch($e){if(O)return;s($e instanceof Error?$e.message:String($e));const Le=Math.min(5e3,750+me*750);z=window.setTimeout(()=>{X(me+1)},Le)}};return X(0),()=>{O=!0,z!==null&&window.clearTimeout(z)}},[Ge,s]);const ze=v.useCallback(()=>{Ge().catch(()=>{})},[Ge]);SG({afterSequence:N?.afterSequence??null,appendEvents:C,connection:h,setApprovals:B,setSessions:He,setError:s,onDisconnected:ze}),v.useEffect(()=>{if(!h||!y){we.current=null;return}const O=wG(P);!O||we.current===O||(we.current=O,Q.profileCurrent(h).then(z=>{w(X=>X&&{...X,profile:z})}).catch(z=>{we.current=null,s(z instanceof Error?z.message:String(z))}))},[y,h,P,s]);const L=v.useCallback(()=>{h&&Q.refreshOpenPondAccount(h).then(({account:O,accountMeta:z})=>{w(X=>X&&{...X,account:O,accountMeta:z})}).catch(O=>s(O instanceof Error?O.message:String(O)))},[h,s]);return{appPreferences:D,applyBootstrapPayload:tt,approvals:U,bootstrap:y,codexHistorySessions:R,connection:h,events:P,runtimeEventStore:_,refreshOpenPondAccount:L,sessions:j,startup:QG(se),setAppPreferences:Se,setBootstrap:w,setCodexHistorySessions:Ze,setEvents:M,setSessions:He}}async function uS(e){return(await Q.organizations(e)).organizations.map(Fu).filter(n=>!!n).filter(n=>n.status==="active")}function a7(e){return e>=e7?0:Math.max(0,XG-e)}function o7(e,t,n){return`${e}::${t||"none"}::${n}`}function r7({appDispatch:e,error:t,setErrorState:n}){const a=v.useRef(null),o=v.useRef(null),i=v.useRef(null),s=v.useRef(0),l=v.useCallback((d,h="info",g={})=>{const y=Date.now()+ ++s.current;return e({type:"showToast",toast:{id:y,message:d,tone:h,...g}}),y},[e]),m=v.useCallback(d=>{const h=o.current,g=typeof d=="function"?d(h):d;if(Object.is(h,g))return;if(o.current=g,n(g),!g){i.current!==null&&(e({type:"clearToast",toastId:i.current}),i.current=null);return}i.current=l(i7(g),"error");const y=a.current;y&&Q.recordClientDiagnostic(y,{message:g,surface:"app",context:{href:window.location.href}}).catch(w=>{console.warn("Unable to record client diagnostic.",w)})},[e,n,l]);return v.useEffect(()=>{o.current=t,!(t||i.current===null)&&(e({type:"clearToast",toastId:i.current}),i.current=null)},[e,t]),{connectionRef:a,setError:m,showToast:l}}function i7(e){return O_(e)}const s7={query:"",searchOpen:!1,archivedChatsOpen:!1,sectionMenuOpen:null,projectsExpanded:!1,cloudProjectsExpanded:!1,chatRowsVisibleCount:Pn,sidebarOpen:!0,view:"chat",selectedAppId:null,selectedProjectId:null,selectedSessionId:null,prompt:"",promptDrafts:{},draftProvider:Qr,draftModel:Pl,draftExperience:"chat",codexPermissionMode:ng,codexReasoningEffort:ag,openPondCommandAccessMode:du,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 Uv(e){return e.selectedSessionId?`session:${e.selectedSessionId}`:e.selectedProjectId?`project:${e.selectedProjectId}`:e.selectedAppId?`app:${e.selectedAppId}`:`new-${e.draftExperience}`}function Xd(e,t,n){if(!n){if(!(t in e))return e;const{[t]:a,...o}=e;return o}return e[t]===n?e:{...e,[t]:n}}function l7(e){return Xd(e.promptDrafts,Uv(e),e.prompt)}function rl(e,t,n={}){const a={...e,...t},o=Uv(a),i=l7(e),s=n.clearSelectedDraft?Xd(i,o,""):n.preserveCurrentPrompt?Xd(i,o,e.prompt):i;return{...e,...t,promptDrafts:s,prompt:n.clearSelectedDraft?"":n.preserveCurrentPrompt?e.prompt:s[o]??""}}function c7(e){return e==="draftExperience"||e==="selectedAppId"||e==="selectedProjectId"||e==="selectedSessionId"}function d7(e,t){switch(t.type){case"field":{const n=e[t.key],a=typeof t.value=="function"?t.value(n):t.value;if(Object.is(n,a))return e;if(t.key==="prompt"){const o=String(a);return{...e,prompt:o,promptDrafts:Xd(e.promptDrafts,Uv(e),o)}}return c7(t.key)?rl(e,{[t.key]:a}):{...e,[t.key]:a}}case"patch":return{...e,...t.patch};case"selectApp":return rl(e,{selectedAppId:t.appId,selectedProjectId:null,selectedSessionId:null,view:"chat"});case"selectProject":return rl(e,{selectedAppId:null,selectedProjectId:t.projectId,selectedSessionId:null,view:"chat"},{preserveCurrentPrompt:!0});case"selectSession":{const n=t.projectId??null;return rl(e,{selectedSessionId:t.sessionId,selectedAppId:n?null:t.appId??null,selectedProjectId:n,view:"chat"})}case"beginNewChat":return rl(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 u7(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 il(e){return e.selectedSessionId?`session:${e.selectedSessionId}`:e.selectedProjectId?`project:${e.selectedProjectId}`:e.selectedAppId?`app:${e.selectedAppId}`:"new-chat"}function m7(e={selectedAppId:null,selectedProjectId:null,selectedSessionId:null}){let t=e,n="";const a=new Map,o=new Set,i=d=>{if(!Object.is(n,d)){n=d;for(const h of o)h()}},s=()=>{const d=il(t);n?a.set(d,n):a.delete(d)},l=(d,h={})=>{const g=n;s(),t={...t,...d};const y=il(t);if(h.clear&&a.delete(y),h.preserveCurrentDraft){g?a.set(y,g):a.delete(y),i(g);return}i(h.clear?"":a.get(y)??"")},m={getScopeKey:()=>il(t),getSnapshot:()=>n,subscribe(d){return o.add(d),()=>o.delete(d)},set:d=>m.setForScope(il(t),d),setForScope(d,h){const g=il(t),y=d===g?n:a.get(d)??"",w=typeof h=="function"?h(y):h;Object.is(y,w)||(w?a.set(d,w):a.delete(d),d===g&&i(w))},applyAppAction(d){if(d.type==="field"){if(d.key==="prompt"){m.set(d.value);return}if(d.key==="selectedAppId"||d.key==="selectedProjectId"||d.key==="selectedSessionId"){const h=t[d.key],g=typeof d.value=="function"?d.value(h):d.value;Object.is(h,g)||l({[d.key]:g})}return}if(d.type==="patch"){const h={};"selectedAppId"in d.patch&&(h.selectedAppId=d.patch.selectedAppId),"selectedProjectId"in d.patch&&(h.selectedProjectId=d.patch.selectedProjectId),"selectedSessionId"in d.patch&&(h.selectedSessionId=d.patch.selectedSessionId),Object.keys(h).length>0&&l(h),"prompt"in d.patch&&typeof d.patch.prompt=="string"&&m.set(d.patch.prompt);return}if(d.type==="selectApp"){l({selectedAppId:d.appId,selectedProjectId:null,selectedSessionId:null});return}if(d.type==="selectProject"){l({selectedAppId:null,selectedProjectId:d.projectId,selectedSessionId:null},{preserveCurrentDraft:!0});return}if(d.type==="selectSession"){const h=d.projectId??null;l({selectedSessionId:d.sessionId,selectedAppId:h?null:d.appId??null,selectedProjectId:h});return}d.type==="beginNewChat"&&l({selectedSessionId:null,selectedAppId:d.appId,selectedProjectId:null})}};return m}function vX(e){return v.useSyncExternalStore(e.subscribe,e.getSnapshot,e.getSnapshot)}function p7(e){return{...e,draftExperience:Ev()}}function f7(){const[e,t]=v.useReducer(d7,s7,p7),[n]=v.useState(()=>m7()),a=v.useCallback(i=>{n.applyAppAction(i),t(i)},[n]),o=v.useMemo(()=>({...u7(a),setPrompt:n.set}),[n,a]);return fc(()=>o.setDraftExperience(Ev())),{composerDraftStore:n,dispatch:a,setters:o,state:e}}function h7(e){return!!(e&&e.includes("Git is required for OpenPond app workspaces")&&e.includes("Command Line Tools"))}function g7(e){const{connection:t,events:n,showToast:a}=e,o=v.useRef(new Set),i=v.useCallback(async()=>{if(t)try{const l=await Q.installMacOSCommandLineTools(t);a(l.message,"info")}catch(l){a(l instanceof Error?l.message:String(l),"error")}},[t,a]),s=v.useCallback((l="OpenPond needs Git to create and sync local projects.")=>{a(l,"error",{actionLabel:"Install Tools",onAction:()=>{i()},persistent:!0})},[a,i]);v.useEffect(()=>{if(!t)return;let l=!1;return Q.gitAvailability(t).then(m=>{l||m.ok||m.installAction!=="macos_command_line_tools"||s("OpenPond needs Git before it can create local projects.")}).catch(()=>{}),()=>{l=!0}},[t,s]),v.useEffect(()=>{for(const l of n){if(o.current.has(l.id))continue;const m=l.error??l.output??null;l.name==="workspace_action_result"&&l.status==="failed"&&h7(m)&&(o.current.add(l.id),s("OpenPond needs Git before it can update this project."))}},[n,s])}function v7({connection:e,preferences:t,sidebarOpen:n,diffPanelExpanded:a,setBootstrap:o,setError:i}){const[s,l]=v.useState(()=>ba().sidebarSectionsCollapsed),m=v.useRef(s),d=v.useRef({}),h=v.useRef(null),g=v.useRef(null),[y,w]=v.useState(IG),[_,P]=v.useState(!1),[M,C]=v.useState(_G),[N,$]=v.useState(!1),{pinned:j,projects:x,cloudProjects:R,chats:E,savedForLater:U}=s;v.useEffect(()=>{if(_)return;const ae=uf(ba(t).sidebarWidth),ue=rS(ae,h.current);h.current=ue.localChange,w(ue.value)},[t,_]),v.useEffect(()=>{if(N)return;const ae=mf(ba(t).diffPanelWidth),ue=rS(ae,g.current);g.current=ue.localChange,C(ue.value)},[N,t]),v.useEffect(()=>{const ae=ba(t).sidebarSectionsCollapsed;l(ue=>{const xe=$G(ue,ae,d.current);return m.current=xe,xe})},[t]);const B=v.useCallback(ae=>{o(ue=>ue&&{...ue,preferences:ae.preferences})},[o]),D=v.useCallback(async ae=>{if(e&&uf(ba(t).sidebarWidth)!==ae)try{B(await Q.savePreferences(e,{sidebarWidth:ae}))}catch(ue){i(ue instanceof Error?ue.message:String(ue))}},[e,t,i,B]),W=v.useCallback(async ae=>{if(e&&mf(ba(t).diffPanelWidth)!==ae)try{B(await Q.savePreferences(e,{diffPanelWidth:ae}))}catch(ue){i(ue instanceof Error?ue.message:String(ue))}},[e,t,i,B]),se=v.useCallback(async ae=>{if(!e)return;const ue=ba(t).sidebarSectionsCollapsed;if(!b7(ue,ae))try{B(await Q.savePreferences(e,{sidebarSectionsCollapsed:ae}))}catch(xe){i(xe instanceof Error?xe.message:String(xe))}},[e,t,i,B]),de=v.useCallback(ae=>{const ue=m.current;OG(d.current,ue,ae),m.current=ae,l(ae),se(ae)},[se]),Me=v.useCallback(()=>{const ae=m.current;de({...ae,pinned:!ae.pinned})},[de]),ke=v.useCallback(()=>{const ae=m.current;de({...ae,projects:!ae.projects})},[de]),te=v.useCallback(()=>{const ae=m.current;de({...ae,cloudProjects:!ae.cloudProjects})},[de]),Ee=v.useCallback(()=>{const ae=m.current;de({...ae,chats:!ae.chats})},[de]),ye=v.useCallback(()=>{const ae=m.current;de({...ae,savedForLater:!ae.savedForLater})},[de]),ne=v.useCallback(ae=>{if(!n)return;ae.preventDefault();const ue=ae.clientX,xe=y;let De=xe;P(!0);function we(Se){De=uf(xe+Se.clientX-ue),w(De)}function oe(){window.removeEventListener("pointermove",we),window.removeEventListener("pointerup",oe);const Se=oS(xe,De);Se&&(h.current=Se),P(!1),D(De)}window.addEventListener("pointermove",we),window.addEventListener("pointerup",oe,{once:!0})},[D,n,y]),be=v.useCallback(ae=>{if(a)return;ae.preventDefault();const ue=ae.clientX,xe=M;let De=xe;$(!0);function we(Se){De=mf(xe-(Se.clientX-ue)),C(De)}function oe(){window.removeEventListener("pointermove",we),window.removeEventListener("pointerup",oe);const Se=oS(xe,De);Se&&(g.current=Se),$(!1),W(De)}window.addEventListener("pointermove",we),window.addEventListener("pointerup",oe,{once:!0})},[a,M,W]);return{pinnedCollapsed:j,projectsCollapsed:x,cloudProjectsCollapsed:R,chatsCollapsed:E,savedForLaterCollapsed:U,sidebarWidth:y,sidebarResizing:_,diffPanelWidth:M,diffPanelResizing:N,togglePinnedCollapsed:Me,toggleProjectsCollapsed:ke,toggleCloudProjectsCollapsed:te,toggleChatsCollapsed:Ee,toggleSavedForLaterCollapsed:ye,startSidebarResize:ne,startDiffPanelResize:be}}function b7(e,t){return e.pinned===t.pinned&&e.projects===t.projects&&e.cloudProjects===t.cloudProjects&&e.chats===t.chats&&e.savedForLater===t.savedForLater}function y7(e){const[t,n]=v.useState({id:0,kind:null}),[a,o]=v.useState(null),i=v.useCallback((d=null)=>{n(h=>({id:h.id+1,kind:d}))},[]),s=v.useCallback(d=>{o(d)},[]),l=null,m=v.useMemo(()=>{if(e)return S7(a,i)},[e,a,i]);return{backAction:l,breadcrumbs:m,closeDetailKind:t.kind,closeDetailRequestId:t.id,onDetailOpenChange:s}}function S7(e,t){return e?[{label:e.rootLabel??"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 mS=new WeakMap,Ch=new WeakMap;function x7(e){if(!e)return"disconnected";let t=mS.get(e);return(!t||t.serverUrl!==e.serverUrl||t.token!==e.token)&&(t={serverUrl:e.serverUrl,token:e.token,id:crypto.randomUUID()},mS.set(e,t)),t.id}function bX(e,t){return Ch.set(e,t),e}function yX(e){if(!e)return["learning","disconnected"];let t=Ch.get(e);return t||(t=["learning",crypto.randomUUID()],Ch.set(e,t)),t}var eu=xt.shape.id,k7=c({schemaVersion:S("openpond.modelBatchReviewInspection.v1"),packageHash:r().regex(/^[a-f0-9]{64}$/),definition:wu,binding:ku,evidence:p(Iu).min(1).max(1e4),decisions:p(jg).min(1).max(1e4)}).strict(),SX=c({schemaVersion:S("openpond.modelBatchReviewRequest.v1"),operationId:eu,modelId:eu,expectedModelRevision:u().int().positive(),tasksetRef:xt,rewardBindingRef:xt.nullable(),definition:c({name:r().trim().min(1).max(500).optional(),instructions:r().trim().min(1).max(2e4).optional(),inputSchema:Ft.optional(),outputSchema:Ft.optional(),requiredOutputs:wu.shape.requiredOutputs}).strict(),examples:p(c({evidence:xt,input:Ft.optional(),expected:Ft.nullable().optional(),evaluatorContext:Ft.nullable().optional(),proposedTarget:Ft.nullable().optional()}).strict()).max(1e4)}).strict(),w7=c({schemaVersion:S("openpond.modelBatchReviewReceipt.v1"),operationId:eu,modelId:eu,source:Mg,evidence:p(Iu).min(1).max(1e4),proposals:p(Gw).max(1e4)}).strict();function I7(e,t,n){return{inspectModelBatch:async a=>{if(!e)throw new Error("Connect to OpenPond to inspect this batch.");return k7.parse(await Q.trainingRequest(e,"/models/batch-review/inspect",{profileId:t,modelId:a},"POST"))},beginModelBatchReview:async a=>{const o=await n(a);return o?w7.parse(o):null}}}function _7(e,t,n,a){async function o(i,s){if(!e)throw new Error("Connect to OpenPond to load tasks.");const l=eB.parse(s),m=new URLSearchParams({profileId:t});for(const[d,h]of Object.entries(l))h!==void 0&&m.set(d,String(h));return Q.trainingRequest(e,`${i}?${m}`,{},"GET")}return{taskInventory:async(i={})=>nB.parse(await o("/tasks",i)),taskInventoryDetail:async i=>{const s=await o("/tasks/detail",i);return{item:pI.parse(s.item),task:Gg.parse(s.task)}},tasksetDraftFiles:async i=>{if(!e)return null;try{return await Q.trainingRequest(e,`/taskset-drafts/${encodeURIComponent(i)}/files?${new URLSearchParams({profileId:t})}`,{},"GET")}catch(s){return a(s),null}},tasksetDraftFile:async(i,s)=>{if(!e)return null;try{return await Q.trainingRequest(e,`/taskset-drafts/${encodeURIComponent(i)}/file?${new URLSearchParams({profileId:t,path:s})}`,{},"GET")}catch(l){return a(l),null}},saveTasksetDraftFile:i=>n("save-taskset-draft-file",`/taskset-drafts/${encodeURIComponent(i.draftId)}/file`,{profileId:t,...i},"PATCH"),inspectTasksetDraftSource:(i,s)=>n("inspect-taskset-draft-source","/taskset-drafts/source",{profileId:t,modelId:i,expectedModelRevision:s}),createTasksetDraftFromSource:i=>n("create-taskset-draft","/taskset-drafts",{profileId:t,sourceRequest:i}),createTasksetDraft:(i="",s)=>n("create-taskset-draft","/taskset-drafts",{profileId:t,name:i,modelId:s??null}),importTasksetDraftPackage:i=>n("import-taskset-draft-package","/taskset-drafts/import",{packagePath:i,profileId:t}),saveTasksetDraft:i=>n("save-taskset-draft",`/taskset-drafts/${encodeURIComponent(i.id)}`,i,"PUT"),tasksetDraftWorkspace:async i=>{if(!e)return null;try{return await Q.trainingRequest(e,`/taskset-drafts/${encodeURIComponent(i)}/workspace`,{},"GET")}catch(s){return a(s),null}},publishTasksetDraft:(i,s)=>n("publish-taskset-draft",`/taskset-drafts/${encodeURIComponent(i)}/publish`,{modelId:s??null}),refreshTasksetDraftModel:(i,s)=>n("refresh-taskset-draft-model",`/taskset-drafts/${encodeURIComponent(i.id)}/model-revision`,{expectedDraftRevision:i.revision,expectedModelRevision:s}),deleteTasksetDraft:i=>n("delete-taskset-draft",`/taskset-drafts/${encodeURIComponent(i)}`,{},"DELETE")}}function FC(e,t){return EU({id:e.id,profileId:e.profileId,name:e.name,objective:e.objective,defaultBaseModel:e.defaultBaseModel,defaultDestinationId:e.defaultDestinationId,trainingSetup:e.trainingSetup},t)}async function C7(e,t,n){if(!e)throw new Error("Connect to the execution owner to check this configuration.");const a=await FC(t,n);return u1.parse(await Q.trainingRequest(e,"/models/check",a,"POST"))}function R7(e,t){return{listModelStarters:async(n,a=!1)=>{if(!e)throw new Error("Connect to OpenPond to browse model starters.");return Q.trainingRequest(e,`/model-starters?limit=30${n?`&afterId=${encodeURIComponent(n)}`:""}${a?"&fresh=true":""}`,{},"GET")},previewModelStarter:async n=>{if(!e)throw new Error("Connect to OpenPond to preview a starter.");return Q.trainingRequest(e,"/model-starters/preview",{id:n.id,revision:n.revision,contentHash:n.contentHash})},checkModelStarter:async n=>{if(!e)throw new Error("Connect to OpenPond to check this starter.");return u1.parse(await Q.trainingRequest(e,"/model-starters/check",n))},createModelFromStarter:n=>t("create-model-from-starter","/model-starters/create",n)}}const pS=1e4,fS=3e4;function P7(e){const{connection:t,profileId:n}=e,a=NS(),o=x7(t),i=v.useMemo(()=>["training",o,n],[o,n]),s=v.useCallback(async()=>I4.parse(await Q.trainingState(t,n)),[t,n]),l=nP({queryKey:i,queryFn:s,enabled:!!t}),m=l.data??null,d=!!t&&l.isPending,[h,g]=v.useState(null),[y,w]=v.useState(null),_=v.useRef(null);_.current=m?.activityRevision??null;const P=v.useCallback(async()=>{if(!t)return null;try{const x=await a.fetchQuery({queryKey:i,queryFn:s,staleTime:0});return w(null),x}catch(x){return w(Ro(x)),null}},[t,a,i,s]),M=v.useCallback(async()=>(await a.cancelQueries({queryKey:i,exact:!0}),await a.invalidateQueries({queryKey:i,exact:!0,refetchType:"none"}),await a.invalidateQueries({queryKey:["task-inventory",o,n]}),P()),[a,i,o,n,P]),C=v.useCallback(async(x,R,E,U="POST",B={})=>{if(!t)return null;B.silent||g(x);try{const D=await Q.trainingRequest(t,R,E,U);return await M(),B.silent||w(null),D}catch(D){return B.silent||w(Ro(D)),null}finally{B.silent||g(null)}},[t,M]),N=m?[m.jobs.some(x=>["queued","starting","running","cancelling","reconciling"].includes(x.status)),m.creations.some(x=>["planning","materializing","validating"].includes(x.state)),m.minerRuns.some(x=>["queued","running","cancelling"].includes(x.status)),m.datasetImports.some(x=>["inspecting","materializing","validating","cancelling"].includes(x.status))].some(Boolean):!1;v.useEffect(()=>{if(!t)return;let x=!0,R=null;const E=N?pS:fS,U=async()=>{let B=E;try{const D=await Q.trainingActivity(t,n);B=D.active?pS:fS,(_.current===null||_.current!==D.revision)&&await P()}catch(D){w(Ro(D))}x&&(R=window.setTimeout(()=>{U()},B))};return R=window.setTimeout(()=>{U()},E),()=>{x=!1,R!==null&&window.clearTimeout(R)}},[t,N,n,P]);const $=v.useMemo(()=>({...R7(t,C),saveComparisonSeries:x=>C("save-comparison-series","/comparison-series",{series:x}),saveContinualBenchIssueReview:x=>C("save-continual-support-issue-review","/continual-support/issue-reviews",{review:x},"PUT"),importContinualLearningDailyBatch:(x,R="json_upload")=>C("import-continual-learning-daily-batch","/continual-learning/daily-batches/import",{manifest:x,source:R}),saveContinualLearningDailyBatch:x=>C("save-continual-learning-daily-batch","/continual-learning/daily-batches",{batch:x},"PUT"),generateContinualLearningResponses:x=>C("generate-continual-learning-responses","/continual-learning/responses",x),sealComparisonSeries:(x,R)=>C("seal-comparison-series",`/comparison-series/${encodeURIComponent(x)}/seal`,{expectedRevision:R}),archiveComparisonSeries:(x,R)=>C("archive-comparison-series",`/comparison-series/${encodeURIComponent(x)}/archive`,{expectedRevision:R}),queueComparisonRelease:x=>C("queue-comparison-release",`/comparison-series/${encodeURIComponent(x.seriesId)}/releases`,x),startComparisonEvaluation:x=>C("start-comparison-evaluation",`/comparison-series-entries/${encodeURIComponent(x.entryId)}/evaluations`,x),loadComparisonAttemptEvidence:x=>t?Q.trainingRequest(t,`/model-runs/${encodeURIComponent(x.runId)}/attempts/${encodeURIComponent(x.attemptId)}/evidence?kind=${x.kind}`,{},"GET"):Promise.resolve(null),linkComparisonRun:x=>C("link-comparison-run",`/comparison-series-entries/${encodeURIComponent(x.entryId)}/run`,x,"PATCH"),decideComparisonEntry:x=>C("decide-comparison-entry",`/comparison-series-entries/${encodeURIComponent(x.entryId)}/decision`,x),recordComparisonPromotion:x=>C("record-comparison-promotion",`/comparison-series-entries/${encodeURIComponent(x.entryId)}/promotion`,x),checkModelProject:(x,R=x.revision)=>C7(t,x,R),...I7(t,n,x=>C("begin-model-batch-review","/models/batch-review",{profileId:n,request:x})),saveModelProject:async(x,R=x.revision)=>C("save-model-project","/models",await FC(x,R),"PUT"),listHostedModelProjects:async(x={})=>{if(!t)return null;x.silent||g("list-hosted-model-projects");try{const R=await Q.trainingRequest(t,`/hosted-model-projects?profileId=${encodeURIComponent(n)}&refresh=${x.refresh===!0}`,{},"GET");return x.silent||w(null),R}catch(R){return x.silent||w(Ro(R)),null}finally{x.silent||g(R=>R==="list-hosted-model-projects"?null:R)}},openHostedModelProject:(x,R,E,U={})=>C(`open-hosted-model-project:${x}`,`/hosted-model-projects/${encodeURIComponent(x)}/open`,{profileId:n,teamId:R,apiOrigin:E},"POST",U),pullHostedModelProject:x=>C(`pull-hosted-model-project:${x}`,`/hosted-model-projects/${encodeURIComponent(x)}/pull`,{profileId:n}),syncModelProject:x=>C("sync-model-project",`/models/${encodeURIComponent(x)}/sync`,{}),publishModelProjectTaskset:(x,R)=>C("publish-model-project-taskset",`/models/${encodeURIComponent(x)}/tasksets/${encodeURIComponent(R)}/publish`,{}),createScorer:(x,R,E)=>C("create-scorer","/scorers",{grader:x,tasksetId:R,modelProjectId:E??null}),prepareLearningBatch:x=>C("prepare-learning-batch","/learning-batches/prepare",{profileId:n,batchId:x}),..._7(t,n,C,x=>w(Ro(x))),tasksetGraderDetails:async x=>{if(!t)return null;try{return await Q.trainingRequest(t,`/tasksets/${encodeURIComponent(x)}/graders`,{},"GET")}catch(R){return w(Ro(R)),null}},inspectHuggingFaceDataset:x=>C("inspect-huggingface-dataset","/dataset-imports/huggingface/inspect",{profileId:n,url:x}),materializeDatasetImport:(x,R)=>C("materialize-dataset-import",`/dataset-imports/${encodeURIComponent(x)}/materialize`,R),cancelDatasetImport:x=>C("cancel-dataset-import",`/dataset-imports/${encodeURIComponent(x)}/cancel`,{}),datasetRows:(x,R={})=>{if(!t)return Promise.resolve(null);const E=new URLSearchParams;R.split&&E.set("split",R.split),R.cursor&&E.set("cursor",R.cursor),E.set("limit",String(R.limit??25));for(const U of R.columns??[])E.append("column",U);return Q.trainingRequest(t,`/tasksets/${encodeURIComponent(x)}/rows?${E}`,{},"GET")},addSource:(x,R)=>C("add-source","/sources",{profileId:n,sessionId:x,turnIds:R}),addSources:x=>C("add-sources","/sources/batch",{profileId:n,sessionIds:x}),estimateSources:x=>t?Q.trainingRequest(t,"/sources/estimate",{sessionIds:x}):Promise.resolve([]),searchChats:(x,R,E=0,U=20)=>t?Q.trainingRequest(t,"/sources/search",{query:x,candidates:R,offset:E,limit:U}):Promise.resolve({schemaVersion:"openpond.trainingChatSearchResult.v1",query:x,offset:E,limit:U,total:0,hasMore:!1,indexedChats:0,totalChats:0,indexing:!1,entries:[]}),removeSource:x=>C("remove-source",`/sources/${encodeURIComponent(x)}`,{},"DELETE"),deleteTaskset:x=>C("delete-model",`/tasksets/${encodeURIComponent(x)}`,{},"DELETE"),runBenchmark:(x,R,E,U)=>C(`run-benchmark-${R}`,`/tasksets/${encodeURIComponent(x)}/benchmark-runs`,{phase:R,model:E,reasoningEffort:U,seeds:[17],repetitions:1}),startHarnessRefinerBenchmark:(x,R,E)=>C("run-harness-refiner-benchmark",`/models/${encodeURIComponent(x)}/harness-refiner-benchmark`,{profileId:n,model:R,reasoningEffort:E,maximumSpendUsd:10}),acceptHarnessReview:(x,R,E=null,U=null)=>C("accept-harness-review","/harness-reviews/accept",{profileId:n,workspaceId:x,reviewRef:R,analysisModel:E,analysisReasoningEffort:U}),startCreation:(x,R={})=>C("create-taskset","/task-creations",{profileId:n,sourceIds:x,surface:R.surface??"training_page",mode:R.mode??"defaults",entryMode:R.entryMode??"manual",resourceIntent:R.resourceIntent??"workproduct",buildIntent:R.buildIntent??"demonstrations",buildSpecification:R.buildSpecification??null,objective:R.objective??null,methodHint:R.methodHint??null,preferredBaseModelId:R.preferredBaseModel?.modelId??null,preferredBaseModel:R.preferredBaseModel??null,candidateId:R.candidateId??null,analysisModel:R.analysisModel??null,analysisReasoningEffort:R.analysisReasoningEffort??null,createImproveRunId:R.createImproveRunId??null,targetIntent:R.targetIntent??{kind:"model",id:null,displayName:null,operation:"create"}}),createModelFromTaskset:(x,R)=>C("create-model","/models/from-taskset",{profileId:n,tasksetId:x,preferredBaseModelId:R.modelId,preferredBaseModel:R}),scanBaseModels:async()=>{if(!t)return null;g("scan-base-models");try{const x=await P();return w(null),x}catch(x){return w(Ro(x)),null}finally{g(null)}},approveDisclosure:(x,R)=>C("approve-disclosure",`/task-creations/${encodeURIComponent(x)}/disclosure`,{approved:R}),retryCreation:x=>C("retry-creation",`/task-creations/${encodeURIComponent(x)}/retry`,{}),answerQuestions:(x,R)=>C("answer-questions",`/task-creations/${encodeURIComponent(x)}/questions`,{answers:R}),materialize:(x,R)=>C("materialize",`/task-creations/${encodeURIComponent(x)}/materialize`,{approved:R}),chatCreation:(x,R)=>C("task-creator-chat",`/task-creations/${encodeURIComponent(x)}/chat`,{message:R}),renameCreation:(x,R)=>C("rename-creation",`/task-creations/${encodeURIComponent(x)}/name`,{name:R},"PATCH"),cancelCreation:x=>C("cancel-creation",`/task-creations/${encodeURIComponent(x)}/cancel`,{}),runMiner:(x=[],R=[],E)=>C("run-miner","/miner/run",{profileId:n,sourceIds:x,sessionIds:R,config:E}),cancelMinerRun:x=>C("cancel-miner-run",`/miner/runs/${encodeURIComponent(x)}/cancel`,{}),configureMiner:x=>C("configure-miner","/miner/config",{profileId:n,config:x},"PUT"),patchCandidate:(x,R)=>C("candidate",`/candidates/${encodeURIComponent(x)}`,R,"PATCH"),createCandidate:(x,R,E,U)=>C("create-candidate",`/candidates/${encodeURIComponent(x)}/create`,{mode:R,analysisModel:E??null,analysisReasoningEffort:U??null}),auditGraders:x=>C("audit-graders","/audit-graders",{tasksetId:x}),executeTasksetAttempt:(x,R,E)=>C("execute-taskset-attempt",`/tasksets/${encodeURIComponent(x)}/attempts`,{taskId:R,model:E,seed:17,attempt:0,sampling:{maxOutputTokens:4096,temperature:0,topP:1}}),materializeSyntheticPreferenceCollection:x=>C("materialize-synthetic-preference-collection",`/tasksets/${encodeURIComponent(x.tasksetId)}/synthetic-preference-collection`,x),tasksetOperationalState:x=>t?Q.trainingRequest(t,`/tasksets/${encodeURIComponent(x)}/operations`,{},"GET"):Promise.resolve(null),calibrateJudges:x=>C("calibrate-judges","/calibrate-judges",{tasksetId:x}),nextPreferenceComparison:(x,R)=>C("next-preference-comparison",`/tasksets/${encodeURIComponent(x)}/preference-comparisons/next`,{reviewerKey:R}),submitPreferenceComparison:x=>C("submit-preference-comparison",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/${encodeURIComponent(x.assignmentId)}/submit`,x),submitSyntheticFixturePreference:x=>C("submit-synthetic-fixture-preference",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/${encodeURIComponent(x.assignmentId)}/fixture-submit`,{...x,id:crypto.randomUUID()}),listPreferenceDatasets:x=>t?Q.trainingRequest(t,`/tasksets/${encodeURIComponent(x)}/preference-datasets`,{},"GET"):Promise.resolve(null),materializePreferenceDataset:x=>C("materialize-preference-dataset",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-datasets`,{...x,id:`preference-dataset-${crypto.randomUUID()}`,revision:1}),launchRewardModelRun:x=>C("launch-reward-model-run",`/tasksets/${encodeURIComponent(x.tasksetId)}/reward-model-runs`,{...x,id:`reward-model-run-${crypto.randomUUID()}`}),learnedPreferenceRewardBinding:x=>C("learned-preference-reward-binding",`/tasksets/${encodeURIComponent(x.tasksetId)}/learned-preference-reward-binding`,x),retryRewardModelQualification:x=>C("retry-reward-model-qualification",`/reward-model-runs/${encodeURIComponent(x.runId)}/retry-qualification`,x),cancelRewardModelRun:x=>C("cancel-reward-model-run",`/reward-model-runs/${encodeURIComponent(x)}/cancel`,{}),markPreferenceComparisonUnreviewable:x=>C("mark-preference-comparison-unreviewable",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/${encodeURIComponent(x.assignmentId)}/unreviewable`,x),preferenceCalibrationStatus:(x,R,E)=>{if(!t)return Promise.resolve(null);const U=new URLSearchParams({reviewerKey:R});return E&&U.set("comparisonReleaseId",E),Q.trainingRequest(t,`/tasksets/${encodeURIComponent(x)}/preference-comparisons/calibration/status?${U}`,{},"GET")},startPreferenceCalibrationBatch:x=>C("start-preference-calibration-batch",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/calibration/batches`,{...x,id:crypto.randomUUID()}),syncPreferenceCalibrationBatch:x=>C("sync-preference-calibration-batch",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/calibration/batches/${encodeURIComponent(x.jobId)}/sync`,x),reviewPreferenceComparisonWithModel:x=>C("review-preference-comparison-with-model",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/${encodeURIComponent(x.assignmentId)}/model-review`,{...x,id:crypto.randomUUID()}),runNextPreferenceCalibrationReview:x=>C("run-next-preference-calibration-review",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/calibration/model-reviews/next`,{...x,id:crypto.randomUUID()}),savePreferenceCalibration:x=>C("save-preference-calibration",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/calibration/report`,{...x,id:crypto.randomUUID()}),preferenceArtifactUrl:async x=>{if(!t)return null;const R=await fetch(`${t.serverUrl}/v1/training/artifacts/${encodeURIComponent(x)}/download`,{headers:{Authorization:`Bearer ${t.token}`}});if(!R.ok)throw new Error(await R.text());return URL.createObjectURL(await R.blob())},readiness:x=>C("readiness","/readiness",{tasksetId:x}),previewExpertBootstrap:x=>C("preview-expert-bootstrap",`/tasksets/${encodeURIComponent(x)}/expert-bootstrap/preview`,{}),approveExpertBootstrap:(x,R)=>C("approve-expert-bootstrap",`/tasksets/${encodeURIComponent(x)}/expert-bootstrap/approve`,{previewHash:R}),createPlan:x=>C("create-plan","/plans",{...x,tasksetId:x.tasksetId}),buildBundle:x=>C("build-bundle","/bundles",{planId:x}),approveTraining:(x,R)=>C("approve-training","/approvals",{planId:x,bundleId:R}),launch:(x,R)=>C("launch","/launch",{planId:x,approvalId:R}),prepareTraining:x=>C("prepare-training","/prepare",x),prepareModelRun:(x,R)=>C("prepare-model-run",`/model-projects/${encodeURIComponent(x)}/training/prepare`,R),startModelRun:(x,R)=>C("start-model-run",`/model-projects/${encodeURIComponent(x)}/training/start`,R),startPreparedTraining:x=>C("start-prepared-training","/start/prepared",x),startTraining:x=>C("start-training","/start",x),cancelJob:x=>C("cancel-job",`/jobs/${encodeURIComponent(x)}/cancel`,{}),retryModelRunCollection:x=>C("retry-model-run-collection",`/model-runs/${encodeURIComponent(x)}/retry-collection`,{}),cancelModelRun:x=>C("cancel-model-run",`/model-runs/${encodeURIComponent(x)}/cancel`,{}),rejectModel:(x,R)=>C("reject-model",`/models/${encodeURIComponent(x)}/reject`,{reason:R}),bindModel:(x,R,E)=>C("bind-model",`/models/${encodeURIComponent(x)}/bind`,{profileId:n,role:R,roleTargetId:E,promotedBy:n}),rollbackModelBinding:x=>C("rollback-model-binding",`/bindings/${encodeURIComponent(x)}/rollback`,{rolledBackBy:n}),updateModelConfiguration:(x,R)=>C("update-model-configuration",`/models/${encodeURIComponent(x)}/configuration`,R,"PATCH",{silent:!0}),setModelPinned:(x,R)=>C("pin-model-version",`/models/${encodeURIComponent(x)}/pin`,{pinned:R},"PATCH"),downloadArtifact:async x=>{if(!t)return!1;g("download-artifact");try{const R=await fetch(`${t.serverUrl}/v1/training/artifacts/${encodeURIComponent(x)}/download`,{headers:{Authorization:`Bearer ${t.token}`}});if(!R.ok)throw new Error(await R.text());const E=R.headers.get("content-disposition")??"",U=/filename="([^"]+)"/.exec(E)?.[1]??"openpond-model-artifact",B=URL.createObjectURL(await R.blob()),D=document.createElement("a");return D.href=B,D.download=U,D.click(),URL.revokeObjectURL(B),!0}catch(R){return w(Ro(R)),!1}finally{g(null)}},downloadModelPackage:async x=>j(`/models/${encodeURIComponent(x)}/download`,`${x}.openpond-lora.tar`),downloadBundle:async x=>j(`/bundles/${encodeURIComponent(x)}/download`,"openpond-model-improvement-bundle.json")}),[t,C,n,P]);async function j(x,R){if(!t)return!1;g("download-bundle");try{const E=await fetch(`${t.serverUrl}/v1/training${x}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!E.ok)throw new Error(await E.text());const U=E.headers.get("content-disposition")??"",B=/filename="([^"]+)"/.exec(U)?.[1]??R,D=URL.createObjectURL(await E.blob()),W=document.createElement("a");return W.href=D,W.download=B,W.click(),URL.revokeObjectURL(D),!0}catch(E){return w(Ro(E)),!1}finally{g(null)}}return{connection:t,payload:m,loading:d,busyAction:h,error:y??l.error?.message??null,refresh:P,actions:$}}function Ro(e){return e instanceof Error?e.message:String(e)}function xX({modelId:e,taskset:t}){const n=t.metadata.toolContractHash===dc?"cross_system":t.environment.kind==="stateful_harness"&&t.environment.actionBindings?.length?"harness":null,a=n?M7(t,n):[];return{model:{providerId:"openpond",modelId:e},tasksetId:t.id,tasksetName:t.name,taskRuntime:n,sourceProjectId:j7(t),tasks:a,selectedTaskIndex:0,sessionId:null}}function kX(e){return{model:{providerId:"openpond",modelId:e.modelId},tasksetId:e.tasksetId,tasksetName:e.modelName,taskRuntime:null,sourceProjectId:null,tasks:[],selectedTaskIndex:0,sessionId:null}}function qi(e){return e?.tasks.length?e.tasks[WC(e,e.selectedTaskIndex)]??null:null}function VC(e,t){return{...e,selectedTaskIndex:WC(e,t)}}function A7(e){return VC(e,e.selectedTaskIndex+1)}function T7(e,t,n){if(!e||KC(e,n))return null;const a=qi(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 KC(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 E7({model:e,connection:t,loadBootstrap:n,applyBootstrap:a}){e.providerId!=="openpond"||!t||a(await n(t))}function M7(e,t){const n=new Set;return e.tasks.flatMap(a=>{const o=t==="cross_system"?a.metadata.taskId:a.metadata.caseId,i=typeof o=="string"?o.trim():"",s=typeof a.input.prompt=="string"?a.input.prompt.trim():"";return!i||!s||n.has(i)?[]:(n.add(i),[{authoredTaskId:a.id,generatedTaskId:i,prompt:s,split:a.split}])})}function j7(e){const t=new Set(e.sourceRefs.filter(wq).flatMap(n=>{const a=n.workspaceId?.trim();return a?[a]:[]}));return t.size===1?t.values().next().value??null:null}function WC(e,t){return e.tasks.length?Math.max(0,Math.min(Math.trunc(t),e.tasks.length-1)):0}function O7({activeModel:e,activeProvider:t,applyBootstrapPayload:n,beginNewChat:a,composerDraftStore:o,connection:i,requestComposerFocus:s,selectedLocalProjectId:l,selectedSessionId:m,selectLocalProject:d,setDraftModel:h,setDraftProvider:g,setError:y,view:w}){const[_,P]=v.useState(null),M=v.useCallback(E=>{E.sourceProjectId?d(E.sourceProjectId):a(null)},[a,d]),C=v.useCallback(E=>{if(!_)return;const U={...VC(_,E),sessionId:_.sessionId?null:_.sessionId},B=qi(U);P(U),B&&(_.sessionId&&M(U),o.set(B.prompt),s())},[M,o,_,s]),N=v.useCallback(()=>{const E=qi(_);E&&o.getSnapshot().trim()===E.prompt.trim()&&o.set(""),P(null)},[o,_]),$=v.useCallback(E=>{const U=E.model;E7({model:U,connection:i,loadBootstrap:Q.bootstrap,applyBootstrap:n}).then(()=>{const B={...E,selectedTaskIndex:0,sessionId:null};g(U.providerId),h(U.modelId),P(B.tasks.length?B:null),M(B);const D=qi(B);D&&o.set(D.prompt)}).catch(y)},[n,M,o,i,h,g,y]),j=v.useCallback(E=>{const U=!!(_&&_.model.providerId===t&&_.model.modelId===e);return{active:U,error:U?KC(_,l):null,metadata:U?T7(_,E,l):null}},[e,t,_,l]),x=v.useCallback(E=>{P(U=>U&&{...U,sessionId:E})},[]),R=v.useCallback(()=>{if(!_)return;const E={...A7(_),sessionId:null},U=qi(E);P(E),U&&(M(E),o.set(U.prompt),s())},[M,o,_,s]);return v.useEffect(()=>{const E=qi(_);!E||w!=="chat"||m||o.set(U=>U.trim()?U:E.prompt)},[o,_,l,m,w]),v.useEffect(()=>{_&&m&&_.sessionId!==m&&P(null)},[_?.sessionId,m]),{advanceAfterTurn:R,begin:$,bindSession:x,dismiss:N,handoff:_,prepareTurn:j,selectTask:C}}const sl=[],pf=500;function $7(e){const{approvals:t,codexHistoryEvents:n,connection:a,latestServerSequence:o,runtimeIndexes:i,runtimeEventStore:s,selectedSessionId:l,serverId:m,setCodexHistoryEvents:d,setCodexHistorySessions:h,setError:g}=e,[y,w]=v.useState({}),[_,P]=v.useState({}),M=v.useRef(new Set);v.useEffect(()=>{w({}),P({}),M.current.clear()},[m]);const C=v.useCallback(async()=>{if(!a||!l||M.current.has(l))return!1;const R=_[l];if(R?.hasMore===!1)return!1;if(Ht(l)){const B=Math.max(R?.totalMatchingEvents??0,n.length,vC),D=Math.min(D0,Math.max(fW,B*2));M.current.add(l),P(W=>({...W,[l]:{cursorSequence:null,hasMore:!0,loading:!0,totalMatchingEvents:W[l]?.totalMatchingEvents??n.length}}));try{const W=await bC(a,l,{force:!0,limit:D,tail:!1});return d(W.events),h(se=>Vu(se,W.session)),P(se=>({...se,[l]:{cursorSequence:null,hasMore:W.events.length>=D&&D<D0,loading:!1,totalMatchingEvents:D}})),W.events.length>n.length}catch(W){return g(W instanceof Error?W.message:String(W)),P(se=>({...se,[l]:{cursorSequence:null,hasMore:se[l]?.hasMore??!0,loading:!1,totalMatchingEvents:se[l]?.totalMatchingEvents??n.length}})),!1}finally{M.current.delete(l)}}const E=Eo(y[l]??sl,s.getSessionEvents(l)),U=R?.cursorSequence??N7(E);if(!U)return!1;M.current.add(l),P(B=>({...B,[l]:{cursorSequence:B[l]?.cursorSequence??U,hasMore:B[l]?.hasMore??!0,loading:!0,totalMatchingEvents:B[l]?.totalMatchingEvents??null}}));try{const B=await Q.runtimeEventsPage(a,{sessionId:l,beforeSequence:U,limit:pf}),D=B.events.map(W=>W.event);return w(W=>({...W,[l]:Eo(D,W[l]??sl)})),P(W=>({...W,[l]:{cursorSequence:B.previousSequence,hasMore:B.hasMore,loading:!1,totalMatchingEvents:B.totalMatchingEvents}})),D.length>0}catch(B){return g(B instanceof Error?B.message:String(B)),P(D=>({...D,[l]:{cursorSequence:D[l]?.cursorSequence??U,hasMore:D[l]?.hasMore??!0,loading:!1,totalMatchingEvents:D[l]?.totalMatchingEvents??null}})),!1}finally{M.current.delete(l)}},[_,n.length,a,y,s,l,d,h,g]),N=l?y[l]??sl:sl,$=v.useMemo(()=>s.getSessionEvents(l).length,[s,l]),j=v.useRef(null);v.useEffect(()=>{if(!a||!l||Ht(l)||M.current.has(l)||N.length>0||$>0)return;const R=o;if(!R)return;const E=l,U=R+1;M.current.add(E),P(B=>({...B,[E]:{cursorSequence:B[E]?.cursorSequence??U,hasMore:B[E]?.hasMore??!0,loading:!0,totalMatchingEvents:B[E]?.totalMatchingEvents??null}})),Q.runtimeEventsPage(a,{sessionId:E,beforeSequence:U,limit:pf}).then(B=>{const D=B.events.map(W=>W.event);w(W=>({...W,[E]:Eo(D,W[E]??sl)})),P(W=>({...W,[E]:{cursorSequence:B.previousSequence,hasMore:B.hasMore,loading:!1,totalMatchingEvents:B.totalMatchingEvents}}))}).catch(B=>{g(B instanceof Error?B.message:String(B)),P(D=>({...D,[E]:{cursorSequence:D[E]?.cursorSequence??U,hasMore:D[E]?.hasMore??!0,loading:!1,totalMatchingEvents:D[E]?.totalMatchingEvents??null}}))}).finally(()=>{M.current.delete(E)})},[o,a,N.length,$,l,g]),v.useEffect(()=>{if(!a||!l||Ht(l)||M.current.has(l)||!o)return;const R=Eo(N,s.getSessionEvents(l)),E=Jd(R);if(!E||E>=o)return;const U=`${l}:${E}:${o}`;if(j.current===U)return;j.current=U;let B=!1;return Q.runtimeEventsPage(a,{sessionId:l,afterSequence:E,limit:pf}).then(D=>{if(B)return;const W=D.events.map(se=>se.event);W.length!==0&&w(se=>_K(se,l,W))}).catch(D=>{B||(j.current=null,g(D instanceof Error?D.message:String(D)))}),()=>{B=!0}},[o,a,s,N,l,g]);const x=v.useMemo(()=>Ht(l)?hh(n,[]):!l||N.length===0?i:hh(Eo(N,s.getSessionEvents(l)),t),[t,n,i,N,l]);return{chatHistoryLoadStates:_,loadMoreSelectedChatHistory:C,selectedPagedSessionEvents:N,selectedRuntimeIndexes:x}}function N7(e){let t=null;for(const n of e)n.sequence!==void 0&&(t===null||n.sequence<t)&&(t=n.sequence);return t}function D7(e,t){const n=v.useRef(null);return v.useMemo(()=>{const a=Q_(e,t,n.current);return n.current={events:e,indexes:a},a},[t,e])}function Xi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ff(e){return Array.isArray(e)?e.filter(t=>!!Xi(t)):[]}function Hr(e){return typeof e=="string"&&e.trim()?e.trim():null}function hS(e){return Hr(e)??Xi(e)}function L7(e){if(!e)return[];const t=Xi(e.sandboxActionRegistry),n=Xi(e.sandboxManifest),a=new Map;for(const o of[...ff(n?.actionCatalog),...ff(t?.actions),...ff(n?.actions)]){const i=Hr(o.id)??Hr(o.name);if(!i)continue;const s=a.get(i);a.set(i,{id:i,name:Hr(o.name)??s?.name??i,label:Hr(o.label)??s?.label??U7(i),description:Hr(o.description)??s?.description??null,visibility:Hr(o.visibility)??s?.visibility??"default",inputSchema:hS(o.inputSchema)??s?.inputSchema??null,outputSchema:hS(o.outputSchema)??s?.outputSchema??null,implementation:Xi(o.implementation)??s?.implementation??null,mcp:Xi(o.mcp)??s?.mcp??null,invokesModel:typeof o.invokesModel=="boolean"?o.invokesModel:s?.invokesModel})}return Array.from(a.values()).filter(o=>o.visibility!=="internal"&&o.visibility!=="debug")}function U7(e){const t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e}function GC(e){if(e.selectedCloudProject)return{id:e.selectedCloudProject.id,teamId:e.selectedCloudProject.teamId,name:e.selectedCloudProject.name,selectionKey:yt("cloud",e.selectedCloudProject.id),localProjectId:null};const t=e.selectedProject?.linkedSandboxProject??null;if(!t?.projectId||!t.teamId)return null;const n=e.cloudProjects?Ca(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:yt("cloud",n?.id??t.projectId),localProjectId:e.selectedProject?.id??null}}const ZC="openpond-agent",JC="openpond-profile-action";function Gu(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Mo(e){return typeof e=="string"&&e.trim()?e.trim():null}function Hv(e){return e.displayPrompt&&/(?:^|\s)@[A-Za-z0-9_-]+/.test(e.displayPrompt)?"mention":"slash"}function H7(e){const t=Gu(e),n=Mo(t?.scope);return n!=="entire_manifest"&&n!=="start"&&n!=="action"&&n!=="service"&&n!=="schedule"?null:{scope:n,name:Mo(t?.name)}}function z7(e){const t=Mo(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 q7(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:ZC,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 B7(e){const t=Gu(e.implementation);if(t?.type!==ZC)return null;const n=Mo(t.agentId),a=Mo(t.teamId),o=Mo(t.projectId),i=H7(t.selectedEntrypoint),s=z7(t.workflowMode);return!n||!a||!o||!i||!s?null:{agentId:n,agentName:Mo(t.agentName)??e.label??e.name??e.id,teamId:a,projectId:o,projectName:Mo(t.projectName),selectedEntrypoint:i,workflowMode:s}}function F7(e,t={}){const n=t.agentName?.trim()||null;return{...e,implementation:{...Gu(e.implementation)??{},type:JC,actionId:e.id,...n?{agentName:n}:{}},invokesModel:e.invokesModel??!0}}function V7(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=>F7(n,{agentName:n.agentId?t.get(n.agentId):null}))}function wX(e){return!!(e&&zv(e))}function IX(e){return!!(e&&zv(e)&&e.sourceActionId==="chat")}function zv(e){const t=Gu(e.implementation);if(t?.type!==JC)return null;const n=Mo(t.actionId)??e.id;return n?{actionId:n,actionLabel:e.label??e.name??n}:null}function K7({action:e,attachments:t=[],displayPrompt:n,prompt:a,sessionId:o}){return{action:e.actionId,input:{prompt:a,message:a,source:"openpond_app",...t.length>0?{attachments:t}:{}},metadata:{source:"openpond_app",selectedActionId:e.actionId,selectedActionLabel:e.actionLabel,selectedBy:Hv({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{},...o?{sessionId:o}:{}}}}function W7({action:e,attachments:t=[],displayPrompt:n,prompt:a,teamId:o}){return{teamId:o,triggerType:"manual",entrypoint:{scope:"action",name:e.id},input:{prompt:a,message:a,actionName:e.id,source:"openpond_app",...t.length>0?{attachments:t}:{}},metadata:{source:"openpond_app",selectedActionId:e.id,selectedActionLabel:e.label??e.name??e.id,selectedBy:Hv({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{}}}}function G7({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:Hv({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{}},workflowMode:e.workflowMode}}const es=new Map;function qv(e,t){const n=e?.trim();return n?`${t?.trim()||"global"}|${n}`:null}function Z7(e,t){const n=qv(e,t);if(!n)return null;const a=es.get(n);return a?.updatedAt?a.projects:null}function J7(e,t,n){const a=qv(e,n);a&&es.set(a,{projects:t,promise:null,updatedAt:Date.now()})}function Y7(e){const t=e.teamId?.trim();if(!t)return Promise.resolve([]);const n=qv(t,e.accountKey);if(!n)return Promise.resolve([]);const a=es.get(n);if(!e.force){if(a?.updatedAt)return Promise.resolve(a.projects);if(a?.promise)return a.promise}const o=e.fetchProjects(t).then(i=>(J7(t,i,e.accountKey),i)).catch(i=>{const s=es.get(n);throw s?.promise===o&&es.set(n,{projects:s.projects,promise:null,updatedAt:s.updatedAt}),i});return es.set(n,{projects:a?.projects??[],promise:o,updatedAt:a?.updatedAt??0}),o}function hf(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 Q7({cloudProjectById:e,cloudProjects:t,connection:n,defaultTeamId:a,accountScopeKey:o,localProjects:i,profile:s,selectedCloudProject:l,selectedProject:m,reportError:d}){const[h,g]=v.useState(null),[y,w]=v.useState([]),[_,P]=v.useState([]),M=v.useMemo(()=>{const E=new Set;a&&E.add(a);for(const U of t)E.add(U.teamId);for(const U of i){const B=t.find(D=>D.id===U.linkedSandboxProject?.projectId&&D.teamId===U.linkedSandboxProject?.teamId);B?.teamId&&E.add(B.teamId)}return[...E].sort()},[t,a,i]),C=M.join("\0"),N=v.useMemo(()=>GC({cloudProjects:t,selectedCloudProject:l,selectedProject:m}),[t,l,m]);v.useEffect(()=>{if(!n||M.length===0){P([]);return}let E=!1;const U=M.flatMap(B=>qC(B,o)??[]);return P(hf(U)),Promise.all(M.map(B=>Dv({teamId:B,accountKey:o,fetchAgents:async D=>(await Q.listSandboxAgents(n,{teamId:D})).agents}))).then(B=>{E||P(hf(B.flat()))}).catch(()=>{E||P(hf(U))}),()=>{E=!0}},[o,n,C]),v.useEffect(()=>{if(!n||!N){g(null);return}const E=Z7(N.teamId,o);E&&g(E.find(B=>B.id===N.id)??null);let U=!1;return Y7({teamId:N.teamId,accountKey:o,fetchProjects:async B=>(await Q.listSandboxProjects(n,{teamId:B})).projects}).then(B=>{U||g(B.find(D=>D.id===N.id)??null)}).catch(()=>{U||g(null)}),()=>{U=!0}},[o,n,N?.id,N?.teamId]),v.useEffect(()=>{if(!n||!m){w([]);return}let E=!1;return Q.localProjectActions(n,m.id).then(U=>{E||w(U.actions)}).catch(U=>{E||(w([]),d?.(`Could not load Project Actions for ${m.name}: ${U instanceof Error?U.message:String(U)}`))}),()=>{E=!0}},[n,d,m?.id,m?.name,m?.updatedAt]);const $=v.useMemo(()=>{const E=new Map;for(const U of L7(h))E.set(U.id,U);for(const U of y)E.set(U.id,U);return[...E.values()]},[y,h]),j=v.useMemo(()=>V7(s),[s]),x=v.useMemo(()=>[..._.map(E=>q7(E,e.get(E.projectId)?.name??null)),...j,...$],[e,j,$,_]);return{openPondActionCatalog:v.useMemo(()=>[...j,...$],[j,$]),selectedActionCatalog:x,selectedProjectActionCatalog:$}}function X7({selectedProjectId:e}){const[t,n]=v.useState(()=>new Set),a=v.useCallback(i=>{n(s=>{if(s.has(i))return s;const l=new Set(s);return l.add(i),l})},[]),o=v.useCallback(i=>{n(s=>{const l=new Set(s);return l.has(i)?l.delete(i):l.add(i),l})},[]);return v.useEffect(()=>{e&&a(e)},[a,e]),{expandedProjectIds:t,expandProject:a,toggleProjectExpanded:o,setExpandedProjectIds:n}}function eZ(){const e=new Map;function t(o,i){const s=e.get(o);if(s)return s.consumers+=1,n(o,s,!0);const l=new AbortController,m={controller:l,consumers:1,settled:!1,promise:Promise.resolve().then(()=>i(l.signal)).finally(()=>{m.settled=!0,e.get(o)===m&&e.delete(o)})};return e.set(o,m),n(o,m,!1)}function n(o,i,s){let l=!1;return{key:o,promise:i.promise,shared:s,release:()=>{l||(l=!0,i.consumers=Math.max(0,i.consumers-1),i.consumers===0&&!i.settled&&i.controller.abort())}}}function a(){for(const o of e.values())o.consumers=0,o.settled||o.controller.abort()}return{request:t,cancelAll:a,inFlightCount:()=>e.size}}function gf(e,t,n){return`workspace-status:${e.serverUrl}:${t}:${n?"ensure":"read"}`}function tZ(e,t){return`workspace-diff:${e.serverUrl}:${t}`}function vf(e){return e instanceof Error&&e.name==="AbortError"}function nZ({connection:e,activeWorkspaceAppId:t,view:n,shouldLoadWorkspaceDiff:a,sidebarWorkspaceAppIds:o,setError:i}){const[s,l]=v.useState(null),[m,d]=v.useState({}),[h,g]=v.useState(null),[y,w]=v.useState(!1),[_,P]=v.useState(!1),M=v.useRef(new Set),C=v.useRef(new Set),N=v.useRef(eZ()),$=t?m[t]??(s?.appId===t?s:null):null,j=h?.appId===t?h:null,x=n==="chat"||n==="labs",R=v.useCallback(B=>{M.current.add(B.appId),l(B),d(D=>({...D,[B.appId]:B}))},[]),E=v.useCallback(async(B,D=!1)=>{if(!e||!B)return l(null),null;w(!0);const W=N.current.request(gf(e,B,D),se=>Q.workspaceStatus(e,B,D,{signal:se}));try{const se=await W.promise;return R(se),D&&se.error?i(`Workspace sync failed: ${se.error}`):D&&i(null),se}catch(se){return vf(se)||(l(null),i(se instanceof Error?se.message:String(se))),null}finally{W.release(),w(!1)}},[e,R,i]),U=v.useCallback(async(B=t,D={})=>{if(!e||!B)return g(null),null;D.silent||P(!0);const W=N.current.request(tZ(e,B),se=>Q.workspaceDiff(e,B,{signal:se}));try{const se=await W.promise;return g(se),se}catch(se){return vf(se)||(g(null),i(se instanceof Error?se.message:String(se))),null}finally{W.release(),D.silent||P(!1)}},[t,e,i]);return v.useEffect(()=>{if(!e||!t||!x){l(null),g(null),w(!1);return}let B=!1;const D=N.current.request(gf(e,t,!1),W=>Q.workspaceStatus(e,t,!1,{signal:W}));return w(!0),D.promise.then(W=>{B||(R(W),W.initialized||g(se=>se?.appId===W.appId?null:se))}).catch(W=>{vf(W)||B||(l(null),i(W instanceof Error?W.message:String(W)))}).finally(()=>{D.release(),B||w(!1)}),()=>{B=!0,D.release()}},[t,e,R,i,x]),v.useEffect(()=>{if(!e||!t||!x){g(null);return}if(!$?.initialized){$&&!$.initialized&&g(B=>B?.appId===t?null:B);return}a&&U(t)},[t,e,U,a,x,$?.dirty,$?.initialized]),v.useEffect(()=>{if(!e||o.length===0)return;const B=o.filter(se=>!M.current.has(se)&&!C.current.has(se));if(B.length===0)return;B.forEach(se=>C.current.add(se));let D=!1;const W=B.map(se=>({appId:se,request:N.current.request(gf(e,se,!1),de=>Q.workspaceStatus(e,se,!1,{signal:de}))}));return Promise.all(W.map(({appId:se,request:de})=>de.promise.then(Me=>({appId:se,state:Me})).catch(()=>({appId:se,state:null})).finally(()=>{de.release(),C.current.delete(se)}))).then(se=>{if(!D)for(const de of se)de.state&&R(de.state)}),()=>{D=!0,W.forEach(({appId:se,request:de})=>{de.release(),C.current.delete(se)})}},[e,R,o]),v.useEffect(()=>()=>N.current.cancelAll(),[]),{workspaceState:s,workspaceStates:m,workspaceDiff:h,workspaceBusy:y,diffBusy:_,visibleWorkspaceState:$,visibleWorkspaceDiff:j,rememberWorkspaceState:R,refreshWorkspace:E,refreshWorkspaceDiff:U,setWorkspaceBusy:w}}const aZ=1,oZ=15e3,rZ=15e3,YC=5*6e4,iZ=5e3,sZ=1e4;function QC(e,t=(a,o)=>new WebSocket(a,o),n={}){const a=new lZ(e,t,n.reconnectDelayMs??cZ);return a.open(),{close:()=>a.close()}}class lZ{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=YC;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===aZ)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-${dZ(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."))},oZ))},n.onmessage=a=>{this.isCurrent(n,t)&&this.handleMessage(n,a)},n.onerror=()=>{this.isCurrent(n,t)&&this.failConnection(new Error("Team chat realtime socket failed."),!1)},n.onclose=a=>{this.isCurrent(n,t)&&(this.socket=null,this.clearConnectionTimers(),this.closed||((a.code===4401||a.code===4403)&&this.reportError(new Error("Team chat realtime authorization expired.")),this.scheduleReconnect()))}}handleMessage(t,n){if(typeof n.data!="string")return;let a;try{const i=JSON.parse(n.data);if(!i||typeof i!="object"||Array.isArray(i))return;a=i}catch{this.reportError(new Error("Team chat realtime returned an invalid frame."));return}const o=typeof a.type=="string"?a.type:"";if(o==="connection_ack"){this.connectionAckTimer&&clearTimeout(this.connectionAckTimer),this.connectionAckTimer=null,this.keepAliveTimeoutMs=mZ(a.connectionTimeoutMs),this.lastKeepAliveAt=Date.now(),this.startKeepAliveMonitor(),this.subscribe(t);return}if(o==="ka"){this.lastKeepAliveAt=Date.now();return}if(o==="subscribe_success"){const i=typeof a.id=="string"?a.id:"";if(!this.subscriptionChannels.has(i))return;this.acknowledgedSubscriptions.add(i),this.markReadyWhenSubscribed();return}if(o==="data"){if(this.lastKeepAliveAt=Date.now(),typeof a.event!="string")return;try{this.input.onEvent(JSON.parse(a.event))}catch{this.reportError(new Error("Team chat realtime returned an invalid event."))}return}if(o==="connection_error"||o==="subscribe_error"){const i=pZ(a);if(this.reportError(i),o==="connection_error")this.failConnection(i,!1);else{const s=typeof a.id=="string"?a.id:"";this.subscriptionChannels.delete(s),this.acknowledgedSubscriptions.delete(s),this.markReadyWhenSubscribed()}}}subscribe(t){const n={Authorization:this.input.authorizationToken,host:new URL(this.input.httpUrl).host};for(const a of Array.from(new Set(this.input.channels))){const o=uZ();this.subscriptionChannels.set(o,a),t.send(JSON.stringify({type:"subscribe",id:o,channel:a,authorization:n}))}this.subscriptionAckTimer=setTimeout(()=>{this.failConnection(new Error("Team chat realtime subscription acknowledgement timed out."))},rZ)}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."))},iZ)}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 cZ(e){const t=Math.min(sZ,500*2**Math.min(e,5));return Math.max(100,Math.floor(Math.random()*t))}function dZ(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 uZ(){return globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random().toString(36).slice(2)}`}function mZ(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:YC}function pZ(e){const n=(Array.isArray(e.errors)?e.errors:[])[0];if(n&&typeof n=="object"){const a=n,o=typeof a.errorType=="string"?a.errorType:"RealtimeError",i=typeof a.message=="string"?a.message:"Request failed";return new Error(`${o}: ${i}`)}return new Error("Team chat realtime request failed.")}function fZ(e,t,n){const a=[`/team-chat/users/${e.session.userId}/${e.session.teamId}`,...Array.from(new Set(e.threadIds)).map(o=>`/team-chat/threads/${o}`)];return QC({realtimeUrl:e.session.realtimeUrl,httpUrl:e.session.httpUrl,authorizationToken:e.session.token,channels:a,onEvent:o=>{const i=Iw.safeParse(o);i.success&&e.onEvent(i.data)},onReady:e.onReady,onError:e.onError},t,n)}function hZ(e){return e.refs.find(t=>t.refType==="message_reply")??null}function gZ(e){return{id:e.id,authorType:e.authorType,authorUserId:e.authorUserId,authorAgentId:e.authorAgentId,body:e.body,deleted:!!e.deletedAt}}function _X(e,t){const n=hZ(e);if(!n)return null;const a=t.get(n.refId);return a?gZ(a):bZ(n)}function vZ(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 CX(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 RX(e){return e.deleted?"Message deleted":e.body.replace(/\s+/g," ").trim()||"Attachment"}function bZ(e){const t=e.preview;return{id:e.refId,authorType:yZ(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 yZ(e){return e==="agent"||e==="system"?e:"user"}function gS(e,t,n){return n===t.conversationId?{...e,aiThread:t}:e}function SZ(e,t){return!e||e.thread.id!==t.thread.id?t:{...t,messages:bc([...e.messages,...t.messages]),hasMoreBefore:e.messages.length>t.messages.length?e.hasMoreBefore:t.hasMoreBefore}}function bf(e,t){const n=Array.from(t.values()).filter(o=>o.threadId===e.thread.id);if(n.length===0)return e;let a=e.thread;for(const o of n)a=Ss(a,o,"message.created",!0,o.authorUserId);return{...e,thread:a,messages:bc([...e.messages,...n])}}function xZ(e,t){const n=new Set(e.map(o=>o.lastMessage?.clientRequestId).filter(o=>!!o)),a=new Map;for(const o of t.values()){if(o.clientRequestId&&n.has(o.clientRequestId))continue;const i=a.get(o.threadId)??[];i.push(o),a.set(o.threadId,i)}return e.map(o=>{let i=o;for(const s of a.get(o.id)??[])i=Ss(i,s,"message.created",!0,s.authorUserId);return i}).sort((o,i)=>i.lastMessageAt.localeCompare(o.lastMessageAt))}function yf(e,t,n){for(const a of e)!a.clientRequestId||a.id.startsWith("pending:")||(t.delete(a.clientRequestId),n.delete(a.clientRequestId))}function Sf(e,t,n){const a=e.get(t);a&&e.set(t,{...a,metadata:{...a.metadata,deliveryStatus:n}})}function vS(e,t,n){const a=e.get(t);a&&e.set(t,{...a,metadata:{...a.metadata,uploadProgress:n}})}function bc(e){const t=new Map,n=new Set(e.filter(a=>!a.id.startsWith("pending:")).map(a=>a.clientRequestId).filter(a=>!!a));for(const a of e)a.id.startsWith("pending:")&&a.clientRequestId&&n.has(a.clientRequestId)||t.set(a.id,a);return Array.from(t.values()).sort((a,o)=>a.sequence!==o.sequence?a.sequence-o.sequence:a.createdAt.localeCompare(o.createdAt))}function XC(e){return e.type!=="message.created"&&e.type!=="message.updated"&&e.type!=="message.deleted"?null:Cg.safeParse(e.payload.message).data??null}function eR(e,t,n){const a=XC(t);if(a){const o=e.selectedThreadId===a.threadId,i=e.detail?.thread.id===a.threadId?{...e.detail,thread:Ss(e.detail.thread,a,t.type,o,n),messages:bc([...e.detail.messages,a])}:e.detail,l=e.threads.some(m=>m.id===a.threadId)?e.threads.map(m=>m.id===a.threadId?Ss(m,a,t.type,o,n):m).sort((m,d)=>d.lastMessageAt.localeCompare(m.lastMessageAt)):e.threads;return{...e,detail:i,threads:l,error:null}}if(t.type==="read.updated"){const o=typeof t.payload.userId=="string"?t.payload.userId:null,i=Number(t.payload.sequence);if(!o||!Number.isSafeInteger(i)||i<0)return e;const s=l=>({...l,participants:l.participants.map(m=>m.userId===o?{...m,lastReadSequence:Math.max(m.lastReadSequence,i)}:m)});return{...e,threads:e.threads.map(l=>l.id===t.threadId?s(l):l),detail:e.detail?.thread.id===t.threadId?{...e.detail,thread:s(e.detail.thread)}:e.detail}}return e}function Ss(e,t,n,a,o){const i=n==="message.created",s=t.sequence>=e.lastMessageSequence;return{...e,lastMessageId:s?t.id:e.lastMessageId,lastMessageSequence:Math.max(e.lastMessageSequence,t.sequence),lastMessageAt:s?t.createdAt:e.lastMessageAt,updatedAt:s?t.createdAt:e.updatedAt,lastMessage:s?t:e.lastMessage,unreadCount:a||t.authorUserId===o?0:i?e.unreadCount+1:e.unreadCount}}function kZ(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:vZ(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 wZ(e,t){const n=e.detail?.thread.id===t.threadId?{...e.detail,thread:Ss(e.detail.thread,t,"message.created",!0,t.authorUserId),messages:bc([...e.detail.messages,t])}:e.detail;return{...e,detail:n,threads:e.threads.map(a=>a.id===t.threadId?Ss(a,t,"message.created",!0,t.authorUserId):a).sort((a,o)=>o.lastMessageAt.localeCompare(a.lastMessageAt)),error:null}}function bS(e,t,n){return eR(e,{teamId:t.teamId,threadId:t.threadId,type:"message.created",payload:{message:t},createdAt:t.createdAt},n)}function IZ(e,t){return Rh(e,t,"failed")}function Rh(e,t,n){const a=o=>o.clientRequestId===t&&o.id.startsWith("pending:")?{...o,metadata:{...o.metadata,deliveryStatus:n}}:o;return{...e,detail:e.detail?{...e.detail,thread:{...e.detail.thread,lastMessage:e.detail.thread.lastMessage?a(e.detail.thread.lastMessage):null},messages:e.detail.messages.map(a)}:null,threads:e.threads.map(o=>({...o,lastMessage:o.lastMessage?a(o.lastMessage):null}))}}function yS(e,t,n){const a=o=>o.clientRequestId===t&&o.id.startsWith("pending:")?{...o,metadata:{...o.metadata,uploadProgress:n}}:o;return{...e,detail:e.detail?{...e.detail,thread:{...e.detail.thread,lastMessage:e.detail.thread.lastMessage?a(e.detail.thread.lastMessage):null},messages:e.detail.messages.map(a)}:null,threads:e.threads.map(o=>({...o,lastMessage:o.lastMessage?a(o.lastMessage):null}))}}function _Z(e,t){const n=e.detail?.messages.filter(i=>i.id!==t)??[],a=n.at(-1)??null,o=e.detail?{...e.detail,thread:e.detail.thread.lastMessageId===t?SS(e.detail.thread,a):e.detail.thread,messages:n}:null;return{...e,detail:o,threads:e.threads.map(i=>i.lastMessageId===t?SS(i,a):i)}}function CZ(e){if(e.length>Vr.maxAttachments)return null;const t=[];for(const n of e){if(n.kind!=="image"||!RZ(n.mediaType)||!n.contentsBase64||n.sizeBytes<=0||n.sizeBytes>Vr.maxAttachmentBytes)return null;t.push({...n,kind:"image",mediaType:n.mediaType,contentsBase64:n.contentsBase64})}return t}function SS(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 RZ(e){return e==="image/png"||e==="image/jpeg"||e==="image/webp"||e==="image/gif"}const PZ={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 AZ(e){const t=e instanceof Error?e.message:String(e),n=t.trim().toLowerCase();for(const[a,o]of Object.entries(PZ))if(n.includes(a))return o;return n.includes("event stream ended")?"Team chat realtime disconnected. Messages will continue to refresh automatically.":OC(t)}const tR="openpond.team-chat.notification-mode";function nR(){try{return typeof window>"u"?null:hc}catch{return null}}function xS(e=nR()){const t=e?.getItem(tR);return t==="direct_mentions"||t==="none"?t:"all"}function TZ(e,t=nR()){try{t?.setItem(tR,e)}catch{}}function EZ(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 MZ(e){const t=e.message.authorUserId?e.members.find(s=>s.userId===e.message.authorUserId)?.name??"Team member":e.message.authorType==="agent"?"Agent":"Team",n=e.thread.title?.trim()||(e.thread.kind==="general"?"general":"conversation"),a=e.thread.kind==="dm"?t:`${t} in #${n}`,i=e.message.body.replace(/\s+/g," ").trim()||(e.message.attachments.length===1?"Sent an image":e.message.attachments.length>1?`Sent ${e.message.attachments.length} images`:"New message");return{eventId:e.eventId,threadId:e.message.threadId,title:a,body:i.length>160?`${i.slice(0,157)}…`:i}}const kS={members:[],agents:[],threads:[],selectedThreadId:null,detail:null,aiThread:null,agentConversation:null,loading:!1,busy:!1,error:null};function td(e,t){return e.map(n=>n.id===t&&n.unreadCount!==0?{...n,unreadCount:0}:n)}function nd(e){return!e||e.thread.unreadCount===0?e:{...e,thread:{...e.thread,unreadCount:0}}}function jZ(e){return{teamId:e.teamId,body:e.body.trim(),clientRequestId:e.clientRequestId,selectedAgentId:e.conversation.agent.id,conversationId:e.conversation.conversationId}}function OZ(e){return{teamId:e.teamId,body:e.body.trim(),clientRequestId:e.clientRequestId,selectedActionKey:e.selectedActionKey,approvalId:e.approvalId??null}}async function wS(e,t=Q.markTeamChatRead){return e.lastMessageSequence<=0?!1:t(e.connection,e.threadId,e.teamId,e.lastMessageSequence).then(()=>!0,()=>!1)}function $Z(e){const[t,n]=v.useState(kS),a=v.useRef(t);a.current=t;const[o,i]=v.useState(xS);fc(()=>i(xS()));const[s,l]=v.useState(null),m=v.useRef(null),d=v.useRef(null),h=v.useRef(0),g=v.useRef(new Map),y=v.useRef(new Map),w=v.useRef(0),_=v.useRef(null),P=v.useRef(0),M=v.useRef(new Set),C=v.useRef(0),N=v.useRef(!1),$=v.useRef(new Map),j=v.useRef(new Map),[x,R]=v.useState(null),[E,U]=v.useState(null),B=v.useCallback(L=>{i(L),TZ(L)},[]),D=v.useCallback(L=>{l(O=>O?.eventId===L?null:O)},[]),W=v.useCallback(async()=>{if(!e.connection||!e.teamId)return[];const L=await Q.teamChatThreads(e.connection,e.teamId),O=xZ(L.threads,$.current);return n(z=>({...z,threads:O})),O},[e.connection,e.teamId]),se=v.useCallback(async()=>{if(!e.connection||!e.teamId)return{members:[],agents:[]};const[L,O]=await Promise.all([Q.teamChatMembers(e.connection,e.teamId),Q.teamChatAgents(e.connection,e.teamId)]);return n(z=>({...z,members:L.members,agents:O.agents})),{members:L.members,agents:O.agents}},[e.connection,e.teamId]),de=v.useCallback(async L=>{const O=L??m.current;if(!e.connection||!e.teamId||!O)return null;const z=(y.current.get(O)??0)+1;y.current.set(O,z);const X=await Q.teamChatThread(e.connection,e.teamId,O);yf(X.messages,$.current,j.current);const me=bf(X,$.current);return y.current.get(O)!==z||(n($e=>$e.selectedThreadId===O?{...$e,threads:td($e.threads,O),detail:nd(SZ($e.detail,me))}:$e),m.current===O&&me.thread.lastMessageSequence>0&&await Q.markTeamChatRead(e.connection,O,e.teamId,me.thread.lastMessageSequence).catch(()=>{})),me},[e.connection,e.teamId]),Me=v.useCallback(async L=>{const O=L??d.current;if(!e.connection||!e.teamId||!O)return null;const z=(g.current.get(O)??0)+1;g.current.set(O,z);const X=await Q.teamChatAiThread(e.connection,e.teamId,O);return g.current.get(O)===z&&d.current===O&&n(me=>gS(me,X,d.current)),X},[e.connection,e.teamId]),ke=v.useCallback(async L=>{const O=L??_.current;if(!e.connection||!e.teamId||!O)return null;const z=await Q.teamChatAgentConversation(e.connection,e.teamId,O);return n(X=>X.agentConversation?.run.id===O?{...X,agentConversation:z}:X),z},[e.connection,e.teamId]);v.useEffect(()=>{m.current=t.selectedThreadId},[t.selectedThreadId]),v.useEffect(()=>{_.current=t.agentConversation?.run.id??null},[t.agentConversation?.run.id]),v.useEffect(()=>{const L=t.agentConversation?.run.status;if(!L||!["pending","queued","running"].includes(L))return;const O=window.setInterval(()=>{ke().catch(z=>{n(X=>({...X,error:hn(z)}))})},2500);return()=>window.clearInterval(O)},[ke,t.agentConversation?.run.status]),v.useEffect(()=>{if(!e.connection||!e.teamId||!e.currentUserId){n(kS),R(null),U(null),j.current.clear(),$.current.clear(),y.current.clear(),g.current.clear(),w.current+=1,l(null),M.current.clear(),C.current=0,P.current=0;return}let L=!1;return d.current=null,h.current+=1,w.current+=1,R(null),U(null),j.current.clear(),$.current.clear(),M.current.clear(),C.current=0,n(O=>({...O,aiThread:null,agentConversation:null,loading:!0,error:null})),(async()=>{try{const O=await Q.teamChatEvents(e.connection,e.teamId);if(L)return;P.current=O.cursor;const z=Q.teamChatMembers(e.connection,e.teamId),X=Q.teamChatAgents(e.connection,e.teamId),me=await Q.teamChatGeneral(e.connection,e.teamId),[$e,Le,nt]=await Promise.all([z,X,Q.teamChatThreads(e.connection,e.teamId)]);if(L)return;const at=m.current&&nt.threads.some(je=>je.id===m.current)?m.current:me.thread.id,lt=at===me.thread.id?me:await Q.teamChatThread(e.connection,e.teamId,at);if(L)return;const pt=nd(lt);n(je=>({...je,members:$e.members,agents:Le.agents,threads:td(nt.threads,at),selectedThreadId:at,detail:pt,loading:!1,error:null})),wS({connection:e.connection,teamId:e.teamId,threadId:at,lastMessageSequence:pt?.thread.lastMessageSequence??0}),U(e.teamId)}catch(O){if(L)return;n(z=>({...z,loading:!1,error:hn(O)}))}})(),()=>{L=!0}},[e.connection,e.currentUserId,e.refreshToken,e.teamId]);const te=v.useCallback(L=>{if(M.current.has(L.id))return;if(M.current.add(L.id),M.current.size>2e3){const z=M.current.values().next().value;typeof z=="number"&&M.current.delete(z)}const O=XC(L);if(O&&L.type==="message.created"){const z=a.current,X=z.threads.find($e=>$e.id===O.threadId)??(z.detail?.thread.id===O.threadId?z.detail.thread:null),me=$e=>{L.id<=C.current||EZ({mode:o,currentUserId:e.currentUserId,message:O,thread:$e})&&(C.current=L.id,l(MZ({eventId:L.id,message:O,thread:$e,members:z.members})))};X?me(X):W().then($e=>{const Le=$e.find(nt=>nt.id===O.threadId);Le&&me(Le)}).catch(()=>{})}O?.clientRequestId&&!O.id.startsWith("pending:")&&($.current.delete(O.clientRequestId),j.current.delete(O.clientRequestId)),n(z=>eR(z,L,e.currentUserId)),L.type==="thread.created"&&W().catch(z=>{n(X=>({...X,error:hn(z)}))}),(L.type==="ai_thread.created"||L.type==="ai_turn.updated")&&(de(L.threadId).catch(z=>{n(X=>({...X,error:hn(z)}))}),L.conversationId===d.current&&Me(L.conversationId).catch(z=>{n(X=>({...X,error:hn(z)}))})),O&&L.type==="message.created"&&m.current===O.threadId&&O.authorUserId!==e.currentUserId&&e.connection&&e.teamId&&Q.markTeamChatRead(e.connection,O.threadId,e.teamId,O.sequence).catch(()=>{})},[e.connection,e.currentUserId,e.teamId,o,Me,de,W]),Ee=v.useCallback(async()=>{if(!(!e.connection||!e.teamId||N.current)){N.current=!0;try{let L=!0;for(;L;){const O=await Q.teamChatEvents(e.connection,e.teamId,{after:P.current,limit:250});for(const z of O.events)te(z);P.current=O.cursor,L=O.hasMore}}finally{N.current=!1}}},[te,e.connection,e.teamId]);v.useEffect(()=>{if(!e.connection||!e.teamId||E!==e.teamId)return;let L=!1,O=null;const z=async()=>{try{const X=await Q.teamChatRealtimeSession(e.connection,e.teamId);if(L||(await Ee(),L))return;R(X);const me=Math.max(3e4,new Date(X.expiresAt).getTime()-Date.now()-3e4);O=window.setTimeout(()=>{z()},me)}catch{L||(Ee().catch(()=>{}),O=window.setTimeout(()=>{z()},1e4))}};return z(),()=>{L=!0,O!==null&&window.clearTimeout(O),R(null)}},[Ee,e.connection,e.teamId,E]);const ye=t.threads.map(L=>L.id).sort().join(",");v.useEffect(()=>{if(!x)return;const L=fZ({session:x,threadIds:ye?ye.split(","):[],onEvent:te,onReady:()=>{Ee().catch(O=>{n(z=>({...z,error:hn(O)}))})},onError:()=>{Ee().catch(()=>{})}});return()=>{L.close()}},[te,Ee,x,ye]),v.useEffect(()=>{if(!e.connection||!e.teamId||E!==e.teamId)return;const L=window.setInterval(()=>{Ee().catch(()=>{})},15e3);return()=>window.clearInterval(L)},[Ee,e.connection,e.teamId,E]);const ne=v.useCallback(async L=>{if(!e.connection||!e.teamId)return;const O=w.current+1;w.current=O;const z=m.current!==L;m.current=L,z&&(h.current+=1,d.current=null),n(X=>({...X,threads:td(X.threads,L),selectedThreadId:L,detail:X.detail?.thread.id===L?nd(X.detail):null,aiThread:z?null:X.aiThread,agentConversation:z?null:X.agentConversation,loading:!0,error:null}));try{const X=await Q.teamChatThread(e.connection,e.teamId,L);if(w.current!==O||m.current!==L)return;yf(X.messages,$.current,j.current);const me=bf(X,$.current);n($e=>({...$e,threads:td($e.threads,L),detail:nd(me),loading:!1})),await Q.markTeamChatRead(e.connection,L,e.teamId,me.thread.lastMessageSequence).catch(()=>{})}catch(X){if(w.current!==O)return;n(me=>({...me,loading:!1,error:hn(X)}))}},[e.connection,e.teamId]),be=v.useCallback(async L=>{if(!e.connection||!e.teamId)return null;const O=w.current+1;w.current=O,n(z=>({...z,busy:!0,error:null}));try{const z=await Q.teamChatDm(e.connection,e.teamId,L);if(w.current!==O)return null;yf(z.messages,$.current,j.current);const X=bf(z,$.current),me=m.current!==X.thread.id;return m.current=X.thread.id,me&&(h.current+=1,d.current=null),n($e=>({...$e,selectedThreadId:X.thread.id,detail:X,aiThread:me?null:$e.aiThread,agentConversation:me?null:$e.agentConversation,busy:!1})),await wS({connection:e.connection,teamId:e.teamId,threadId:X.thread.id,lastMessageSequence:X.thread.lastMessageSequence}),await W(),X}catch(z){return w.current!==O||n(X=>({...X,busy:!1,error:hn(z)})),null}},[e.connection,e.teamId,W]),ae=v.useCallback(async()=>{const L=t.detail,O=L?.messages[0]?.sequence;if(!e.connection||!e.teamId||!L||!L.hasMoreBefore||O==null)return!1;n(z=>({...z,loading:!0,error:null}));try{const z=await Q.teamChatThread(e.connection,e.teamId,L.thread.id,{beforeSequence:O,limit:50});return n(X=>{if(X.detail?.thread.id!==L.thread.id)return X;const me=[...z.messages,...X.detail.messages];return{...X,loading:!1,detail:{...X.detail,messages:bc(me),hasMoreBefore:z.hasMoreBefore}}}),!0}catch(z){return n(X=>({...X,loading:!1,error:hn(z)})),!1}},[e.connection,e.teamId,t.detail]),ue=v.useCallback(async L=>{const O=m.current,z=CZ(L.attachments??[]);if(!z)return n($e=>({...$e,error:"Team chat supports up to 10 PNG, JPEG, WebP, or GIF images per message."})),!1;if(!e.connection||!e.teamId||!O||!L.body.trim()&&z.length===0)return!1;if(L.replyToMessage&&(L.replyToMessage.threadId!==O||L.replyToMessage.teamId!==e.teamId||L.replyToMessage.id.startsWith("pending:")||L.replyToMessage.deletedAt))return n($e=>({...$e,error:"That message is no longer available to reply to."})),!1;if(L.useModel){if(z.length>0)return n(Le=>({...Le,error:"Images can be sent to the team thread with Use model turned off."})),!1;const $e=h.current;n(Le=>({...Le,busy:!0,error:null}));try{const Le=await Q.createTeamChatAiThread(e.connection,O,{teamId:e.teamId,body:L.body.trim(),clientRequestId:crypto.randomUUID(),providerId:L.providerId,modelId:L.modelId}),nt=h.current===$e&&m.current===O;return nt&&(h.current+=1,d.current=Le.conversationId),n(at=>({...at,aiThread:nt?Le:at.aiThread})),Le.activeTurn&&await Q.executeTeamChatAiTurn(e.connection,Le.activeTurn.id,e.teamId),await Promise.all([de(O),W()]),n(at=>({...at,busy:!1})),!0}catch(Le){return n(nt=>({...nt,busy:!1,error:hn(Le)})),!1}}const X=crypto.randomUUID();if(L.selectedActionKey){if(z.length>0)return n($e=>({...$e,error:"Agent invocations do not support image attachments yet."})),!1;n($e=>({...$e,busy:!0,error:null}));try{return await Q.createTeamChatAgentRun(e.connection,O,OZ({teamId:e.teamId,body:L.body,clientRequestId:X,selectedActionKey:L.selectedActionKey,approvalId:L.approvalId})),await Promise.all([de(O),W()]),n($e=>({...$e,busy:!1})),!0}catch($e){return n(Le=>({...Le,busy:!1,error:hn($e)})),!1}}j.current.set(X,{inputs:z,uploaded:null});const me=kZ({clientRequestId:X,threadId:O,teamId:e.teamId,userId:e.currentUserId,body:L.body.trim(),mentionUserIds:L.mentionUserIds??[],attachments:z,replyToMessage:L.replyToMessage,sequence:(t.detail?.thread.lastMessageSequence??0)+1});$.current.set(X,me),n($e=>wZ($e,me));try{const $e=[];for(const[at,lt]of z.entries())$e.push(await Q.uploadTeamChatAttachment(e.connection,O,{teamId:e.teamId,attachment:lt})),vS($.current,X,`${at+1} of ${z.length}`),n(pt=>yS(pt,X,`${at+1} of ${z.length}`));const Le=j.current.get(X);Le&&(Le.uploaded=$e);const nt=await Q.sendTeamChatMessage(e.connection,O,{teamId:e.teamId,body:L.body.trim(),clientRequestId:X,mentionUserIds:L.mentionUserIds,attachmentIds:$e.map(at=>at.id),replyToMessageId:L.replyToMessage?.id??null});return j.current.delete(X),$.current.delete(X),n(at=>bS(at,nt,e.currentUserId)),!0}catch($e){return Sf($.current,X,"failed"),n(Le=>({...IZ(Le,X),error:hn($e)})),!1}},[e.connection,e.currentUserId,e.teamId,de,W,t.detail?.thread.lastMessageSequence]),xe=v.useCallback(async L=>{if(!(!e.connection||!e.teamId)){h.current+=1,d.current=L,n(O=>({...O,aiThread:O.aiThread?.conversationId===L?O.aiThread:null,busy:!0,error:null}));try{const O=await Q.teamChatAiThread(e.connection,e.teamId,L);if(d.current!==L)return;n(z=>({...z,aiThread:O,busy:!1}))}catch(O){if(d.current!==L)return;n(z=>({...z,busy:!1,error:hn(O)}))}}},[e.connection,e.teamId]),De=v.useCallback(async L=>{if(!(!e.connection||!e.teamId)){_.current=L,n(O=>({...O,busy:!0,error:null}));try{const O=await Q.teamChatAgentConversation(e.connection,e.teamId,L);n(z=>({...z,agentConversation:O,busy:!1}))}catch(O){n(z=>({...z,busy:!1,error:hn(O)}))}}},[e.connection,e.teamId]),we=v.useCallback(()=>{_.current=null,n(L=>({...L,agentConversation:null}))},[]),oe=v.useCallback(async L=>{const O=m.current,z=t.agentConversation;if(!e.connection||!e.teamId||!O||!z||!L.body.trim())return!1;n(X=>({...X,busy:!0,error:null}));try{const X=await Q.createTeamChatAgentRun(e.connection,O,jZ({teamId:e.teamId,body:L.body,clientRequestId:L.clientRequestId,conversation:z}));_.current=X.run.id;const[me]=await Promise.all([Q.teamChatAgentConversation(e.connection,e.teamId,X.run.id),de(O),W()]);return n($e=>({...$e,agentConversation:me,busy:!1})),!0}catch(X){return n(me=>({...me,busy:!1,error:hn(X)})),!1}},[e.connection,e.teamId,de,W,t.agentConversation]),Se=v.useCallback(()=>{h.current+=1,d.current=null,n(L=>({...L,aiThread:null}))},[]),He=v.useCallback(async L=>{const O=d.current;if(!e.connection||!e.teamId||!O||!L.body.trim())return!1;n(z=>({...z,busy:!0,error:null}));try{const z=await Q.sendTeamChatAiTurn(e.connection,O,{teamId:e.teamId,body:L.body.trim(),clientRequestId:crypto.randomUUID(),providerId:L.providerId,modelId:L.modelId});return n(X=>({...gS(X,z,d.current),busy:!1})),z.activeTurn&&await Q.executeTeamChatAiTurn(e.connection,z.activeTurn.id,e.teamId),!0}catch(z){return n(X=>({...X,busy:!1,error:hn(z)})),!1}},[e.connection,e.teamId]),Ze=v.useCallback(async()=>{const L=t.aiThread?.activeTurn?.id;return!e.connection||!e.teamId||!L?!1:(await Q.cancelTeamChatAiTurnExecution(e.connection,L,e.teamId)).cancelled},[e.connection,e.teamId,t.aiThread?.activeTurn?.id]),Ke=v.useCallback(async(L,O)=>{if(!e.connection||!e.teamId)return!1;try{return await Q.editTeamChatMessage(e.connection,L.threadId,L.id,{teamId:e.teamId,body:O}),await de(L.threadId),!0}catch(z){return n(X=>({...X,error:hn(z)})),!1}},[e.connection,e.teamId,de]),tt=v.useCallback(async L=>{if(!e.connection||!e.teamId)return!1;try{return await Q.deleteTeamChatMessage(e.connection,L.threadId,L.id,e.teamId),await de(L.threadId),!0}catch(O){return n(z=>({...z,error:hn(O)})),!1}},[e.connection,e.teamId,de]),qe=v.useCallback(async L=>{if(!e.connection||!e.teamId||!L.clientRequestId||!L.id.startsWith("pending:"))return!1;const O=Array.isArray(L.metadata.mentionUserIds)?L.metadata.mentionUserIds.filter(me=>typeof me=="string"):[],z=j.current.get(L.clientRequestId),X=L.refs.find(me=>me.refType==="message_reply");Sf($.current,L.clientRequestId,"sending"),n(me=>Rh(me,L.clientRequestId,"sending"));try{let me=z?.uploaded??[];if(z&&!z.uploaded){me=[];for(const[Le,nt]of z.inputs.entries())me.push(await Q.uploadTeamChatAttachment(e.connection,L.threadId,{teamId:e.teamId,attachment:nt})),vS($.current,L.clientRequestId,`${Le+1} of ${z.inputs.length}`),n(at=>yS(at,L.clientRequestId,`${Le+1} of ${z.inputs.length}`));z.uploaded=me}const $e=await Q.sendTeamChatMessage(e.connection,L.threadId,{teamId:e.teamId,body:L.body,clientRequestId:L.clientRequestId,mentionUserIds:O,attachmentIds:me.map(Le=>Le.id),replyToMessageId:X?.refId??null});return j.current.delete(L.clientRequestId),$.current.delete(L.clientRequestId),n(Le=>bS(Le,$e,e.currentUserId)),!0}catch(me){return Sf($.current,L.clientRequestId,"failed"),n($e=>({...Rh($e,L.clientRequestId,"failed"),error:hn(me)})),!1}},[e.connection,e.currentUserId,e.teamId]),Ge=v.useCallback(L=>{L.id.startsWith("pending:")&&(L.clientRequestId&&j.current.delete(L.clientRequestId),L.clientRequestId&&$.current.delete(L.clientRequestId),n(O=>_Z(O,L.id)))},[]),ze=v.useCallback(async(L,O)=>{if(!e.connection||!e.teamId)return!1;try{const z=await Q.setTeamChatThreadMuted(e.connection,L,e.teamId,O),X=me=>me.id===z.threadId?{...me,mutedAt:z.mutedAt}:me;return n(me=>({...me,threads:me.threads.map(X),detail:me.detail?.thread.id===z.threadId?{...me.detail,thread:X(me.detail.thread)}:me.detail,error:null})),!0}catch(z){return n(X=>({...X,error:hn(z)})),!1}},[e.connection,e.teamId]);return{...t,currentUserId:e.currentUserId,notificationMode:o,incomingNotification:s,setNotificationMode:B,dismissIncomingNotification:D,setThreadMuted:ze,selectThread:ne,openDm:be,loadMoreMessages:ae,sendMessage:ue,openAiThread:xe,openAgentConversation:De,closeAgentConversation:we,sendAgentTurn:oe,closeAiThread:Se,sendAiTurn:He,stopAiTurn:Ze,editMessage:Ke,deleteMessage:tt,retryMessage:qe,dismissFailedMessage:Ge,refreshDirectory:se,refresh:async()=>{await Promise.all([se(),W(),de(),Me(),ke()])}}}function hn(e){return AZ(e)}const aR="local-profile-agent";function PX(e){const t=e.profile;if(!t||t.mode!=="local")return e.hostedActions;const n=new Set(e.hostedActions.flatMap(s=>{const l=s.implementation;return l?.type!=="openpond-agent"||l.profileName!==t.activeProfile?[]:[zr(l.agentName),zr(s.name),zr(s.label)].filter(Boolean)})),a=t.hosted?.teamId===e.teamId?t.hosted.hostedSourceMaterialization:null,o=new Set(e.hostedActions.map(s=>s.implementation?.agentId).filter(s=>typeof s=="string")),i=t.agents.flatMap(s=>s.enabled?a?.agentId===s.id&&!!(a.runtimeAgentId&&o.has(a.runtimeAgentId))||n.has(zr(s.name))||n.has(zr(s.id))?[]:[LZ(t,s)]:[]);return[...e.hostedActions,...i]}function AX(e){return e?.implementation?.type===aR}function TX(e){const t=e.implementation?.profileAgentId;return typeof t=="string"&&t.trim()?t.trim():null}function NZ(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 DZ(e,t){const n=t.runtimeAgentId?.trim()??"",a=t.profileName?.trim()??"",o=zr(t.agentName);return e.find(i=>{const s=i.implementation;return s?.type!=="openpond-agent"?!1:n&&typeof s.agentId=="string"&&s.agentId===n?!0:!!(a&&s.profileName===a&&o&&[s.agentName,i.name,i.label].some(l=>zr(l)===o))})??null}function LZ(e,t){return{id:`local-profile:${e.activeProfile??"default"}:${t.id}:chat`,name:t.name,label:t.name,description:UZ(e),approvalPolicy:{required:!1,risk:"write"},setupRequirements:e.setupGate.blockingRequirements,invokesModel:!0,implementation:{type:aR,profileAgentId:t.id,profileName:e.activeProfile??"default"}}}function UZ(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 zr(e){return typeof e=="string"?e.trim().toLowerCase().replace(/[^a-z0-9]+/g,""):""}const IS=5;function HZ(e){return v.useCallback(async t=>{if(!e.connection||!e.teamId)throw new Error("Connect OpenPond to a Team before publishing an agent.");const n=await Q.profileCheck(e.connection,{kind:"all"}),a=NZ(n,t);if(a)throw new Error(a);const o=n?.agents.find(d=>d.id===t);if(!o)throw new Error(`Profile agent not found: ${t}`);const s=(await Q.profilePush(e.connection,{teamId:e.teamId,ensureHosted:!0,hostedSourceAgentId:t,message:null})).localProfile?.hosted?.hostedSourceMaterialization,l=s?.agentId===t?s.runtimeAgentId:null;e.applyBootstrapPayload(await Q.bootstrap(e.connection));let m=null;for(let d=0;d<IS;d+=1){const h=await e.refreshDirectory();if(m=DZ(h.agents,{runtimeAgentId:l,profileName:n.activeProfile,agentName:o.name}),m)break;d<IS-1&&await zZ(200*(d+1))}if(!m)throw new Error(`${o.name} was published, but the Team agent directory has not refreshed yet. Retry the mention in a moment.`);return m},[e.applyBootstrapPayload,e.connection,e.refreshDirectory,e.teamId])}function zZ(e){return new Promise(t=>{setTimeout(t,e)})}function qZ(e){v.useEffect(()=>{if(!e.notification)return;const{eventId:t,threadId:n,title:a,body:o}=e.notification;e.showToast(`${a}: ${o}`,"info",{actionLabel:"Open",onAction:()=>{e.setView("team"),e.selectThread(n)},durationMs:6500,placement:"top-right"}),e.dismiss(t)},[e.dismiss,e.notification,e.selectThread,e.setView,e.showToast])}function BZ(e){const{connection:t,refreshToken:n=null}=e,[a,o]=v.useState([]),[i,s]=v.useState(null),[l,m]=v.useState(null),[d,h]=v.useState(null),[g,y]=v.useState(!1),[w,_]=v.useState(!1),[P,M]=v.useState(!1),[C,N]=v.useState(null),[$,j]=v.useState(null),[x,R]=v.useState(null),[E,U]=v.useState(0),B=v.useRef(0),D=v.useMemo(()=>a.find(ae=>ae.id===l)??null,[a,l]),W=v.useCallback(async()=>{if(!t)return!1;y(!0),N(null);try{const ae=await Q.communities(t);return o(ae.items),s(ae.nextCursor),m(ue=>ue&&ae.items.some(xe=>xe.id===ue)?ue:null),!0}catch(ae){return N(_d(ae)),!1}finally{y(!1)}},[t]),se=v.useCallback(async()=>{if(!t||!i||g)return!1;y(!0),N(null);try{const ae=await Q.communities(t,i);return o(ue=>FZ(ue,ae.items)),s(ae.nextCursor),!0}catch(ae){return N(_d(ae)),!1}finally{y(!1)}},[t,g,i]),de=v.useCallback(async ae=>{if(!t)return null;const ue=++B.current;_(!0),j(null);try{const xe=await Q.communityPreview(t,ae.slug);return B.current===ue&&h(xe),xe}catch(xe){return B.current===ue&&j(_d(xe)),null}finally{B.current===ue&&_(!1)}},[t]),Me=v.useCallback(ae=>{const ue=a.find(xe=>xe.id===ae);ue&&(m(ue.id),h(xe=>xe?.id===ue.id?xe:null),R(null),de(ue))},[a,de]),ke=v.useCallback(()=>{B.current+=1,m(null),h(null),j(null),R(null)},[]);v.useEffect(()=>{if(!t){o([]),h(null),m(null);return}W()},[t,W,n]),v.useEffect(()=>{!D||d?.id===D.id||w||de(D)},[de,d?.id,w,D]);const te=v.useCallback(async()=>{const ae=D;await W(),ae&&await de(ae)},[de,W,D]),Ee=v.useCallback(async()=>{if(!t||!d?.currentRules||P)return!1;M(!0),R(null);try{return await Q.joinCommunity(t,d.id,d.currentRules.id),U(ae=>ae+1),await te(),!0}catch(ae){const ue=ad(ae);return R(ue),ue.kind==="rules_stale"&&await te(),!1}finally{M(!1)}},[t,P,d,te]),ye=v.useCallback(async()=>{if(!t||!d?.currentRules||P)return!1;M(!0),R(null);try{return await Q.acceptCommunityRules(t,d.id,d.currentRules.id),U(ae=>ae+1),await te(),!0}catch(ae){const ue=ad(ae);return R(ue),ue.kind==="rules_stale"&&await te(),!1}finally{M(!1)}},[t,P,d,te]),ne=v.useCallback(async()=>{if(!t||!d||P)return!1;M(!0),R(null);try{return await Q.leaveCommunity(t,d.id),U(ae=>ae+1),await te(),!0}catch(ae){return R(ad(ae)),!1}finally{M(!1)}},[t,P,d,te]),be=v.useCallback(async ae=>{if(!t||!d||P)return!1;M(!0),R(null);try{return await Q.updateCommunityNotifications(t,d.id,ae),o(ue=>ue.map(xe=>xe.id===d.id&&xe.membership?{...xe,membership:{...xe.membership,notificationMode:ae}}:xe)),h(ue=>ue?.id===d.id&&ue.membership?{...ue,membership:{...ue.membership,notificationMode:ae}}:ue),!0}catch(ue){return R(ad(ue)),!1}finally{M(!1)}},[t,P,d]);return{items:a,nextCursor:i,selectedCommunityId:l,selectedSummary:D,preview:d,discoveryLoading:g,previewLoading:w,membershipBusy:P,discoveryError:C,previewError:$,membershipError:x,membershipVersion:E,refresh:W,loadMore:se,showDiscovery:ke,selectCommunity:Me,join:Ee,acceptRules:ye,leave:ne,updateNotifications:be,clearMembershipError:()=>R(null)}}function FZ(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 _d(e){return e instanceof Error?e.message:String(e)}function ad(e){const t=_d(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 VZ(e,t,n){return QC({realtimeUrl:e.session.realtimeUrl,httpUrl:e.session.httpUrl,authorizationToken:e.session.token,channels:[e.session.channel],onEvent:a=>{const o=jw.safeParse(a);o.success&&e.onEvent(o.data)},onReady:e.onReady,onError:e.onError},t,n)}function KZ(e){const{connection:t,preview:n,currentUserId:a,membershipVersion:o}=e,i=n?.id??null,s=n?.membership?.status==="active",l=!n?.capabilities.requiresRulesAcceptance,[m,d]=v.useState([]),[h,g]=v.useState(null),[y,w]=v.useState({}),[_,P]=v.useState([]),[M,C]=v.useState(!1),[N,$]=v.useState(!1),[j,x]=v.useState(!1),[R,E]=v.useState(!1),[U,B]=v.useState(null),[D,W]=v.useState(null),[se,de]=v.useState(null),[Me,ke]=v.useState(null),[te,Ee]=v.useState(!1),[ye,ne]=v.useState(null),[be,ae]=v.useState(null),ue=v.useRef(null),xe=v.useRef([]),De=v.useRef("mentions"),we=v.useRef(0),oe=v.useRef({}),Se=v.useRef(new Set),He=v.useMemo(()=>m.find(je=>je.id===h)??null,[m,h]),Ze=h?y[h]??null:null;v.useEffect(()=>{ue.current=h},[h]),v.useEffect(()=>{xe.current=m},[m]),v.useEffect(()=>{De.current=n?.membership?.notificationMode??"mentions"},[n?.membership?.notificationMode]);const Ke=v.useCallback(async()=>{if(!t||!i)return!1;C(!0),B(null);try{const je=await Q.communityChannels(t,i);return d(je.channels),g(Ye=>Ye&&je.channels.some(f=>f.id===Ye)?Ye:je.channels.find(f=>f.isDefault)?.id??je.channels[0]?.id??null),Ee(!1),!0}catch(je){const Ye=oa(je);return B(Ye),ll(Ye)&&Ee(!0),!1}finally{C(!1)}},[i,t]),tt=v.useCallback(async je=>{if(!t||!i)return!1;const Ye=++we.current;$(!0),W(null);try{const f=await Q.communityMessages(t,i,je,{limit:50});return Ye!==we.current?!1:(w(H=>({...H,[je]:{items:f.messages,hasMoreBefore:f.hasMoreBefore,preview:f.preview}})),Ee(!1),!0)}catch(f){if(Ye!==we.current)return!1;const H=oa(f);return W(H),ll(H)&&Ee(!0),!1}finally{Ye===we.current&&$(!1)}},[i,t]);v.useEffect(()=>{d(n?.channels??[]),w({}),g(n?.channels.find(je=>je.isDefault)?.id??n?.channels[0]?.id??null),B(null),W(null),de(null),Ee(!1),Se.current.clear(),i&&Ke()},[i,Ke,o]),v.useEffect(()=>{h&&tt(h)},[tt,h]);const qe=v.useCallback(async(je,Ye)=>{if(!t||!i||!s||!l||Ye<=0)return!1;if((oe.current[je]??0)>=Ye)return!0;oe.current[je]=Ye;try{const f=await Q.markCommunityRead(t,i,je,Ye);return d(H=>H.map(Y=>Y.id===je?{...Y,unreadCount:0,readState:Y.readState?{...Y.readState,lastReadSequence:f.sequence,lastReadAt:new Date().toISOString()}:{lastReadSequence:f.sequence,lastReadAt:new Date().toISOString(),mutedAt:null,pinnedAt:null}}:Y)),!0}catch(f){const H=oa(f);return ll(H)&&Ee(!0),!1}},[i,t,s,l]);v.useEffect(()=>{const je=Ze?.items.at(-1)?.sequence??0;h&&je>0&&qe(h,je)},[qe,h,Ze?.items]);const Ge=v.useCallback(je=>{if(je.communityId!==i||Se.current.has(je.id))return;Se.current.add(je.id);const Ye=Mw.safeParse(je.payload.message);if(Ye.success&&je.type!=="read.updated"){const f=Ye.data;if(w(H=>{const Y=H[je.channelId];if(!Y)return H;const ie=Y.items.some(K=>K.id===f.id)?Y.items.map(K=>K.id===f.id?f:K):[...Y.items,f].sort((K,I)=>K.sequence-I.sequence);return{...H,[je.channelId]:{...Y,items:ie}}}),d(H=>H.map(Y=>Y.id===je.channelId?{...Y,lastMessageSequence:Math.max(Y.lastMessageSequence,f.sequence),unreadCount:ue.current===je.channelId||f.authorUserId===a?0:Math.max(Y.unreadCount+(je.type==="message.created"?1:0),0)}:Y)),je.type==="message.created"&&f.authorUserId!==a){const H=xe.current.find(ie=>ie.id===je.channelId),Y=WZ(f).includes(a??""),he=De.current;!H?.readState?.mutedAt&&(he==="all"||he==="mentions"&&Y)&&ae({communityId:je.communityId,channelId:je.channelId,message:f})}ue.current===je.channelId&&qe(je.channelId,f.sequence);return}je.type==="read.updated"&&je.payload.userId===a&&Ke()},[i,a,Ke,qe]);v.useEffect(()=>{if(!t||!i||!s||!l)return;let je=!1,Ye=null;return de(null),Promise.all([Q.communityRealtimeSession(t,i),Q.communityEvents(t,i)]).then(async([f,H])=>{if(je)return;const Y=async()=>{let ie=H.cursor;for(;;){const K=await Q.communityEvents(t,i,{after:ie,limit:200});if(je)return;for(const I of K.events)Ge(I);if(ie=K.cursor,!K.hasMore)return}},he=VZ({session:f,onEvent:Ge,onReady:()=>{de(null),Y().catch(ie=>de(oa(ie)))},onError:ie=>de(oa(ie))});Ye=()=>he.close(),await Y()}).catch(f=>{if(!je){const H=oa(f);de(H),ll(H)&&Ee(!0)}}),()=>{je=!0,Ye?.()}},[Ge,i,t,s,o,l]);const ze=v.useCallback(async()=>{if(!t||!i||!h||j)return!1;const je=y[h],Ye=je?.items[0]?.sequence;if(!je?.hasMoreBefore||Ye==null)return!1;x(!0),W(null);try{const f=await Q.communityMessages(t,i,h,{beforeSequence:Ye,limit:50});return w(H=>{const Y=H[h]??je,he=new Set(Y.items.map(ie=>ie.id));return{...H,[h]:{...Y,items:[...f.messages.filter(ie=>!he.has(ie.id)),...Y.items],hasMoreBefore:f.hasMoreBefore}}}),!0}catch(f){return W(oa(f)),!1}finally{x(!1)}},[i,t,y,j,h]),L=v.useCallback(async je=>{if(!t||!i||!h||R)return!1;E(!0),ke(null),ne(null);try{const Ye=await Promise.all(je.attachments.map(H=>Q.uploadCommunityAttachment(t,i,h,H))),f=await Q.sendCommunityMessage(t,i,h,{body:je.body,clientRequestId:je.clientRequestId,mentionUserIds:je.mentionUserIds,attachmentIds:Ye.map(H=>H.id),replyToMessageId:je.replyToMessageId});return w(H=>{const Y=H[h]??{items:[],hasMoreBefore:!1,preview:!1};return Y.items.some(he=>he.id===f.id)?H:{...H,[h]:{...Y,items:[...Y.items,f]}}}),await qe(h,f.sequence),!0}catch(Ye){const f=oa(Ye);return ke(f),ne({...je,message:f}),ll(f)&&Ee(!0),!1}finally{E(!1)}},[i,t,qe,h,R]),O=v.useCallback(je=>L({body:je.body,clientRequestId:crypto.randomUUID(),mentionUserIds:je.mentionUserIds??[],attachments:je.attachments??[],replyToMessageId:je.replyToMessageId??null}),[L]),z=v.useCallback(async(je,Ye)=>{if(!t||!i||!h)return!1;ke(null);try{const f=await Q.editCommunityMessage(t,i,h,je,Ye);return _S(w,h,f),!0}catch(f){return ke(oa(f)),!1}},[i,t,h]),X=v.useCallback(async je=>{if(!t||!i||!h)return!1;ke(null);try{const Ye=await Q.deleteCommunityMessage(t,i,h,je);return _S(w,h,Ye),!0}catch(Ye){return ke(oa(Ye)),!1}},[i,t,h]),me=v.useCallback(async(je,Ye)=>{if(!t||!i)return!1;ke(null);try{const f=await Q.setCommunityChannelMuted(t,i,je,Ye);return d(H=>H.map(Y=>Y.id===je&&Y.readState?{...Y,readState:{...Y.readState,mutedAt:f.mutedAt}}:Y)),!0}catch(f){return ke(oa(f)),!1}},[i,t]),$e=v.useCallback(async(je="")=>{if(!t||!i||!s)return[];try{const Ye=await Q.searchCommunityMembers(t,i,{query:je,limit:50});return P(f=>GZ(f,Ye.items)),Ye.items}catch(Ye){return ke(oa(Ye)),[]}},[i,t,s]);v.useEffect(()=>{s&&l?$e():P([])},[s,l,$e]);const Le=v.useCallback(async je=>{if(!t||!i||!h)return!1;try{const Ye=await Q.communityAttachmentDownload(t,i,h,je);return window.open(Ye.url,"_blank","noopener,noreferrer"),!0}catch(Ye){return ke(oa(Ye)),!1}},[i,t,h]),nt=v.useCallback(()=>h?tt(h):Promise.resolve(!1),[tt,h]),at=v.useCallback(()=>ye?L(ye):Promise.resolve(!1),[ye,L]),lt=v.useCallback(()=>ne(null),[]),pt=v.useCallback(()=>ae(null),[]);return{channels:m,selectedChannelId:h,selectedChannel:He,messages:Ze?.items??[],hasMoreBefore:Ze?.hasMoreBefore??!1,previewMode:Ze?.preview??!s,members:_,channelsLoading:M,messagesLoading:N,olderMessagesLoading:j,sending:R,channelsError:U,messagesError:D,realtimeError:se,actionError:Me,lostMembership:te,failedSend:ye,incomingNotification:be,selectChannel:g,loadChannels:Ke,loadMessages:nt,loadOlder:ze,sendMessage:O,retrySend:at,dismissFailedSend:lt,editMessage:z,deleteMessage:X,setMuted:me,searchMembers:$e,downloadAttachment:Le,dismissIncomingNotification:pt}}function _S(e,t,n){e(a=>{const o=a[t];return o?{...a,[t]:{...o,items:o.items.map(i=>i.id===n.id?n:i)}}:a})}function WZ(e){const t=e.metadata.mentionUserIds;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function GZ(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 ll(e){return e.includes("community_membership_required")||e.includes("community_rules")}function oa(e){return e instanceof Error?e.message:String(e)}function ZZ(e){const t=BZ({connection:e.connection,refreshToken:e.refreshToken}),n=KZ({connection:e.connection,preview:t.preview,currentUserId:e.currentUserId,membershipVersion:t.membershipVersion}),a=n.incomingNotification,o=t.items,i=n.channels,s=t.selectCommunity,l=n.selectChannel,m=n.dismissIncomingNotification,{setView:d,showToast:h}=e,g=v.useCallback(()=>{t.showDiscovery(),d("community")},[t.showDiscovery,d]),y=v.useCallback(_=>{t.selectCommunity(_),d("community")},[t.selectCommunity,d]),w=v.useCallback(_=>{n.selectChannel(_),d("community")},[n.selectChannel,d]);return v.useEffect(()=>{if(!a)return;const _=o.find(M=>M.id===a.communityId),P=i.find(M=>M.id===a.channelId);h(`${_?.displayName??"Community"} · #${P?.displayName??"channel"}: ${a.message.body.slice(0,120)||"New message"}`,"info",{actionLabel:"View",onAction:()=>{s(a.communityId),l(a.channelId),d("community")},placement:"top-right"}),m()},[i,o,m,a,l,s,d,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:g,selectCommunity:y,selectCommunityChannel:w},view:{communities:t,chat:n,currentUserId:e.currentUserId}}}const JZ=[];function YZ(e){const t=v.useCallback(a=>_9(e,a),[e]),n=v.useCallback(()=>w9(e)??JZ,[e]);return v.useSyncExternalStore(t,n,n)}function QZ(e){const[t,n]=v.useState(()=>Dp());return v.useEffect(()=>{let a=!0;return e?(Q.connectedAppStatus(e,{status:"all"}).then(o=>{a&&n(o.apps)}).catch(o=>{console.warn("Unable to load connected app mention status.",o),a&&n(Dp())}),()=>{a=!1}):(n(Dp()),()=>{a=!1})},[e]),t}function XZ(){const{composerDraftStore:e,dispatch:t,setters:n,state:a}=f7(),[o,i]=v.useState(null),[s,l]=v.useState([]),[m,d]=v.useState(null),[h,g]=v.useState(null),[y,w]=v.useState([]),[_,P]=v.useState(null),[M,C]=v.useState(null),[N,$]=v.useState(lC),[j,x]=v.useState({}),[R,E]=v.useState(()=>new Set),U=v.useCallback((ot,zt)=>{E(qt=>{if(qt.has(ot)===zt)return qt;const Bt=new Set(qt);return zt?Bt.add(ot):Bt.delete(ot),Bt})},[]),[B,D]=v.useState(0),[W,se]=v.useState(null),de=v.useRef(null),{confirmProjectAction:Me,projectConfirmDialog:ke,resolveProjectConfirmDialog:te}=fK(),{query:Ee,searchOpen:ye,archivedChatsOpen:ne,sectionMenuOpen:be,projectsExpanded:ae,cloudProjectsExpanded:ue,chatRowsVisibleCount:xe,sidebarOpen:De,view:we,selectedAppId:oe,selectedProjectId:Se,selectedSessionId:He,draftProvider:Ze,draftModel:Ke,draftExperience:tt,codexPermissionMode:qe,codexReasoningEffort:Ge,openPondCommandAccessMode:ze,busy:L,diffPanelOpen:O,diffPanelExpanded:z,rightPanelMode:X,rightChatPanels:me,terminalOpen:$e,settingsSection:Le,newProjectDialogOpen:nt,newProjectMode:at,newProjectName:lt,newProjectPath:pt,newProjectBusy:je,commitDialogOpen:Ye,commitMessage:f,commitIncludeUnstaged:H,commitNextStep:Y,commitDraft:he,branchDialogOpen:ie,branchDialogName:K,toast:I,error:V}=a,ee=y7(we==="labs"),{setQuery:G,setSearchOpen:le,setArchivedChatsOpen:pe,setSectionMenuOpen:fe,setProjectsExpanded:Pe,setCloudProjectsExpanded:_e,setChatRowsVisibleCount:Ne,setSidebarOpen:Re,setView:Xe,setSelectedAppId:st,setSelectedProjectId:on,setSelectedSessionId:At,setPrompt:tn,setDraftProvider:dn,setDraftModel:un,setDraftExperience:Kt,setCodexPermissionMode:Aa,setCodexReasoningEffort:la,setOpenPondCommandAccessMode:Mn,setDiffPanelOpen:_n,setDiffPanelExpanded:jt,setRightPanelMode:ht,setRightChatPanels:mn,setTerminalOpen:vt,setSyncingWorkspaceAppId:Et,setSettingsSection:ca,setNewProjectDialogOpen:Ut,setNewProjectMode:pn,setNewProjectName:rt,setNewProjectPath:kn,setNewProjectBusy:Wa,setCommitDialogOpen:Ga,setCommitMessage:ea,setCommitIncludeUnstaged:da,setCommitNextStep:jn,setCommitDraft:go,setBranchDialogOpen:Ta,setBranchDialogName:F,setError:Ue}=n,{connectionRef:Ie,setError:Be,showToast:bt}=r7({appDispatch:t,error:V,setErrorState:Ue}),{appPreferences:Bn,applyBootstrapPayload:fn,bootstrap:We,codexHistorySessions:vn,connection:ut,events:Cn,runtimeEventStore:Ea,approvals:Jo,sessions:ua,startup:Yo,setAppPreferences:Rr,setBootstrap:vo,setCodexHistorySessions:On,setEvents:ma,setSessions:Fn}=n7({setDraftModel:un,setDraftProvider:dn,setCodexPermissionMode:Aa,setCodexReasoningEffort:la,setOpenPondCommandAccessMode:Mn,setError:Be,setSelectedAppId:st,setSelectedProjectId:on,setSelectedSessionId:At});Ie.current=ut,v.useEffect(()=>{We&&w(We.sidebarFileBookmarks??[])},[We?.sidebarFileBookmarks]);const Qo=v.useMemo(()=>[...Cn].reverse().find(ot=>ot.name==="tool.completed"&&ot.action==="manage_sidebar_file")??null,[Cn]),Pr=v.useRef(null);v.useEffect(()=>{!ut||!Qo||Pr.current===Qo.id||(Pr.current=Qo.id,Q.sidebarFiles(ut).then(ot=>w(ot.items)).catch(ot=>Be(ot instanceof Error?ot.message:String(ot))))},[ut,Qo,Be]);const Xo=v.useCallback(async(ot,zt)=>{if(!ut)return;const qt=y;w(Bt=>zt==="none"?Bt.filter(Oa=>Oa.id!==ot.id):Bt.some(Oa=>Oa.id===ot.id)?Bt.map(Oa=>Oa.id===ot.id?{...Oa,status:zt}:Oa):[...Bt,{...ot,status:zt}]);try{const Bt=await Q.patchSidebarFile(ut,{workspaceKind:ot.workspaceKind,workspaceId:ot.workspaceId,workspaceName:ot.workspaceName,path:ot.path,status:zt,sourceSessionId:ot.sourceSessionId});w(Bt.items)}catch(Bt){w(qt),Be(Bt instanceof Error?Bt.message:String(Bt))}},[ut,Be,y]),er=QZ(ut),St=P7({connection:ut,profileId:We?.profile?.activeProfile??"default"}),{pinnedCollapsed:Ts,projectsCollapsed:Ar,cloudProjectsCollapsed:Es,chatsCollapsed:di,savedForLaterCollapsed:Ms,sidebarWidth:bo,sidebarResizing:js,diffPanelWidth:ui,diffPanelResizing:mi,togglePinnedCollapsed:pi,toggleProjectsCollapsed:Os,toggleCloudProjectsCollapsed:$s,toggleChatsCollapsed:Za,toggleSavedForLaterCollapsed:Ns,startSidebarResize:fi,startDiffPanelResize:hi}=v7({connection:ut,preferences:We?.preferences,sidebarOpen:De,diffPanelExpanded:z,setBootstrap:vo,setError:Be}),{cloudProjectById:tr,linkedProjectByAppId:gi,localProjectById:ta,mentionableSandboxApps:Ds,selectedApp:Tr,selectedCloudProject:yo,selectedProject:Vn,selectedProjectLinkedApp:Ls,selectedProjectLinkedOpenPondApp:Us,selectedSession:bn,selectedSessionLinkedProject:nr,sidebarSessions:pa}=q9({bootstrap:We,codexHistorySessions:vn,selectedAppId:oe,selectedProjectId:Se,selectedSessionId:He,sessions:ua}),Ma=bn?.experience??tt;v.useEffect(()=>{h9(Ma)},[Ma]);const Er=v.useMemo(()=>p6(pa,Ma),[Ma,pa]),ar=D7(Cn,Jo),{chatMentionApps:Hs,connectedAppMentions:vi,pendingApproval:Mr}=sW({bootstrap:We,connectedAppRows:er,mentionableSandboxApps:Ds,runtimeIndexes:ar,selectedApp:Tr,selectedCloudProject:yo,selectedProject:Vn,selectedSession:bn,selectedSessionId:He}),{codexHistoryEvents:So,setCodexHistoryEvents:or}=CW({connection:ut,selectedSessionId:He,selectedSessionLocallyActive:!!(He&&R.has(He)),selectedSessionStatus:bn?.status,setCodexHistorySessions:On,setError:Be}),{account:rr,accountPending:bi,accountSignedOut:yi,activeModel:fa,activeProvider:ha,activeWorkspaceAppId:Si,activeWorkspaceId:jr,activeWorkspaceKind:Ja,activeWorkspaceLocation:Or,appDefaults:xo,cloudLinked:xi,selectedCodexHistoryPending:ki,selectedSessionProjectId:wi,startMessage:zs,workspaceName:Ii}=D9({bootstrap:We,draftModel:Ke,draftProvider:Ze,selectedApp:Tr,selectedAppId:oe,selectedCloudProject:yo,selectedProject:Vn,selectedSession:bn,selectedSessionId:He,selectedSessionLinkedProject:nr}),_i=v.useMemo(()=>P9(We?.account??null),[We?.account]),qs=v.useMemo(()=>gh(We?.account??null),[We?.account]),ir=YZ(qs),Ci=v.useMemo(()=>E9(ir,xo.defaultTeamId),[xo.defaultTeamId,ir]),$r=Ci?.teamId??null,Ya=$Z({connection:ut,teamId:$r,currentUserId:rr?.profile?.id??null,refreshToken:We?.accountMeta.asOf??null}),Bs=HZ({connection:ut,teamId:$r,applyBootstrapPayload:fn,refreshDirectory:Ya.refreshDirectory});qZ({notification:Ya.incomingNotification,dismiss:Ya.dismissIncomingNotification,selectThread:Ya.selectThread,setView:Xe,showToast:bt});const{communities:Fs,sidebar:Vs,view:Ks}=ZZ({connection:ut,currentUserId:rr?.profile?.id??null,refreshToken:We?.accountMeta.asOf??null,setView:Xe,showToast:bt}),Qa=Ya.aiThread?.conversationId??null,Ri=we==="team"&&!!Qa&&O&&X==="chat";v.useEffect(()=>{if(we==="team"){if(Qa){ht("chat"),_n(!0);return}X==="chat"&&_n(!1)}},[X,_n,ht,Qa,we]);const Ws=v.useCallback(()=>{if(Qa){if(Ri){_n(!1);return}ht("chat"),_n(!0)}},[_n,ht,Ri,Qa]),Gs=v.useMemo(()=>Ca(Vn,We?.cloudProjects??[]),[We?.cloudProjects,Vn]),Zs=bn?.provider==="codex"?ze:bn?.openPondCommandAccessMode??ze,na=Si,Pi=jr,Js=Ja,ct=Ii,{openPondActionCatalog:Jt,selectedActionCatalog:Kn}=Q7({cloudProjectById:tr,cloudProjects:We?.cloudProjects??[],connection:ut,defaultTeamId:xo.defaultTeamId,accountScopeKey:_i,localProjects:We?.localProjects??[],profile:We?.profile,selectedCloudProject:yo,selectedProject:Vn,reportError:Be}),{expandedProjectIds:rn,expandProject:Rn,toggleProjectExpanded:aa,setExpandedProjectIds:Yu}=X7({selectedProjectId:Se});Z9({activeWorkspaceId:jr,activeWorkspaceKind:Ja,appDispatch:t,connection:ut,expandProject:Rn,linkedProjectByAppId:gi,providerSettings:We?.providers??null,selectedAppId:oe,selectedSession:bn,selectedSessionId:He,selectedSessionProjectId:wi,setDiffPanelExpanded:jt,setDraftModel:un,setDraftProvider:dn,setError:Be,setSelectedAppId:st,setSelectedProjectId:on,setSessions:Fn,setTerminalOpen:vt,toast:I});const{changeCodexPermissionMode:Qu,changeCodexReasoningEffort:Xu}=lW({connection:ut,setBootstrap:vo,setCodexPermissionMode:Aa,setCodexReasoningEffort:la,setError:Be}),{changeOpenPondCommandAccessMode:yc}=uG({connection:ut,selectedSession:bn,setBootstrap:vo,setError:Be,setOpenPondCommandAccessMode:Mn,setSessions:Fn}),em=J9({connection:ut,setError:Be}),Nr=v.useCallback(()=>{D(ot=>ot+1)},[]),Sc=Q9({appDispatch:t,expandProject:Rn,linkedProjectByAppId:gi,requestComposerFocus:Nr,onBeginNewChat:()=>{Qt({kind:"chat",sessionId:null}),se(null),Kt(ot=>ot==="development"?"work":ot)},setMentionedAppId:g}),Ai=v.useCallback(ot=>{const zt=yt("local",ot);t({type:"selectProject",projectId:zt}),Rn(zt)},[t,Rn]),{advanceAfterTurn:tm,begin:nm,bindSession:am,dismiss:om,handoff:rm,prepareTurn:im,selectTask:sm}=O7({activeModel:fa,activeProvider:ha,applyBootstrapPayload:fn,beginNewChat:Sc,composerDraftStore:e,connection:ut,requestComposerFocus:Nr,selectedLocalProjectId:Vn?.id??null,selectedSessionId:He,selectLocalProject:Ai,setDraftModel:un,setDraftProvider:dn,setError:Be,view:we});g7({connection:ut,events:Cn,showToast:bt}),yG({searchOpen:ye,sectionMenuOpen:be,setSectionMenuOpen:fe,setSearchOpen:le,setQuery:G}),v.useEffect(()=>{x({})},[We?.server.id]);const{chatHistoryLoadStates:lm,loadMoreSelectedChatHistory:cm,selectedPagedSessionEvents:dm,selectedRuntimeIndexes:xc}=$7({approvals:Jo,codexHistoryEvents:So,connection:ut,latestServerSequence:We?.eventWindow?.latestSequence,runtimeIndexes:ar,runtimeEventStore:Ea,selectedSessionId:He,serverId:We?.server.id,setCodexHistoryEvents:or,setCodexHistorySessions:On,setError:Be}),{activeSessions:um,archivedSessions:mm,pinnedProjects:pm,pinnedSessions:Ys,savedForLaterSessions:kc,pinnedFiles:fm,savedForLaterFiles:hm,pinnedItems:wc,projectRows:Ic,localProjectRows:gm,visibleProjectRows:Ti,cloudProjectRows:vm,projectSessionRowsByProjectId:_c,childSessionRowsByParentId:bm,sidebarProjectIdBySessionId:Qs,chatRows:Cc,visibleChatRows:Rc,sessionEvents:ym,chatMessages:Pc,contextUsage:Sm,goalRuntime:xm,subagentRuntime:Ac}=mG({localProjects:We?.localProjects??[],cloudProjects:We?.cloudProjects??[],sessions:Er,runtimeIndexes:xc,appPreferences:Bn,selectedSessionId:He,selectedProjectId:Se,archivedChatsOpen:ne,projectsExpanded:ae,chatRowsVisibleCount:xe,sidebarFileBookmarks:y}),km=v.useCallback(ot=>{Kt(ot);const zt=[...Er].filter(qt=>ot==="work"?qt.experience==="work"||qt.experience==="development":qt.experience===ot).sort((qt,Bt)=>Bt.updatedAt.localeCompare(qt.updatedAt))[0]??[...pa].filter(qt=>qt.experience===ot).sort((qt,Bt)=>Bt.updatedAt.localeCompare(qt.updatedAt))[0]??null;if(zt)t({type:"selectSession",sessionId:zt.id,appId:ot!=="chat"?zt.appId:null,projectId:ot!=="chat"?Qs[zt.id]??null:null});else if(t({type:"beginNewChat",appId:null}),ot==="chat"&&ha==="codex"){const qt=dh(We?.providers,{enabledOnly:!0}).find(Bt=>Bt.value!=="codex")?.value??Qr;dn(qt),un(Wd(qt,We?.providers)??Pl)}ot==="chat"&&(vt(!1),jt(!1),ht("home")),Xe("chat")},[t,ha,We?.providers,Er,jt,Kt,un,dn,ht,vt,Xe,Qs,pa]),Tc=v.useCallback(ot=>{const zt=e.getSnapshot();if(Kt(ot),(He||oe||Se)&&(t({type:"beginNewChat",appId:null}),zt&&e.set(zt)),ot==="chat"&&ha==="codex"){const qt=dh(We?.providers,{enabledOnly:!0}).find(Bt=>Bt.value!=="codex")?.value??Qr;dn(qt),un(Wd(qt,We?.providers)??Pl)}ot==="chat"&&(vt(!1),jt(!1),ht("home")),Xe("chat")},[ha,t,We?.providers,e,oe,Se,He,jt,Kt,un,dn,ht,vt,Xe]),{pendingChatUserMessages:wm,recordPendingChatUserMessage:Im,visibleChatMessages:_m}=dG({chatMessages:Pc,runtimeIndexes:xc,selectedSessionId:He}),sr=v.useMemo(()=>_6({selectedAppId:oe,selectedProjectId:Se,selectedSessionId:He}),[oe,Se,He]),Ec=v.useRef(null);v.useEffect(()=>{const ot=Ec.current;Ec.current=sr,!(!ot||ot.kind!=="draft"||sr.kind!=="session")&&(Fl(ot,sr)||l(zt=>{const qt=C6({tabs:zt,previousScope:ot,activeScope:sr});return qt.some((Oa,np)=>Oa!==zt[np])?qt:zt}))},[sr]);const Cm=v.useMemo(()=>R6(s),[s]),{goalRuntime:Rm,runningSessionIds:Xs,selectedSessionRunning:Pm,sidebarGoalRuntimeBySessionId:Am,sidebarSubagentRuntimeBySessionId:Tm}=bG({codexHistoryEvents:So,codexHistorySessions:vn,connection:ut,expandedProjectIds:rn,goalRuntime:xm,locallyActiveCodexHistorySessionIds:R,pinnedSessions:Ys,savedForLaterSessions:kc,projectSessionRowsByProjectId:_c,rightChatHistoryEvents:j,runtimeIndexes:ar,selectedSession:bn,selectedSessionId:He,serverId:We?.server.id,setCodexHistorySessions:On,sidebarSessions:pa,subagentRuntime:Ac,visibleChatRows:Rc,visibleProjectRows:Ti}),{dragItem:Em,pinnedPreviewKeys:Mm,startPinnedDrag:jm,clearSidebarDrag:Om,previewPinnedDrop:$m,commitPinnedDrop:Nm,commitPinnedPreviewDrop:Dm}=RW({connection:ut,appPreferences:Bn,sessions:pa,pinnedItems:wc,setAppPreferences:Rr,setCodexHistorySessions:On,setSessions:Fn,sidebarFileBookmarks:y,setSidebarFileBookmarks:w,setError:Be}),{clearTaskDrag:Lm,commitTaskDrop:Mc,commitTaskPreviewDrop:Um,previewTaskDrop:ja,startTaskDrag:Ei,taskDragSessionId:Hm,taskPreviewSessionIds:zm}=PW({connection:ut,sessions:pa,setCodexHistorySessions:On,setError:Be,setSessions:Fn}),{commandProjectRows:qm,contextWindowStatus:el,pinnedRows:Bm,sidebarWorkspaceAppIds:Fm}=Y9({activeProvider:ha,contextCompaction:xo.contextCompaction,contextUsage:Sm,pinnedItems:wc,pinnedPreviewKeys:Mm??[],pinnedProjects:pm,projectRows:Ic,visibleProjectRows:Ti}),ko=!!(na&&(we==="chat"||we==="labs")&&(Ye||O&&(X==="changes"||X==="goal"))),{workspaceStates:Mi,workspaceBusy:ji,diffBusy:Vm,visibleWorkspaceState:Dr,visibleWorkspaceDiff:tl,rememberWorkspaceState:Oi,refreshWorkspace:nl,refreshWorkspaceDiff:Xa,setWorkspaceBusy:Oc}=nZ({connection:ut,activeWorkspaceAppId:na,view:we,shouldLoadWorkspaceDiff:ko,sidebarWorkspaceAppIds:Fm,setError:Be});de.current=Oi;const Km=v.useCallback((ot=na)=>!ot||ot!==na||!ko?Promise.resolve(null):Xa(ot),[Xa,ko,na]),Wm=v.useCallback(async(ot={})=>{!na||!ko||await Xa(na,ot)},[Xa,ko,na]),Gm=!1,Zm=!!(bn?.provider==="codex"&&bn.cwd&&!po(bn.workspaceKind)),Jm=!!(Dr&&!Dr.initialized&&Ja!=="local_project"&&ha!=="codex"&&!Zm&&!ki),Ym=Ja==="local_project"&&!!Vn?.sandboxTemplate?.detected&&!Vn?.linkedOpenPondApp?.appId,[$c,Nc]=v.useState(null),[Qm,Xm]=v.useState(null),{projectTarget:ep,workspaceTarget:tp}=L9({accountPending:bi,accountSignedOut:yi,activeWorkspaceLocation:Or,bootstrap:We,busy:L,cloudLinked:xi,selectedCloudProject:yo,selectedProject:Vn,selectedSession:bn,pendingWorkspaceTarget:$c,workspaceStates:Mi,workspaceBusy:ji});return v.useEffect(()=>{Nc(null)},[bn?.id]),{composerDraftStore:e,appDispatch:t,pendingTerminalCommand:o,setPendingTerminalCommand:i,terminalTabs:s,setTerminalTabs:l,trainingDetailTasksetId:m,setTrainingDetailTasksetId:d,mentionedAppId:h,setMentionedAppId:g,cloudSetupDialog:_,setCloudSetupDialog:P,rightPanelTabRequest:M,setRightPanelTabRequest:C,workspaceDiffPanelViewState:N,setWorkspaceDiffPanelViewState:$,rightChatHistoryEvents:j,setRightChatHistoryEvents:x,locallyActiveCodexHistorySessionIds:R,setCodexHistoryTurnLocallyActive:U,mainComposerFocusRequestId:B,requestMainComposerFocus:Nr,draftSubagentDelegationMode:W,setDraftSubagentDelegationMode:se,confirmProjectAction:Me,projectConfirmDialog:ke,resolveProjectConfirmDialog:te,query:Ee,searchOpen:ye,archivedChatsOpen:ne,sectionMenuOpen:be,projectsExpanded:ae,cloudProjectsExpanded:ue,sidebarOpen:De,view:we,selectedAppId:oe,selectedProjectId:Se,selectedSessionId:He,draftProvider:Ze,draftModel:Ke,draftExperience:tt,activeExperience:Ma,changeExperience:km,changeNewExperience:Tc,codexPermissionMode:qe,codexReasoningEffort:Ge,openPondCommandAccessMode:ze,busy:L,diffPanelOpen:O,diffPanelExpanded:z,rightPanelMode:X,rightChatPanels:me,terminalOpen:$e,settingsSection:Le,newProjectDialogOpen:nt,newProjectMode:at,newProjectName:lt,newProjectPath:pt,newProjectBusy:je,commitDialogOpen:Ye,commitMessage:f,commitIncludeUnstaged:H,commitNextStep:Y,commitDraft:he,branchDialogOpen:ie,branchDialogName:K,toast:I,error:V,labDetailNavigation:ee,setQuery:G,setSearchOpen:le,setArchivedChatsOpen:pe,setSectionMenuOpen:fe,setProjectsExpanded:Pe,setCloudProjectsExpanded:_e,setChatRowsVisibleCount:Ne,setSidebarOpen:Re,setView:Xe,setSelectedAppId:st,setSelectedProjectId:on,setSelectedSessionId:At,setPrompt:tn,setDraftProvider:dn,setDraftModel:un,setDraftExperience:Kt,setDiffPanelOpen:_n,setDiffPanelExpanded:jt,setRightPanelMode:ht,setRightChatPanels:mn,setTerminalOpen:vt,setSyncingWorkspaceAppId:Et,setSettingsSection:ca,setNewProjectDialogOpen:Ut,setNewProjectMode:pn,setNewProjectName:rt,setNewProjectPath:kn,setNewProjectBusy:Wa,setCommitDialogOpen:Ga,setCommitMessage:ea,setCommitIncludeUnstaged:da,setCommitNextStep:jn,setCommitDraft:go,setBranchDialogOpen:Ta,setBranchDialogName:F,setError:Be,showToast:bt,appPreferences:Bn,applyBootstrapPayload:fn,approvals:Jo,bootstrap:We,connection:ut,events:Cn,runtimeEventStore:Ea,sessions:ua,startup:Yo,setAppPreferences:Rr,setCodexHistorySessions:On,setEvents:ma,setSessions:Fn,training:St,pinnedCollapsed:Ts,projectsCollapsed:Ar,cloudProjectsCollapsed:Es,chatsCollapsed:di,savedForLaterCollapsed:Ms,sidebarWidth:bo,sidebarResizing:js,diffPanelWidth:ui,diffPanelResizing:mi,togglePinnedCollapsed:pi,toggleProjectsCollapsed:Os,toggleCloudProjectsCollapsed:$s,toggleChatsCollapsed:Za,toggleSavedForLaterCollapsed:Ns,startSidebarResize:fi,startDiffPanelResize:hi,cloudProjectById:tr,localProjectById:ta,selectedApp:Tr,selectedCloudProject:yo,selectedProject:Vn,selectedProjectLinkedApp:Ls,selectedProjectLinkedOpenPondApp:Us,selectedSession:bn,sidebarSessions:pa,runtimeIndexes:ar,chatMentionApps:Hs,connectedAppMentions:vi,pendingApproval:Mr,codexHistoryEvents:So,setCodexHistoryEvents:or,account:rr,accountPending:bi,accountSignedOut:yi,activeModel:fa,activeProvider:ha,activeWorkspaceAppId:Si,activeWorkspaceId:jr,activeWorkspaceKind:Ja,activeWorkspaceLocation:Or,appDefaults:xo,selectedSessionProjectId:wi,startMessage:zs,workspaceName:Ii,accountScopeKey:_i,organizations:ir,teamChatOrganization:Ci,teamChatTeamId:$r,teamChat:Ya,publishTeamProfileAgent:Bs,communities:Fs,communitySidebar:Vs,communityView:Ks,teamAiThreadId:Qa,toggleTeamAiSidebar:Ws,selectedProjectConfirmedCloudProject:Gs,activeOpenPondCommandAccessMode:Zs,viewWorkspaceAppId:na,viewWorkspaceId:Pi,viewWorkspaceKind:Js,viewWorkspaceName:ct,openPondActionCatalog:Jt,selectedActionCatalog:Kn,expandedProjectIds:rn,expandProject:Rn,toggleProjectExpanded:aa,setExpandedProjectIds:Yu,changeCodexPermissionMode:Qu,changeCodexReasoningEffort:Xu,changeOpenPondCommandAccessMode:yc,resolveApproval:em,beginNewChat:Sc,advanceTrainingModelChatAfterTurn:tm,beginNewChatWithTrainingModel:nm,bindTrainingModelChatSession:am,dismissTrainingChatHandoff:om,trainingChatHandoff:rm,prepareTrainingModelChatTurn:im,selectTrainingChatTaskForComposer:sm,chatHistoryLoadStates:lm,loadMoreSelectedChatHistory:cm,selectedPagedSessionEvents:dm,activeSessions:um,archivedSessions:mm,pinnedSessions:Ys,savedForLaterSessions:kc,pinnedFiles:fm,savedForLaterFiles:hm,sidebarFileBookmarks:y,setSidebarFileStatus:Xo,projectRows:Ic,localProjectRows:gm,visibleProjectRows:Ti,cloudProjectRows:vm,projectSessionRowsByProjectId:_c,childSessionRowsByParentId:bm,sidebarProjectIdBySessionId:Qs,chatRows:Cc,visibleChatRows:Rc,chatRowsVisibleCount:xe,sessionEvents:ym,chatMessages:Pc,goalRuntime:Rm,subagentRuntime:Ac,pendingChatUserMessages:wm,recordPendingChatUserMessage:Im,visibleChatMessages:_m,activeTerminalScope:sr,terminalSummaries:Cm,runningSessionIds:Xs,selectedSessionRunning:Pm,sidebarGoalRuntimeBySessionId:Am,sidebarSubagentRuntimeBySessionId:Tm,taskDragSessionId:Hm,taskPreviewSessionIds:zm,startTaskDrag:Ei,clearTaskDrag:Lm,previewTaskDrop:ja,commitTaskDrop:Mc,commitTaskPreviewDrop:Um,dragItem:Em,startPinnedDrag:jm,clearSidebarDrag:Om,previewPinnedDrop:$m,commitPinnedDrop:Nm,commitPinnedPreviewDrop:Dm,commandProjectRows:qm,contextWindowStatus:el,pinnedRows:Bm,workspaceStates:Mi,workspaceBusy:ji,diffBusy:Vm,visibleWorkspaceState:Dr,visibleWorkspaceDiff:tl,rememberWorkspaceState:Oi,refreshWorkspace:nl,refreshWorkspaceDiff:Xa,setWorkspaceBusy:Oc,refreshWorkspaceDiffWhenNeeded:Km,refreshVisibleWorkspaceDiff:Wm,managedWorkspace:Gm,canSyncActiveWorkspace:Jm,canPublishOpenPondProject:Ym,pendingWorkspaceTarget:$c,setPendingWorkspaceTarget:Nc,pendingSidebarWorkspaceTarget:Qm,setPendingSidebarWorkspaceTarget:Xm,projectTarget:ep,workspaceTarget:tp}}const eJ=/^(localhost|\[::1\]|127(?:\.\d{1,3}){3})(?::\d+)?(?:[/?#].*)?$/i,tJ=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+(?:[:/?#].*)?$/i;function nJ(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)?od(n,new Set(["http:","https:"])):/^file:\/\//i.test(n)?t.explicitFile?od(n,new Set(["file:"])):null:eJ.test(n)?od(`http://${n}`,new Set(["http:"])):tJ.test(n)?od(`https://${n}`,new Set(["https:"])):null}function od(e,t){try{const n=new URL(e);return t.has(n.protocol)?n.toString():null}catch{return null}}async function aJ(e){const t=nJ(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 oJ="openpond-coding-core-v1",rJ="feature";function Ph(e){const t=new URL("/sandboxes",Bv(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",rJ),t.searchParams.set("runtimeProfileId",oJ),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 EX(e){const t=e.organizationSlug?.trim(),n=t?`/sandboxes/${encodeURIComponent(t)}/billing`:"/sandboxes/billing",a=new URL(n,Bv(e.accountBaseUrl));return!t&&e.teamId?.trim()&&a.searchParams.set("teamId",e.teamId.trim()),a.toString()}function CS(e){const t=e.organizationSlug?.trim(),n=e.projectSlug?.trim();return!t||!n?null:new URL(`/${encodeURIComponent(t)}/${encodeURIComponent(n)}`,Bv(e.accountBaseUrl)).toString()}function Bv(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 iJ({account:e,browserConversationId:t,cloudProjectById:n,cloudProjects:a,diffPanelOpen:o,rightPanelMode:i,selectedProjectId:s,setDiffPanelOpen:l,setNewProjectDialogOpen:m,setNewProjectMode:d,setNewProjectName:h,setRightPanelMode:g}){const y=v.useCallback(()=>{g("changes"),l(!0)},[l,g]),w=v.useCallback(()=>{if(o&&i==="changes"){l(!1);return}y()},[o,i,l,y]),_=v.useCallback(()=>{g("browser"),l(!0)},[l,g]),P=v.useCallback(()=>{g("goal"),l(!0)},[l,g]),M=v.useCallback((j,x)=>{aJ({conversationId:t,href:j,explicitFile:x?.explicitFile,newTab:x?.newTab}).then(R=>{R&&_()})},[t,_]),C=v.useCallback(()=>{d("cloud"),h(""),m(!0)},[m,d,h]),N=v.useCallback(j=>{const x=n.get(j);x&&M(Ph({accountBaseUrl:e?.baseUrl??e?.activeProfile?.baseUrl??null,teamId:x.teamId,projectId:x.id,projectName:x.name,baseBranch:x.defaultBranch,source:"openpond-app"}),{newTab:!0})},[e,n,M]);return{createCloudEnvironmentFromSidebar:v.useCallback(()=>{const j=s?.startsWith("cloud:")?s.slice(6):a[0]?.id??null;if(j){N(j);return}C()},[a,C,s,N]),openCloudProjectDialog:C,openUrlInBrowserPanel:M,showBrowserPanel:_,showChangesPanel:y,showGoalSidebarTab:P,toggleChangesPanel:w}}function sJ(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 lJ({browserConversationId:e,sessionIds:t,onOpenSession:n,onShowBrowserPanel:a}){v.useEffect(()=>window.openpond?.browser?.onRevealRequest?.(i=>{const s=sJ({currentConversationId:e,requestConversationId:i.conversationId,sessionIds:t});s.reveal&&(s.sessionIdToOpen&&n(s.sessionIdToOpen),a())}),[e,n,a,t])}const cJ="chat",dJ=["help me","please","can you","could you","make","create","build"],uJ=new Set(["a","an","and","for","from","i","me","my","of","our","please","produce","summary","the","to","with"]);function RS(e){const t=xf(e.label);if(t&&!Ah(t))return PS(t);const n=xf(e.name);if(n&&!Ah(n))return PS(n);const a=xf(e.actionId)?.replace(/\.chat$/i,"")??"";return mJ(a||t||"Profile Agent")}function Ah(e){return e.trim().toLowerCase()===cJ}function mJ(e){const t=pJ(e.replace(/\.chat$/i,"").replace(/[._-]+/g," ").replace(/\s+/g," ").trim()),a=t.toLowerCase().split(/\s+/).map(o=>o.replace(/[^a-z0-9]/g,"")).filter(o=>o&&!uJ.has(o)).slice(0,3);return oR(a.length?a.join(" "):t||e)}function PS(e){return oR(e).split(/\s+/).slice(0,4).join(" ")}function pJ(e){let t=e.trim();for(const n of dJ)if(t.toLowerCase().startsWith(`${n} `)){t=t.slice(n.length).trim();break}return t}function xf(e){return typeof e=="string"&&e.trim()?e.trim():null}function oR(e){return e.replace(/[._-]+/g," ").replace(/\s+/g," ").trim().replace(/\b[a-z0-9]/gi,t=>t.toUpperCase())}const fJ="openpond-profile-action";function hJ(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function rd(e){return typeof e=="string"&&e.trim()?e.trim():null}function gJ(e){const t=hJ(e.implementation);if(t?.type!==fJ)return null;const n=rd(t.actionId)??e.id;if(e.sourceActionId!=="chat"&&n!=="chat"&&!n.endsWith(".chat"))return null;const a=rd(e.label);if(a&&!Ah(a))return RS({label:a,description:e.description});const o=rd(t.agentName)??rd(e.name);return RS({actionId:n,description:e.description,name:o})}function vJ(e){const t=gJ(e);return t||e.label?.trim()||e.name?.trim()||e.id}function rR(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 bJ=new Set(["action","agent","chat","customer","default","filter","items","open","openpond","profile","run","summarize","track","workflow"]);function iR(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function xs(e){return typeof e=="string"&&e.trim()?e.trim():null}function ts(e,t,n={}){const a=xs(t)?Dn(String(t)):"";a&&(!n.generic&&bJ.has(a)||e.add(a))}function id(e,t){const n=xs(t);if(n)for(const a of n.split(/[.:/\\\s]+/g))ts(e,a)}function yJ(e,t){const n=xs(t);if(n)for(const a of n.split(/[^A-Za-z0-9_-]+/g))a.length<4||ts(e,a)}function sR(e){const t=new Set,n=iR(e.implementation),a=xs(n?.actionId);return ts(t,e.id,{generic:!0}),id(t,e.id),ts(t,a,{generic:!0}),id(t,a),ts(t,e.name,{generic:!0}),id(t,e.name),ts(t,e.label,{generic:!0}),id(t,e.label),yJ(t,e.description),t}function SJ(e){const t=iR(e.implementation);return[e.id,e.name??"",e.label??"",e.description??"",xs(t?.actionId)??"",xs(t?.agentName)??"",rR(e),...Array.from(sR(e))].join(" ").toLowerCase()}function MX(e,t,n=8){const a=Dn(t);return e.length===0?[]:e.filter(o=>a?SJ(o).includes(a):!0).slice(0,n)}function xJ(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>Dn(t[1]??"")).filter(Boolean)}function kJ(e,t){const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return e.replace(new RegExp(`(^|\\s)@${n}(?=\\s|$)`,"g"),"$1").replace(/\s+/g," ").trim()}function wJ(e,t){const n=xJ(e);if(n.length===0||t.length===0)return null;const a=new Map;for(const i of n)for(const s of t)sR(s).has(i)&&a.set(s.id,{action:s,mention:i});if(a.size!==1)return null;const o=Array.from(a.values())[0];return{action:o.action,mention:o.mention,prompt:kJ(e,o.mention)}}function jX(e){return vJ(e)}function OX(e){return e.description||rR(e)}const Fv=[{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 IJ(e){return Fv.filter(t=>t.id!=="goal"||e==="codex")}function lR(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 $X(e,t){return IJ(e).filter(n=>lR(n,t))}const _J=new Set(Fv.map(e=>e.id));function NX(e){return e.subcommands?.length?e.subcommands.join(", "):e.description}function CJ(e){return[e.id,e.command,e.label,e.description].join(" ")}function RJ(e){return(e.subcommands??[]).flatMap(t=>[t,`${e.id} ${t}`,`${e.command} ${t}`]).join(" ")}function PJ(e){const t=/^\/([a-z][a-z0-9_-]*)(?:\s+([\s\S]*))?$/.exec(e.trim());if(!t)return null;const n=t[1];return _J.has(n)?{command:n,args:t[2]?.trim()??""}:null}function AJ(e){const t=e.trim();if(!t.startsWith("!"))return null;const n=t.slice(1).trim();return n?{command:n}:null}function DX({commands:e=Fv,prompt:t,limit:n=10}){if(!t.startsWith("/"))return[];const a=t.slice(1).trim().toLowerCase();if(!a)return e.slice(0,n);const o=e.filter(l=>l.id.startsWith(a));if(o.length>0)return o.slice(0,n);const i=e.filter(l=>CJ(l).toLowerCase().includes(a));return(i.length>0?i:e.filter(l=>RJ(l).toLowerCase().includes(a))).slice(0,n)}function LX(e){return e==="owner"?"Owner":e==="admin"?"Admin":"Member"}function Zu(e){return e?.role==="owner"||e?.role==="admin"}function UX(e){const t=Ju(e.organizations,e.defaultTeamId),n=Zu(t),a=e.localProject??null;if(!a)return TJ("Open a local project to set up an Agent.");const o=EJ(a,e.projects),i=MJ(a,o,e.agents),s=!!a.sandboxTemplate?.detected,l=t&&!n?"Ask an owner or admin to connect this project.":null;return s?o?jJ(a,o)?sd({state:"needs_sync",actionLabel:"Sync Project",project:o,agent:i,canManage:n,actionBlockedReason:l}):i?{state:"ready",actionLabel:"Run Agent",canAct:!0,reason:null,project:o,agent:i}:sd({state:"needs_agent",actionLabel:"Create Agent",project:o,agent:null,canManage:n,actionBlockedReason:l}):sd({state:"needs_project",actionLabel:"Connect Project",project:null,agent:null,canManage:n,actionBlockedReason:l}):sd({state:"missing_config",actionLabel:"Add Agent config",project:o,agent:i,canManage:n,actionBlockedReason:l})}function sd(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 TJ(e){return{state:"blocked",actionLabel:"Ask admin",canAct:!1,reason:e,project:null,agent:null}}function Ju(e,t){if(e.length===0)return null;const n=t?.trim()??"";if(n){const a=e.find(o=>o.teamId===n);if(a)return a}return e.length===1?e[0]??null:e.find(a=>a.role==="owner")??e.find(a=>a.role==="admin")??e[0]??null}function EJ(e,t){const n=e.linkedSandboxProject;return n?.projectId?t.find(a=>a.id===n.projectId)??null:null}function MJ(e,t,n){if(!t)return null;const a=e.preferredSandboxAgentId;if(a){const o=n.find(i=>i.id===a&&i.projectId===t.id);if(o)return o}return n.find(o=>o.projectId===t.id)??null}function jJ(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 Lr=e=>e.slice(0,2e4);function OJ({model:e,provider:t,providerSettings:n}){return{model:Iv(t,e,n),modelRef:Na(t,e,n)}}function $J(e,t){return e.some(n=>n.id===t.id)?e:[...e,t]}function NJ(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 DJ(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 AS({action:e,prompt:t,runPayload:n,sessionId:a}){const o=new Date().toISOString(),i=`openpond_action_${n.run.id}`,s=n.run.status==="failed"?"failed":n.run.status==="succeeded"?"completed":"started";return[{id:`${i}_user`,sessionId:a,turnId:i,name:"turn.started",timestamp:o,source:"chat_action",args:{prompt:t}},{id:`${i}_result`,sessionId:a,turnId:i,name:"workspace_action_result",timestamp:n.run.updatedAt??o,source:"chat_action",action:"sandbox_run_action",appId:null,status:s,output:s==="completed"?`Ran ${e.label??e.name??e.id}`:`Started ${e.label??e.name??e.id}`,data:{openPondActionRun:!0,action:{name:e.id,label:e.label??e.name??e.id,implementation:e.implementation},agent:n.agent,run:n.run,sandbox:n.sandbox??null,actionSummary:n.run.actionSummary??null,responseSummary:n.run.responseSummary??null,traceSummary:n.run.traceSummary??null,evalSummary:n.run.evalSummary??null,sourceSummary:n.run.sourceSummary??null}}]}function LJ({applyBootstrapPayload:e,connection:t,codexPermissionMode:n,codexReasoningEffort:a,openPondCommandAccessMode:o,draftModel:i,draftProvider:s,experience:l,expandProject:m,ensureCloudSessionReady:d,getPrompt:h,bootstrap:g,chatMessages:y,apps:w,connectedAppMentions:_,mentionedAppId:P,refreshWorkspace:M,refreshWorkspaceDiff:C,selectedApp:N,selectedActionCatalog:$,openPondActionCatalog:j,cloudProjects:x,accountScopeKey:R,selectedCloudProject:E,selectedProject:U,selectedProjectLinkedOpenPondApp:B,selectedSession:D,workspaceTarget:W,subagentDelegationMode:se,setDraftModel:de,setDraftProvider:Me,setError:ke,setPrompt:te,setMentionedAppId:Ee,setCodexHistoryEvents:ye,setCodexHistorySessions:ne,onCodexHistoryTurnActivityChange:be,onCodexHistoryTurnPayload:ae,onPendingUserMessage:ue,setEvents:xe,setSelectedAppId:De,setSelectedProjectId:we,setSelectedSessionId:oe,setSessions:Se,setView:He,setWorkspaceBusy:Ze}){function Ke(K){Q.bootstrap(K).then(e).catch(I=>{console.warn("[chat] Message was accepted, but the post-send bootstrap refresh failed.",I);const V=I instanceof Error?I.message:String(I);ke(`Message sent, but the chat list could not refresh: ${V}`)})}const tt=v.useRef(new Set),qe=g?.providers??null;function Ge(K,I){return K==="codex"?void 0:I}function ze(K){return!!(K&&K.provider!=="codex"&&(K.workspaceKind==="local_project"&&K.cwd?.trim()||(K.workspaceKind==="sandbox"||K.workspaceKind==="sandbox_template"||K.workspaceKind==="sandbox_app")&&K.workspaceId))}function L(K){Me(K),de(I=>_r(K,I,qe)),He("chat")}async function O(K,I){return(qC(I,R)??await Dv({teamId:I,accountKey:R,fetchAgents:async G=>(await Q.listSandboxAgents(t,{teamId:G})).agents})).find(G=>G.projectId===K)??null}async function z(){if(!t)throw new Error("OpenPond App server is not connected.");if(g?.account.state!=="signed_in")throw new Error("Add an OpenPond account before syncing a Project to Cloud.");const K=await Q.organizations(t),I=Ju(K.organizations.map(Fu).filter(V=>!!V).filter(V=>V.status==="active"),g?.preferences.defaultTeamId??null);if(!I)throw new Error("Add an OpenPond account before syncing a Project to Cloud.");if(!Zu(I))throw new Error(`You need owner or admin access to create projects in ${I.displayName}.`);return I}async function X(K){if(!t)return!1;const I=U;if(!I)throw new Error("Select a local Project before using /sync-cloud.");const V=await z(),ee=I.linkedSandboxProject?.defaultBranch?.trim()||"main",G=yt("local",I.id),le=Ca(I,x),pe=await Q.createSession(t,{provider:"openpond",modelRef:Na("openpond",us,qe),openPondCommandAccessMode:Ge("openpond",o),appId:null,appName:null,workspaceKind:"local_project",workspaceId:I.id,workspaceName:I.name,localProjectId:I.id,cloudProjectId:le?.id??null,cloudTeamId:le?.teamId??null,cwd:I.workspacePath,title:`Sync ${I.name} to Cloud`});Se(fe=>[pe,...fe]),K.onSessionCreated?.(pe),K.selectSession&&(oe(pe.id),we(G),De(null),He("chat"),m(G)),K.clearPromptForTurn(),Ze(!0);try{const fe=await Q.uploadLocalProjectCloudSource(t,I.id,{teamId:V.teamId,projectName:I.name,branch:ee,chatSessionId:pe.id,displayPrompt:K.displayPrompt});return e(fe.bootstrap),m(G),m(yt("cloud",fe.project.id)),!0}catch(fe){const Pe=await Q.bootstrap(t).catch(()=>null);throw Pe&&e(Pe),fe}finally{Ze(!1)}}async function me(K){if(!t||K.providerForTurn==="codex"||K.selectedSessionForTurn?.provider==="codex")return!1;let I=ze(K.selectedSessionForTurn)?K.selectedSessionForTurn:null;if(!I&&K.selectedSessionForTurn)throw new Error("Select a project to use this.");if(!I)if(E){const ee=yt("cloud",E.id),G=K.providerForTurn;I=await Q.createSession(t,{provider:G,modelRef:Na(G,K.modelForTurnValue,qe),openPondCommandAccessMode:Ge(G,K.openPondCommandAccessModeForTurn),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:E.id,workspaceName:E.name,localProjectId:null,cloudProjectId:E.id,cloudTeamId:E.teamId,cwd:null,autoTitlePrompt:Lr(K.command)}),Se(le=>[I,...le]),K.onSessionCreated?.(I),K.selectSession&&(oe(I.id),we(ee),De(null),He("chat"),m(ee))}else{const ee=U;if(!ee)throw new Error("Select a project to use this.");const G=Ca(ee,x),le=yt("local",ee.id),pe=K.providerForTurn;I=await Q.createSession(t,{provider:pe,modelRef:Na(pe,K.modelForTurnValue,qe),openPondCommandAccessMode:Ge(pe,K.openPondCommandAccessModeForTurn),appId:null,appName:null,workspaceKind:"local_project",workspaceId:ee.id,workspaceName:ee.name,localProjectId:ee.id,cloudProjectId:G?.id??null,cloudTeamId:G?.teamId??null,cwd:ee.workspacePath,autoTitlePrompt:Lr(K.command)}),Se(fe=>[I,...fe]),K.onSessionCreated?.(I),K.selectSession&&(oe(I.id),we(le),De(null),He("chat"),m(le))}if(!I)throw new Error("Select a project to use this.");K.clearPromptForTurn();const V=await Q.runSessionCommand(t,I.id,{command:K.command,cwd:I.cwd});return Se(ee=>fl(ee,V.session)),xe(ee=>Ao(ee,V.events)),!0}async function $e(K=[],I=null,V,ee={}){const G=V??h();let le=G.trim()||(K.length>0?"Please review the attached files.":"");if(!t||!le)return!1;const pe=ee.displayPrompt?.trim()||le,fe=ee.provider??s,Pe=ee.model??i,_e=ee.openPondCommandAccessMode??o,Ne=ee.session!==void 0,Re=Ne?ee.session??null:D,Xe=ee.experience??Re?.experience??l,st=Xe==="development"||Xe==="work"&&(Re?.workspaceKind==="local_project"||!!Re?.localProjectId||!!Re?.cloudProjectId||!Ne&&!!(U||E||N||W==="hybrid"||W==="local")),on=Ne||!st?null:N,At=Ne||!st?null:U,tn=Ne||!st?null:E,dn=Ne||!st?null:B,un=!Ne&&st&&W==="hybrid",Kt=ee.selectSession??!0,Aa=ee.chatMessages??y,la=ee.session!==void 0?null:P,Mn=ee.clearPrompt===void 0?()=>{te(""),Ee(null)}:ee.clearPrompt,_n=I?null:wJ(le,$),jt=I??_n?.action??null,ht=_n?.prompt||le,mn=st&&!jt?AJ(le):null,vt=jt||mn?null:PJ(le),Et=vt&&!lR({id:vt.command},Xe)?vt:null,ca=ee.usageAttribution??(vt?{surface:"chat",workflowKind:"slash_command",commandName:`/${vt.command}`,commandSource:"prompt_parse"}:void 0);ke(null);let Ut=null,pn=null;try{if(!st&&fe==="codex")throw new Error("The Codex provider requires repository-aware Work.");if(Et)throw new Error(`/${Et.command} isn't available in ${Xe}.`);if(mn&&fe!=="codex"&&Re?.provider!=="codex"){if(K.length>0)throw new Error("Direct commands do not accept attachments.");return await me({command:mn.command,clearPromptForTurn:Mn,modelForTurnValue:Pe,onSessionCreated:ee.onSessionCreated,openPondCommandAccessModeForTurn:_e,providerForTurn:fe,selectedSessionForTurn:Re,selectSession:Kt})}if(!Ne&&vt?.command==="sync-cloud")return await X({clearPromptForTurn:Mn,displayPrompt:pe,onSessionCreated:ee.onSessionCreated,selectSession:Kt});if(jt){const F=B7(jt);if(F){let We=Re;if(!We||We.cloudProjectId!==F.projectId){We=await Q.createSession(t,{provider:"openpond",modelRef:Na("openpond",Pe,qe),openPondCommandAccessMode:Ge("openpond",_e),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:F.projectId,workspaceName:F.projectName??F.agentName,localProjectId:null,cloudProjectId:F.projectId,cloudTeamId:F.teamId,cwd:null,autoTitlePrompt:Lr(pe)}),Se(Ea=>[We,...Ea]),ee.onSessionCreated?.(We),Kt&&oe(We.id);const Cn=yt("cloud",F.projectId);Kt&&we(Cn),Kt&&m(Cn)}const vn=await Q.runSandboxAgent(t,F.agentId,G7({agent:F,attachments:K,displayPrompt:pe,prompt:ht})),ut=await Q.bootstrap(t);return e(ut),Mn(),xe(Cn=>Ao(Cn,AS({action:jt,prompt:pe,runPayload:vn,sessionId:We.id}))),!0}const Ue=zv(jt);if(Ue){let We=Re;(!We||We.provider!=="openpond")&&(We=await Q.createSession(t,{provider:"openpond",modelRef:Na("openpond",Pe,qe),openPondCommandAccessMode:Ge("openpond",_e),appId:null,appName:null,workspaceId:null,workspaceName:"OpenPond profile",localProjectId:null,cloudProjectId:null,cloudTeamId:null,cwd:null,autoTitlePrompt:Lr(pe)}),Se(ut=>[We,...ut]),ee.onSessionCreated?.(We),Kt&&oe(We.id)),await Q.runProfileAction(t,K7({action:Ue,attachments:K,displayPrompt:pe,prompt:ht,sessionId:We.id}));const vn=await Q.bootstrap(t);return e(vn),Mn(),!0}const Ie=GC({cloudProjects:x,selectedCloudProject:E,selectedProject:U});if(!Ie)throw new Error("Select a Project linked to an OpenPond Cloud Project before running an action.");let Be=Re;(!Be||Be.cloudProjectId!==Ie.id)&&(Be=await Q.createSession(t,{provider:"openpond",modelRef:Na("openpond",Pe,qe),openPondCommandAccessMode:Ge("openpond",_e),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:Ie.id,workspaceName:Ie.name,localProjectId:Ie.localProjectId,cloudProjectId:Ie.id,cloudTeamId:Ie.teamId,cwd:null,autoTitlePrompt:Lr(pe)}),Se(We=>[Be,...We]),ee.onSessionCreated?.(Be),Kt&&(oe(Be.id),we(Ie.selectionKey),m(Ie.selectionKey)));const bt=await O(Ie.id,Ie.teamId);if(!bt)throw new Error("No OpenPond Agent is available for this Project.");Mn();const Bn=await Q.runSandboxAgent(t,bt.id,W7({action:jt,attachments:K,displayPrompt:pe,prompt:ht,teamId:Ie.teamId})),fn=await Q.bootstrap(t);return e(fn),xe(We=>Ao(We,AS({action:jt,prompt:pe,runPayload:Bn,sessionId:Be.id}))),!0}let rt=Re;if(rt&&Ht(rt.id)){pn=H0({afterMessageId:Aa.at(-1)?.id??null,attachments:K,content:le,sessionId:rt.id}),Mn(),Ut=rt.id,tt.current.add(Ut),ue?.(pn),be?.(Ut,!0);const F=NJ(rt.id,le),Ue=Be=>{(!Ne||D?.id===rt.id)&&ye(bt=>$J(bt,Be)),ee.onCodexHistoryOptimisticEvent?.(Be)};Ue(F),ne(Be=>Be.map(bt=>bt.id===rt.id?{...bt,status:"active"}:bt));const Ie=await Q.sendCodexHistoryTurn(t,rt.id,{prompt:le,attachments:K.length>0?K:void 0,model:Iv("codex",Pe,qe),modelRef:Na("codex",Pe,qe),...a0(n),codexPermissionMode:n,codexReasoningEffort:a}).catch(Be=>{throw Ue(DJ(F,Be)),Be});return(!Ne||D?.id===rt.id)&&ye(Be=>Ao(Be,Ie.events)),ne(Be=>fl(Be,Ie.session)),ae?.(Ie),Ke(t),!0}const Wa=(la?w.find(F=>F.id===la&&U9(G,F)&&F.sandbox)??null:null)??H9(G,mC(w)),Ga=Xe==="chat"?[]:tW(G,_).map(F=>F.ref);if(!rt){const F=dn?.appId??on?.id??null,Ue=dn?.appName??on?.name??null,Ie=tn,Be=Ne?null:Ca(At,x),bt=un?iC({cloudProjects:x,selectedCloudProject:Ie,selectedProject:At}):null;if(bt?.kind==="missing_cloud_project")throw new Error(bt.message);const Bn=bt?.kind==="ready",fn=Bn?fe:Ie?"openpond":fe,We=Na(fn,Pe,qe),vn=Ge(fn,_e),ut=Bn?sC({modelRef:We,provider:fn,target:bt,title:le.slice(0,64)}):null;rt=await Q.createSession(t,ut?{...ut,subagentDelegationMode:se,metadata:{...ut.metadata,...ee.sessionMetadata??{}},...vn?{openPondCommandAccessMode:vn}:{},autoTitlePrompt:Lr(le)}:{experience:Xe,provider:fn,modelRef:We,subagentDelegationMode:se,...vn?{openPondCommandAccessMode:vn}:{},appId:F,appName:Ue,workspaceKind:Ie?"sandbox":At?"local_project":on?"sandbox_app":void 0,workspaceId:At?.id??(on?F:void 0),workspaceName:Ie?.name??At?.name??Ue,localProjectId:At?.id??null,cloudProjectId:Ie?.id??Be?.id??null,cloudTeamId:Ie?.teamId??Be?.teamId??null,...!Ie&&!At&&!on&&W==="local"?{metadata:{...b9(),...ee.sessionMetadata??{}}}:{cwd:At?At.workspacePath:null,...ee.sessionMetadata?{metadata:ee.sessionMetadata}:{}},autoTitlePrompt:Lr(le)}),Se(Cn=>[rt,...Cn]),ee.onSessionCreated?.(rt),Kt&&(oe(rt.id),Ie&&we(yt("cloud",Ie.id)),rt.workspaceKind==="local_project"&&rt.workspaceId&&m(yt("local",rt.workspaceId)),Ie&&m(yt("cloud",Ie.id)))}if(TS(rt)&&po(rt.workspaceKind)&&rt.provider!=="openpond"&&!fo(rt))throw new Error("Cloud workspaces use OpenPond Chat. Switch to Local to use local providers.");if(TS(rt)&&po(rt.workspaceKind)&&d)try{rt=await d(rt)}catch(F){const Ue=F instanceof Error?F.message:String(F);throw await Q.recordPreflightTurnFailure(t,rt.id,{prompt:le,error:Ue,target:fo(rt)?"hybrid_sandbox":"cloud_workspace"}).then(e).catch(()=>{}),F}pn=H0({afterMessageId:Aa.at(-1)?.id??null,attachments:K,content:le,sessionId:rt.id}),Mn(),Ut=rt.id,tt.current.add(Ut),ue?.(pn),Se(F=>F.map(Ue=>Ue.id===Ut?{...Ue,status:"active"}:Ue));const ea=fe,da=OJ({provider:ea,model:Pe,providerSettings:qe}),jn=m6(ea,da.model??Pe,qe),go=ea==="codex"?a0(n):{approvalPolicy:"on-request",sandbox:"workspace-write"};await Q.sendTurn(t,rt.id,{prompt:le,metadata:ee.turnMetadata,attachments:K.length>0?K:void 0,mentionedAppIds:Wa?[Wa.id]:void 0,mentionedConnectedApps:Ga.length>0?Ga:void 0,openPondActionCatalog:j.length>0?j:void 0,usageAttribution:ca,...da,...go,codexPermissionMode:ea==="codex"?n:"default",codexReasoningEffort:jn?u6(ea,da.model??Pe,a,qe):void 0}),Ke(t);const Ta=rt.workspaceId??rt.appId;return Ta&&rt.workspaceKind!=="sandbox"&&rt.workspaceKind!=="sandbox_template"&&M(Ta,!1).then(F=>{F?.initialized&&C(Ta)}),!0}catch(rt){return ke(rt instanceof Error?rt.message:String(rt)),!1}finally{Ut&&tt.current.delete(Ut),Ut&&Ht(Ut)&&be?.(Ut,!1),Ut&&(Ht(Ut)?ne(rt=>rt.map(kn=>kn.id===Ut&&kn.status==="active"?{...kn,status:"idle"}:kn)):Se(rt=>rt.map(kn=>kn.id===Ut&&kn.status==="active"?{...kn,status:"idle"}:kn)))}}async function Le(K,I){const V=tt.current.values().next().value??null,ee=K??D?.id??V;if(!t||!ee)return!1;if(ke(null),Ht(ee))try{const G=await Q.interruptCodexHistoryTurn(t,ee);if(!G.interrupted){if(G.reason==="no_active_openpond_turn"){const pe=await Q.codexHistoryThread(t,ee,{tail:!0}),fe={...pe.session,status:"idle"};return D?.id===ee&&ye(Pe=>Ao(Pe,pe.events)),ne(Pe=>fl(Pe,fe)),ke("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 ke("This Codex history turn is still starting. Try stopping it again in a moment."),!1}const le=await Q.codexHistoryThread(t,ee,{tail:!0});return D?.id===ee&&ye(pe=>Ao(pe,le.events)),ne(pe=>fl(pe,le.session)),!0}catch(G){const le=G instanceof Error?G.message:String(G);return ke(le==="Not found"?"OpenPond could not find this Codex history session, so it cannot interrupt it here.":le),!1}try{await Q.interruptTurn(t,ee,I);const G=await Q.bootstrap(t);return e(G),!0}catch(G){return ke(G instanceof Error?G.message:String(G)),!1}}async function nt(K,I){if(!t){ke("OpenPond App server is not connected.");return}ke(null),await Q.applyCreateImproveAction(t,K.id,{...I,runId:K.id,expectedRevision:K.revision,actionId:`web:${I.type}:${crypto.randomUUID()}`});const V=await Q.bootstrap(t);e(V)}async function at(K){await nt(K.run,{type:"approve_plan"})}async function lt(K){await nt(K.run,{type:"cancel",reason:null})}async function pt(K,I){await nt(K.run,{type:"revise_plan",revision:I})}async function je(K,I,V){await nt(K.run,{type:"answer_question",questionId:I,value:V})}async function Ye(K){await nt(K.run,{type:"pause"})}async function f(K){await nt(K.run,{type:"resume"})}async function H(K,I){await nt(K.run,{type:"open_pull_request",candidateId:I})}async function Y(K,I){await nt(K.run,{type:"apply_candidate",candidateId:I})}async function he(K,I){await nt(K.run,{type:"reject_candidate",candidateId:I,reason:null})}async function ie(K,I){await nt(K.run,{type:"reconcile_pull_request",candidateId:I})}return{answerCreateImproveQuestion:je,approveCreateImproveRun:at,applyCreateImproveCandidate:Y,cancelCreateImproveRun:lt,changeDraftProvider:L,openCreateImprovePullRequest:H,pauseCreateImproveRun:Ye,reconcileCreateImprovePullRequest:ie,rejectCreateImproveCandidate:he,resumeCreateImproveRun:f,reviseCreateImproveRun:pt,sendPrompt:$e,stopTurn:Le}}function TS(e){return e.experience==="development"||e.experience==="work"&&(e.workspaceKind==="local_project"||!!e.localProjectId||!!e.cloudProjectId||e.metadata?.workspaceTarget==="local")}async function UJ({branch:e,connection:t,session:n}){if(!po(n.workspaceKind))return{sandbox:null,session:n,status:"already_running"};const a=await Q.ensureCloudWorkspaceReady(t,n.id,{branch:e,surface:"desktop"});return{bootstrap:await Q.bootstrap(t),output:a.output,sandbox:null,session:a.session,status:a.status}}function HJ(e){return fo(e)?"Preparing Hybrid sandbox...":"Starting Cloud workspace..."}function zJ(e,t){if(e==="already_running")return null;const n=fo(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 qJ(e,t){return!e.cloudProjectId||!e.cloudTeamId?!0:t.some(n=>n.id===e.cloudProjectId&&n.teamId===e.cloudTeamId)}function BJ({applyBootstrapPayload:e,cloudProjects:t,connection:n,localProjectById:a,selectedCloudProject:o,selectedProject:i,setWorkspaceBusy:s,showToast:l,visibleWorkspaceState:m}){return v.useCallback(async d=>{if(!n)throw new Error("OpenPond App server is not connected.");const h=i??(d.localProjectId?a.get(d.localProjectId)??null:null);if(d.cloudProjectId&&d.cloudTeamId&&!qJ(d,t))throw new Error("This Cloud session belongs to a different OpenPond account. Sync or select a Project in the current account.");d.workspaceId||l(HJ(d),"info"),s(!0);try{const g=await UJ({branch:i?.linkedSandboxProject?.defaultBranch??o?.defaultBranch??m?.currentBranch??null,connection:n,localProject:h,session:d,source:fo(d)?"openpond-app-hybrid-chat-preflight":"openpond-app-cloud-chat-preflight"});g.bootstrap&&e(g.bootstrap);const y=zJ(g.status,d);return y&&l(y,"success"),g.session}finally{s(!1)}},[e,t,n,a,o,i,s,l,m?.currentBranch])}function FJ(){return{diffPanelOpen:!1,diffPanelExpanded:!1,rightPanelMode:"changes",rightChatPanels:[]}}function VJ(e){return{diffPanelOpen:e.diffPanelOpen,diffPanelExpanded:e.diffPanelExpanded,rightPanelMode:e.rightPanelMode,rightChatPanels:e.rightChatPanels}}function ES(e){return{...e,rightChatPanels:e.rightChatPanels.map(t=>({...t}))}}function KJ(e,t){return e.diffPanelOpen!==t.diffPanelOpen||e.diffPanelExpanded!==t.diffPanelExpanded||e.rightPanelMode!==t.rightPanelMode||e.rightChatPanels.length!==t.rightChatPanels.length?!1:e.rightChatPanels.every((n,a)=>{const o=t.rightChatPanels[a];return!!(o&&n.id===o.id&&n.activationVersion===o.activationVersion&&n.sessionId===o.sessionId&&n.prompt===o.prompt&&n.provider===o.provider&&n.model===o.model&&n.scrollTop===o.scrollTop&&n.stickyToBottom===o.stickyToBottom)})}function WJ(e){return`${e.conversationId}\0${e.workspaceSourceKey||"none"}`}function GJ(e){const{appDispatch:t,diffPanelExpanded:n,diffPanelOpen:a,rightChatPanels:o,rightPanelMode:i,selectedAppId:s,selectedCloudProject:l,selectedProjectId:m,selectedSession:d,selectedSessionId:h,setWorkspaceDiffPanelViewState:g,view:y,viewWorkspaceAppId:w,viewWorkspaceId:_,viewWorkspaceKind:P,workspaceDiffPanelViewState:M}=e,C=v.useRef(new Map),N=v.useRef(new Map),$=v.useRef(null),j=v.useRef(null),x=h??`draft:${m??s??l?.id??"general"}`,R=v.useMemo(()=>_?`${P??"workspace"}:${_}`:w?`app:${w}`:d?.cwd&&!po(d.workspaceKind)?`cwd:${d.cwd}`:"none",[d?.cwd,d?.workspaceKind,y,w,_,P]),E=WJ({conversationId:x,workspaceSourceKey:R}),U=v.useMemo(()=>VJ({diffPanelExpanded:n,diffPanelOpen:a,rightChatPanels:o,rightPanelMode:i}),[n,a,o,i]);v.useEffect(()=>{const D=$.current;D&&C.current.set(D,ES(U))},[x,U]),v.useEffect(()=>{if($.current===x)return;$.current=x;const W=C.current.get(x)??FJ();KJ(U,W)||t({type:"patch",patch:ES(W)})},[x,U]),v.useEffect(()=>{const D=j.current;D&&N.current.set(D,af(M))},[E,M]),v.useEffect(()=>{if(j.current===E)return;j.current=E;const W=N.current.get(E)??lC();g(se=>P0(se,W)?se:af(W))},[E]);const B=v.useCallback(D=>{g(W=>P0(W,D)?W:af(D))},[]);return{browserConversationId:x,handleWorkspaceDiffPanelViewStateChange:B}}function ZJ({account:e,accountPending:t,accountSignedOut:n,activeWorkspaceKind:a,activeWorkspaceLocation:o,appDispatch:i,applyBootstrapPayload:s,busy:l,cloudSetupDialog:m,cloudProjects:d,connection:h,defaultTeamId:g,expandProject:y,localProjectById:w,selectedCloudProject:_,selectedProject:P,selectedSession:M,selectedSessionProjectId:C,setCloudSetupDialog:N,setDiffPanelOpen:$,setError:j,setSessions:x,setWorkspaceBusy:R,showToast:E,visibleWorkspaceState:U,workspaceBusy:B}){const D=e?.baseUrl??e?.activeProfile?.baseUrl??null,W=v.useCallback(async(te,Ee)=>{if(h)try{const ye=await Q.previewLocalProjectCloudSource(h,te.id,{branch:Ee});N(ne=>!ne||ne.status!=="confirm"||ne.localProjectId!==te.id||ne.branch!==Ee?ne:{...ne,branch:ye.preview.branch,cloudProjectId:ye.preview.targetProjectId,preview:ye.preview,previewLoading:!1,previewError:null})}catch(ye){const ne=ye instanceof Error?ye.message:String(ye);N(be=>!be||be.status!=="confirm"||be.localProjectId!==te.id||be.branch!==Ee?be:{...be,preview:null,previewLoading:!1,previewError:ne})}},[h,N]),se=v.useCallback(async()=>{const te=m;if(!te||te.status==="uploading")return;if(te.projectKind==="cloud"){N(be=>be&&{...be,status:"ready",error:null});return}if(!h){N(be=>be&&{...be,status:"error",error:"OpenPond App server is not connected."});return}const Ee=te.localProjectId??"",ye=w.get(Ee);if(!ye){N(be=>be&&{...be,status:"error",error:"Project is no longer available."});return}R(!0);const ne=Ca(ye,d);N(be=>be&&{...be,status:"uploading",error:null,previewLoading:!1});try{const be=await Q.organizations(h),ae=Ju(be.organizations.map(Fu).filter(He=>!!He).filter(He=>He.status==="active"),g);if(!ae)throw new Error("Add an OpenPond account before creating a Cloud environment.");if(!Zu(ae))throw new Error(`You need owner or admin access to create projects in ${ae.displayName}.`);const ue=te.branch||ye.linkedSandboxProject?.defaultBranch||"main",xe=yt("local",ye.id),De=await Q.createSession(h,{provider:"openpond",appId:null,appName:null,workspaceKind:"local_project",workspaceId:ye.id,workspaceName:ye.name,localProjectId:ye.id,cloudProjectId:ne?.id??null,cloudTeamId:ne?.teamId??null,cwd:ye.workspacePath,title:`Sync ${ye.name} to Cloud`});x(He=>[De,...He]),i({type:"selectSession",sessionId:De.id,projectId:xe}),y(xe);const we=await Q.uploadLocalProjectCloudSource(h,ye.id,{teamId:ae.teamId,projectName:ye.name,branch:ue,chatSessionId:De.id,displayPrompt:`/sync-cloud ${ye.name}`});s(we.bootstrap),y(xe),y(yt("cloud",we.project.id));const oe=Ph({accountBaseUrl:D,teamId:we.project.teamId,projectId:we.project.id,projectName:we.project.name,baseBranch:we.upload.branch,localProjectId:ye.id,source:"openpond-app"}),Se=CS({accountBaseUrl:D,organizationSlug:we.project.organizationSlug,projectSlug:we.project.slug});N({status:"ready",localProjectId:ye.id,cloudProjectId:we.project.id,teamId:we.project.teamId,projectName:we.project.name,projectKind:"local",projectUrl:Se,setupUrl:oe,branch:we.upload.branch,preview:te.preview??null,previewLoading:!1,previewError:null,upload:{branch:we.upload.branch,headCommit:we.upload.headCommit,fileCount:we.upload.fileCount,byteCount:we.upload.byteCount,skippedCount:we.upload.skippedCount,initializedEmptyProject:we.upload.initializedEmptyProject},error:null}),E("Source uploaded to OpenPond Git. Cloud setup link is ready.","success")}catch(be){const ae=be instanceof Error?be.message:String(be),ue=h?await Q.bootstrap(h).catch(()=>null):null;ue&&s(ue),j(ae),N(xe=>xe&&{...xe,status:"error",error:ae})}finally{R(!1)}},[D,i,s,m,d,h,g,y,w,N,j,x,R,E]),de=v.useCallback((te,Ee)=>{if(!h){E("OpenPond App server is not connected.","error");return}if(t){E("Checking OpenPond account. Try again in a moment.","info");return}if(n){E("Add an OpenPond account before using Cloud.","error");return}const ye=Ee||te.linkedSandboxProject?.defaultBranch||"main";N({status:"confirm",localProjectId:te.id,projectName:te.name,projectKind:"local",projectUrl:null,setupUrl:null,branch:ye,preview:null,previewLoading:!0,previewError:null,upload:null,error:null}),W(te,ye)},[t,n,h,W,N,E]),Me=v.useCallback(async te=>{if(te===o||B||l)return;if(j(null),te==="upload_cloud"){if(!P){E("Select a local Project before uploading source.","error");return}de(P,U?.currentBranch??null);return}if(te==="local"){const ne=M?.localProjectId??P?.id??C??null,be=ne?w.get(ne)??null:null;if(!be){E("No linked local workspace for this Cloud chat.","error");return}if(po(a)&&!window.confirm("Switch to Local? Cloud changes will stay in the hosted workspace until you preserve or export them."))return;const ae=yt("local",be.id);i({type:"selectProject",projectId:ae}),y(ae),$(!1),E(`Switched to Local: ${be.name}`,"info");return}if(!h){E("OpenPond App server is not connected.","error");return}if(t){E("Checking OpenPond account. Try again in a moment.","info");return}if(n){E("Add an OpenPond account before using Cloud.","error");return}if(_){N({status:"ready",cloudProjectId:_.id,teamId:_.teamId,projectName:_.name,projectKind:"cloud",projectUrl:CS({accountBaseUrl:D,organizationSlug:_.organizationSlug,projectSlug:_.slug}),setupUrl:Ph({accountBaseUrl:D,teamId:_.teamId,projectId:_.id,projectName:_.name,baseBranch:_.defaultBranch,source:"openpond-app"}),branch:_.defaultBranch??"main",preview:null,previewLoading:!1,previewError:null,upload:null,error:null});return}const Ee=P;if(!Ee){E("Select a Project before Cloud coding.","error");return}const ye=U?.currentBranch||Ee.linkedSandboxProject?.defaultBranch||"main";de(Ee,ye)},[D,t,n,a,o,i,l,h,d,y,w,de,_,P,M,C,N,$,j,E,U?.currentBranch,B]),ke=v.useCallback(te=>{xv(te)&&de(te.project)},[de]);return{changeWorkspaceTarget:Me,moveProjectToCloud:ke,openCloudSetupForLocalProject:de,startCloudSetupUpload:se}}function JJ({advanceTrainingTurn:e,bindTrainingSession:t,composerDraftStore:n,onSessionCreated:a,onSubmitted:o,prepareTrainingTurn:i,sendPrompt:s,setMentionedAppId:l,showToast:m}){return v.useCallback(async(d=[],h=null,g,y={})=>{const w=g??n.getSnapshot(),_=i(w);if(_.active&&w.trim()&&!_.metadata)return m(_.error??"Load the selected generated Taskset question before sending, or close the generated-question handoff to write a normal prompt.","error"),!1;const P=await s(d,h,g,{clearPrompt:y.preservePrompt?()=>{}:void 0,displayPrompt:y.displayPrompt,onSessionCreated:M=>{a(M),_.metadata&&t(M.id)},turnMetadata:_.metadata||y.turnMetadata?{..._.metadata??{},...y.turnMetadata??{}}:void 0,sessionMetadata:_.metadata?{trainingTasksetId:_.metadata.trainingTasksetId,trainingTasksetName:_.metadata.trainingTasksetName}:void 0});return P&&await o?.(),P&&_.metadata&&e(),P},[e,t,n,a,o,i,s,l,m])}function YJ({appDispatch:e,connection:t,sessions:n,setDiffPanelOpen:a,setRightPanelMode:o,setSessions:i,setView:s}){return v.useCallback(async l=>{if(!t)return;const m=n.find(g=>!g.archived&&g.workspaceKind==="sandbox"&&g.workspaceId===l.sandboxId);if(m){e({type:"selectSession",sessionId:m.id,appId:null,projectId:null}),o("changes"),a(!0),s("chat");return}const d=l.name??`Sandbox ${l.sandboxId.slice(0,8)}`,h=await Q.createSession(t,{provider:"openpond",appId:null,appName:null,workspaceKind:"sandbox",workspaceId:l.sandboxId,workspaceName:d,cwd:null,title:d});i(g=>[h,...g]),e({type:"selectSession",sessionId:h.id,appId:null,projectId:null}),o("changes"),a(!0),s("chat")},[e,t,n,a,o,i,s])}function QJ({connection:e,defaultTeamId:t,sessions:n,selectedProjectId:a,confirmProjectAction:o,applyBootstrapPayload:i,expandProject:s,setExpandedProjectIds:l,setSelectedAppId:m,setSelectedProjectId:d,setSelectedSessionId:h,setError:g,setView:y,showToast:w}){function _($){const j=yt("local",$.id);m(null),d(j),h(null),y("chat"),s(j)}async function P($){if(!e)return!1;g(null);try{const j=await Q.createLocalProject(e,$);return i(j.bootstrap),_(j.project),w(j.created===!1?`Opened ${j.project.name}`:`Created ${j.project.name}`,"success"),!0}catch(j){const x=j instanceof Error?j.message:String(j);return g(x),w(x,"error"),!1}}async function M($){if(!e)return!1;const j=$.trim();if(!j)return!1;g(null);try{const x=await Q.createLocalProject(e,{createNew:!0,name:j});return i(x.bootstrap),_(x.project),w(`Created ${x.project.name}`,"success"),!0}catch(x){return g(x instanceof Error?x.message:String(x)),w("Project could not be created","error"),!1}}async function C($){if(!e)return!1;const j=$.trim();if(!j)return!1;g(null);try{const x=await Q.organizations(e),R=Ju(x.organizations.map(Fu).filter(W=>!!W).filter(W=>W.status==="active"),t);if(!R)throw new Error("Add an OpenPond account before creating a Cloud Project.");if(!Zu(R))throw new Error(`You need owner or admin access to create projects in ${R.displayName}.`);const E=`${cC(j)}-${Date.now().toString(36)}`;let U=(await Q.upsertSandboxProject(e,{teamId:R.teamId,name:j,sourceType:"internal_repo",normalizedSourceIdentity:E,internalRepoPath:E,defaultBranch:"main",sourceConfig:{sourceType:"internal_repo",sourceValue:E},metadata:{source:"openpond-app-new-cloud-project"}})).project;U=(await Q.uploadSandboxProjectSource(e,U.id,{teamId:R.teamId,branch:"main",commitMessage:"Initialize cloud project",entries:[{path:"README.md",type:"file",contentsBase64:A9(`# ${j}
|
|
211
|
-
|
|
212
|
-
Created in OpenPond Cloud.
|
|
213
|
-
`)}]})).project;const B=await Q.bootstrap(e);i(B);const D=yt("cloud",U.id);return m(null),d(D),h(null),y("chat"),s(D),w(`Created Cloud Project: ${U.name}`,"success"),!0}catch(x){const R=x instanceof Error?x.message:String(x);return g(R),w(R,"error"),!1}}async function N($){if(!e)return;if(r6($)){const E=`Archive ${$.project.name} in OpenPond Cloud?`;if(!(o?await o({title:"Archive Cloud Project",body:`${$.project.name} will be archived in OpenPond Cloud. Existing task history stays available through Cloud history.`,confirmLabel:"Archive project"}):window.confirm(E)))return;g(null);try{await Q.archiveSandboxProject(e,$.project.id,{teamId:$.project.teamId}),i(await Q.bootstrap(e)),l(B=>{const D=new Set(B);return D.delete($.id),D}),a===$.id&&(d(null),h(null)),w(`Archived ${$.project.name}`,"success")}catch(B){g(B instanceof Error?B.message:String(B)),w("Cloud Project could not be archived","error")}return}if(!xv($))return;const j=$.project,x=`Remove ${j.name} from Projects? The folder will not be deleted.`;if(o?await o({title:"Remove Project",body:`${j.name} will be removed from the sidebar. The folder and files on disk will not be deleted.`,confirmLabel:"Remove project"}):window.confirm(x)){g(null);try{const E=await Q.deleteLocalProject(e,j.id);i(E),l(U=>{const B=new Set(U);return B.delete($.id),B}),a===$.id&&(d(null),h(U=>{const B=n.find(D=>D.id===U);return B?.workspaceKind==="local_project"&&B.workspaceId===j.id?null:U})),w(`Removed ${j.name}`,"success")}catch(E){g(E instanceof Error?E.message:String(E)),w("Project could not be removed","error")}}}return{createCloudProjectFromScratch:C,createProjectFromScratch:M,createProjectCollection:P,removeProject:N}}function XJ({appDispatch:e,busy:t,cloudProjectById:n,createCloudProjectFromScratch:a,createProjectFromScratch:o,createProjectCollection:i,expandProject:s,localProjectById:l,onCreateCloudEnvironment:m,onNewCloudProject:d,onNewLocalProject:h,onUseExistingFolderPath:g,newProjectBusy:y,newProjectMode:w,newProjectName:_,projectTargetValue:P,setDiffPanelOpen:M,setDraftModel:C,setDraftProvider:N,setError:$,setNewProjectBusy:j,setNewProjectDialogOpen:x,setNewProjectName:R,setNewProjectPath:E,showToast:U,workspaceBusy:B}){const D=v.useCallback(se=>{if(se===P||t||B)return;if($(null),se==="action:new-local-project"){h();return}if(se==="action:add-local-project"){g();return}if(se==="action:add-local-project-path"){g();return}if(se==="action:new-cloud-project"){d();return}if(se==="action:create-cloud-environment"){m();return}if(se==="none"){e({type:"selectProject",projectId:null}),M(!1),U("Started a chat without project files.","info");return}const de=se.indexOf(":"),Me=de>=0?se.slice(0,de):"",ke=de>=0?se.slice(de+1):"";if(Me==="local"){const te=l.get(ke);if(!te){U("Project is no longer available.","error");return}const Ee=yt("local",te.id);e({type:"selectProject",projectId:Ee}),s(Ee),M(!1);return}if(Me==="cloud"){const te=n.get(ke);if(!te){U("Cloud Project is no longer available.","error");return}const Ee=yt("cloud",te.id);e({type:"selectProject",projectId:Ee}),s(Ee),N("openpond"),C(ye=>_r("openpond",ye)),M(!1)}},[e,t,n,s,l,m,d,h,g,P,M,C,N,$,U,B]),W=v.useCallback(async se=>{const de=_.trim();if(!y){if(w==="existing-local"?!se?.name.trim()||!se.sourceFolders.length:!de)return!1;j(!0);try{const Me=w==="cloud"?await a(de):w==="existing-local"?await i(se):await o(de);return Me&&(x(!1),R(""),E("")),!!Me}finally{j(!1)}}},[a,o,i,y,w,_,j,x,R,E]);return{changeProjectTarget:D,submitNewProjectDialog:W}}function eY(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 HX(e){return e.reduce((t,n)=>!t||n.activationVersion>=t.activationVersion?n:t,null)}function tY(e,t){const n=Math.max(0,...e.map(i=>i.activationVersion))+1;let a=!1;const o=e.map(i=>i.id!==t?i:(a=!0,{...i,activationVersion:n}));return a?o:[...e]}function nY(e,t){const n=Math.max(0,...e.map(i=>i.activationVersion))+1;let a=!1;const o=e.map(i=>i.sessionId!==t.sessionId?i:(a=!0,{...i,activationVersion:n,prompt:t.prompt??i.prompt}));return a?o:[...e]}function cR(e){return!!(e.parentSessionId&&e.subagentRunId)}function aY(e){const t=e.sessions.filter(cR);return{knownSessionIds:new Set(t.map(n=>n.id)),newSessions:t.filter(n=>!e.knownSessionIds.has(n.id))}}function oY(e,t){const n=new Set(e.map(o=>o.sessionId).filter(Boolean)),a=t.filter(cR).filter(o=>!n.has(o.id)).map(o=>({id:`right-subagent-${o.id}`,activationVersion:1,sessionId:o.id,prompt:"",provider:o.provider,model:o.modelRef?.modelId??"",scrollTop:0,stickyToBottom:!0}));return a.length>0?[...e,...a]:e}const MS="openpond/openpond",rY="github.issue.write";function iY(e){return e.some(t=>t.provider==="github"&&(t.ref.capabilities??[]).includes(rY))}function zX(e){return[`Title: ${e.title.trim()}`,"","Description:",e.description.trim()].join(`
|
|
214
|
-
`)}function sY(e){const t=e.trim();return[`@github Submit this request as a new GitHub issue in ${MS}.`,`Use the GitHub connected app write operation github.issue.create with input.repo set to ${MS}, 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:
|
|
215
|
-
${t}`].join(`
|
|
216
|
-
`)}function lY(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(`
|
|
217
|
-
|
|
218
|
-
`),requiresInstructions:!0};case"train":return{kind:"open_training",objective:n||null};case"submit-issue":return{kind:"send_prompt",prompt:sY(n),requiresInstructions:!0};case"sync-cloud":return{kind:"send_prompt",prompt:`/sync-cloud ${n}`,requiresInstructions:!1}}}const jS=[];function cY(e){const{approvals:t,codexHistoryEvents:n,contextCompaction:a,pendingChatUserMessages:o,rightChatHistoryEvents:i,rightChatPanels:s,runningSessionIds:l,selectedSessionId:m,sidebarSessions:d}=e;return v.useMemo(()=>{const h=new Map(d.map(y=>[y.id,y])),g=dY(t);return s.map(y=>{const w=y.sessionId?h.get(y.sessionId)??null:null,_=Ht(y.sessionId),P=_?(y.sessionId?i[y.sessionId]:void 0)??(y.sessionId===m?n:jS):jS,M=hh(P,[]),C=y.sessionId?g.get(y.sessionId)??null:null,N=!!(w&&l.has(w.id)),$=_?DK({events:P}):null,j=w?.cwd??null,x=w?.appId??w?.localProjectId??(w?.workspaceKind==="local_project"?w.workspaceId??null:null)??(w?.cwd&&!po(w.workspaceKind)?pk(w.cwd):null),R=y.sessionId?o[y.sessionId]??null:null;return{...y,session:w,title:LK($,w?.title??"New task"),messages:_?xC(Wu(P),R):[],createImproveRun:$,contextWindowStatus:U_({provider:y.provider,snapshot:tC(M,y.sessionId),preferences:a}),goalRuntime:nC(M,y.sessionId),pendingApproval:C,running:N,workspaceRootPath:j,activeWorkspaceAppId:x,pendingUserMessage:R,runtimeSource:_?"history":"live"}})},[t,n,a,o,i,s,l,m,d])}function dY(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 uY(e){const{applyPayload:t,connection:n,locallyActiveSessionIds:a,panels:o,sessions:i,setError:s}=e,l=v.useMemo(()=>{const h=new Set,g=[];for(const y of o)!Ht(y.sessionId)||!y.sessionId||h.has(y.sessionId)||(h.add(y.sessionId),g.push(y.sessionId));return g.join(`
|
|
219
|
-
`)},[o]),m=v.useMemo(()=>{if(!l)return"";const h=new Set(l.split(`
|
|
220
|
-
`).filter(Boolean));return i.filter(g=>h.has(g.id)&&g.status==="active").map(g=>g.id).join(`
|
|
221
|
-
`)},[l,i]),d=v.useMemo(()=>l?l.split(`
|
|
222
|
-
`).filter(h=>a.has(h)).join(`
|
|
223
|
-
`):"",[a,l]);v.useEffect(()=>{if(!n||!l)return;const h=l.split(`
|
|
224
|
-
`).filter(Boolean),g=new Set(m.split(`
|
|
225
|
-
`).filter(Boolean)),y=new Set(d.split(`
|
|
226
|
-
`).filter(Boolean)),w=h.map(_=>Ov({connection:n,locallyActive:y.has(_),onError:P=>s(P instanceof Error?P.message:String(P)),onPayload:P=>t(jv(P,y.has(_))),reportedActive:g.has(_),sessionId:_,surface:"thread"}));return()=>w.forEach(_=>_())},[m,t,n,d,l,s])}const OS=[];function mY(e){const{activeModel:t,activeProvider:n,approvals:a,applyRightCodexHistoryPayload:o,codexHistoryEvents:i,connectedAppMentions:s,connection:l,contextCompaction:m,openLabTraining:d,locallyActiveCodexHistorySessionIds:h,openPondCommandAccessMode:g,pendingChatUserMessages:y,providerSettings:w,rightChatHistoryEvents:_,rightChatPanels:P,rightPanelMode:M,runtimeIndexes:C,runtimeEventStore:N,runningSessionIds:$,selectedSession:j,selectedSessionId:x,sendPrompt:R,setDiffPanelOpen:E,setError:U,setRightChatHistoryEvents:B,setRightChatPanels:D,setRightPanelMode:W,setRightPanelTabRequest:se,setView:de,showChangesPanel:Me,showToast:ke,sidebarSessions:te,startupReady:Ee}=e,ye=v.useRef(null),ne=v.useRef(new Map),be=v.useRef(new Set);v.useEffect(()=>{if(!l)return;const qe=P.flatMap(Ge=>Ge.sessionId&&!Ht(Ge.sessionId)?[Ge.sessionId]:[]);for(const Ge of qe)Object.hasOwn(_,Ge)||be.current.has(Ge)||(be.current.add(Ge),Q.runtimeEventsPage(l,{sessionId:Ge,beforeSequence:Number.MAX_SAFE_INTEGER,limit:500}).then(ze=>{const L=ze.events.map(O=>O.event);B(O=>({...O,[Ge]:Eo(O[Ge]??OS,L)}))}).catch(ze=>{U(ze instanceof Error?ze.message:String(ze))}).finally(()=>{be.current.delete(Ge)}))},[l,_,P,U,B]);const ae=v.useCallback(qe=>{se(Ge=>({id:(Ge?.id??0)+1,tab:qe})),Me()},[Me]),ue=v.useCallback((qe=null,Ge={})=>{const ze=qe?.id?P.find(O=>O.sessionId===qe.id)??null:null;if(ze)return D(O=>nY(O,{sessionId:qe.id,prompt:Ge.prompt})),E(!0),W("chat"),Ge.preserveView||de("chat"),ze.id;const L=eY({sessionId:qe?.id??null,provider:qe?.provider??n,model:qe?.modelRef?.modelId??t,prompt:Ge.prompt});return D(O=>[...O,L]),E(!0),W("chat"),Ge.preserveView||de("chat"),L.id},[t,n,P,E,D,W,de]);v.useEffect(()=>{if(!Ee)return;const qe=ye.current;if(!qe){ye.current=new Set(te.filter(O=>!!(O.parentSessionId&&O.subagentRunId)).map(O=>O.id));return}const Ge=aY({sessions:te,knownSessionIds:qe});ye.current=Ge.knownSessionIds;for(const O of Ge.newSessions)ne.current.set(O.id,O);const ze=j?.parentSessionId??j?.id??null;if(!ze)return;const L=[...ne.current.values()].filter(O=>O.parentSessionId===ze);if(L.length!==0){for(const O of L)ne.current.delete(O.id);D(O=>oY(O,L)),E(!0),W("chat")}},[j?.id,j?.parentSessionId,E,D,W,te,Ee]);const xe=v.useCallback(()=>{if(P.length===0){ue(null);return}E(!0),W("chat"),de("chat")},[ue,P.length,E,W,de]),De=v.useCallback(qe=>{const Ge=P.length<=1&&P.some(L=>L.id===qe),ze=()=>{D(L=>L.filter(O=>O.id!==qe))};if(Ge&&M==="chat"){if(ae("files"),typeof window>"u"){ze();return}window.requestAnimationFrame(ze);return}ze()},[P,M,D,ae]),we=v.useCallback((qe,Ge)=>{D(ze=>ze.map(L=>L.id===qe?{...L,prompt:Ge}:L))},[D]),oe=v.useCallback(qe=>{D(Ge=>tY(Ge,qe))},[D]),Se=v.useCallback((qe,Ge)=>{D(ze=>ze.map(L=>L.id===qe?{...L,...Ge}:L))},[D]),He=v.useCallback((qe,Ge)=>{D(ze=>ze.map(L=>L.id===qe?{...L,model:Ge}:L))},[D]),Ze=v.useCallback((qe,Ge)=>{D(ze=>ze.map(L=>L.id===qe?{...L,provider:Ge,model:_r(Ge,L.model,w)}:L))},[w,D]);uY({applyPayload:o,connection:l,locallyActiveSessionIds:h,panels:P,sessions:te,setError:U});const Ke=cY({approvals:a,codexHistoryEvents:i,contextCompaction:m,pendingChatUserMessages:y,rightChatHistoryEvents:_,rightChatPanels:P,runningSessionIds:$,selectedSessionId:x,sidebarSessions:te}),tt=v.useCallback(async(qe,Ge=[],ze=null,L=null,O={})=>{const z=P.find(pt=>pt.id===qe);if(!z)return!1;const X=O.promptOverride??z.prompt,me=L?lY(L,X):null;if(me?.kind==="open_training")return Ge.length>0?(ke("/train uses this chat; add other chats from Models.","error"),!1):(d({objective:me.objective,sessionId:z.sessionId}),O.preservePrompt||we(qe,""),!0);if(L&&me?.kind==="send_prompt"&&me.requiresInstructions&&!X.trim())return ke(`Add instructions after ${L.command}.`,"info"),!1;if(L&&Ge.length>0)return ke(`${L.command} tasks do not accept attachments yet. Add file context in the task thread.`,"error"),!1;if(L?.id==="submit-issue"&&!iY(s))return ke("Connect the GitHub app before using /submit-issue.","error"),!1;const $e=z.sessionId?te.find(pt=>pt.id===z.sessionId)??null:null,Le=z.provider==="codex"?g:$e?.openPondCommandAccessMode??g,nt=me?.kind==="send_prompt"?me.prompt:X,at=Ht(z.sessionId)?(z.sessionId?_[z.sessionId]:void 0)??(z.sessionId===x?i:OS):N.getSessionEvents(z.sessionId),lt=Ht(z.sessionId)&&z.sessionId?pt=>{const je=z.sessionId;B(Ye=>({...Ye,[je]:Eo(Ye[je]??at,[pt])}))}:void 0;return R(Ge,ze,nt,{session:$e,selectSession:!1,provider:z.provider,model:z.model,openPondCommandAccessMode:Le,chatMessages:Wu(at),displayPrompt:O.displayPrompt,turnMetadata:O.turnMetadata,usageAttribution:L?.id==="submit-issue"?{surface:"chat",workflowKind:"slash_command",commandName:L.command,commandSource:"composer_selection"}:void 0,onCodexHistoryOptimisticEvent:lt,clearPrompt:O.preservePrompt?()=>{}:()=>we(qe,""),onSessionCreated:pt=>{D(je=>je.map(Ye=>Ye.id===qe?{...Ye,sessionId:pt.id,provider:pt.provider,model:pt.modelRef?.modelId??Ye.model}:Ye))}})},[i,s,_,P,C,N,x,d,g,R,D,de,te,ke,we]);return{activateRightChatPanel:oe,closeRightChatPanel:De,openRightChatPanel:ue,rightChatPanelViews:Ke,showRightChatPanel:xe,showRightPanelDiffTab:ae,submitRightChatPrompt:tt,updateRightChatModel:He,updateRightChatPrompt:we,updateRightChatProvider:Ze,updateRightChatScrollState:Se}}function pY(e){const{appPreferences:t,connection:n,selectedSessionId:a,setAppPreferences:o,setCodexHistorySessions:i,setError:s,setSelectedSessionId:l,setSessions:m}=e;async function d(C,N){if(!n)return;const $=t[C]??{},j={...$,...N,archived:N.pinned?!1:N.archived??$.archived};o(x=>({...x,[C]:j}));try{const x=await Q.patchSidebarAppPreference(n,C,N);o(R=>({...R,[C]:x}))}catch(x){s(x instanceof Error?x.message:String(x)),o(R=>({...R,[C]:$}))}}function h(C){d(C.id,{pinned:!C.pinned,archived:!1})}async function g(C,N){if(!n)return;const $=Ht(C.id)?i:m,j={...C,...N};$(x=>x.some(R=>R.id===C.id)?x.map(R=>R.id===C.id?j:R):[j,...x]);try{const x=await Q.patchSession(n,C.id,N);$(R=>R.some(E=>E.id===x.id)?R.map(E=>E.id===x.id?x:E):[x,...R])}catch(x){s(x instanceof Error?x.message:String(x)),$(R=>R.map(E=>E.id===C.id?C:E))}}function y(C){g(C,{pinned:!1,savedForLater:!C.savedForLater,archived:!1})}function w(C){g(C,{pinned:!C.pinned,savedForLater:!1,archived:!1})}function _(C){g(C,{pinned:!1,savedForLater:!1,archived:!0}),a===C.id&&l(null)}function P(C){g(C,{archived:!1})}function M(C,N){const $=N.trim();!$||$===C.title||g(C,{title:$})}return{archiveSession:_,renameSession:M,restoreSession:P,toggleProjectPinned:h,toggleSessionPinned:w,toggleSessionSavedForLater:y}}function fY(e){return e.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,72)||"new-branch"}function hY({connection:e,activeWorkspaceAppId:t,appDefaults:n,bootstrap:a,branchDialogName:o,commitIncludeUnstaged:i,commitMessage:s,commitNextStep:l,draftModel:m,draftProvider:d,cloudProjects:h,selectedApp:g,selectedProject:y,selectedProjectLinkedOpenPondApp:w,selectedSession:_,sessions:P,title:M,visibleWorkspaceDiff:C,visibleWorkspaceState:N,workspaceBusy:$,workspaceName:j,appDispatch:x,applyBootstrapPayload:R,expandProject:E,refreshWorkspace:U,refreshWorkspaceDiff:B,rememberWorkspaceState:D,setBranchDialogOpen:W,setCommitDialogOpen:se,setError:de,setSessions:Me,setSettingsSection:ke,setSyncingWorkspaceAppId:te,setView:Ee,setWorkspaceBusy:ye,showToast:ne}){function be(){return`${v_(n.defaultBranchPrefix)}${fY(j??M??"new-branch")}`}function ae(){return j?`Update ${j}`:(C?.filesChanged??N?.changedFilesCount??0)===1?"Update workspace file":"Update workspace files"}function ue(ze="commit"){x({type:"openCommitDialog",nextStep:ze})}function xe(){x({type:"openBranchDialog",branchName:be()})}function De(){$||W(!1),ke("configuration"),Ee("settings"),Qt({kind:"settings",section:"configuration"})}async function we(ze){if(!(!e||!t)){ye(!0),de(null);try{const L=await Q.checkoutWorkspaceBranch(e,t,{branch:ze});D(L),L.initialized&&B(t)}catch(L){de(L instanceof Error?L.message:String(L))}finally{ye(!1)}}}async function oe(){if(!e||!t)return;const ze=o.trim();if(ze){ye(!0),de(null);try{const L=await Q.createWorkspaceBranch(e,t,{branch:ze});D(L),L.initialized&&B(t),W(!1),ne(`Checked out ${ze}`,"success")}catch(L){de(L instanceof Error?L.message:String(L))}finally{ye(!1)}}}async function Se(ze){te(ze);const L=a?.apps.find(O=>O.id===ze)?.name??a?.localProjects.find(O=>O.id===ze)?.name??"Workspace";try{const O=await U(ze,!0);O?.initialized&&ze===t&&B(ze),O?.initialized&&!O.error?ne(`${L} synced locally`,"success"):O?.error&&ne("Workspace sync failed","error")}finally{te(O=>O===ze?null:O)}}async function He(){t&&await Se(t)}async function Ze(ze,L,O={}){if(!e)return null;const z=_&&!Ht(_.id)?_:null;if(yY(L,z,O)||z&&gY(z,y,g))return z;const X=z?await Ke(z):null;if(X)return X;const me=vY(P,y,g);if(me){const at=me.workspaceKind==="local_project"&&me.workspaceId?yt("local",me.workspaceId):null;return x({type:"selectSession",sessionId:me.id,appId:me.appId,projectId:at}),me.workspaceKind==="local_project"&&me.workspaceId&&E(yt("local",me.workspaceId)),me}const $e=Ca(y,h),Le=await Q.createSession(e,{provider:d,modelRef:Na(d,m,a?.providers??null),appId:w?.appId??g?.id??null,appName:w?.appName??g?.name??null,workspaceKind:y?"local_project":g?"sandbox_app":void 0,workspaceId:y?.id??g?.id??null,workspaceName:y?.name??g?.name??null,localProjectId:y?.id??null,cloudProjectId:$e?.id??null,cloudTeamId:$e?.teamId??null,cwd:y?y.workspacePath:null,title:ze});Me(at=>[Le,...at]);const nt=Le.workspaceKind==="local_project"&&Le.workspaceId?yt("local",Le.workspaceId):null;return x({type:"selectSession",sessionId:Le.id,appId:Le.appId,projectId:nt}),Le.workspaceKind==="local_project"&&Le.workspaceId&&E(yt("local",Le.workspaceId)),Le}async function Ke(ze){if(!e||!y||!w?.appId||Ht(ze.id)||ze.workspaceKind==="local_project"||ze.appId!==w.appId)return null;const L=Ca(y,h),O=await Q.patchSession(e,ze.id,{appId:w.appId,appName:w.appName,workspaceKind:"local_project",workspaceId:y.id,workspaceName:y.name,localProjectId:y.id,cloudProjectId:L?.id??null,cloudTeamId:L?.teamId??null,cwd:y.workspacePath});return Me(z=>z.map(X=>X.id===O.id?O:X)),x({type:"selectSession",sessionId:O.id,appId:O.appId,projectId:yt("local",y.id)}),E(yt("local",y.id)),O}async function tt(ze,L={}){if(!e)return null;const O=await Ze(j?`${j} workspace`:"Workspace action",ze,L);if(!O)return null;const z=await Q.workspaceTool(e,O.id,{action:ze,args:L,source:"ui_button"});ne(z.output,z.ok?"success":"error"),R(await Q.bootstrap(e));const X=z.appId??bY(O);return X&&(await U(X,!1))?.initialized&&await B(X),z}async function qe(ze,L={}){if(ze==="git_commit"&&typeof L.message!="string")return ue("commit"),null;ye(!0),de(null);try{return await tt(ze,L)}catch(O){return de(O instanceof Error?O.message:String(O)),null}finally{ye(!1)}}async function Ge(){const ze=s.trim()||ae(),L=l==="commit_publish",O=L&&!!N?.remoteUrl;if(!(O&&!window.confirm("Replace the current origin remote with the new OpenPond repo after committing?"))){ye(!0),de(null);try{if(!(await tt("git_commit",{message:ze,includeUnstaged:i}))?.ok||l==="commit_push"&&!(await tt("git_push",{runChecks:!1}))?.ok||L&&!(await tt("publish_openpond_repo",{replaceOrigin:O}))?.ok)return;se(!1)}catch(z){de(z instanceof Error?z.message:String(z))}finally{ye(!1)}}}return{changeWorkspaceBranch:we,openCommitDialog:ue,openCreateWorkspaceBranchDialog:xe,openDefaultsSettingsFromBranchDialog:De,runWorkspaceTool:qe,submitCommitDialog:Ge,submitCreateWorkspaceBranch:oe,syncWorkspaceLocally:He,syncWorkspaceLocallyForApp:Se}}function gY(e,t,n){return!t&&!n?!0:dR(e,t,n)}function vY(e,t,n){if(!t&&!n)return null;let a=null,o=Number.NEGATIVE_INFINITY;for(const i of e){if(i.archived||!dR(i,t,n))continue;const s=Date.parse(i.updatedAt),l=Number.isFinite(s)?s:0;(!a||l>o)&&(a=i,o=l)}return a}function dR(e,t,n){return t?e.workspaceKind==="local_project"&&e.workspaceId===t.id:n?e.appId===n.id||e.workspaceId===n.id:!1}function bY(e){return e.workspaceKind==="sandbox"?e.localProjectId??null:e.workspaceId??e.appId??null}function yY(e,t,n={}){return(SY(e)||kY(e,n))&&xY(t)}function SY(e){return e.startsWith("sandbox_")?e!=="sandbox_create"&&e!=="sandbox_templates"&&e!=="sandbox_template_launch":!1}function xY(e){return e?.workspaceKind==="sandbox"||e?.workspaceKind==="sandbox_template"}function kY(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 wY(e,t){return e.kind==="general"?"# general":e.title?e.title:e.participants.find(a=>a.userId!==t)?.name??"Direct message"}const IY=[];function _Y(e){const{composerDraftStore:t,appDispatch:n,mentionedAppId:a,setMentionedAppId:o,cloudSetupDialog:i,setCloudSetupDialog:s,setRightPanelTabRequest:l,workspaceDiffPanelViewState:m,setWorkspaceDiffPanelViewState:d,rightChatHistoryEvents:h,setRightChatHistoryEvents:g,locallyActiveCodexHistorySessionIds:y,setCodexHistoryTurnLocallyActive:w,draftSubagentDelegationMode:_,setDraftSubagentDelegationMode:P,confirmProjectAction:M,view:C,selectedAppId:N,selectedProjectId:$,selectedSessionId:j,draftProvider:x,draftModel:R,activeExperience:E,codexPermissionMode:U,codexReasoningEffort:B,openPondCommandAccessMode:D,busy:W,diffPanelOpen:se,diffPanelExpanded:de,rightPanelMode:Me,rightChatPanels:ke,newProjectMode:te,newProjectName:Ee,newProjectBusy:ye,commitMessage:ne,commitIncludeUnstaged:be,commitNextStep:ae,branchDialogName:ue,setSectionMenuOpen:xe,setView:De,setSelectedAppId:we,setSelectedProjectId:oe,setSelectedSessionId:Se,setPrompt:He,setDraftProvider:Ze,setDraftModel:Ke,setDiffPanelOpen:tt,setRightPanelMode:qe,setRightChatPanels:Ge,setSyncingWorkspaceAppId:ze,setSettingsSection:L,setNewProjectDialogOpen:O,setNewProjectMode:z,setNewProjectName:X,setNewProjectPath:me,setNewProjectBusy:$e,setCommitDialogOpen:Le,setBranchDialogOpen:nt,setError:at,showToast:lt,appPreferences:pt,applyBootstrapPayload:je,approvals:Ye,bootstrap:f,connection:H,events:Y,runtimeEventStore:he,sessions:ie,startup:K,setAppPreferences:I,setCodexHistorySessions:V,setEvents:ee,setSessions:G,cloudProjectById:le,localProjectById:pe,selectedApp:fe,selectedCloudProject:Pe,selectedProject:_e,selectedProjectLinkedOpenPondApp:Ne,selectedSession:Re,sidebarSessions:Xe,runtimeIndexes:st,connectedAppMentions:on,codexHistoryEvents:At,setCodexHistoryEvents:tn,account:dn,accountPending:un,accountSignedOut:Kt,activeModel:Aa,activeProvider:la,activeWorkspaceAppId:Mn,activeWorkspaceKind:_n,activeWorkspaceLocation:jt,appDefaults:ht,selectedSessionProjectId:mn,workspaceName:vt,accountScopeKey:Et,teamChat:ca,communities:Ut,selectedProjectConfirmedCloudProject:pn,activeOpenPondCommandAccessMode:rt,viewWorkspaceAppId:kn,viewWorkspaceId:Wa,viewWorkspaceKind:Ga,openPondActionCatalog:ea,selectedActionCatalog:da,expandProject:jn,setExpandedProjectIds:go,advanceTrainingModelChatAfterTurn:Ta,bindTrainingModelChatSession:F,prepareTrainingModelChatTurn:Ue,chatMessages:Ie,pendingChatUserMessages:Be,recordPendingChatUserMessage:bt,runningSessionIds:Bn,workspaceBusy:fn,visibleWorkspaceState:We,visibleWorkspaceDiff:vn,rememberWorkspaceState:ut,refreshWorkspace:Cn,setWorkspaceBusy:Ea,refreshWorkspaceDiffWhenNeeded:Jo,setPendingWorkspaceTarget:ua,pendingSidebarWorkspaceTarget:Yo,setPendingSidebarWorkspaceTarget:Rr,projectTarget:vo,workspaceTarget:On}=e,ma=C==="apps"?"Apps":C==="get-started"?"Walkthroughs":C==="labs"?"Models":C==="scheduled"?"Workflows":C==="outputs"?"Outputs":C==="projects"?"Projects":C==="team"?ca.detail?wY(ca.detail.thread,ca.currentUserId):"Team Chat":C==="community"?Ut.preview?.displayName??"Communities":Re?.title??o_(E),{browserConversationId:Fn,handleWorkspaceDiffPanelViewStateChange:Qo}=GJ({appDispatch:n,diffPanelExpanded:de,diffPanelOpen:se,rightChatPanels:ke,rightPanelMode:Me,selectedAppId:N,selectedCloudProject:Pe,selectedProjectId:$,selectedSession:Re,selectedSessionId:j,setWorkspaceDiffPanelViewState:d,view:C,viewWorkspaceAppId:kn,viewWorkspaceId:Wa,viewWorkspaceKind:Ga,workspaceDiffPanelViewState:m}),Pr=v.useCallback(ct=>{Qt({kind:"chat",sessionId:ct}),Se(ct),we(null),oe(null),De("chat")},[we,oe,Se,De]),Xo=v.useCallback(()=>{z("existing-local"),X(""),me(""),O(!0)},[O,z,X,me]),er=v.useCallback(()=>{z("local"),X(""),me(""),O(!0)},[O,z,X,me]),{createCloudProjectFromScratch:St,createProjectFromScratch:Ts,createProjectCollection:Ar,removeProject:Es}=QJ({connection:H,defaultTeamId:ht.defaultTeamId,sessions:ie,selectedProjectId:$,confirmProjectAction:M,applyBootstrapPayload:je,expandProject:jn,setExpandedProjectIds:go,setSelectedAppId:we,setSelectedProjectId:oe,setSelectedSessionId:Se,setError:at,setView:De,showToast:lt}),{changeWorkspaceBranch:di,openCommitDialog:Ms,openCreateWorkspaceBranchDialog:bo,openDefaultsSettingsFromBranchDialog:js,runWorkspaceTool:ui,submitCommitDialog:mi,submitCreateWorkspaceBranch:pi,syncWorkspaceLocally:Os}=hY({connection:H,activeWorkspaceAppId:Mn,appDefaults:ht,bootstrap:f,branchDialogName:ue,commitIncludeUnstaged:be,commitMessage:ne,commitNextStep:ae,draftModel:R,draftProvider:x,cloudProjects:f?.cloudProjects??[],selectedApp:fe,selectedProject:_e,selectedProjectLinkedOpenPondApp:Ne,selectedSession:Re,sessions:ie,title:ma,visibleWorkspaceDiff:vn,visibleWorkspaceState:We,workspaceBusy:fn,workspaceName:vt,appDispatch:n,applyBootstrapPayload:je,expandProject:jn,refreshWorkspace:Cn,refreshWorkspaceDiff:Jo,rememberWorkspaceState:ut,setBranchDialogOpen:nt,setCommitDialogOpen:Le,setError:at,setSessions:G,setSettingsSection:L,setSyncingWorkspaceAppId:ze,setView:De,setWorkspaceBusy:Ea,showToast:lt}),$s=BJ({applyBootstrapPayload:je,cloudProjects:f?.cloudProjects??[],connection:H,localProjectById:pe,selectedCloudProject:Pe,selectedProject:_e,setWorkspaceBusy:Ea,showToast:lt,visibleWorkspaceState:We}),Za=f?.preferences.subagents.delegationMode??"manual",Ns=Re?.subagentDelegationMode??_,fi=!!(E==="development"&&f?.preferences.subagents.enabled&&la!=="codex"&&!Ht(j)&&!Re?.subagentRunId),hi=v.useCallback(ct=>{if(!Re){P(ct);return}if(!H||Ht(Re.id)||Re.subagentRunId)return;const Jt=Re.id,Kn=Re.subagentDelegationMode??null;G(rn=>rn.map(Rn=>Rn.id===Jt?{...Rn,subagentDelegationMode:ct}:Rn)),Q.patchSession(H,Jt,{subagentDelegationMode:ct}).then(rn=>{G(Rn=>Rn.map(aa=>aa.id===rn.id?rn:aa))}).catch(rn=>{G(Rn=>Rn.map(aa=>aa.id===Jt?{...aa,subagentDelegationMode:Kn}:aa)),at(rn instanceof Error?rn.message:String(rn))})},[H,Re,at,G]),tr=v.useCallback(ct=>{g(Jt=>Jt[ct.session.id]===ct.events?Jt:{...Jt,[ct.session.id]:ct.events}),V(Jt=>Vu(Jt,ct.session))},[V]),{answerCreateImproveQuestion:gi,applyCreateImproveCandidate:ta,approveCreateImproveRun:Ds,cancelCreateImproveRun:Tr,changeDraftProvider:yo,openCreateImprovePullRequest:Vn,reconcileCreateImprovePullRequest:Ls,rejectCreateImproveCandidate:Us,pauseCreateImproveRun:bn,resumeCreateImproveRun:nr,reviseCreateImproveRun:pa,sendPrompt:Ma,stopTurn:Er}=LJ({applyBootstrapPayload:je,bootstrap:f,chatMessages:Ie,connection:H,codexPermissionMode:U,codexReasoningEffort:B,openPondCommandAccessMode:rt,draftModel:R,draftProvider:x,experience:E,expandProject:jn,getPrompt:t.getSnapshot,apps:f?.apps??[],connectedAppMentions:on,mentionedAppId:a,ensureCloudSessionReady:$s,refreshWorkspace:Cn,refreshWorkspaceDiff:Jo,selectedApp:fe,selectedActionCatalog:da,openPondActionCatalog:ea,cloudProjects:f?.cloudProjects??[],accountScopeKey:Et,selectedCloudProject:Pe,selectedProject:_e,selectedProjectLinkedOpenPondApp:Ne,selectedSession:Re,sessions:ie,workspaceTarget:On.value,subagentDelegationMode:Re?.subagentDelegationMode??_,setDraftModel:Ke,setDraftProvider:Ze,setError:at,setPrompt:He,setMentionedAppId:o,setCodexHistoryEvents:tn,setCodexHistorySessions:V,onCodexHistoryTurnActivityChange:w,onCodexHistoryTurnPayload:tr,onPendingUserMessage:bt,setEvents:ee,setSelectedAppId:we,setSelectedProjectId:oe,setSelectedSessionId:Se,setSessions:G,setView:De,setWorkspaceBusy:Ea}),{archiveSession:ar,restoreSession:Hs,renameSession:vi,toggleProjectPinned:Mr,toggleSessionPinned:So,toggleSessionSavedForLater:or}=pY({appPreferences:pt,connection:H,selectedSessionId:j,setAppPreferences:I,setCodexHistorySessions:V,setError:at,setSelectedSessionId:Se,setSessions:G}),{changeWorkspaceTarget:rr,moveProjectToCloud:bi,startCloudSetupUpload:yi}=ZJ({account:dn,accountPending:un,accountSignedOut:Kt,activeWorkspaceKind:_n,activeWorkspaceLocation:jt,appDispatch:n,applyBootstrapPayload:je,busy:W,cloudSetupDialog:i,cloudProjects:f?.cloudProjects??[],connection:H,defaultTeamId:ht.defaultTeamId,expandProject:jn,localProjectById:pe,selectedCloudProject:Pe,selectedProject:_e,selectedSession:Re,selectedSessionProjectId:mn,setCloudSetupDialog:s,setDiffPanelOpen:tt,setError:at,setSessions:G,setWorkspaceBusy:Ea,showToast:lt,visibleWorkspaceState:We,workspaceBusy:fn}),fa=v.useCallback(async ct=>{if(E==="work"&&!Re){if(ct==="local"){ua("local"),lt(_e?`Next task will use the local ${_e.name} checkout.`:"Next task will use an app-managed local workspace.","info");return}if(ct==="cloud"&&!_e&&!Pe){if(un){lt("Checking OpenPond account. Try again in a moment.","info");return}if(Kt){lt("Add an OpenPond account before using Hosted.","error");return}ua("cloud"),lt("Next task will use Hosted without a Project.","info");return}}if(ct==="hybrid"){const Jt=Pe?.id??pn?.id??Re?.cloudProjectId??null,Kn=Pe?.teamId??pn?.teamId??Re?.cloudTeamId??null;if(un){lt("Checking OpenPond account. Try again in a moment.","info");return}if(Kt){lt("Add an OpenPond account before using Hybrid.","error");return}if(!Jt||!Kn){ua(null),lt("Upload/sync this Project to Cloud before using Hybrid.","error");return}if(Re&&!Ht(Re.id)){if(fo(Re))return;if(!H){lt("OpenPond App server is not connected.","error");return}const rn=await Q.patchSession(H,Re.id,{provider:x,modelRef:Na(x,R,f?.providers??null),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:null,workspaceName:Pe?.name??pn?.name??_e?.name??Re.workspaceName??"Hybrid workspace",localProjectId:_e?.id??Re.localProjectId??null,cloudProjectId:Jt,cloudTeamId:Kn,metadata:rC(Re.metadata),cwd:_e?.workspacePath??Re.cwd??null});G(Rn=>Rn.map(aa=>aa.id===rn.id?rn:aa)),ua(null),lt("Hybrid will use your selected model with hosted sandbox edits.","info");return}ua("hybrid"),lt("Next message will use Hybrid with a hosted sandbox.","info");return}ua(null),await rr(ct)},[un,Kt,E,f?.providers,rr,H,R,x,Pe?.id,Pe?.name,Pe?.teamId,_e?.id,pn?.id,pn?.name,pn?.teamId,_e?.name,_e?.workspacePath,Re,ua,G,lt]),ha=v.useCallback((ct,Jt)=>{we(null),oe(ct),Se(null),De("chat"),jn(ct),Rr({projectId:ct,target:Jt})},[jn,we,oe,Se,De]);v.useEffect(()=>{if(!Yo||C!=="chat"||$!==Yo.projectId||j!==null)return;const ct=Yo.target;Rr(null),fa(ct)},[fa,Yo,$,j,C]);const Si=JJ({advanceTrainingTurn:Ta,bindTrainingSession:F,composerDraftStore:t,onSessionCreated:ct=>{Se(ct.id),De("chat"),Qt({kind:"chat",sessionId:ct.id}),P(null)},onSubmitted:async()=>{const ct=Re;if(!(!H||!ct||!Bl(ct)))try{const Jt=await Q.patchSession(H,ct.id,{metadata:g6(ct.metadata)});G(Kn=>Kn.map(rn=>rn.id===Jt.id?Jt:rn))}catch(Jt){lt(Jt instanceof Error?`Task started, but its Draft label could not be cleared: ${Jt.message}`:"Task started, but its Draft label could not be cleared.","error")}},prepareTrainingTurn:Ue,sendPrompt:Ma,setMentionedAppId:o,showToast:lt}),jr=YJ({appDispatch:n,connection:H,sessions:ie,setDiffPanelOpen:tt,setRightPanelMode:qe,setSessions:G,setView:De}),{createCloudEnvironmentFromSidebar:Ja,openCloudProjectDialog:Or,openUrlInBrowserPanel:xo,showBrowserPanel:xi,showChangesPanel:ki,showGoalSidebarTab:wi}=iJ({account:dn,browserConversationId:Fn,cloudProjectById:le,cloudProjects:f?.cloudProjects??[],diffPanelOpen:se,rightPanelMode:Me,selectedProjectId:$,setDiffPanelOpen:tt,setNewProjectDialogOpen:O,setNewProjectMode:z,setNewProjectName:X,setRightPanelMode:qe}),{changeProjectTarget:zs,submitNewProjectDialog:Ii}=XJ({appDispatch:n,busy:W,cloudProjectById:le,createCloudProjectFromScratch:St,createProjectFromScratch:Ts,createProjectCollection:Ar,expandProject:jn,localProjectById:pe,newProjectBusy:ye,newProjectMode:te,newProjectName:Ee,onCreateCloudEnvironment:Ja,onNewCloudProject:Or,onNewLocalProject:er,onUseExistingFolderPath:Xo,projectTargetValue:vo.value,setDiffPanelOpen:tt,setDraftModel:Ke,setDraftProvider:Ze,setError:at,setNewProjectBusy:$e,setNewProjectDialogOpen:O,setNewProjectName:X,setNewProjectPath:me,showToast:lt,workspaceBusy:fn}),_i=v.useMemo(()=>ie.map(ct=>ct.id),[ie]);lJ({browserConversationId:Fn,sessionIds:_i,onOpenSession:Pr,onShowBrowserPanel:xi});const[qs,ir]=v.useState(null),Ci=v.useCallback(ct=>{ir({id:Date.now(),objective:ct.objective,initialSessionIds:ct.sessionId?[ct.sessionId]:[]}),rs(za()),De("labs")},[De]),{activateRightChatPanel:$r,closeRightChatPanel:Ya,openRightChatPanel:Bs,rightChatPanelViews:Fs,showRightChatPanel:Vs,showRightPanelDiffTab:Ks,submitRightChatPrompt:Qa,updateRightChatModel:Ri,updateRightChatPrompt:Ws,updateRightChatProvider:Gs,updateRightChatScrollState:Zs}=mY({activeModel:Aa,activeProvider:la,approvals:Ye,applyRightCodexHistoryPayload:tr,codexHistoryEvents:At,connectedAppMentions:on,connection:H,contextCompaction:ht.contextCompaction,openLabTraining:Ci,locallyActiveCodexHistorySessionIds:y,openPondCommandAccessMode:D,pendingChatUserMessages:Be,providerSettings:f?.providers??null,rightChatHistoryEvents:h,rightChatPanels:ke,rightPanelMode:Me,runtimeIndexes:st,runtimeEventStore:he,runningSessionIds:Bn,selectedSession:Re,selectedSessionId:j,sendPrompt:Ma,setDiffPanelOpen:tt,setError:at,setRightChatHistoryEvents:g,setRightChatPanels:Ge,setRightPanelMode:qe,setRightPanelTabRequest:l,setView:De,showChangesPanel:ki,showToast:lt,sidebarSessions:Xe,startupReady:K.ready}),na=v.useCallback(()=>{xe(null),L("profile"),De("settings"),Qt({kind:"settings",section:"profile"})},[xe,L,De]),Pi=v.useMemo(()=>Ao(f?.diagnostics??IY,Y.filter(ct=>ct.name==="diagnostic")),[f?.diagnostics,Y]),Js=v.useCallback(()=>{if(se){tt(!1);return}if(C==="labs"){qe("changes"),l({id:Date.now(),tab:"summary"}),tt(!0);return}qe("home"),tt(!0)},[se,tt,qe,l,C]);return{title:ma,browserConversationId:Fn,handleWorkspaceDiffPanelViewStateChange:Qo,openSessionInChat:Pr,openExistingProjectPathDialog:Xo,removeProject:Es,changeProjectTarget:zs,submitNewProjectDialog:Ii,changeWorkspaceBranch:di,openCommitDialog:Ms,openCreateWorkspaceBranchDialog:bo,openDefaultsSettingsFromBranchDialog:js,runWorkspaceTool:ui,submitCommitDialog:mi,submitCreateWorkspaceBranch:pi,syncWorkspaceLocally:Os,subagentDelegationDefaultMode:Za,subagentDelegationMode:Ns,subagentDelegationAvailable:fi,changeSubagentDelegationMode:hi,answerCreateImproveQuestion:gi,applyCreateImproveCandidate:ta,approveCreateImproveRun:Ds,cancelCreateImproveRun:Tr,changeDraftProvider:yo,openCreateImprovePullRequest:Vn,reconcileCreateImprovePullRequest:Ls,rejectCreateImproveCandidate:Us,pauseCreateImproveRun:bn,resumeCreateImproveRun:nr,reviseCreateImproveRun:pa,sendPrompt:Ma,stopTurn:Er,archiveSession:ar,restoreSession:Hs,renameSession:vi,toggleProjectPinned:Mr,toggleSessionPinned:So,toggleSessionSavedForLater:or,moveProjectToCloud:bi,startCloudSetupUpload:yi,changeWorkspaceTarget:fa,switchProjectWorkspaceTarget:ha,sendPromptFromMainComposer:Si,openSandboxWorkspace:jr,createCloudEnvironmentFromSidebar:Ja,openCloudProjectDialog:Or,openUrlInBrowserPanel:xo,showBrowserPanel:xi,showChangesPanel:ki,showGoalSidebarTab:wi,rightChatTrainingLaunchRequest:qs,setRightChatTrainingLaunchRequest:ir,closeRightChatPanel:Ya,openRightChatPanel:Bs,rightChatPanelViews:Fs,showRightChatPanel:Vs,showRightPanelDiffTab:Ks,submitRightChatPrompt:Qa,activateRightChatPanel:$r,updateRightChatModel:Ri,updateRightChatPrompt:Ws,updateRightChatProvider:Gs,updateRightChatScrollState:Zs,openProfileSettings:na,diagnosticEvents:Pi,toggleRightSidebar:Js}}const CY=aP();function RY(){return k.jsx(yR,{client:CY,children:k.jsx(PY,{})})}function PY(){const e=XZ(),t=_Y(e);return k.jsx(k9,{primary:e,secondary:t})}const qX=Object.freeze(Object.defineProperty({__proto__:null,App:RY},Symbol.toStringTag,{value:"Module"}));export{lX as $,t5 as A,Yy as B,Ko as C,N3 as D,jQ as E,YI as F,a_ as G,ql as H,Wd as I,d6 as J,i3 as K,MS as L,Vr as M,Fv as N,TV as O,w3 as P,Dn as Q,MX as R,Qy as S,dC as T,dX as U,DX as V,_r as W,mc as X,$X as Y,dh as Z,DQ as _,a0 as a,gh as a$,U9 as a0,zX as a1,PJ as a2,sX as a3,cX as a4,IX as a5,vX as a6,vK as a7,Na as a8,DK as a9,Eo as aA,xC as aB,YQ as aC,d9 as aD,V7 as aE,JQ as aF,r9 as aG,wX as aH,F7 as aI,ba as aJ,po as aK,lR as aL,iY as aM,sY as aN,aJ as aO,QQ as aP,r6 as aQ,cv as aR,GI as aS,Uu as aT,pX as aU,xv as aV,X3 as aW,TQ as aX,y0 as aY,t_ as aZ,mK as a_,qi as aa,dS as ab,gX as ac,RS as ad,Ah as ae,hd as af,o3 as ag,mX as ah,eh as ai,uh as aj,lK as ak,IC as al,V5 as am,Hu as an,u3 as ao,R3 as ap,XI as aq,XY as ar,fX as as,hX as at,EX as au,G5 as av,c3 as aw,Fp as ax,q as ay,Ht as az,aG as b,FQ as b$,T9 as b0,LX as b1,w9 as b2,R0 as b3,Fu as b4,pK as b5,Dv as b6,v_ as b7,J5 as b8,OQ as b9,UX as bA,Ju as bB,h3 as bC,cu as bD,dv as bE,ZI as bF,uc as bG,eX as bH,rX as bI,iX as bJ,A0 as bK,nX as bL,af as bM,oX as bN,aX as bO,tX as bP,P0 as bQ,XQ as bR,Tt as bS,FO as bT,QY as bU,lC as bV,eQ as bW,CQ as bX,Dp as bY,YY as bZ,BQ as b_,$Q as ba,cj as bb,c9 as bc,l9 as bd,QI as be,p3 as bf,Fh as bg,NQ as bh,LQ as bi,_3 as bj,JI as bk,JY as bl,eg as bm,EQ as bn,zu as bo,uv as bp,Qt as bq,$3 as br,wC as bs,Jn as bt,ZY as bu,Wh as bv,Gh as bw,Zc as bx,GY as by,P5 as bz,dt as c,Iu as c$,VQ as c0,KQ as c1,e6 as c2,zQ as c3,qQ as c4,LR as c5,MY as c6,EY as c7,tP as c8,jY as c9,CL as cA,Dt as cB,Yw as cC,ZL as cD,Jw as cE,ML as cF,Kw as cG,RL as cH,$L as cI,qL as cJ,UL as cK,Z as cL,A as cM,Ww as cN,lQ as cO,sQ as cP,aQ as cQ,nQ as cR,PL as cS,EL as cT,Vw as cU,WL as cV,KL as cW,BL as cX,Zw as cY,jg as cZ,Gw as c_,Ix as ca,Mg as cb,iQ as cc,Wo as cd,NL as ce,Ow as cf,oQ as cg,Xt as ch,c as ci,ku as cj,wu as ck,xt as cl,p as cm,Ft as cn,r as co,xu as cp,S as cq,Oe as cr,J as cs,T as ct,u as cu,b as cv,FL as cw,It as cx,rc as cy,wL as cz,x7 as d,xX as d$,_u as d0,GL as d1,LL as d2,Go as d3,Bh as d4,In as d5,iH as d6,rH as d7,yu as d8,e_ as d9,hQ as dA,yQ as dB,bQ as dC,vQ as dD,SX as dE,dQ as dF,i1 as dG,si as dH,_H as dI,SU as dJ,gQ as dK,v4 as dL,dc as dM,SQ as dN,wQ as dO,kQ as dP,xQ as dQ,t4 as dR,m1 as dS,H3 as dT,rs as dU,za as dV,W3 as dW,RQ as dX,pQ as dY,fQ as dZ,qu as d_,zU as da,tQ as db,Jr as dc,Do as dd,xx as de,Nd as df,re as dg,ce as dh,r1 as di,yL as dj,uQ as dk,Je as dl,Fe as dm,PQ as dn,mQ as dp,bX as dq,yX as dr,rQ as ds,ZQ as dt,mv as du,Ua as dv,cQ as dw,rU as dx,Gg as dy,wq as dz,nP as e,kX as e0,GQ as e1,L5 as e2,CS as e3,nJ as e4,hh as e5,nC as e6,U_ as e7,tC as e8,HX as e9,RX as ea,_X as eb,CX as ec,gZ as ed,wY as ee,PX as ef,AX as eg,TX as eh,Xy as ei,I_ as ej,UQ as ek,Fl as el,IQ as em,_Q as en,HQ as eo,AQ as ep,qX as eq,ti as f,M5 as g,Po as h,Lu as i,u6 as j,uX as k,WQ as l,lv as m,vJ as n,jX as o,NX as p,rR as q,h_ as r,s5 as s,OX as t,NS as u,fc as v,Q as w,hc as x,m6 as y,MQ as z};
|