openpond 0.2.32 → 0.2.34
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 +14 -0
- package/dist/app-server.js +1 -1
- package/dist/chunks/{app-layer-ZZHTHTJU.js → app-layer-HK2GTSRX.js} +1 -1
- package/dist/chunks/app-server-runtime-QI2PKYDK.js +2 -0
- package/dist/chunks/{apps-C2BMJ7DO.js → apps-YJRRLX2N.js} +1 -1
- package/dist/chunks/{chunk-MVAJMRCW.js → chunk-77BXXOHW.js} +4 -4
- package/dist/chunks/{chunk-T22TCCWW.js → chunk-BOQBDCVU.js} +1 -1
- package/dist/chunks/{chunk-2OQ6LFSG.js → chunk-C472WX3L.js} +1 -1
- package/dist/chunks/chunk-CC7BNJCF.js +15 -0
- package/dist/chunks/chunk-CWW2EK77.js +4 -0
- package/dist/chunks/{chunk-JFR34MIK.js → chunk-E4U7LXSW.js} +2 -2
- package/dist/chunks/{chunk-QTEYV4TW.js → chunk-JFSDNQHW.js} +7 -7
- package/dist/chunks/{chunk-PZXZYP6Z.js → chunk-MLBXB6IG.js} +176 -176
- package/dist/chunks/{chunk-UU7RXSJS.js → chunk-PZ2ZILPN.js} +1 -1
- package/dist/chunks/{chunk-55UCBRIX.js → chunk-QWENRTVW.js} +4 -4
- package/dist/chunks/{chunk-JVIHGSOV.js → chunk-SRQVXHSM.js} +1 -1
- package/dist/chunks/chunk-TBX3Z7TX.js +2 -0
- package/dist/chunks/chunk-UOPUBKJ4.js +2406 -0
- package/dist/chunks/chunk-UYBZNV72.js +42 -0
- package/dist/chunks/{chunk-7FX5ABXG.js → chunk-WJD5NVVH.js} +1 -1
- package/dist/chunks/cli-CJGAH3AL.js +2 -0
- package/dist/chunks/{configuration-command-IHUB6BBM.js → configuration-command-CYUWO6CD.js} +1 -1
- package/dist/chunks/{core-commands-F2HIN7V4.js → core-commands-Z5C7S6OH.js} +1 -1
- package/dist/chunks/{desktop-test-BFFUGVRS.js → desktop-test-JBZCCTSN.js} +1 -1
- package/dist/chunks/{extension-D7IYZW7H.js → extension-RMJAXEKN.js} +1 -1
- package/dist/chunks/{help-5MKQV36D.js → help-QDMTLEIL.js} +1 -1
- package/dist/chunks/hosted-profile-compiler-WJWQQFBN.js +3 -0
- package/dist/chunks/{opchat-XO7EDHY7.js → opchat-MHH4C5YQ.js} +1 -1
- package/dist/chunks/{organizations-DIRGTVK5.js → organizations-5KM2JD32.js} +1 -1
- package/dist/chunks/{profile-EMVJ5DJQ.js → profile-KVDJTM4D.js} +1 -1
- package/dist/chunks/{project-agent-4QC7N3MB.js → project-agent-SXUMNJLZ.js} +1 -1
- package/dist/chunks/{sandbox-command-L263BBOL.js → sandbox-command-FQGX5MSS.js} +1 -1
- package/dist/chunks/{sandbox-template-RYKWTBW7.js → sandbox-template-Q6K5JXA3.js} +1 -1
- package/dist/chunks/{src-RINMQ7IQ.js → src-42VXY5DZ.js} +1 -1
- package/dist/chunks/{src-Q4W4NIPB.js → src-ZJQAFIKJ.js} +111 -111
- package/dist/chunks/{teams-bot-NIZB6DOY.js → teams-bot-7TPB34DR.js} +1 -1
- package/dist/chunks/{workspaces-PFLMSDBR.js → workspaces-O575SJO4.js} +1 -1
- package/dist/cli.js +2 -2
- package/dist/web/assets/App-BKY1b22z.js +226 -0
- package/dist/web/assets/{AppDialog-C1cvE0gH.js → AppDialog-C64bP66E.js} +1 -1
- package/dist/web/assets/{AppTerminalPanel-BFJNR2ik.js → AppTerminalPanel-fVkWSvWK.js} +2 -2
- package/dist/web/assets/{AppsView-CReOofAf.js → AppsView-DHnab11q.js} +1 -1
- package/dist/web/assets/{BrowserSidebar-CPxAck2O.js → BrowserSidebar-C7YeQ9KS.js} +1 -1
- package/dist/web/assets/{CartesianChart-SlZ8Qfkg.js → CartesianChart-CYX3IXBM.js} +1 -1
- package/dist/web/assets/{CollaborationTabs-DgFEunqQ.js → CollaborationTabs-j2oBkesr.js} +1 -1
- package/dist/web/assets/{CommandMenu-BiROlSdv.js → CommandMenu-BN1a4dTn.js} +1 -1
- package/dist/web/assets/{CommunityView-DVST_ZxO.js → CommunityView-CNoxP71Z.js} +1 -1
- package/dist/web/assets/{ComposerCreateImproveStrip-jRBhdiFB.js → ComposerCreateImproveStrip-IoK3lqK8.js} +1 -1
- package/dist/web/assets/{GetStartedView-Ck4EW1_s.js → GetStartedView-QPabIxZC.js} +1 -1
- package/dist/web/assets/HostedModelLearningReview-CNd3-FrC.js +1 -0
- package/dist/web/assets/{HostedModelLearningSettings-BD7quEFA.js → HostedModelLearningSettings-TkSSxw8x.js} +1 -1
- package/dist/web/assets/{LabModelVersionDetailPage-8-Gb5AAH.js → LabModelVersionDetailPage-CRFw6V7e.js} +1 -1
- package/dist/web/assets/{LabSkillSidebar-DO-kFl9Z.js → LabSkillSidebar-Dl8KWUe0.js} +1 -1
- package/dist/web/assets/{LabsRoute-Dc9RQKdA.js → LabsRoute-BzdL7mUM.js} +4 -4
- package/dist/web/assets/{MainChatThread-DZXcFgmJ.js → MainChatThread-C3IdxbN3.js} +2 -2
- package/dist/web/assets/{MainPane-BYrnuI30.js → MainPane-BdR1K59_.js} +4 -4
- package/dist/web/assets/{MarkdownText-ueZFkEyk.js → MarkdownText-CkLxqh2M.js} +1 -1
- package/dist/web/assets/{NativeSkillSidebar-DlAX2-dH.js → NativeSkillSidebar-VkWpZX6S.js} +1 -1
- package/dist/web/assets/{NewExperienceSwitcher-BHYLG0IZ.js → NewExperienceSwitcher-D_K16Ho-.js} +1 -1
- package/dist/web/assets/{NewProjectDialog-BwN6SnxR.js → NewProjectDialog-B6E1wWOM.js} +1 -1
- package/dist/web/assets/{OutputsPage-Q0kpdfq_.js → OutputsPage-27MuutGA.js} +1 -1
- package/dist/web/assets/{ProjectsPage-TnlBYfFy.js → ProjectsPage-CokpZHgx.js} +1 -1
- package/dist/web/assets/{RightChatPanelStack-D2qZ-1nK.js → RightChatPanelStack-B6JhJdlc.js} +1 -1
- package/dist/web/assets/{RightSidebarHomePanel-q6FF-DR9.js → RightSidebarHomePanel-nn0dqUF0.js} +1 -1
- package/dist/web/assets/{ScheduledWorkPage-BTX3Sjoa.js → ScheduledWorkPage-idJ8AO15.js} +1 -1
- package/dist/web/assets/{SettingsView-gAhNO4Rg.js → SettingsView-ZH2gDC6E.js} +3 -3
- package/dist/web/assets/{TeamChatView-DZtfZ12z.js → TeamChatView-B5cG9M6w.js} +1 -1
- package/dist/web/assets/{TerminalOverlay-MJqx0xg6.js → TerminalOverlay-9SPRce9W.js} +1 -1
- package/dist/web/assets/{TrainingCreationPanel-ORoKcc3m.js → TrainingCreationPanel-2dkxe7py.js} +1 -1
- package/dist/web/assets/{TrainingDraftPanel-oolNVDIx.js → TrainingDraftPanel-oYbOFapi.js} +1 -1
- package/dist/web/assets/{UsageSettingsSection-Lh_fLOcC.js → UsageSettingsSection-zWs4Z_9b.js} +1 -1
- package/dist/web/assets/{WorkSidebarPanel-BIqP9SXr.js → WorkSidebarPanel-CiBQztz6.js} +1 -1
- package/dist/web/assets/{WorkspaceDiffPanel-B0Zwyx9a.js → WorkspaceDiffPanel-BPt29A2a.js} +3 -3
- package/dist/web/assets/{WorkspaceEnvironmentMenu-BpgvG43X.js → WorkspaceEnvironmentMenu-pb6fs4-2.js} +1 -1
- package/dist/web/assets/{WorkspaceGitDialogs-Bw5ADFuc.js → WorkspaceGitDialogs-DHD-L4Vs.js} +1 -1
- package/dist/web/assets/{WorkspaceMonacoEditor-BpivuGzo.js → WorkspaceMonacoEditor-BxtCNaRo.js} +3 -3
- package/dist/web/assets/{arrow-up-right-BjC4ygxR.js → arrow-up-right-DcP3EZaY.js} +1 -1
- package/dist/web/assets/{clipboard-BOJ-sNJz.js → clipboard-BXulVWTJ.js} +1 -1
- package/dist/web/assets/{cloud-upload-D-_3UWhI.js → cloud-upload-B3hP6o0H.js} +1 -1
- package/dist/web/assets/{cssMode-CnHRib-_.js → cssMode-c85YG3Pd.js} +1 -1
- package/dist/web/assets/{folder-open-CO3Vz0rT.js → folder-open-CtOXE4jL.js} +1 -1
- package/dist/web/assets/{folder-plus-CL6B10XJ.js → folder-plus-KO96VZiR.js} +1 -1
- package/dist/web/assets/{git-commit-horizontal-C_SNHoOD.js → git-commit-horizontal-Bhtev2bN.js} +1 -1
- package/dist/web/assets/{htmlMode-DBpIV7Gx.js → htmlMode-BbCawv2y.js} +1 -1
- package/dist/web/assets/{index-Dx0lr1R3.js → index-Hynq87d2.js} +2 -2
- package/dist/web/assets/{info-C1C3X2vW.js → info-Dqf1UVHA.js} +1 -1
- package/dist/web/assets/{jsonMode-B9puI-La.js → jsonMode-CFycP8DE.js} +1 -1
- package/dist/web/assets/{lspLanguageFeatures-DwPRvLkn.js → lspLanguageFeatures-CYX4VXe2.js} +1 -1
- package/dist/web/assets/{minimize-2-Cr76Lc_J.js → minimize-2-BCmNskf_.js} +1 -1
- package/dist/web/assets/{monaco.contribution-DKa3PSXH.js → monaco.contribution-3ZJbmsu3.js} +2 -2
- package/dist/web/assets/{monaco.contribution-OemObo_b.js → monaco.contribution-CJYgsAyM.js} +2 -2
- package/dist/web/assets/{monaco.contribution-CnlZLXhW.js → monaco.contribution-CPkt_0fd.js} +2 -2
- package/dist/web/assets/{monaco.contribution-DQxsY08y.js → monaco.contribution-DR_TcZx7.js} +2 -2
- package/dist/web/assets/{monitor-CktBkAZk.js → monitor-DWlfguJj.js} +1 -1
- package/dist/web/assets/{python-CVC74_7Q.js → python-rAXzgbqp.js} +1 -1
- package/dist/web/assets/{refresh-cw-JaxiGpHD.js → refresh-cw-BUPgzu5R.js} +1 -1
- package/dist/web/assets/{save-DFm1K29k.js → save-Mb-ECgFZ.js} +1 -1
- package/dist/web/assets/{square-D5fFhDFt.js → square-CxNbsHso.js} +1 -1
- package/dist/web/assets/{toggleHighContrast-D_EkCruq.js → toggleHighContrast-DUvtEJ40.js} +1 -1
- package/dist/web/assets/{tsMode-BczIS4rA.js → tsMode-IPAavolh.js} +1 -1
- package/dist/web/assets/{upload-DvED7nbd.js → upload-Bn6_UQEa.js} +1 -1
- package/dist/web/assets/{useLocalAgentSchedules-DWd5OvYb.js → useLocalAgentSchedules-DAHspLJg.js} +1 -1
- package/dist/web/assets/{useSessionTurnCache-oMoxBcGj.js → useSessionTurnCache-CUiJuUjd.js} +1 -1
- package/dist/web/assets/{wifi-off-BZL-Op_B.js → wifi-off-Bsy0Wjm8.js} +1 -1
- package/dist/web/assets/{workers-DapCJCaQ.js → workers-35o3qFXU.js} +1 -1
- package/dist/web/assets/{yaml-DB9KLqu1.js → yaml-Ba5fmKgb.js} +1 -1
- package/dist/web/index.html +1 -1
- package/package.json +1 -1
- package/dist/chunks/app-server-runtime-C7YELTKS.js +0 -2
- package/dist/chunks/chunk-L54LZUGH.js +0 -2
- package/dist/chunks/chunk-PSZKG3E3.js +0 -4
- package/dist/chunks/chunk-YD2IWF3T.js +0 -2419
- package/dist/chunks/chunk-YW6HS6TZ.js +0 -42
- package/dist/chunks/cli-HGDLR5TC.js +0 -2
- package/dist/web/assets/App-BcbjzSeU.js +0 -226
- package/dist/web/assets/HostedModelLearningReview-DYFjp-96.js +0 -1
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CommandMenu-BN1a4dTn.js","./index-Hynq87d2.js","./index-lqk3IxE0.css","./CommandMenu-Cb3vNGJr.css","./SettingsView-ZH2gDC6E.js","./refresh-cw-BUPgzu5R.js","./save-Mb-ECgFZ.js","./MarkdownText-CkLxqh2M.js","./folder-open-CtOXE4jL.js","./wifi-off-Bsy0Wjm8.js","./useLocalAgentSchedules-DAHspLJg.js","./cloud-upload-B3hP6o0H.js","./git-commit-horizontal-Bhtev2bN.js","./folder-plus-KO96VZiR.js","./AppDialog-C64bP66E.js","./WorkspaceDiffPanel-BPt29A2a.js","./training-model-data-CKOkpBBL.js","./info-Dqf1UVHA.js","./minimize-2-BCmNskf_.js","./clipboard-BXulVWTJ.js","./SettingsView-C7av3zwv.css","./git-dialogs-C-F47S10.css","./NewProjectDialog-B6E1wWOM.js","./monitor-DWlfguJj.js","./WorkspaceGitDialogs-DHD-L4Vs.js","./upload-Bn6_UQEa.js","./WorkspaceEnvironmentMenu-pb6fs4-2.js","./square-CxNbsHso.js","./WorkspaceEnvironmentMenu-DGIFdG3o.css","./MainPane-BdR1K59_.js","./arrow-up-right-DcP3EZaY.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as g,j as x,a as mR,_ as Qr}from"./index-Hynq87d2.js";const jS=g.createContext(void 0),OS=e=>{const t=g.useContext(jS);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},pR=({client:e,children:t})=>(g.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),x.jsx(jS.Provider,{value:e,children:t})),fR={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)};var hR=class{#e=fR;#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 Lr=new hR;function gR(e){setTimeout(e,0)}const vR=typeof window>"u"||"Deno"in globalThis;function Gn(){}function bR(e,t){return typeof e=="function"?e(t):e}function $S(e){return typeof e=="number"&&e>=0&&e!==1/0}function NS(e,t){return Math.max(e+(t||0)-Date.now(),0)}function an(e,t){return typeof e=="function"?e(t):e}function Bv(e,t){const{type:n="all",exact:a,fetchStatus:o,predicate:i,queryKey:s,stale:l}=e;if(s){if(a){if(t.queryHash!==Ph(s,t.options))return!1}else if(!ss(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 Fv(e,t){const{exact:n,status:a,predicate:o,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(El(t.options.mutationKey)!==El(i))return!1}else if(!ss(t.options.mutationKey,i))return!1}return!(a&&t.state.status!==a||o&&!o(t))}function Ph(e,t){return(t?.queryKeyHashFn||El)(e)}function El(e){return JSON.stringify(e,(t,n)=>Sf(n)?Object.keys(n).sort().reduce((a,o)=>(a[o]=n[o],a),{}):n)}function ss(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(!ss(e[a],t[a]))return!1;return!0}const n=Object.keys(t);for(const a of n)if(!ss(e[a],t[a]))return!1;return!0}return!1}const yR=Object.prototype.hasOwnProperty;function DS(e,t,n=0){if(e===t)return e;if(n>500)return t;const a=Vv(e)&&Vv(t);if(!a&&!(Sf(e)&&Sf(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],v=e[h],y=t[h];if(v===y){l[h]=v,(a?d<o:yR.call(e,h))&&m++;continue}if(v===null||y===null||typeof v!="object"||typeof y!="object"){l[h]=y;continue}const w=DS(v,y,n+1);l[h]=w,w===v&&m++}return o===s&&m===o?e:l}function np(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 Vv(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Sf(e){if(!Kv(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!Kv(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Kv(e){return Object.prototype.toString.call(e)==="[object Object]"}function SR(e){return new Promise(t=>{Lr.setTimeout(t,e)})}function xf(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?DS(e,t):t}function xR(e,t,n=0){const a=[...e,t];return n&&a.length>n?a.slice(1):a}function kR(e,t,n=0){const a=[t,...e];return n&&a.length>n?a.slice(0,-1):a}const Ah=Symbol();function LS(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Ah?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function US(e,t){return typeof e=="function"?e(...t):!!e}function wR(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 IR=()=>vR;const Th=()=>IR();var Xl=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(){}},_R=class extends Xl{#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 Eh=new _R,CR=gR;function RR(){let e=[],t=0,n=l=>{l()},a=l=>{l()},o=CR;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 Tn=RR();var PR=class extends Xl{#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 Pd=new PR;function AR(e){return Math.min(1e3*2**e,3e4)}function HS(e){return(e??"online")==="online"?Pd.isOnline():!0}var kf=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function zS(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 kf(N);R($),e.onCancel?.($)}},h=()=>{t=!0},v=()=>{t=!1},y=()=>Eh.isFocused()&&(e.networkMode==="always"||Pd.isOnline())&&e.canRun(),w=()=>HS(e.networkMode)&&e.canRun(),_=N=>{m()||(a?.(),o="resolved",i(N))},R=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 k=e.retry??(Th()?0:3),P=e.retryDelay??AR,T=typeof P=="function"?P(n,j):P,U=k===!0||typeof k=="number"&&n<k||typeof k=="function"&&k(n,j);if(t||!U){R(j);return}n++,e.onFail?.(n,j),SR(T).then(()=>y()?void 0:M()).then(()=>{t?R(j):C()})})};return{promise:l,status:()=>o,cancel:d,continue:()=>(a?.(),l),cancelRetry:h,continueRetry:v,canStart:w,start:()=>(w()?C():M().then(C),l)}}var qS=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),$S(this.gcTime)&&(this.#e=Lr.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Th()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(Lr.clearTimeout(this.#e),this.#e=void 0)}};function TR(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 v=_=>{wR(_,()=>t.signal,()=>h=!0)},y=LS(t.options,t.fetchOptions),w=async(_,R,M)=>{if(h)return Promise.reject(t.signal.reason);if(R==null&&_.pages.length)return Promise.resolve(_);const N=(()=>{const P={client:t.client,queryKey:t.queryKey,pageParam:R,direction:M?"backward":"forward",meta:t.options.meta};return v(P),P})(),$=await y(N),{maxPages:j}=t.options,k=M?kR:xR;return{pages:k(_.pages,$,j),pageParams:k(_.pageParams,R,j)}};if(o&&i.length){const _=o==="backward",R=_?ER:Wv,M={pages:i,pageParams:s};l=await w(M,R(a,M),_)}else{const _=e??i.length;do{const R=m===0?s[0]??a.initialPageParam:Wv(a,l);if(m>0&&R==null)break;l=await w(l,R),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 Wv(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 ER(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var MR=class extends qS{#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=Zv(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=Zv(this.options);t.data!==void 0&&(this.setState(Gv(t.data,t.dataUpdatedAt)),this.#t=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#a.remove(this)}setData(e,t){const n=xf(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=>an(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Ah||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>an(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:!NS(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=LS(this.options,t),h=(()=>{const v={client:this.#r,queryKey:this.queryKey,meta:this.meta};return a(v),v})();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"?TR(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=zS({initialPromise:t?.initialPromise,fn:s.fetchFn,onCancel:m=>{m instanceof kf&&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 kf){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,...BS(n.data,this.options),fetchMeta:e.meta??null};case"success":const a={...n,...Gv(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),Tn.batch(()=>{this.observers.slice().forEach(n=>{n.onQueryUpdate()}),this.#a.notify({query:this,type:"updated",action:e})})}};function BS(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:HS(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Gv(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Zv(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 jR=class extends Xl{#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),Jv(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return wf(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return wf(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 an(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&&!np(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const a=this.hasListeners();a&&Yv(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),a&&(this.#t!==n||an(this.options.enabled,this.#t)!==an(t.enabled,this.#t)||an(this.options.staleTime,this.#t)!==an(t.staleTime,this.#t))&&this.#g();const o=this.#v();a&&(this.#t!==n||an(this.options.enabled,this.#t)!==an(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 np(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!Th()&&an(this.options.enabled,this.#t)!==!1&&$S(e)}#g(){this.#S();const e=an(this.options.staleTime,this.#t);if(this.#a.isStale||!this.#h(e))return;const t=NS(this.#a.dataUpdatedAt,e)+1;this.#d=Lr.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=Lr.setInterval(()=>{(this.options.refetchIntervalInBackground||Eh.isFocused())&&this.#m()},this.#c))}#y(){this.#g(),this.#b(this.#v())}#S(){this.#d!==void 0&&(Lr.clearTimeout(this.#d),this.#d=void 0)}#x(){this.#u!==void 0&&(Lr.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,v;if(t._optimisticResults){const k=this.hasListeners(),P=!k&&Jv(e,t),T=k&&Yv(e,n,t,a);(P||T)&&(d={...d,...BS(m.data,e.options)}),t._optimisticResults==="isRestoring"&&(d.fetchStatus="idle")}let{error:y,errorUpdatedAt:w,status:_}=d;v=d.data;let R=!1;if(t.placeholderData!==void 0&&v===void 0&&_==="pending"){let k;o?.isPlaceholderData&&t.placeholderData===s?.placeholderData?(k=o.data,R=!0):k=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,k!==void 0&&(_="success",v=xf(o?.data,k,t),h=!0)}if(t.select&&v!==void 0&&!R)if(o&&v===i?.data&&t.select===this.#l)v=this.#s;else try{this.#l=t.select,v=t.select(v),v=xf(o?.data,v,t),this.#s=v,this.#i=null}catch(k){this.#i=k}else v===void 0&&(this.#i=null);this.#i&&(y=this.#i,v=this.#s,w=Date.now(),_="error",h=!1);const M=d.fetchStatus==="fetching",C=_==="pending",N=_==="error",$=C&&M,j=v!==void 0;return{status:_,fetchStatus:d.fetchStatus,isPending:C,isSuccess:_==="success",isError:N,isInitialLoading:$,isLoading:$,data:v,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:Mh(e,t),refetch:this.refetch,isEnabled:an(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),np(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)})})();Tn.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 OR(e,t){return an(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&an(t.retryOnMount,e)===!1)}function Jv(e,t){return OR(e,t)||e.state.data!==void 0&&wf(e,t,t.refetchOnMount)}function wf(e,t,n){if(an(t.enabled,e)!==!1&&an(t.staleTime,e)!=="static"){const a=typeof n=="function"?n(e):n;return a==="always"||a!==!1&&Mh(e,t)}return!1}function Yv(e,t,n,a){return(e!==t||an(a.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Mh(e,n)}function Mh(e,t){return an(t.enabled,e)!==!1&&e.isStaleByTime(an(t.staleTime,e))}var $R=class extends qS{#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||NR(),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=zS({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),Tn.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:"updated",action:e})})}};function NR(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var DR=class extends Xl{#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 $R({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=zc(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=zc(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=zc(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=zc(e);return typeof t=="string"?this.#t.get(t)?.find(n=>n!==e&&n.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){Tn.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=>Fv(t,n))}findAll(e={}){return this.getAll().filter(t=>Fv(e,t))}notify(e){Tn.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return Tn.batch(()=>Promise.all(e.map(t=>t.continue().catch(Gn))))}};function zc(e){return e.options.scope?.id}var LR=class extends Xl{#e;constructor(e={}){super(),this.config=e,this.#e=new Map}build(e,t,n){const a=t.queryKey,o=t.queryHash??Ph(a,t);let i=this.get(o);return i||(i=new MR({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(){Tn.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=>Bv(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>Bv(e,n)):t}notify(e){Tn.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){Tn.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Tn.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},UR=class{#e;#t;#n;#a;#r;#o;#i;#l;constructor(e={}){this.#e=e.queryCache||new LR,this.#t=e.mutationCache||new DR,this.#n=e.defaultOptions||{},this.#a=new Map,this.#r=new Map,this.#o=0}mount(){this.#o++,this.#o===1&&(this.#i=Eh.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#l=Pd.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(an(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=bR(t,o);if(i!==void 0)return this.#e.build(this,a).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return Tn.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;Tn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return Tn.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=Tn.batch(()=>this.#e.findAll(e).map(o=>o.cancel(n)));return Promise.all(a).then(Gn).catch(Gn)}invalidateQueries(e,t={}){return Tn.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=Tn.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(an(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(an(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 Pd.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(El(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#a.values()],n={};return t.forEach(a=>{ss(e,a.queryKey)&&Object.assign(n,a.defaultOptions)}),n}setMutationDefaults(e,t){this.#r.set(El(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#r.values()],n={};return t.forEach(a=>{ss(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=Ph(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===Ah&&(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 FS=g.createContext(!1),HR=()=>g.useContext(FS);FS.Provider;function zR(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}const qR=g.createContext(zR()),BR=()=>g.useContext(qR),FR=(e,t,n)=>{const a=n?.state.error&&typeof e.throwOnError=="function"?US(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||a)&&(t.isReset()||(e.retryOnMount=!1))},VR=e=>{g.useEffect(()=>{e.clearReset()},[e])},KR=({result:e,errorResetBoundary:t,throwOnError:n,query:a,suspense:o})=>e.isError&&!t.isReset()&&!e.isFetching&&a&&(o&&e.data===void 0||US(n,[e.error,a])),WR=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))}},GR=(e,t)=>e?.suspense&&t.isPending,ZR=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function JR(e,t,n){const a=HR(),o=BR(),i=OS(),s=i.defaultQueryOptions(e),l=i.getQueryCache().get(s.queryHash),m=e.subscribed!==!1;s._optimisticResults=a?"isRestoring":m?"optimistic":void 0,WR(s),FR(s,o,l),VR(o);const[d]=g.useState(()=>new t(i,s)),h=d.getOptimisticResult(s),v=!a&&m;if(g.useSyncExternalStore(g.useCallback(y=>{const w=v?d.subscribe(Tn.batchCalls(y)):Gn;return d.updateResult(),w},[d,v]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),g.useEffect(()=>{d.setOptions(s)},[s,d]),GR(s,h))throw ZR(s,d,o);if(KR({result:h,errorResetBoundary:o,throwOnError:s.throwOnError,query:l,suspense:s.suspense}))throw h.error;return s.notifyOnChangeProps?h:d.trackResult(h)}function YR(e,t){return JR(e,jR)}function QR(){return new UR({defaultOptions:{queries:{staleTime:6e4,gcTime:15*6e4,retry:1,refetchOnWindowFocus:!1}}})}var Qv;function he(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 v=0;v<h.length;v++){const y=h[v];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 ts extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class VS extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(Qv=globalThis).__zod_globalConfig??(Qv.__zod_globalConfig={});const jh=globalThis.__zod_globalConfig;function Vo(e){return jh}function KS(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 If(e,t){return typeof t=="bigint"?t.toString():t}function au(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Oh(e){return e==null}function $h(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function XR(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 Xv=Symbol("evaluating");function _t(e,t,n){let a;Object.defineProperty(e,t,{get(){if(a!==Xv)return a===void 0&&(a=Xv,a=n()),a},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function Xr(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function hr(...e){const t={};for(const n of e){const a=Object.getOwnPropertyDescriptors(n);Object.assign(t,a)}return Object.defineProperties({},t)}function eb(e){return JSON.stringify(e)}function eP(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const WS="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Ml(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const tP=au(()=>{if(jh.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function ls(e){if(Ml(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Ml(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function GS(e){return ls(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const nP=new Set(["string","number","symbol"]);function cs(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function gr(e,t,n){const a=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(a._zod.parent=e),a}function tt(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function aP(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const oP={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 rP(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=hr(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 Xr(this,"shape",s),s},checks:[]});return gr(e,i)}function iP(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=hr(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 Xr(this,"shape",s),s},checks:[]});return gr(e,i)}function sP(e,t){if(!ls(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=hr(e._zod.def,{get shape(){const i={...e._zod.def.shape,...t};return Xr(this,"shape",i),i}});return gr(e,o)}function lP(e,t){if(!ls(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=hr(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t};return Xr(this,"shape",a),a}});return gr(e,n)}function cP(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=hr(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t._zod.def.shape};return Xr(this,"shape",a),a},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return gr(e,n)}function dP(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=hr(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 Xr(this,"shape",m),m},checks:[]});return gr(t,s)}function uP(e,t,n){const a=hr(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 Xr(this,"shape",i),i}});return gr(t,a)}function qi(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 mP(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 Bi(e,t){return t.map(n=>{var a;return(a=n).path??(a.path=[]),n.path.unshift(e),n})}function qc(e){return typeof e=="string"?e:e?.message}function Ko(e,t,n){const a=e.message?e.message:qc(e.inst?._zod.def?.error?.(e))??qc(t?.error?.(e))??qc(n.customError?.(e))??qc(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 Nh(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function jl(...e){const[t,n,a]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:a}:{...t}}const ZS=(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,If,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},JS=he("$ZodError",ZS),YS=he("$ZodError",ZS,{Parent:Error});function pP(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 fP(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 Dh=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 ts;if(s.issues.length){const l=new(o?.Err??e)(s.issues.map(m=>Ko(m,i,Vo())));throw WS(l,o?.callee),l}return s.value},Lh=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=>Ko(m,i,Vo())));throw WS(l,o?.callee),l}return s.value},ou=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 ts;return i.issues.length?{success:!1,error:new(e??JS)(i.issues.map(s=>Ko(s,o,Vo())))}:{success:!0,data:i.value}},hP=ou(YS),ru=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=>Ko(s,o,Vo())))}:{success:!0,data:i.value}},gP=ru(YS),vP=e=>(t,n,a)=>{const o=a?{...a,direction:"backward"}:{direction:"backward"};return Dh(e)(t,n,o)},bP=e=>(t,n,a)=>Dh(e)(t,n,a),yP=e=>async(t,n,a)=>{const o=a?{...a,direction:"backward"}:{direction:"backward"};return Lh(e)(t,n,o)},SP=e=>async(t,n,a)=>Lh(e)(t,n,a),xP=e=>(t,n,a)=>{const o=a?{...a,direction:"backward"}:{direction:"backward"};return ou(e)(t,n,o)},kP=e=>(t,n,a)=>ou(e)(t,n,a),wP=e=>async(t,n,a)=>{const o=a?{...a,direction:"backward"}:{direction:"backward"};return ru(e)(t,n,o)},IP=e=>async(t,n,a)=>ru(e)(t,n,a),_P=/^[cC][0-9a-z]{6,}$/,CP=/^[0-9a-z]+$/,RP=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,PP=/^[0-9a-vA-V]{20}$/,AP=/^[A-Za-z0-9]{27}$/,TP=/^[a-zA-Z0-9_-]{21}$/,EP=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,MP=/^([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})$/,tb=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)$/,jP=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,OP="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function $P(){return new RegExp(OP,"u")}const NP=/^(?:(?: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])$/,DP=/^(([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}|:))$/,LP=/^((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])$/,UP=/^(([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])$/,HP=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,QS=/^[A-Za-z0-9_-]*$/,zP=/^https?$/,qP=/^\+[1-9]\d{6,14}$/,XS="(?:(?:\\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])))",BP=new RegExp(`^${XS}$`);function ex(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 FP(e){return new RegExp(`^${ex(e)}$`)}function VP(e){const t=ex({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(`^${XS}T(?:${a})$`)}const KP=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},WP=/^-?\d+$/,tx=/^-?\d+(?:\.\d+)?$/,GP=/^(?:true|false)$/i,ZP=/^null$/i,JP=/^[^A-Z]*$/,YP=/^[^a-z]*$/,Xn=he("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),nx={number:"number",bigint:"bigint",object:"date"},ax=he("$ZodCheckLessThan",(e,t)=>{Xn.init(e,t);const n=nx[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})}}),ox=he("$ZodCheckGreaterThan",(e,t)=>{Xn.init(e,t);const n=nx[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})}}),QP=he("$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):XR(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})}}),XP=he("$ZodCheckNumberFormat",(e,t)=>{Xn.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),a=n?"int":"number",[o,i]=oP[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=WP)}),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})}}),eA=he("$ZodCheckMaxLength",(e,t)=>{var n;Xn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const o=a.value;return!Oh(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=Nh(o);a.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),tA=he("$ZodCheckMinLength",(e,t)=>{var n;Xn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const o=a.value;return!Oh(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=Nh(o);a.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),nA=he("$ZodCheckLengthEquals",(e,t)=>{var n;Xn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const o=a.value;return!Oh(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=Nh(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})}}),iu=he("$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=()=>{})}),aA=he("$ZodCheckRegex",(e,t)=>{iu.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})}}),oA=he("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=JP),iu.init(e,t)}),rA=he("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=YP),iu.init(e,t)}),iA=he("$ZodCheckIncludes",(e,t)=>{Xn.init(e,t);const n=cs(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})}}),sA=he("$ZodCheckStartsWith",(e,t)=>{Xn.init(e,t);const n=new RegExp(`^${cs(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})}}),lA=he("$ZodCheckEndsWith",(e,t)=>{Xn.init(e,t);const n=new RegExp(`.*${cs(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})}}),cA=he("$ZodCheckOverwrite",(e,t)=>{Xn.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class dA{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 uA={major:4,minor:4,patch:3},Vt=he("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=uA;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=qi(s),h;for(const v of l){if(v._zod.def.when){if(mP(s)||!v._zod.def.when(s))continue}else if(d)continue;const y=s.issues.length,w=v._zod.check(s);if(w instanceof Promise&&m?.async===!1)throw new ts;if(h||w instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await w,s.issues.length!==y&&(d||(d=qi(s,y)))});else{if(s.issues.length===y)continue;d||(d=qi(s,y))}}return h?h.then(()=>s):s},i=(s,l,m)=>{if(qi(s))return s.aborted=!0,s;const d=o(l,a,m);if(d instanceof Promise){if(m.async===!1)throw new ts;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 ts;return m.then(d=>o(d,a,l))}return o(m,a,l)}}_t(e,"~standard",()=>({validate:o=>{try{const i=hP(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return gP(e,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),Uh=he("$ZodString",(e,t)=>{Vt.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??KP(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=he("$ZodStringFormat",(e,t)=>{iu.init(e,t),Uh.init(e,t)}),mA=he("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=MP),Yt.init(e,t)}),pA=he("$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=tb(a))}else t.pattern??(t.pattern=tb());Yt.init(e,t)}),fA=he("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=jP),Yt.init(e,t)}),hA=he("$ZodURL",(e,t)=>{Yt.init(e,t),e._zod.check=n=>{try{const a=n.value.trim();if(!t.normalize&&t.protocol?.source===zP.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})}}}),gA=he("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=$P()),Yt.init(e,t)}),vA=he("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=TP),Yt.init(e,t)}),bA=he("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=_P),Yt.init(e,t)}),yA=he("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=CP),Yt.init(e,t)}),SA=he("$ZodULID",(e,t)=>{t.pattern??(t.pattern=RP),Yt.init(e,t)}),xA=he("$ZodXID",(e,t)=>{t.pattern??(t.pattern=PP),Yt.init(e,t)}),kA=he("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=AP),Yt.init(e,t)}),wA=he("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=VP(t)),Yt.init(e,t)}),IA=he("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=BP),Yt.init(e,t)}),_A=he("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=FP(t)),Yt.init(e,t)}),CA=he("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=EP),Yt.init(e,t)}),RA=he("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=NP),Yt.init(e,t),e._zod.bag.format="ipv4"}),PA=he("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=DP),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})}}}),AA=he("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=LP),Yt.init(e,t)}),TA=he("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=UP),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 rx(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const EA=he("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=HP),Yt.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{rx(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function MA(e){if(!QS.test(e))return!1;const t=e.replace(/[-_]/g,a=>a==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return rx(n)}const jA=he("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=QS),Yt.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{MA(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),OA=he("$ZodE164",(e,t)=>{t.pattern??(t.pattern=qP),Yt.init(e,t)});function $A(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 NA=he("$ZodJWT",(e,t)=>{Yt.init(e,t),e._zod.check=n=>{$A(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),ix=he("$ZodNumber",(e,t)=>{Vt.init(e,t),e._zod.pattern=e._zod.bag.pattern??tx,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}}),DA=he("$ZodNumberFormat",(e,t)=>{XP.init(e,t),ix.init(e,t)}),LA=he("$ZodBoolean",(e,t)=>{Vt.init(e,t),e._zod.pattern=GP,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}}),UA=he("$ZodNull",(e,t)=>{Vt.init(e,t),e._zod.pattern=ZP,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}}),HA=he("$ZodUnknown",(e,t)=>{Vt.init(e,t),e._zod.parse=n=>n}),zA=he("$ZodNever",(e,t)=>{Vt.init(e,t),e._zod.parse=(n,a)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function nb(e,t,n){e.issues.length&&t.issues.push(...Bi(n,e.issues)),t.value[n]=e.value}const qA=he("$ZodArray",(e,t)=>{Vt.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=>nb(d,n,s))):nb(m,n,s)}return i.length?Promise.all(i).then(()=>n):n}});function Ad(e,t,n,a,o,i){const s=n in a;if(e.issues.length){if(o&&i&&!s)return;t.issues.push(...Bi(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 sx(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=aP(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function lx(e,t,n,a,o,i){const s=[],l=o.keySet,m=o.catchall._zod,d=m.def.type,h=m.optin==="optional",v=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(_=>Ad(_,n,y,t,h,v))):Ad(w,n,y,t,h,v)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i}),e.length?Promise.all(e).then(()=>n):n}const BA=he("$ZodObject",(e,t)=>{if(Vt.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=au(()=>sx(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 v of h.values)m[d].add(v)}}return m});const o=Ml,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=[],v=s.shape;for(const y of s.keys){const w=v[y],_=w._zod.optin==="optional",R=w._zod.optout==="optional",M=w._zod.run({value:d[y],issues:[]},m);M instanceof Promise?h.push(M.then(C=>Ad(C,l,y,d,_,R))):Ad(M,l,y,d,_,R)}return i?lx(h,d,l,m,a.value,e):h.length?Promise.all(h).then(()=>l):l}}),FA=he("$ZodObjectJIT",(e,t)=>{BA.init(e,t);const n=e._zod.parse,a=au(()=>sx(t)),o=y=>{const w=new dA(["shape","payload","ctx"]),_=a.value,R=$=>{const j=eb($);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[$],k=eb($),P=y[$],T=P?._zod?.optin==="optional",U=P?._zod?.optout==="optional";w.write(`const ${j} = ${R($)};`),T&&U?w.write(`
|
|
5
|
+
if (${j}.issues.length) {
|
|
6
|
+
if (${k} in input) {
|
|
7
|
+
payload.issues = payload.issues.concat(${j}.issues.map(iss => ({
|
|
8
|
+
...iss,
|
|
9
|
+
path: iss.path ? [${k}, ...iss.path] : [${k}]
|
|
10
|
+
})));
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
if (${j}.value === undefined) {
|
|
15
|
+
if (${k} in input) {
|
|
16
|
+
newResult[${k}] = undefined;
|
|
17
|
+
}
|
|
18
|
+
} else {
|
|
19
|
+
newResult[${k}] = ${j}.value;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
`):T?w.write(`
|
|
23
|
+
if (${j}.issues.length) {
|
|
24
|
+
payload.issues = payload.issues.concat(${j}.issues.map(iss => ({
|
|
25
|
+
...iss,
|
|
26
|
+
path: iss.path ? [${k}, ...iss.path] : [${k}]
|
|
27
|
+
})));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
if (${j}.value === undefined) {
|
|
31
|
+
if (${k} in input) {
|
|
32
|
+
newResult[${k}] = undefined;
|
|
33
|
+
}
|
|
34
|
+
} else {
|
|
35
|
+
newResult[${k}] = ${j}.value;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
`):w.write(`
|
|
39
|
+
const ${j}_present = ${k} in input;
|
|
40
|
+
if (${j}.issues.length) {
|
|
41
|
+
payload.issues = payload.issues.concat(${j}.issues.map(iss => ({
|
|
42
|
+
...iss,
|
|
43
|
+
path: iss.path ? [${k}, ...iss.path] : [${k}]
|
|
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: [${k}]
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (${j}_present) {
|
|
56
|
+
if (${j}.value === undefined) {
|
|
57
|
+
newResult[${k}] = undefined;
|
|
58
|
+
} else {
|
|
59
|
+
newResult[${k}] = ${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=Ml,l=!jh.jitless,d=l&&tP.value,h=t.catchall;let v;e._zod.parse=(y,w)=>{v??(v=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?lx([],_,y,w,v,e):y):n(y,w):(y.issues.push({expected:"object",code:"invalid_type",input:_,inst:e}),y)}});function ab(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=>!qi(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=>Ko(s,a,Vo())))}),t)}const cx=he("$ZodUnion",(e,t)=>{Vt.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=>$h(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=>ab(l,a,e,o)):ab(s,a,e,o)}}),VA=he("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,cx.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=au(()=>{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(!Ml(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)}}),KA=he("$ZodIntersection",(e,t)=>{Vt.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])=>ob(n,m,d)):ob(n,i,s)}});function _f(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(ls(e)&&ls(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=_f(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=_f(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 ob(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}),qi(e))return e;const s=_f(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 WA=he("$ZodRecord",(e,t)=>{Vt.init(e,t),e._zod.parse=(n,a)=>{const o=n.value;if(!ls(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=>Ko(w,a,Vo())),input:d,path:[d],inst:e});continue}const v=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(...Bi(d,w.issues)),n.value[v]=w.value})):(y.issues.length&&n.issues.push(...Bi(d,y.issues)),n.value[v]=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"&&tx.test(l)&&m.issues.length){const v=t.keyType._zod.run({value:Number(l),issues:[]},a);if(v instanceof Promise)throw new Error("Async schemas not supported in object keys currently");v.issues.length===0&&(m=v)}if(m.issues.length){t.mode==="loose"?n.value[l]=o[l]:n.issues.push({code:"invalid_key",origin:"record",issues:m.issues.map(v=>Ko(v,a,Vo())),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(v=>{v.issues.length&&n.issues.push(...Bi(l,v.issues)),n.value[m.value]=v.value})):(h.issues.length&&n.issues.push(...Bi(l,h.issues)),n.value[m.value]=h.value)}}return i.length?Promise.all(i).then(()=>n):n}}),GA=he("$ZodEnum",(e,t)=>{Vt.init(e,t);const n=KS(t.entries),a=new Set(n);e._zod.values=a,e._zod.pattern=new RegExp(`^(${n.filter(o=>nP.has(typeof o)).map(o=>typeof o=="string"?cs(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}}),ZA=he("$ZodLiteral",(e,t)=>{if(Vt.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"?cs(a):a?cs(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}}),JA=he("$ZodTransform",(e,t)=>{Vt.init(e,t),e._zod.optin="optional",e._zod.parse=(n,a)=>{if(a.direction==="backward")throw new VS(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 ts;return n.value=o,n.fallback=!0,n}});function rb(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const dx=he("$ZodOptional",(e,t)=>{Vt.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(`^(${$h(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=>rb(s,o)):rb(i,o)}return n.value===void 0?n:t.innerType._zod.run(n,a)}}),YA=he("$ZodExactOptional",(e,t)=>{dx.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)}),QA=he("$ZodNullable",(e,t)=>{Vt.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(`^(${$h(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)}),XA=he("$ZodDefault",(e,t)=>{Vt.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=>ib(i,t)):ib(o,t)}});function ib(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const eT=he("$ZodPrefault",(e,t)=>{Vt.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))}),tT=he("$ZodNonOptional",(e,t)=>{Vt.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=>sb(i,e)):sb(o,e)}});function sb(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 nT=he("$ZodCatch",(e,t)=>{Vt.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=>Ko(s,a,Vo()))},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=>Ko(i,a,Vo()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),ux=he("$ZodPipe",(e,t)=>{Vt.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=>Bc(s,t.in,a)):Bc(i,t.in,a)}const o=t.in._zod.run(n,a);return o instanceof Promise?o.then(i=>Bc(i,t.out,a)):Bc(o,t.out,a)}});function Bc(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 aT=he("$ZodPreprocess",(e,t)=>{ux.init(e,t)}),oT=he("$ZodReadonly",(e,t)=>{Vt.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(lb):lb(o)}});function lb(e){return e.value=Object.freeze(e.value),e}const rT=he("$ZodLazy",(e,t)=>{Vt.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)}),iT=he("$ZodCustom",(e,t)=>{Xn.init(e,t),Vt.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=>cb(i,n,a,e));cb(o,n,a,e)}});function cb(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(jl(o))}}var db;class sT{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 lT(){return new sT}(db=globalThis).__zod_globalRegistry??(db.__zod_globalRegistry=lT());const vl=globalThis.__zod_globalRegistry;function cT(e,t){return new e({type:"string",...tt(t)})}function dT(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...tt(t)})}function ub(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...tt(t)})}function uT(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...tt(t)})}function mT(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...tt(t)})}function pT(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...tt(t)})}function fT(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...tt(t)})}function hT(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...tt(t)})}function gT(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...tt(t)})}function vT(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...tt(t)})}function bT(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...tt(t)})}function yT(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...tt(t)})}function ST(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...tt(t)})}function xT(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...tt(t)})}function kT(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...tt(t)})}function wT(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...tt(t)})}function IT(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...tt(t)})}function _T(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...tt(t)})}function CT(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...tt(t)})}function RT(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...tt(t)})}function PT(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...tt(t)})}function AT(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...tt(t)})}function TT(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...tt(t)})}function ET(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...tt(t)})}function MT(e,t){return new e({type:"string",format:"date",check:"string_format",...tt(t)})}function jT(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...tt(t)})}function OT(e,t){return new e({type:"string",format:"duration",check:"string_format",...tt(t)})}function $T(e,t){return new e({type:"number",checks:[],...tt(t)})}function NT(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...tt(t)})}function DT(e,t){return new e({type:"boolean",...tt(t)})}function LT(e,t){return new e({type:"null",...tt(t)})}function UT(e){return new e({type:"unknown"})}function HT(e,t){return new e({type:"never",...tt(t)})}function mb(e,t){return new ax({check:"less_than",...tt(t),value:e,inclusive:!1})}function ap(e,t){return new ax({check:"less_than",...tt(t),value:e,inclusive:!0})}function pb(e,t){return new ox({check:"greater_than",...tt(t),value:e,inclusive:!1})}function op(e,t){return new ox({check:"greater_than",...tt(t),value:e,inclusive:!0})}function fb(e,t){return new QP({check:"multiple_of",...tt(t),value:e})}function mx(e,t){return new eA({check:"max_length",...tt(t),maximum:e})}function Td(e,t){return new tA({check:"min_length",...tt(t),minimum:e})}function px(e,t){return new nA({check:"length_equals",...tt(t),length:e})}function zT(e,t){return new aA({check:"string_format",format:"regex",...tt(t),pattern:e})}function qT(e){return new oA({check:"string_format",format:"lowercase",...tt(e)})}function BT(e){return new rA({check:"string_format",format:"uppercase",...tt(e)})}function FT(e,t){return new iA({check:"string_format",format:"includes",...tt(t),includes:e})}function VT(e,t){return new sA({check:"string_format",format:"starts_with",...tt(t),prefix:e})}function KT(e,t){return new lA({check:"string_format",format:"ends_with",...tt(t),suffix:e})}function ks(e){return new cA({check:"overwrite",tx:e})}function WT(e){return ks(t=>t.normalize(e))}function GT(){return ks(e=>e.trim())}function ZT(){return ks(e=>e.toLowerCase())}function JT(){return ks(e=>e.toUpperCase())}function YT(){return ks(e=>eP(e))}function QT(e,t,n){return new e({type:"array",element:t,...tt(n)})}function XT(e,t,n){const a=tt(n);return a.abort??(a.abort=!0),new e({type:"custom",check:"custom",fn:t,...a})}function eE(e,t,n){return new e({type:"custom",check:"custom",fn:t,...tt(n)})}function tE(e,t){const n=nE(a=>(a.addIssue=o=>{if(typeof o=="string")a.issues.push(jl(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(jl(i))}},e(a.value,a)),t);return n}function nE(e,t){const n=new Xn({check:"custom",...tt(t)});return n._zod.check=e,n}function fx(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??vl,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 cn(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 v=e._zod.parent;v&&(s.ref||(s.ref=v),cn(v,t,h),t.seen.get(v).isParent=!0)}const m=t.metadataRegistry.get(e);return m&&Object.assign(s.schema,m),t.io==="input"&&Hn(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 hx(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 v=e.external.registry.get(s[0])?.id,y=e.external.uri??(_=>_);if(v)return{ref:y(v)};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 v in h)delete h[v];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 gx(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},v=m.ref;if(m.ref=null,v){a(v);const w=e.seen.get(v),_=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===v)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!==v){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:Ed(t,"input",e.processors),output:Ed(t,"output",e.processors)}},enumerable:!1,writable:!1}),l}catch{throw new Error("Error converting schema to JSON.")}}function Hn(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 Hn(a.element,n);if(a.type==="set")return Hn(a.valueType,n);if(a.type==="lazy")return Hn(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 Hn(a.innerType,n);if(a.type==="intersection")return Hn(a.left,n)||Hn(a.right,n);if(a.type==="record"||a.type==="map")return Hn(a.keyType,n)||Hn(a.valueType,n);if(a.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:Hn(a.in,n)||Hn(a.out,n);if(a.type==="object"){for(const o in a.shape)if(Hn(a.shape[o],n))return!0;return!1}if(a.type==="union"){for(const o of a.options)if(Hn(o,n))return!0;return!1}if(a.type==="tuple"){for(const o of a.items)if(Hn(o,n))return!0;return!!(a.rest&&Hn(a.rest,n))}return!1}const aE=(e,t={})=>n=>{const a=fx({...n,processors:t});return cn(e,a),hx(a,e),gx(a,e)},Ed=(e,t,n={})=>a=>{const{libraryOptions:o,target:i}=a??{},s=fx({...o??{},target:i,io:t,processors:n});return cn(e,s),hx(s,e),gx(s,e)},oE={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},rE=(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=oE[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(v=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:v.source}))])}},iE=(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 v=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";v?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)},sE=(e,t,n,a)=>{n.type="boolean"},lE=(e,t,n,a)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},cE=(e,t,n,a)=>{n.not={}},dE=(e,t,n,a)=>{},uE=(e,t,n,a)=>{const o=e._zod.def,i=KS(o.entries);i.every(s=>typeof s=="number")&&(n.type="number"),i.every(s=>typeof s=="string")&&(n.type="string"),n.enum=i},mE=(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},pE=(e,t,n,a)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},fE=(e,t,n,a)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},hE=(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=cn(i.element,t,{...a,path:[...a.path,"items"]})},gE=(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]=cn(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=cn(i.catchall,t,{...a,path:[...a.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},vE=(e,t,n,a)=>{const o=e._zod.def,i=o.inclusive===!1,s=o.options.map((l,m)=>cn(l,t,{...a,path:[...a.path,i?"oneOf":"anyOf",m]}));i?n.oneOf=s:n.anyOf=s},bE=(e,t,n,a)=>{const o=e._zod.def,i=cn(o.left,t,{...a,path:[...a.path,"allOf",0]}),s=cn(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},yE=(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=cn(i.valueType,t,{...a,path:[...a.path,"patternProperties","*"]});o.patternProperties={};for(const v of m)o.patternProperties[v.source]=h}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(o.propertyNames=cn(i.keyType,t,{...a,path:[...a.path,"propertyNames"]})),o.additionalProperties=cn(i.valueType,t,{...a,path:[...a.path,"additionalProperties"]});const d=s._zod.values;if(d){const h=[...d].filter(v=>typeof v=="string"||typeof v=="number");h.length>0&&(o.required=h)}},SE=(e,t,n,a)=>{const o=e._zod.def,i=cn(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"}]},xE=(e,t,n,a)=>{const o=e._zod.def;cn(o.innerType,t,a);const i=t.seen.get(e);i.ref=o.innerType},kE=(e,t,n,a)=>{const o=e._zod.def;cn(o.innerType,t,a);const i=t.seen.get(e);i.ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))},wE=(e,t,n,a)=>{const o=e._zod.def;cn(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)))},IE=(e,t,n,a)=>{const o=e._zod.def;cn(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},_E=(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;cn(s,t,a);const l=t.seen.get(e);l.ref=s},CE=(e,t,n,a)=>{const o=e._zod.def;cn(o.innerType,t,a);const i=t.seen.get(e);i.ref=o.innerType,n.readOnly=!0},vx=(e,t,n,a)=>{const o=e._zod.def;cn(o.innerType,t,a);const i=t.seen.get(e);i.ref=o.innerType},RE=(e,t,n,a)=>{const o=e._zod.innerType;cn(o,t,a);const i=t.seen.get(e);i.ref=o},PE=he("ZodISODateTime",(e,t)=>{wA.init(e,t),tn.init(e,t)});function bx(e){return ET(PE,e)}const AE=he("ZodISODate",(e,t)=>{IA.init(e,t),tn.init(e,t)});function TE(e){return MT(AE,e)}const EE=he("ZodISOTime",(e,t)=>{_A.init(e,t),tn.init(e,t)});function ME(e){return jT(EE,e)}const jE=he("ZodISODuration",(e,t)=>{CA.init(e,t),tn.init(e,t)});function OE(e){return OT(jE,e)}const yx=(e,t)=>{JS.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>fP(e,n)},flatten:{value:n=>pP(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,If,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,If,2)}},isEmpty:{get(){return e.issues.length===0}}})},$E=he("ZodError",yx),wa=he("ZodError",yx,{Parent:Error}),NE=Dh(wa),DE=Lh(wa),LE=ou(wa),UE=ru(wa),HE=vP(wa),zE=bP(wa),qE=yP(wa),BE=SP(wa),FE=xP(wa),VE=kP(wa),KE=wP(wa),WE=IP(wa),hb=new WeakMap;function ec(e,t,n){const a=Object.getPrototypeOf(e);let o=hb.get(a);if(o||(o=new Set,hb.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 Kt=he("ZodType",(e,t)=>(Vt.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Ed(e,"input"),output:Ed(e,"output")}}),e.toJSONSchema=aE(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,a)=>NE(e,n,a,{callee:e.parse}),e.safeParse=(n,a)=>LE(e,n,a),e.parseAsync=async(n,a)=>DE(e,n,a,{callee:e.parseAsync}),e.safeParseAsync=async(n,a)=>UE(e,n,a),e.spa=e.safeParseAsync,e.encode=(n,a)=>HE(e,n,a),e.decode=(n,a)=>zE(e,n,a),e.encodeAsync=async(n,a)=>qE(e,n,a),e.decodeAsync=async(n,a)=>BE(e,n,a),e.safeEncode=(n,a)=>FE(e,n,a),e.safeDecode=(n,a)=>VE(e,n,a),e.safeEncodeAsync=async(n,a)=>KE(e,n,a),e.safeDecodeAsync=async(n,a)=>WE(e,n,a),ec(e,"ZodType",{check(...n){const a=this.def;return this.clone(hr(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 gr(this,n,a)},brand(){return this},register(n,a){return n.add(this,a),this},refine(n,a){return this.check(DM(n,a))},superRefine(n,a){return this.check(LM(n,a))},overwrite(n){return this.check(ks(n))},optional(){return yb(this)},exactOptional(){return IM(this)},nullable(){return Sb(this)},nullish(){return yb(Sb(this))},nonoptional(n){return TM(this,n)},array(){return p(this)},or(n){return Nt([this,n])},and(n){return SM(this,n)},transform(n){return xb(this,_x(n))},default(n){return RM(this,n)},prefault(n){return AM(this,n)},catch(n){return MM(this,n)},pipe(n){return xb(this,n)},readonly(){return $M(this)},describe(n){const a=this.clone();return vl.add(a,{description:n}),a},meta(...n){if(n.length===0)return vl.get(this);const a=this.clone();return vl.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 vl.get(e)?.description},configurable:!0}),e)),Sx=he("_ZodString",(e,t)=>{Uh.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(a,o,i)=>rE(e,a,o);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,ec(e,"_ZodString",{regex(...a){return this.check(zT(...a))},includes(...a){return this.check(FT(...a))},startsWith(...a){return this.check(VT(...a))},endsWith(...a){return this.check(KT(...a))},min(...a){return this.check(Td(...a))},max(...a){return this.check(mx(...a))},length(...a){return this.check(px(...a))},nonempty(...a){return this.check(Td(1,...a))},lowercase(a){return this.check(qT(a))},uppercase(a){return this.check(BT(a))},trim(){return this.check(GT())},normalize(...a){return this.check(WT(...a))},toLowerCase(){return this.check(ZT())},toUpperCase(){return this.check(JT())},slugify(){return this.check(YT())}})}),GE=he("ZodString",(e,t)=>{Uh.init(e,t),Sx.init(e,t),e.email=n=>e.check(dT(ZE,n)),e.url=n=>e.check(hT(JE,n)),e.jwt=n=>e.check(TT(uM,n)),e.emoji=n=>e.check(gT(YE,n)),e.guid=n=>e.check(ub(gb,n)),e.uuid=n=>e.check(uT(Fc,n)),e.uuidv4=n=>e.check(mT(Fc,n)),e.uuidv6=n=>e.check(pT(Fc,n)),e.uuidv7=n=>e.check(fT(Fc,n)),e.nanoid=n=>e.check(vT(QE,n)),e.guid=n=>e.check(ub(gb,n)),e.cuid=n=>e.check(bT(XE,n)),e.cuid2=n=>e.check(yT(eM,n)),e.ulid=n=>e.check(ST(tM,n)),e.base64=n=>e.check(RT(lM,n)),e.base64url=n=>e.check(PT(cM,n)),e.xid=n=>e.check(xT(nM,n)),e.ksuid=n=>e.check(kT(aM,n)),e.ipv4=n=>e.check(wT(oM,n)),e.ipv6=n=>e.check(IT(rM,n)),e.cidrv4=n=>e.check(_T(iM,n)),e.cidrv6=n=>e.check(CT(sM,n)),e.e164=n=>e.check(AT(dM,n)),e.datetime=n=>e.check(bx(n)),e.date=n=>e.check(TE(n)),e.time=n=>e.check(ME(n)),e.duration=n=>e.check(OE(n))});function r(e){return cT(GE,e)}const tn=he("ZodStringFormat",(e,t)=>{Yt.init(e,t),Sx.init(e,t)}),ZE=he("ZodEmail",(e,t)=>{fA.init(e,t),tn.init(e,t)}),gb=he("ZodGUID",(e,t)=>{mA.init(e,t),tn.init(e,t)}),Fc=he("ZodUUID",(e,t)=>{pA.init(e,t),tn.init(e,t)}),JE=he("ZodURL",(e,t)=>{hA.init(e,t),tn.init(e,t)}),YE=he("ZodEmoji",(e,t)=>{gA.init(e,t),tn.init(e,t)}),QE=he("ZodNanoID",(e,t)=>{vA.init(e,t),tn.init(e,t)}),XE=he("ZodCUID",(e,t)=>{bA.init(e,t),tn.init(e,t)}),eM=he("ZodCUID2",(e,t)=>{yA.init(e,t),tn.init(e,t)}),tM=he("ZodULID",(e,t)=>{SA.init(e,t),tn.init(e,t)}),nM=he("ZodXID",(e,t)=>{xA.init(e,t),tn.init(e,t)}),aM=he("ZodKSUID",(e,t)=>{kA.init(e,t),tn.init(e,t)}),oM=he("ZodIPv4",(e,t)=>{RA.init(e,t),tn.init(e,t)}),rM=he("ZodIPv6",(e,t)=>{PA.init(e,t),tn.init(e,t)}),iM=he("ZodCIDRv4",(e,t)=>{AA.init(e,t),tn.init(e,t)}),sM=he("ZodCIDRv6",(e,t)=>{TA.init(e,t),tn.init(e,t)}),lM=he("ZodBase64",(e,t)=>{EA.init(e,t),tn.init(e,t)}),cM=he("ZodBase64URL",(e,t)=>{jA.init(e,t),tn.init(e,t)}),dM=he("ZodE164",(e,t)=>{OA.init(e,t),tn.init(e,t)}),uM=he("ZodJWT",(e,t)=>{NA.init(e,t),tn.init(e,t)}),xx=he("ZodNumber",(e,t)=>{ix.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(a,o,i)=>iE(e,a,o),ec(e,"ZodNumber",{gt(a,o){return this.check(pb(a,o))},gte(a,o){return this.check(op(a,o))},min(a,o){return this.check(op(a,o))},lt(a,o){return this.check(mb(a,o))},lte(a,o){return this.check(ap(a,o))},max(a,o){return this.check(ap(a,o))},int(a){return this.check(vb(a))},safe(a){return this.check(vb(a))},positive(a){return this.check(pb(0,a))},nonnegative(a){return this.check(op(0,a))},negative(a){return this.check(mb(0,a))},nonpositive(a){return this.check(ap(0,a))},multipleOf(a,o){return this.check(fb(a,o))},step(a,o){return this.check(fb(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 $T(xx,e)}const mM=he("ZodNumberFormat",(e,t)=>{DA.init(e,t),xx.init(e,t)});function vb(e){return NT(mM,e)}const pM=he("ZodBoolean",(e,t)=>{LA.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>sE(e,n,a)});function A(e){return DT(pM,e)}const fM=he("ZodNull",(e,t)=>{UA.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>lE(e,n,a)});function su(e){return LT(fM,e)}const hM=he("ZodUnknown",(e,t)=>{HA.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>dE()});function de(){return UT(hM)}const gM=he("ZodNever",(e,t)=>{zA.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>cE(e,n,a)});function kx(e){return HT(gM,e)}const vM=he("ZodArray",(e,t)=>{qA.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>hE(e,n,a,o),e.element=t.element,ec(e,"ZodArray",{min(n,a){return this.check(Td(n,a))},nonempty(n){return this.check(Td(1,n))},max(n,a){return this.check(mx(n,a))},length(n,a){return this.check(px(n,a))},unwrap(){return this.element}})});function p(e,t){return QT(vM,e,t)}const wx=he("ZodObject",(e,t)=>{FA.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>gE(e,n,a,o),_t(e,"shape",()=>t.shape),ec(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:de()})},loose(){return this.clone({...this._zod.def,catchall:de()})},strict(){return this.clone({...this._zod.def,catchall:kx()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return sP(this,n)},safeExtend(n){return lP(this,n)},merge(n){return cP(this,n)},pick(n){return rP(this,n)},omit(n){return iP(this,n)},partial(...n){return dP(Cx,this,n[0])},required(...n){return uP(Rx,this,n[0])}})});function c(e,t){const n={type:"object",shape:e??{},...tt(t)};return new wx(n)}function rp(e,t){return new wx({type:"object",shape:e,catchall:kx(),...tt(t)})}const Ix=he("ZodUnion",(e,t)=>{cx.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>vE(e,n,a,o),e.options=t.options});function Nt(e,t){return new Ix({type:"union",options:e,...tt(t)})}const bM=he("ZodDiscriminatedUnion",(e,t)=>{Ix.init(e,t),VA.init(e,t)});function It(e,t,n){return new bM({type:"union",options:t,discriminator:e,...tt(n)})}const yM=he("ZodIntersection",(e,t)=>{KA.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>bE(e,n,a,o)});function SM(e,t){return new yM({type:"intersection",left:e,right:t})}const bb=he("ZodRecord",(e,t)=>{WA.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>yE(e,n,a,o),e.keyType=t.keyType,e.valueType=t.valueType});function re(e,t,n){return!t||!t._zod?new bb({type:"record",keyType:r(),valueType:e,...tt(t)}):new bb({type:"record",keyType:e,valueType:t,...tt(n)})}const Cf=he("ZodEnum",(e,t)=>{GA.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(a,o,i)=>uE(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 Cf({...t,checks:[],...tt(o),entries:i})},e.exclude=(a,o)=>{const i={...t.entries};for(const s of a)if(n.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new Cf({...t,checks:[],...tt(o),entries:i})}});function b(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(a=>[a,a])):e;return new Cf({type:"enum",entries:n,...tt(t)})}const xM=he("ZodLiteral",(e,t)=>{ZA.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>mE(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 xM({type:"literal",values:Array.isArray(e)?e:[e],...tt(t)})}const kM=he("ZodTransform",(e,t)=>{JA.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>fE(e,n),e._zod.parse=(n,a)=>{if(a.direction==="backward")throw new VS(e.constructor.name);n.addIssue=i=>{if(typeof i=="string")n.issues.push(jl(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(jl(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 _x(e){return new kM({type:"transform",transform:e})}const Cx=he("ZodOptional",(e,t)=>{dx.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>vx(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function yb(e){return new Cx({type:"optional",innerType:e})}const wM=he("ZodExactOptional",(e,t)=>{YA.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>vx(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function IM(e){return new wM({type:"optional",innerType:e})}const _M=he("ZodNullable",(e,t)=>{QA.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>SE(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function Sb(e){return new _M({type:"nullable",innerType:e})}const CM=he("ZodDefault",(e,t)=>{XA.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>kE(e,n,a,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function RM(e,t){return new CM({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():GS(t)}})}const PM=he("ZodPrefault",(e,t)=>{eT.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>wE(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function AM(e,t){return new PM({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():GS(t)}})}const Rx=he("ZodNonOptional",(e,t)=>{tT.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>xE(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function TM(e,t){return new Rx({type:"nonoptional",innerType:e,...tt(t)})}const EM=he("ZodCatch",(e,t)=>{nT.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>IE(e,n,a,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function MM(e,t){return new EM({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const Px=he("ZodPipe",(e,t)=>{ux.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>_E(e,n,a,o),e.in=t.in,e.out=t.out});function xb(e,t){return new Px({type:"pipe",in:e,out:t})}const jM=he("ZodPreprocess",(e,t)=>{Px.init(e,t),aT.init(e,t)}),OM=he("ZodReadonly",(e,t)=>{oT.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>CE(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function $M(e){return new OM({type:"readonly",innerType:e})}const NM=he("ZodLazy",(e,t)=>{rT.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>RE(e,n,a,o),e.unwrap=()=>e._zod.def.getter()});function Ax(e){return new NM({type:"lazy",getter:e})}const Tx=he("ZodCustom",(e,t)=>{iT.init(e,t),Kt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>pE(e,n)});function ip(e,t){return XT(Tx,(()=>!0),t)}function DM(e,t={}){return eE(Tx,e,t)}function LM(e,t){return tE(e,t)}function Wr(e){const t=Ax(()=>Nt([r(e),u(),A(),su(),p(t),re(r(),t)]));return t}function UM(e,t){return new jM({type:"pipe",in:_x(e),out:t})}const qn={custom:"custom"},HM=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),zM=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 qM(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(HM),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,k=no($,17)^no($,19)^$>>>10;l[C]=l[C-16]+j+l[C-7]+k>>>0}let d=s[0],h=s[1],v=s[2],y=s[3],w=s[4],_=s[5],R=s[6],M=s[7];for(let C=0;C<64;C+=1){const N=w&_^~w&R,$=d&h^d&v^h&v,j=no(d,2)^no(d,13)^no(d,22),k=no(w,6)^no(w,11)^no(w,25),P=M+k+N+zM[C]+l[C]>>>0,T=j+$>>>0;M=R,R=_,_=w,w=y+P>>>0,y=v,v=h,h=d,d=P+T>>>0}s[0]=s[0]+d>>>0,s[1]=s[1]+h>>>0,s[2]=s[2]+v>>>0,s[3]=s[3]+y>>>0,s[4]=s[4]+w>>>0,s[5]=s[5]+_>>>0,s[6]=s[6]+R>>>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}const BM=2e3,Ex=25e7,E=r().trim().min(1).max(240),Q=r().regex(/^[a-f0-9]{64}$/),Ee=r().datetime({offset:!0}),_n=re(r(),de()).default({}),J=c({id:E,contentHash:Q}).strict(),zt=J.extend({revision:u().int().positive()}).strict(),ln=c({id:E,path:r().trim().min(1).max(BM).refine(VM),contentHash:Q,sizeBytes:u().int().nonnegative().max(Ex),mediaType:r().trim().min(1).max(200),visibility:b(["policy","verifier","host_private"])}).strict(),Va=c({id:E,contentHash:Q,mediaType:r().trim().min(1).max(200).nullable().default(null),sizeBytes:u().int().nonnegative().max(Ex).nullable().default(null)}).strict(),tc=b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]);function FM(e){return`${JSON.stringify(Rf(e),null,2)}
|
|
66
|
+
`}function Hh(e){return qM(e)}function rn(e){return Hh(FM(e))}function VM(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function Rf(e){return Array.isArray(e)?e.map(Rf):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,Rf(n)]))}const zh=c({provider:E,model:E,revision:r().trim().min(1).max(500).nullable().default(null),artifactHash:Q.nullable().default(null),tokenizerRevision:r().trim().min(1).max(500).nullable().default(null),chatTemplateHash:Q.nullable().default(null)}).strict(),qh=["openpond","codex","anthropic","openai","xai","google","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],ei=b(qh),dn=c({providerId:ei,modelId:r().trim().min(1).max(300)}),lu=b(["active","preview","planned","deprecated"]),Mx=b(["openpond-account","openpond-managed","codex-login","chatgpt-subscription","local-byok","hosted-byok","custom"]),KM=b(["none","local_secret","env","openpond_account","codex_login","chatgpt_subscription","hosted"]),kb=c({connected:A().default(!1),source:KM.default("none"),redacted:r().nullable().default(null),lastValidatedAt:r().nullable().default(null),lastError:r().nullable().default(null)}),Pf=c({hostedOpChat:A().default(!1),localRuntime:A().default(!0),localByok:A().default(!1),hostedByok:A().default(!1)}),WM=b(["hosted","provider","manual","none"]),Af=c({chatCompletions:A().default(!0),streaming:A().default(!0),modelDiscovery:WM.default("none"),toolCalling:A().default(!1),reasoning:A().default(!1),imageInput:A().default(!1),structuredOutput:A().default(!1)}),GM=b(["hosted","provider","curated","manual","cache"]),Tf=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)}),ZM=c({id:r().trim().min(1).max(300),providerId:ei,displayName:r().trim().min(1).max(300),contextWindow:u().int().positive().nullable().default(null),outputLimit:u().int().positive().nullable().default(null),lifecycleStatus:lu.default("active"),source:GM,capabilities:Tf.default(()=>Tf.parse({})),raw:re(r(),de()).optional()}),JM=c({providerId:ei,models:p(ZM).default([]),fetchedAt:r().nullable().default(null),lastError:r().nullable().default(null),source:b(["none","hosted","provider","curated","manual"]).default("none")}),YM=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)}),QM=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()}),XM=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:lu.optional(),capabilities:Tf.partial().optional()}),ej=c({id:ei,displayName:r().trim().min(1).max(160),lifecycleStatus:lu.default("active"),credentialModes:p(Mx).default([]),routing:Pf,capabilities:Af,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(XM).default([])});c({version:S(1).default(1),generatedAt:r().datetime(),providers:p(ej)});const tj=c({id:ei,displayName:r().trim().min(1).max(160),lifecycleStatus:lu.default("active"),credentialModes:p(Mx).default([]),routing:Pf.default(()=>Pf.parse({})),capabilities:Af.default(()=>Af.parse({})),credential:kb.default(()=>kb.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)}),wb=c({version:S(1).default(1),providers:re(r(),YM).default({}),statuses:re(r(),tj).default({}),modelCaches:re(r(),JM).default({}),updatedAt:r().nullable().default(null)});c({providers:re(r(),QM).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 nj=["coding","research","review","test","docs","planner","summarizer"];b(nj);const ws=r().trim().min(1).max(80).regex(/^[a-z][a-z0-9_-]*$/),jx=b(["none","worktree","copy_on_write"]),Ox=b(["read_only","workspace_write","full_tools"]),$x=b(["disabled","parent_scoped"]),cu=b(["manual","balanced","proactive"]),aj=b(["queued","running","completed","failed","cancelled","needs_resume"]),Nx=["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(Nx);const oj=[{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"}],Bh=c({id:ws,enabled:A().default(!0),modelRef:dn.nullable().default(null),isolationMode:jx.default("none"),maxConcurrentRuns:u().int().min(1).max(16).default(1),toolPolicy:Ox.default("read_only"),background:A().default(!0),peerMessages:$x.default("parent_scoped")}),Ol=c({enabled:A().default(!0),workspaceDefaultsVersion:S(1).default(1),toolDefaultsVersion:S(1).default(1),delegationMode:cu.default("manual"),defaultModelRef:dn.nullable().default(null),roles:p(Bh).max(64).default(()=>Ux()),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:hj(e.roles)})),wl=c({kind:b(["session","turn","file","diff","artifact"]),id:r().trim().min(1).max(500),label:r().trim().min(1).max(500)}),rj=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})),ij=b(["orient","edit","validate","report"]),sj=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)}),lj=c({phase:ij.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(wl).max(100).default([]),validationAttempts:p(sj).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})),cj=c({summary:r().trim().max(2e4).default(""),findings:p(r().trim().min(1).max(5e3)).max(200).default([]),artifacts:p(wl).max(200).default([]),patchRef:wl.nullable().default(null),diffRef:wl.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)}),Dx=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:dn.nullable().default(null),isolationMode:jx.default("none"),toolPolicy:Ox.default("read_only"),background:A().default(!0),peerMessages:$x.default("parent_scoped"),status:aj.default("queued"),progress:lj,evidenceRetention:rj,createdAt:r(),startedAt:r().nullable().default(null),completedAt:r().nullable().default(null),updatedAt:r().nullable().default(null),error:r().nullable().default(null),report:cj.nullable().default(null),metadata:re(r(),de()).optional().default({})}),Lx=b(["cleanup","archive","cleanup_and_archive"]);c({action:Lx,reason:r().trim().min(1).max(2e3).nullable().default(null)});c({action:Lx,run:Dx,workspaceCleanup:re(r(),de()).nullable().default(null),sessionArchive:re(r(),de()).nullable().default(null),nextStep:r()});const dj=b(["question","answer","handoff","artifact","status","blocker"]),uj=b(["normal","interrupt"]),mj=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)}),pj=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:dj,priority:uj.optional(),body:r().trim().min(1).max(5e4),refs:p(wl).max(100).default([]),delivery:mj.optional(),createdAt:r()});function Ux(){return oj.map(e=>Bh.parse({id:e.id,toolPolicy:e.defaultToolPolicy}))}function fj(){return Ol.parse({})}function hj(e){const t=Ux(),n=new Map(t.map(o=>[o.id,o])),a=[];for(const o of e??[]){const i=Bh.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 gj=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",...Nx,"diagnostic"]),Ib=c({id:r(),sequence:u().int().positive().optional(),sessionId:r().optional(),turnId:r().optional(),name:gj,timestamp:r(),source:b(["ui_button","chat_action","terminal_command","hook","provider","server"]).optional(),action:r().optional(),appId:r().nullable().optional(),args:re(r(),de()).optional(),status:b(["started","completed","failed","pending"]).optional(),output:r().optional(),error:r().optional(),relatedDeploymentId:r().optional(),data:de().optional()}),vj=c({id:r().trim().min(1).max(80),label:r().trim().min(1).max(160),description:r().trim().max(500).nullable().optional().default(null)}),bj=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(vj).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()}),yj=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 Sj(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var jn={},Vc={},ar={},_b;function nc(){if(_b)return ar;_b=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 v=m[d];s[v]=l[v]}}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 ar.isNothing=e,ar.isObject=t,ar.toArray=n,ar.repeat=o,ar.isNegativeZero=i,ar.extend=a,ar}var sp,Cb;function ac(){if(Cb)return sp;Cb=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)},sp=t,sp}var lp,Rb;function xj(){if(Rb)return lp;Rb=1;const e=nc();function t(o,i,s,l,m){let d="",h="";const v=Math.floor(m/2)-1;return l-i>v&&(d=" ... ",i=l-v+d.length),s-l>v&&(h=" ...",s=l+v-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 v="";const y=Math.min(o.line+i.linesAfter,m.length).toString().length,w=i.maxLength-(i.indent+y+3);for(let R=1;R<=i.linesBefore&&!(h-R<0);R++){const M=t(o.buffer,l[h-R],m[h-R],o.position-(l[h]-l[h-R]),w);v=e.repeat(" ",i.indent)+n((o.line-R+1).toString(),y)+" | "+M.str+`
|
|
69
|
+
`+v}const _=t(o.buffer,l[h],m[h],o.position,w);v+=e.repeat(" ",i.indent)+n((o.line+1).toString(),y)+" | "+_.str+`
|
|
70
|
+
`,v+=e.repeat("-",i.indent+y+3+_.pos)+`^
|
|
71
|
+
`;for(let R=1;R<=i.linesAfter&&!(h+R>=m.length);R++){const M=t(o.buffer,l[h+R],m[h+R],o.position-(l[h]-l[h+R]),w);v+=e.repeat(" ",i.indent)+n((o.line+R+1).toString(),y)+" | "+M.str+`
|
|
72
|
+
`}return v.replace(/\n$/,"")}return lp=a,lp}var cp,Pb;function Bn(){if(Pb)return cp;Pb=1;const e=ac(),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 cp=o,cp}var dp,Ab;function Hx(){if(Ab)return dp;Ab=1;const e=ac(),t=Bn();function n(i,s){const l=[];return i[s].forEach(function(m){let d=l.length;l.forEach(function(h,v){h.tag===m.tag&&h.kind===m.kind&&h.multi===m.multi&&(d=v)}),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},dp=o,dp}var up,Tb;function zx(){if(Tb)return up;Tb=1;const e=Bn();return up=new e("tag:yaml.org,2002:str",{kind:"scalar",construct:function(t){return t!==null?t:""}}),up}var mp,Eb;function qx(){if(Eb)return mp;Eb=1;const e=Bn();return mp=new e("tag:yaml.org,2002:seq",{kind:"sequence",construct:function(t){return t!==null?t:[]}}),mp}var pp,Mb;function Bx(){if(Mb)return pp;Mb=1;const e=Bn();return pp=new e("tag:yaml.org,2002:map",{kind:"mapping",construct:function(t){return t!==null?t:{}}}),pp}var fp,jb;function Fx(){if(jb)return fp;jb=1;const e=Hx();return fp=new e({explicit:[zx(),qx(),Bx()]}),fp}var hp,Ob;function Vx(){if(Ob)return hp;Ob=1;const e=Bn();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 hp=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"}),hp}var gp,$b;function Kx(){if($b)return gp;$b=1;const e=Bn();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 gp=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"}),gp}var vp,Nb;function Wx(){if(Nb)return vp;Nb=1;const e=nc(),t=Bn();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 v=0,y=!1;if(!h)return!1;let w=d[v];if((w==="-"||w==="+")&&(w=d[++v]),w==="0"){if(v+1===h)return!0;if(w=d[++v],w==="b"){for(v++;v<h;v++){if(w=d[v],w!=="0"&&w!=="1")return!1;y=!0}return y&&isFinite(s(d))}if(w==="x"){for(v++;v<h;v++){if(!n(d.charCodeAt(v)))return!1;y=!0}return y&&isFinite(s(d))}if(w==="o"){for(v++;v<h;v++){if(!a(d.charCodeAt(v)))return!1;y=!0}return y&&isFinite(s(d))}}for(;v<h;v++){if(!o(d.charCodeAt(v)))return!1;y=!0}return y?isFinite(s(d)):!1}function s(d){let h=d,v=1,y=h[0];if((y==="-"||y==="+")&&(y==="-"&&(v=-1),h=h.slice(1),y=h[0]),h==="0")return 0;if(y==="0"){if(h[1]==="b")return v*parseInt(h.slice(2),2);if(h[1]==="x")return v*parseInt(h.slice(2),16);if(h[1]==="o")return v*parseInt(h.slice(2),8)}return v*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 vp=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"]}}),vp}var bp,Db;function Gx(){if(Db)return bp;Db=1;const e=nc(),t=Bn(),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 v=h[0]==="-"?-1:1;return"+-".indexOf(h[0])>=0&&(h=h.slice(1)),h===".inf"?v===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:h===".nan"?NaN:v*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 v=d.toString(10);return s.test(v)?v.replace("e",".e"):v}function m(d){return Object.prototype.toString.call(d)==="[object Number]"&&(d%1!==0||e.isNegativeZero(d))}return bp=new t("tag:yaml.org,2002:float",{kind:"scalar",resolve:o,construct:i,predicate:m,represent:l,defaultStyle:"lowercase"}),bp}var yp,Lb;function Zx(){return Lb||(Lb=1,yp=Fx().extend({implicit:[Vx(),Kx(),Wx(),Gx()]})),yp}var Sp,Ub;function Jx(){return Ub||(Ub=1,Sp=Zx()),Sp}var xp,Hb;function Yx(){if(Hb)return xp;Hb=1;const e=Bn(),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],v=+d[2]-1,y=+d[3];if(!d[4])return new Date(Date.UTC(h,v,y));const w=+d[4],_=+d[5],R=+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,v,y,w,_,R,l));return m&&M.setTime(M.getTime()-m),M}function i(s){return s.toISOString()}return xp=new e("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:a,construct:o,instanceOf:Date,represent:i}),xp}var kp,zb;function Qx(){if(zb)return kp;zb=1;const e=Bn();function t(n){return n==="<<"||n===null}return kp=new e("tag:yaml.org,2002:merge",{kind:"scalar",resolve:t}),kp}var wp,qb;function Xx(){if(qb)return wp;qb=1;const e=Bn(),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 v=d.indexOf(s.charAt(h));if(!(v>64)){if(v<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 v=[];for(let w=0;w<m;w++)w%4===0&&w&&(v.push(h>>16&255),v.push(h>>8&255),v.push(h&255)),h=h<<6|d.indexOf(l.charAt(w));const y=m%4*6;return y===0?(v.push(h>>16&255),v.push(h>>8&255),v.push(h&255)):y===18?(v.push(h>>10&255),v.push(h>>2&255)):y===12&&v.push(h>>4&255),new Uint8Array(v)}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 v=d%3;return v===0?(l+=h[m>>18&63],l+=h[m>>12&63],l+=h[m>>6&63],l+=h[m&63]):v===2?(l+=h[m>>10&63],l+=h[m>>4&63],l+=h[m<<2&63],l+=h[64]):v===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 wp=new e("tag:yaml.org,2002:binary",{kind:"scalar",resolve:n,construct:a,predicate:i,represent:o}),wp}var Ip,Bb;function ek(){if(Bb)return Ip;Bb=1;const e=Bn(),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 v=!1;if(n.call(h)!=="[object Object]")return!1;let y;for(y in h)if(t.call(h,y))if(!v)v=!0;else return!1;if(!v)return!1;if(s.indexOf(y)===-1)s.push(y);else return!1}return!0}function o(i){return i!==null?i:[]}return Ip=new e("tag:yaml.org,2002:omap",{kind:"sequence",resolve:a,construct:o}),Ip}var _p,Fb;function tk(){if(Fb)return _p;Fb=1;const e=Bn(),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 _p=new e("tag:yaml.org,2002:pairs",{kind:"sequence",resolve:n,construct:a}),_p}var Cp,Vb;function nk(){if(Vb)return Cp;Vb=1;const e=Bn(),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 Cp=new e("tag:yaml.org,2002:set",{kind:"mapping",resolve:n,construct:a}),Cp}var Rp,Kb;function Fh(){return Kb||(Kb=1,Rp=Jx().extend({implicit:[Yx(),Qx()],explicit:[Xx(),ek(),tk(),nk()]})),Rp}var Wb;function kj(){if(Wb)return Vc;Wb=1;const e=nc(),t=ac(),n=xj(),a=Fh(),o=Object.prototype.hasOwnProperty,i=1,s=2,l=3,m=4,d=1,h=2,v=3,y=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,w=/[\x85\u2028\u2029]/,_=/[,\[\]{}]/,R=/^(?:!|!!|![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 k(f){return f===44||f===91||f===93||f===123||f===125}function P(f){if(f>=48&&f<=57)return f-48;const H=f|32;return H>=97&&H<=102?H-97+10:-1}function T(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,Z){H==="__proto__"?Object.defineProperty(f,H,{configurable:!0,enumerable:!0,writable:!0,value:Z}):f[H]=Z}const se=new Array(256),me=new Array(256);for(let f=0;f<256;f++)se[f]=B(f)?1:0,me[f]=B(f);function Te(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 Z={name:f.filename,buffer:f.input.slice(0,-1),position:f.position,line:f.line,column:f.position-f.lineStart};return Z.snippet=n(Z),new t(H,Z)}function V(f,H){throw ke(f,H)}function Re(f,H){f.onWarning&&f.onWarning.call(null,ke(f,H))}function be(f,H,Z){const le=f.anchorMapTransactions;if(le.length!==0){const ee=le[le.length-1];o.call(ee,H)||(ee[H]={existed:o.call(f.anchorMap,H),value:f.anchorMap[H]})}f.anchorMap[H]=Z}function ce(f){f.anchorMapTransactions.push(Object.create(null))}function ye(f){const H=f.anchorMapTransactions.pop(),Z=f.anchorMapTransactions;if(Z.length===0)return;const le=Z[Z.length-1],ee=Object.keys(H);for(let F=0,I=ee.length;F<I;F+=1){const G=ee[F];o.call(le,G)||(le[G]=H[G])}}function ne(f){const H=f.anchorMapTransactions.pop(),Z=Object.keys(H);for(let le=Z.length-1;le>=0;le-=1){const ee=H[Z[le]];ee.existed?f.anchorMap[Z[le]]=ee.value:delete f.anchorMap[Z[le]]}}function ge(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,Z,le){H.version!==null&&V(H,"duplication of %YAML directive"),le.length!==1&&V(H,"YAML directive accepts exactly one argument");const ee=/^([0-9]+)\.([0-9]+)$/.exec(le[0]);ee===null&&V(H,"ill-formed argument of the YAML directive");const F=parseInt(ee[1],10),I=parseInt(ee[2],10);F!==1&&V(H,"unacceptable YAML version of the document"),H.version=le[0],H.checkLineBreaks=I<2,I!==1&&I!==2&&Re(H,"unsupported YAML version of the document")},TAG:function(H,Z,le){let ee;le.length!==2&&V(H,"TAG directive accepts exactly two arguments");const F=le[0];ee=le[1],R.test(F)||V(H,"ill-formed tag handle (first argument) of the TAG directive"),o.call(H.tagMap,F)&&V(H,'there is a previously declared suffix for "'+F+'" tag handle'),M.test(ee)||V(H,"ill-formed tag prefix (second argument) of the TAG directive");try{ee=decodeURIComponent(ee)}catch{V(H,"tag prefix is malformed: "+ee)}H.tagMap[F]=ee}};function we(f,H,Z,le){if(H<Z){const ee=f.input.slice(H,Z);if(le)for(let F=0,I=ee.length;F<I;F+=1){const G=ee.charCodeAt(F);G===9||G>=32&&G<=1114111||V(f,"expected valid JSON character")}else y.test(ee)&&V(f,"the stream contains non-printable characters");f.result+=ee}}function ae(f,H,Z,le){e.isObject(Z)||V(f,"cannot merge mappings; the provided source object is unacceptable");const ee=Object.keys(Z);for(let F=0,I=ee.length;F<I;F+=1){const G=ee[F];f.maxTotalMergeKeys!==-1&&++f.totalMergeKeys>f.maxTotalMergeKeys&&V(f,"merge keys exceeded maxTotalMergeKeys ("+f.maxTotalMergeKeys+")"),o.call(H,G)||(W(H,G,Z[G]),le[G]=!0)}}function Se(f,H,Z,le,ee,F,I,G,ie){if(Array.isArray(ee)){ee=Array.prototype.slice.call(ee);for(let te=0,oe=ee.length;te<oe;te+=1)Array.isArray(ee[te])&&V(f,"nested arrays are not supported inside keys"),typeof ee=="object"&&C(ee[te])==="[object Object]"&&(ee[te]="[object Object]")}if(typeof ee=="object"&&C(ee)==="[object Object]"&&(ee="[object Object]"),ee=String(ee),H===null&&(H={}),le==="tag:yaml.org,2002:merge")if(Array.isArray(F))for(let te=0,oe=F.length;te<oe;te+=1)ae(f,H,F[te],Z);else ae(f,H,F,Z);else!f.json&&!o.call(Z,ee)&&o.call(H,ee)&&(f.line=I||f.line,f.lineStart=G||f.lineStart,f.position=ie||f.position,V(f,"duplicated mapping key")),W(H,ee,F),delete Z[ee];return H}function ze(f){const H=f.input.charCodeAt(f.position);H===10?f.position++:H===13?(f.position++,f.input.charCodeAt(f.position)===10&&f.position++):V(f,"a line break is expected"),f.line+=1,f.lineStart=f.position,f.firstTabInLine=-1}function Qe(f,H,Z){let le=0,ee=f.input.charCodeAt(f.position);for(;ee!==0;){for(;$(ee);)ee===9&&f.firstTabInLine===-1&&(f.firstTabInLine=f.position),ee=f.input.charCodeAt(++f.position);if(H&&ee===35)do ee=f.input.charCodeAt(++f.position);while(ee!==10&&ee!==13&&ee!==0);if(N(ee))for(ze(f),ee=f.input.charCodeAt(f.position),le++,f.lineIndent=0;ee===32;)f.lineIndent++,ee=f.input.charCodeAt(++f.position);else break}return Z!==-1&&le!==0&&f.lineIndent<Z&&Re(f,"deficient indentation"),le}function We(f){let H=f.position,Z=f.input.charCodeAt(H);return!!((Z===45||Z===46)&&Z===f.input.charCodeAt(H+1)&&Z===f.input.charCodeAt(H+2)&&(H+=3,Z=f.input.charCodeAt(H),Z===0||j(Z)))}function nt(f,H){H===1?f.result+=" ":H>1&&(f.result+=e.repeat(`
|
|
75
|
+
`,H-1))}function qe(f,H,Z){let le,ee,F,I,G,ie;const te=f.kind,oe=f.result;let ue=f.input.charCodeAt(f.position);if(j(ue)||k(ue)||ue===35||ue===38||ue===42||ue===33||ue===124||ue===62||ue===39||ue===34||ue===37||ue===64||ue===96)return!1;if(ue===63||ue===45){const pe=f.input.charCodeAt(f.position+1);if(j(pe)||Z&&k(pe))return!1}for(f.kind="scalar",f.result="",le=ee=f.position,F=!1;ue!==0;){if(ue===58){const pe=f.input.charCodeAt(f.position+1);if(j(pe)||Z&&k(pe))break}else if(ue===35){const pe=f.input.charCodeAt(f.position-1);if(j(pe))break}else{if(f.position===f.lineStart&&We(f)||Z&&k(ue))break;if(N(ue))if(I=f.line,G=f.lineStart,ie=f.lineIndent,Qe(f,!1,-1),f.lineIndent>=H){F=!0,ue=f.input.charCodeAt(f.position);continue}else{f.position=ee,f.line=I,f.lineStart=G,f.lineIndent=ie;break}}F&&(we(f,le,ee,!1),nt(f,f.line-I),le=ee=f.position,F=!1),$(ue)||(ee=f.position+1),ue=f.input.charCodeAt(++f.position)}return we(f,le,ee,!1),f.result?!0:(f.kind=te,f.result=oe,!1)}function Ze(f,H){let Z,le,ee=f.input.charCodeAt(f.position);if(ee!==39)return!1;for(f.kind="scalar",f.result="",f.position++,Z=le=f.position;(ee=f.input.charCodeAt(f.position))!==0;)if(ee===39)if(we(f,Z,f.position,!0),ee=f.input.charCodeAt(++f.position),ee===39)Z=f.position,f.position++,le=f.position;else return!0;else N(ee)?(we(f,Z,le,!0),nt(f,Qe(f,!1,H)),Z=le=f.position):f.position===f.lineStart&&We(f)?V(f,"unexpected end of the document within a single quoted scalar"):(f.position++,$(ee)||(le=f.position));V(f,"unexpected end of the stream within a single quoted scalar")}function He(f,H){let Z,le,ee,F=f.input.charCodeAt(f.position);if(F!==34)return!1;for(f.kind="scalar",f.result="",f.position++,Z=le=f.position;(F=f.input.charCodeAt(f.position))!==0;){if(F===34)return we(f,Z,f.position,!0),f.position++,!0;if(F===92){if(we(f,Z,f.position,!0),F=f.input.charCodeAt(++f.position),N(F))Qe(f,!1,H);else if(F<256&&se[F])f.result+=me[F],f.position++;else if((ee=T(F))>0){let I=ee,G=0;for(;I>0;I--)F=f.input.charCodeAt(++f.position),(ee=P(F))>=0?G=(G<<4)+ee:V(f,"expected hexadecimal character");f.result+=D(G),f.position++}else V(f,"unknown escape sequence");Z=le=f.position}else N(F)?(we(f,Z,le,!0),nt(f,Qe(f,!1,H)),Z=le=f.position):f.position===f.lineStart&&We(f)?V(f,"unexpected end of the document within a double quoted scalar"):(f.position++,$(F)||(le=f.position))}V(f,"unexpected end of the stream within a double quoted scalar")}function L(f,H){let Z=!0,le,ee,F;const I=f.tag;let G;const ie=f.anchor;let te,oe,ue,pe;const Ie=Object.create(null);let je,Ne,$e,at=f.input.charCodeAt(f.position);if(at===91)te=93,pe=!1,G=[];else if(at===123)te=125,pe=!0,G={};else return!1;for(f.anchor!==null&&be(f,f.anchor,G),at=f.input.charCodeAt(++f.position);at!==0;){if(Qe(f,!0,H),at=f.input.charCodeAt(f.position),at===te)return f.position++,f.tag=I,f.anchor=ie,f.kind=pe?"mapping":"sequence",f.result=G,!0;if(Z?at===44&&V(f,"expected the node content, but found ','"):V(f,"missed comma between flow collection entries"),Ne=je=$e=null,oe=ue=!1,at===63){const pt=f.input.charCodeAt(f.position+1);j(pt)&&(oe=ue=!0,f.position++,Qe(f,!0,H))}le=f.line,ee=f.lineStart,F=f.position,Xe(f,H,i,!1,!0),Ne=f.tag,je=f.result,Qe(f,!0,H),at=f.input.charCodeAt(f.position),(ue||f.line===le)&&at===58&&(oe=!0,at=f.input.charCodeAt(++f.position),Qe(f,!0,H),Xe(f,H,i,!1,!0),$e=f.result),pe?Se(f,G,Ie,Ne,je,$e,le,ee,F):oe?G.push(Se(f,null,Ie,Ne,je,$e,le,ee,F)):G.push(je),Qe(f,!0,H),at=f.input.charCodeAt(f.position),at===44?(Z=!0,at=f.input.charCodeAt(++f.position)):Z=!1}V(f,"unexpected end of the stream within a flow collection")}function O(f,H){let Z,le=d,ee=!1,F=!1,I=H,G=0,ie=!1,te,oe=f.input.charCodeAt(f.position);if(oe===124)Z=!1;else if(oe===62)Z=!0;else return!1;for(f.kind="scalar",f.result="";oe!==0;)if(oe=f.input.charCodeAt(++f.position),oe===43||oe===45)d===le?le=oe===43?v:h:V(f,"repeat of a chomping mode identifier");else if((te=U(oe))>=0)te===0?V(f,"bad explicit indentation width of a block scalar; it cannot be less than one"):F?V(f,"repeat of an indentation width identifier"):(I=H+te-1,F=!0);else break;if($(oe)){do oe=f.input.charCodeAt(++f.position);while($(oe));if(oe===35)do oe=f.input.charCodeAt(++f.position);while(!N(oe)&&oe!==0)}for(;oe!==0;){for(ze(f),f.lineIndent=0,oe=f.input.charCodeAt(f.position);(!F||f.lineIndent<I)&&oe===32;)f.lineIndent++,oe=f.input.charCodeAt(++f.position);if(!F&&f.lineIndent>I&&(I=f.lineIndent),N(oe)){G++;continue}if(!F&&I===0&&V(f,"missing indentation for block scalar"),f.lineIndent<I){le===v?f.result+=e.repeat(`
|
|
76
|
+
`,ee?1+G:G):le===d&&ee&&(f.result+=`
|
|
77
|
+
`);break}Z?$(oe)?(ie=!0,f.result+=e.repeat(`
|
|
78
|
+
`,ee?1+G:G)):ie?(ie=!1,f.result+=e.repeat(`
|
|
79
|
+
`,G+1)):G===0?ee&&(f.result+=" "):f.result+=e.repeat(`
|
|
80
|
+
`,G):f.result+=e.repeat(`
|
|
81
|
+
`,ee?1+G:G),ee=!0,F=!0,G=0;const ue=f.position;for(;!N(oe)&&oe!==0;)oe=f.input.charCodeAt(++f.position);we(f,ue,f.position,!1)}return!0}function z(f,H){const Z=f.tag,le=f.anchor,ee=[];let F=!1;if(f.firstTabInLine!==-1)return!1;f.anchor!==null&&be(f,f.anchor,ee);let I=f.input.charCodeAt(f.position);for(;I!==0&&(f.firstTabInLine!==-1&&(f.position=f.firstTabInLine,V(f,"tab characters must not be used in indentation")),I===45);){const G=f.input.charCodeAt(f.position+1);if(!j(G))break;if(F=!0,f.position++,Qe(f,!0,-1)&&f.lineIndent<=H){ee.push(null),I=f.input.charCodeAt(f.position);continue}const ie=f.line;if(Xe(f,H,l,!1,!0),ee.push(f.result),Qe(f,!0,-1),I=f.input.charCodeAt(f.position),(f.line===ie||f.lineIndent>H)&&I!==0)V(f,"bad indentation of a sequence entry");else if(f.lineIndent<H)break}return F?(f.tag=Z,f.anchor=le,f.kind="sequence",f.result=ee,!0):!1}function X(f,H,Z){let le,ee,F,I;const G=f.tag,ie=f.anchor,te={},oe=Object.create(null);let ue=null,pe=null,Ie=null,je=!1,Ne=!1;if(f.firstTabInLine!==-1)return!1;f.anchor!==null&&be(f,f.anchor,te);let $e=f.input.charCodeAt(f.position);for(;$e!==0;){!je&&f.firstTabInLine!==-1&&(f.position=f.firstTabInLine,V(f,"tab characters must not be used in indentation"));const at=f.input.charCodeAt(f.position+1),pt=f.line;if(($e===63||$e===58)&&j(at))$e===63?(je&&(Se(f,te,oe,ue,pe,null,ee,F,I),ue=pe=Ie=null),Ne=!0,je=!0,le=!0):je?(je=!1,le=!0):V(f,"incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line"),f.position+=1,$e=at;else{if(ee=f.line,F=f.lineStart,I=f.position,!Xe(f,Z,s,!1,!0))break;if(f.line===pt){for($e=f.input.charCodeAt(f.position);$($e);)$e=f.input.charCodeAt(++f.position);if($e===58)$e=f.input.charCodeAt(++f.position),j($e)||V(f,"a whitespace character is expected after the key-value separator within a block mapping"),je&&(Se(f,te,oe,ue,pe,null,ee,F,I),ue=pe=Ie=null),Ne=!0,je=!1,le=!1,ue=f.tag,pe=f.result;else if(Ne)V(f,"can not read an implicit mapping pair; a colon is missed");else return f.tag=G,f.anchor=ie,!0}else if(Ne)V(f,"can not read a block mapping entry; a multiline key may not be an implicit key");else return f.tag=G,f.anchor=ie,!0}if((f.line===pt||f.lineIndent>H)&&(je&&(ee=f.line,F=f.lineStart,I=f.position),Xe(f,H,m,!0,le)&&(je?pe=f.result:Ie=f.result),je||(Se(f,te,oe,ue,pe,Ie,ee,F,I),ue=pe=Ie=null),Qe(f,!0,-1),$e=f.input.charCodeAt(f.position)),(f.line===pt||f.lineIndent>H)&&$e!==0)V(f,"bad indentation of a mapping entry");else if(f.lineIndent<H)break}return je&&Se(f,te,oe,ue,pe,null,ee,F,I),Ne&&(f.tag=G,f.anchor=ie,f.kind="mapping",f.result=te),Ne}function fe(f){let H=!1,Z=!1,le,ee,F=f.input.charCodeAt(f.position);if(F!==33)return!1;f.tag!==null&&V(f,"duplication of a tag property"),F=f.input.charCodeAt(++f.position),F===60?(H=!0,F=f.input.charCodeAt(++f.position)):F===33?(Z=!0,le="!!",F=f.input.charCodeAt(++f.position)):le="!";let I=f.position;if(H){do F=f.input.charCodeAt(++f.position);while(F!==0&&F!==62);f.position<f.length?(ee=f.input.slice(I,f.position),F=f.input.charCodeAt(++f.position)):V(f,"unexpected end of the stream within a verbatim tag")}else{for(;F!==0&&!j(F);)F===33&&(Z?V(f,"tag suffix cannot contain exclamation marks"):(le=f.input.slice(I-1,f.position+1),R.test(le)||V(f,"named tag handle cannot contain such characters"),Z=!0,I=f.position+1)),F=f.input.charCodeAt(++f.position);ee=f.input.slice(I,f.position),_.test(ee)&&V(f,"tag suffix cannot contain flow indicator characters")}ee&&!M.test(ee)&&V(f,"tag name cannot contain such characters: "+ee);try{ee=decodeURIComponent(ee)}catch{V(f,"tag name is malformed: "+ee)}return H?f.tag=ee:o.call(f.tagMap,le)?f.tag=f.tagMap[le]+ee:le==="!"?f.tag="!"+ee:le==="!!"?f.tag="tag:yaml.org,2002:"+ee:V(f,'undeclared tag handle "'+le+'"'),!0}function Me(f){let H=f.input.charCodeAt(f.position);if(H!==38)return!1;f.anchor!==null&&V(f,"duplication of an anchor property"),H=f.input.charCodeAt(++f.position);const Z=f.position;for(;H!==0&&!j(H)&&!k(H);)H=f.input.charCodeAt(++f.position);return f.position===Z&&V(f,"name of an anchor node must contain at least one character"),f.anchor=f.input.slice(Z,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 Z=f.position;for(;H!==0&&!j(H)&&!k(H);)H=f.input.charCodeAt(++f.position);f.position===Z&&V(f,"name of an alias node must contain at least one character");const le=f.input.slice(Z,f.position);return o.call(f.anchorMap,le)||V(f,'unidentified alias "'+le+'"'),f.result=f.anchorMap[le],Qe(f,!0,-1),!0}function et(f,H,Z,le){const ee=ge(f);return ce(f),xe(f,H),f.tag=null,f.anchor=null,f.kind=null,f.result=null,X(f,Z,le)&&f.kind==="mapping"?(ye(f),!0):(ne(f),xe(f,ee),!1)}function Xe(f,H,Z,le,ee){let F,I,G=1,ie=!1,te=!1,oe=null,ue,pe,Ie;f.depth>=f.maxDepth&&V(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 je=F=I=m===Z||l===Z;if(le&&Qe(f,!0,-1)&&(ie=!0,f.lineIndent>H?G=1:f.lineIndent===H?G=0:f.lineIndent<H&&(G=-1)),G===1)for(;;){const Ne=f.input.charCodeAt(f.position),$e=ge(f);if(ie&&(Ne===33&&f.tag!==null||Ne===38&&f.anchor!==null)||!fe(f)&&!Me(f))break;oe===null&&(oe=$e),Qe(f,!0,-1)?(ie=!0,I=je,f.lineIndent>H?G=1:f.lineIndent===H?G=0:f.lineIndent<H&&(G=-1)):I=!1}if(I&&(I=ie||ee),G===1||m===Z)if(i===Z||s===Z?pe=H:pe=H+1,Ie=f.position-f.lineStart,G===1)if(I&&(z(f,Ie)||X(f,Ie,pe))||L(f,pe))te=!0;else{const Ne=f.input.charCodeAt(f.position);oe!==null&&je&&!I&&Ne!==124&&Ne!==62&&et(f,oe,oe.position-oe.lineStart,pe)||F&&O(f,pe)||Ze(f,pe)||He(f,pe)?te=!0:Le(f)?(te=!0,(f.tag!==null||f.anchor!==null)&&V(f,"alias node should not have any properties")):qe(f,pe,i===Z)&&(te=!0,f.tag===null&&(f.tag="?")),f.anchor!==null&&be(f,f.anchor,f.result)}else G===0&&(te=I&&z(f,Ie));if(f.tag===null)f.anchor!==null&&be(f,f.anchor,f.result);else if(f.tag==="?"){f.result!==null&&f.kind!=="scalar"&&V(f,'unacceptable node kind for !<?> tag; it should be "scalar", not "'+f.kind+'"');for(let Ne=0,$e=f.implicitTypes.length;Ne<$e;Ne+=1)if(ue=f.implicitTypes[Ne],ue.resolve(f.result)){f.result=ue.construct(f.result),f.tag=ue.tag,f.anchor!==null&&be(f,f.anchor,f.result);break}}else if(f.tag!=="!"){if(o.call(f.typeMap[f.kind||"fallback"],f.tag))ue=f.typeMap[f.kind||"fallback"][f.tag];else{ue=null;const Ne=f.typeMap.multi[f.kind||"fallback"];for(let $e=0,at=Ne.length;$e<at;$e+=1)if(f.tag.slice(0,Ne[$e].tag.length)===Ne[$e].tag){ue=Ne[$e];break}}ue||V(f,"unknown tag !<"+f.tag+">"),f.result!==null&&ue.kind!==f.kind&&V(f,"unacceptable node kind for !<"+f.tag+'> tag; it should be "'+ue.kind+'", not "'+f.kind+'"'),ue.resolve(f.result,f.tag)?(f.result=ue.construct(f.result,f.tag),f.anchor!==null&&be(f,f.anchor,f.result)):V(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||te}function st(f){const H=f.position;let Z=!1,le;for(f.version=null,f.checkLineBreaks=f.legacy,f.tagMap=Object.create(null),f.anchorMap=Object.create(null);(le=f.input.charCodeAt(f.position))!==0&&(Qe(f,!0,-1),le=f.input.charCodeAt(f.position),!(f.lineIndent>0||le!==37));){Z=!0,le=f.input.charCodeAt(++f.position);let ee=f.position;for(;le!==0&&!j(le);)le=f.input.charCodeAt(++f.position);const F=f.input.slice(ee,f.position),I=[];for(F.length<1&&V(f,"directive name must not be less than one character in length");le!==0;){for(;$(le);)le=f.input.charCodeAt(++f.position);if(le===35){do le=f.input.charCodeAt(++f.position);while(le!==0&&!N(le));break}if(N(le))break;for(ee=f.position;le!==0&&!j(le);)le=f.input.charCodeAt(++f.position);I.push(f.input.slice(ee,f.position))}le!==0&&ze(f),o.call(De,F)?De[F](f,F,I):Re(f,'unknown document directive "'+F+'"')}if(Qe(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,Qe(f,!0,-1)):Z&&V(f,"directives end mark is expected"),Xe(f,f.lineIndent-1,m,!1,!0),Qe(f,!0,-1),f.checkLineBreaks&&w.test(f.input.slice(H,f.position))&&Re(f,"non-ASCII line breaks are interpreted as content"),f.documents.push(f.result),f.position===f.lineStart&&We(f)){f.input.charCodeAt(f.position)===46&&(f.position+=3,Qe(f,!0,-1));return}f.position<f.length-1&&V(f,"end of the stream or a document separator is expected")}function mt(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 Z=new Te(f,H),le=f.indexOf("\0");for(le!==-1&&(Z.position=le,V(Z,"null byte is not allowed in input")),Z.input+="\0";Z.input.charCodeAt(Z.position)===32;)Z.lineIndent+=1,Z.position+=1;for(;Z.position<Z.length-1;)st(Z);return Z.documents}function Oe(f,H,Z){H!==null&&typeof H=="object"&&typeof Z>"u"&&(Z=H,H=null);const le=mt(f,Z);if(typeof H!="function")return le;for(let ee=0,F=le.length;ee<F;ee+=1)H(le[ee])}function Ge(f,H){const Z=mt(f,H);if(Z.length!==0){if(Z.length===1)return Z[0];throw new t("expected a single document in the stream, but found more")}}return Vc.loadAll=Oe,Vc.load=Ge,Vc}var Pp={},Gb;function wj(){if(Gb)return Pp;Gb=1;const e=nc(),t=ac(),n=Fh(),a=Object.prototype.toString,o=Object.prototype.hasOwnProperty,i=65279,s=9,l=10,m=13,d=32,h=33,v=34,y=35,w=37,_=38,R=39,M=42,C=44,N=45,$=58,j=61,k=62,P=63,T=64,U=91,B=93,D=96,W=123,se=124,me=125,Te={};Te[0]="\\0",Te[7]="\\a",Te[8]="\\b",Te[9]="\\t",Te[10]="\\n",Te[11]="\\v",Te[12]="\\f",Te[13]="\\r",Te[27]="\\e",Te[34]='\\"',Te[92]="\\\\",Te[133]="\\N",Te[160]="\\_",Te[8232]="\\L",Te[8233]="\\P";const ke=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"],V=/^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;function Re(I,G){if(G===null)return{};const ie={},te=Object.keys(G);for(let oe=0,ue=te.length;oe<ue;oe+=1){let pe=te[oe],Ie=String(G[pe]);pe.slice(0,2)==="!!"&&(pe="tag:yaml.org,2002:"+pe.slice(2));const je=I.compiledTypeMap.fallback[pe];je&&o.call(je.styleAliases,Ie)&&(Ie=je.styleAliases[Ie]),ie[pe]=Ie}return ie}function be(I){let G,ie;const te=I.toString(16).toUpperCase();if(I<=255)G="x",ie=2;else if(I<=65535)G="u",ie=4;else if(I<=4294967295)G="U",ie=8;else throw new t("code point within a string may not be greater than 0xFFFFFFFF");return"\\"+G+e.repeat("0",ie-te.length)+te}const ce=1,ye=2;function ne(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=Re(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==='"'?ye:ce,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 ge(I,G){const ie=e.repeat(" ",G);let te=0,oe="";const ue=I.length;for(;te<ue;){let pe;const Ie=I.indexOf(`
|
|
83
|
+
`,te);Ie===-1?(pe=I.slice(te),te=ue):(pe=I.slice(te,Ie+1),te=Ie+1),pe.length&&pe!==`
|
|
84
|
+
`&&(oe+=ie),oe+=pe}return oe}function xe(I,G){return`
|
|
85
|
+
`+e.repeat(" ",I.indent*G)}function De(I,G){for(let ie=0,te=I.implicitTypes.length;ie<te;ie+=1)if(I.implicitTypes[ie].resolve(G))return!0;return!1}function we(I){return I===d||I===s}function ae(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 ae(I)&&I!==i&&I!==m&&I!==l}function ze(I,G,ie){const te=Se(I),oe=te&&!we(I);return(ie?te:te&&I!==C&&I!==U&&I!==B&&I!==W&&I!==me)&&I!==y&&!(G===$&&!oe)||Se(G)&&!we(G)&&I===y||G===$&&oe}function Qe(I){return ae(I)&&I!==i&&!we(I)&&I!==N&&I!==P&&I!==$&&I!==C&&I!==U&&I!==B&&I!==W&&I!==me&&I!==y&&I!==_&&I!==M&&I!==h&&I!==se&&I!==j&&I!==k&&I!==R&&I!==v&&I!==w&&I!==T&&I!==D}function We(I){return!we(I)&&I!==$}function nt(I,G){const ie=I.charCodeAt(G);let te;return ie>=55296&&ie<=56319&&G+1<I.length&&(te=I.charCodeAt(G+1),te>=56320&&te<=57343)?(ie-55296)*1024+te-56320+65536:ie}function qe(I){return/^\n* /.test(I)}const Ze=1,He=2,L=3,O=4,z=5;function X(I,G,ie,te,oe,ue,pe,Ie){let je,Ne=0,$e=null,at=!1,pt=!1;const sn=te!==-1;let At=-1,nn=Qe(nt(I,0))&&We(nt(I,I.length-1));if(G||pe)for(je=0;je<I.length;Ne>=65536?je+=2:je++){if(Ne=nt(I,je),!ae(Ne))return z;nn=nn&&ze(Ne,$e,Ie),$e=Ne}else{for(je=0;je<I.length;Ne>=65536?je+=2:je++){if(Ne=nt(I,je),Ne===l)at=!0,sn&&(pt=pt||je-At-1>te&&I[At+1]!==" ",At=je);else if(!ae(Ne))return z;nn=nn&&ze(Ne,$e,Ie),$e=Ne}pt=pt||sn&&je-At-1>te&&I[At+1]!==" "}return!at&&!pt?nn&&!pe&&!oe(I)?Ze:ue===ye?z:He:ie>9&&qe(I)?z:pe?ue===ye?z:He:pt?O:L}function fe(I,G,ie,te,oe){I.dump=(function(){if(G.length===0)return I.quotingType===ye?'""':"''";if(!I.noCompatMode&&(ke.indexOf(G)!==-1||V.test(G)))return I.quotingType===ye?'"'+G+'"':"'"+G+"'";const ue=I.indent*Math.max(1,ie),pe=I.lineWidth===-1?-1:Math.max(Math.min(I.lineWidth,40),I.lineWidth-ue),Ie=te||I.flowLevel>-1&&ie>=I.flowLevel;function je(Ne){return De(I,Ne)}switch(X(G,Ie,I.indent,pe,je,I.quotingType,I.forceQuotes&&!te,oe)){case Ze:return G;case He:return"'"+G.replace(/'/g,"''")+"'";case L:return"|"+Me(G,I.indent)+Le(ge(G,ue));case O:return">"+Me(G,I.indent)+Le(ge(et(G,pe),ue));case z:return'"'+st(G)+'"';default:throw new t("impossible error: invalid scalar style")}})()}function Me(I,G){const ie=qe(I)?String(G):"",te=I[I.length-1]===`
|
|
86
|
+
`,ue=te&&(I[I.length-2]===`
|
|
87
|
+
`||I===`
|
|
88
|
+
`)?"+":te?"":"-";return ie+ue+`
|
|
89
|
+
`}function Le(I){return I[I.length-1]===`
|
|
90
|
+
`?I.slice(0,-1):I}function et(I,G){const ie=/(\n+)([^\n]*)/g;let te=(function(){let Ie=I.indexOf(`
|
|
91
|
+
`);return Ie=Ie!==-1?Ie:I.length,ie.lastIndex=Ie,Xe(I.slice(0,Ie),G)})(),oe=I[0]===`
|
|
92
|
+
`||I[0]===" ",ue,pe;for(;pe=ie.exec(I);){const Ie=pe[1],je=pe[2];ue=je[0]===" ",te+=Ie+(!oe&&!ue&&je!==""?`
|
|
93
|
+
`:"")+Xe(je,G),oe=ue}return te}function Xe(I,G){if(I===""||I[0]===" ")return I;const ie=/ [^ ]/g;let te,oe=0,ue,pe=0,Ie=0,je="";for(;te=ie.exec(I);)Ie=te.index,Ie-oe>G&&(ue=pe>oe?pe:Ie,je+=`
|
|
94
|
+
`+I.slice(oe,ue),oe=ue+1),pe=Ie;return je+=`
|
|
95
|
+
`,I.length-oe>G&&pe>oe?je+=I.slice(oe,pe)+`
|
|
96
|
+
`+I.slice(pe+1):je+=I.slice(oe),je.slice(1)}function st(I){let G="",ie=0;for(let te=0;te<I.length;ie>=65536?te+=2:te++){ie=nt(I,te);const oe=Te[ie];!oe&&ae(ie)?(G+=I[te],ie>=65536&&(G+=I[te+1])):G+=oe||be(ie)}return G}function mt(I,G,ie){let te="";const oe=I.tag;for(let ue=0,pe=ie.length;ue<pe;ue+=1){let Ie=ie[ue];I.replacer&&(Ie=I.replacer.call(ie,String(ue),Ie)),(Z(I,G,Ie,!1,!1)||typeof Ie>"u"&&Z(I,G,null,!1,!1))&&(te!==""&&(te+=","+(I.condenseFlow?"":" ")),te+=I.dump)}I.tag=oe,I.dump="["+te+"]"}function Oe(I,G,ie,te){let oe="";const ue=I.tag;for(let pe=0,Ie=ie.length;pe<Ie;pe+=1){let je=ie[pe];I.replacer&&(je=I.replacer.call(ie,String(pe),je)),(Z(I,G+1,je,!0,!0,!1,!0)||typeof je>"u"&&Z(I,G+1,null,!0,!0,!1,!0))&&((!te||oe!=="")&&(oe+=xe(I,G)),I.dump&&l===I.dump.charCodeAt(0)?oe+="-":oe+="- ",oe+=I.dump)}I.tag=ue,I.dump=oe||"[]"}function Ge(I,G,ie){let te="";const oe=I.tag,ue=Object.keys(ie);for(let pe=0,Ie=ue.length;pe<Ie;pe+=1){let je="";te!==""&&(je+=", "),I.condenseFlow&&(je+='"');const Ne=ue[pe];let $e=ie[Ne];I.replacer&&($e=I.replacer.call(ie,Ne,$e)),Z(I,G,Ne,!1,!1)&&(I.dump.length>1024&&(je+="? "),je+=I.dump+(I.condenseFlow?'"':"")+":"+(I.condenseFlow?"":" "),Z(I,G,$e,!1,!1)&&(je+=I.dump,te+=je))}I.tag=oe,I.dump="{"+te+"}"}function f(I,G,ie,te){let oe="";const ue=I.tag,pe=Object.keys(ie);if(I.sortKeys===!0)pe.sort();else if(typeof I.sortKeys=="function")pe.sort(I.sortKeys);else if(I.sortKeys)throw new t("sortKeys must be a boolean or a function");for(let Ie=0,je=pe.length;Ie<je;Ie+=1){let Ne="";(!te||oe!=="")&&(Ne+=xe(I,G));const $e=pe[Ie];let at=ie[$e];if(I.replacer&&(at=I.replacer.call(ie,$e,at)),!Z(I,G+1,$e,!0,!0,!0))continue;const pt=I.tag!==null&&I.tag!=="?"||I.dump&&I.dump.length>1024;pt&&(I.dump&&l===I.dump.charCodeAt(0)?Ne+="?":Ne+="? "),Ne+=I.dump,pt&&(Ne+=xe(I,G)),Z(I,G+1,at,!0,pt)&&(I.dump&&l===I.dump.charCodeAt(0)?Ne+=":":Ne+=": ",Ne+=I.dump,oe+=Ne)}I.tag=ue,I.dump=oe||"{}"}function H(I,G,ie){const te=ie?I.explicitTypes:I.implicitTypes;for(let oe=0,ue=te.length;oe<ue;oe+=1){const pe=te[oe];if((pe.instanceOf||pe.predicate)&&(!pe.instanceOf||typeof G=="object"&&G instanceof pe.instanceOf)&&(!pe.predicate||pe.predicate(G))){if(ie?pe.multi&&pe.representName?I.tag=pe.representName(G):I.tag=pe.tag:I.tag="?",pe.represent){const Ie=I.styleMap[pe.tag]||pe.defaultStyle;let je;if(a.call(pe.represent)==="[object Function]")je=pe.represent(G,Ie);else if(o.call(pe.represent,Ie))je=pe.represent[Ie](G,Ie);else throw new t("!<"+pe.tag+'> tag resolver accepts not "'+Ie+'" style');I.dump=je}return!0}}return!1}function Z(I,G,ie,te,oe,ue,pe){I.tag=null,I.dump=ie,H(I,ie,!1)||H(I,ie,!0);const Ie=a.call(I.dump),je=te;te&&(te=I.flowLevel<0||I.flowLevel>G);const Ne=Ie==="[object Object]"||Ie==="[object Array]";let $e,at;if(Ne&&($e=I.duplicates.indexOf(ie),at=$e!==-1),(I.tag!==null&&I.tag!=="?"||at||I.indent!==2&&G>0)&&(oe=!1),at&&I.usedDuplicates[$e])I.dump="*ref_"+$e;else{if(Ne&&at&&!I.usedDuplicates[$e]&&(I.usedDuplicates[$e]=!0),Ie==="[object Object]")te&&Object.keys(I.dump).length!==0?(f(I,G,I.dump,oe),at&&(I.dump="&ref_"+$e+I.dump)):(Ge(I,G,I.dump),at&&(I.dump="&ref_"+$e+" "+I.dump));else if(Ie==="[object Array]")te&&I.dump.length!==0?(I.noArrayIndent&&!pe&&G>0?Oe(I,G-1,I.dump,oe):Oe(I,G,I.dump,oe),at&&(I.dump="&ref_"+$e+I.dump)):(mt(I,G,I.dump),at&&(I.dump="&ref_"+$e+" "+I.dump));else if(Ie==="[object String]")I.tag!=="?"&&fe(I,I.dump,G,ue,je);else{if(Ie==="[object Undefined]")return!1;if(I.skipInvalid)return!1;throw new t("unacceptable kind of an object to dump "+Ie)}if(I.tag!==null&&I.tag!=="?"){let pt=encodeURI(I.tag[0]==="!"?I.tag.slice(1):I.tag).replace(/!/g,"%21");I.tag[0]==="!"?pt="!"+pt:pt.slice(0,18)==="tag:yaml.org,2002:"?pt="!!"+pt.slice(18):pt="!<"+pt+">",I.dump=pt+" "+I.dump}}return!0}function le(I,G){const ie=[],te=[];ee(I,ie,te);const oe=te.length;for(let ue=0;ue<oe;ue+=1)G.duplicates.push(ie[te[ue]]);G.usedDuplicates=new Array(oe)}function ee(I,G,ie){if(I!==null&&typeof I=="object"){const te=G.indexOf(I);if(te!==-1)ie.indexOf(te)===-1&&ie.push(te);else if(G.push(I),Array.isArray(I))for(let oe=0,ue=I.length;oe<ue;oe+=1)ee(I[oe],G,ie);else{const oe=Object.keys(I);for(let ue=0,pe=oe.length;ue<pe;ue+=1)ee(I[oe[ue]],G,ie)}}}function F(I,G){G=G||{};const ie=new ne(G);ie.noRefs||le(I,ie);let te=I;return ie.replacer&&(te=ie.replacer.call({"":te},"",te)),Z(ie,0,te,!0,!0)?ie.dump+`
|
|
97
|
+
`:""}return Pp.dump=F,Pp}var Zb;function Ij(){if(Zb)return jn;Zb=1;const e=kj(),t=wj();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 jn.Type=Bn(),jn.Schema=Hx(),jn.FAILSAFE_SCHEMA=Fx(),jn.JSON_SCHEMA=Zx(),jn.CORE_SCHEMA=Jx(),jn.DEFAULT_SCHEMA=Fh(),jn.load=e.load,jn.loadAll=e.loadAll,jn.dump=t.dump,jn.YAMLException=ac(),jn.types={binary:Xx(),float:Gx(),map:Bx(),null:Vx(),pairs:tk(),set:nk(),timestamp:Yx(),bool:Kx(),int:Wx(),merge:Qx(),omap:ek(),seq:qx(),str:zx()},jn.safeLoad=n("safeLoad","load"),jn.safeLoadAll=n("safeLoadAll","loadAll"),jn.safeDump=n("safeDump","dump"),jn}var _j=Ij();const Cj=Sj(_j),{Type:PY,Schema:AY,FAILSAFE_SCHEMA:TY,JSON_SCHEMA:EY,CORE_SCHEMA:MY,DEFAULT_SCHEMA:jY,load:OY,loadAll:$Y,dump:NY,YAMLException:DY,types:LY,safeLoad:UY,safeLoadAll:HY,safeDump:zY}=Cj,Vh=3e3,Kh=9999,qY="openpond.yaml",Rj=["google","github","x"],Wh=new Set([22,2222,2375,2376,3108,5900,5901,6080,7818]),Jb=p(r().trim().min(1).max(1e3)).max(50),$l=r().trim().min(1).max(4096).refine(ik,{message:"path must be a relative workspace path"}),Pj=r().trim().min(1).max(500).refine(e=>!e.includes("\0")&&!/\s/.test(e),"image ref must be a single OCI reference"),Aj=r().trim().regex(/^sha256:[0-9a-f]{64}$/i),ak=r().trim().min(1).max(500).refine(e=>e.startsWith("/")&&!e.includes("\0"),"workspaceRoot must be an absolute guest path"),Tj=c({ref:Pj,digest:Aj.optional(),registrySecretRef:r().trim().min(1).max(500).optional(),platform:S("linux/amd64").optional(),workspaceRoot:ak.optional()}).strict(),Ej=c({context:$l.default("."),path:$l.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:ak.optional()}).strict(),Mj=c({base:r().trim().min(1).max(120).optional(),snapshot:r().trim().min(1).max(191).optional(),image:Tj.optional(),dockerfile:Ej.optional()}).strict().superRefine((e,t)=>{[e.base,e.snapshot,e.image,e.dockerfile].filter(Boolean).length!==1&&t.addIssue({code:qn.custom,message:"runtime must declare exactly one of base, snapshot, image, or dockerfile"})}),ok=c({cpu:u().positive().max(8).optional(),memoryGb:u().positive().max(32).optional(),diskGb:u().positive().max(100).optional()}).strict(),jj=c({provider:b(Rj),scopes:p(r().trim().min(1).max(200)).max(100).default([]),capabilities:p(r().trim().min(1).max(200)).max(100).default([])}).strict(),Oj=c({models:p(r().trim().min(1).max(200)).max(100).default([]),scopes:p(r().trim().min(1).max(200)).max(100).default([])}).strict(),$j=c({opchat:Oj.optional()}).catchall(re(r(),de())).default({}),Nj=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(),Dj=c({port:u().int().min(Vh).max(Kh).refine(e=>!Wh.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(),rk=c({command:r().trim().min(1).max(1e3),cwd:$l.optional(),timeoutSeconds:u().int().positive().max(86400).optional(),requiresStart:A().default(!1),ports:p(Dj).max(20).default([]),artifactPaths:p($l).max(100).default([])}).strict(),Yb=rk.extend({name:r().trim().min(1).max(80)}).strict(),Lj=c({name:r().trim().min(1).max(80).optional(),service:r().trim().min(1).max(80).optional(),port:u().int().min(Vh).max(Kh).refine(e=>!Wh.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(),Uj=c({name:r().trim().min(1).max(80).optional(),port:u().int().min(Vh).max(Kh).refine(e=>!Wh.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(),Hj=re(r(),de()).refine(e=>e.type==="object","input schema must be a JSON schema object"),zj=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(),Ap=r().trim().min(1).max(120),qj=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:Ap.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:Ap.optional(),endAt:Ap.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:ok.optional(),quotas:re(r(),de()).optional(),lifecycle:re(r(),de()).optional(),retentionPolicy:re(r(),de()).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(),de())).max(20).optional(),metadata:re(r(),de()).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:qn.custom,path:["scheduleExpression"],message:"schedule must declare exactly one of cron, rate, once, or scheduleExpression"}),e.scheduleExpression&&!e.scheduleType&&t.addIssue({code:qn.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:qn.custom,path:["action"],message:"schedule action target is required"}),s==="service"&&!o&&t.addIssue({code:qn.custom,path:["target","name"],message:"schedule service target name is required"}),s==="command"&&!a&&t.addIssue({code:qn.custom,path:["command"],message:"schedule command target is required"})}),Bj=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:Mj,resources:ok.optional(),setup:c({commands:Jb.default([])}).strict().default({commands:[]}),validation:c({commands:Jb.min(1),probes:p(Uj).max(20).default([])}).strict(),start:rk,actions:p(Yb).max(20).default([]),services:p(Yb).max(20).default([]),schedules:p(qj).max(20).default([]),mcp:c({endpoints:p(Lj).max(10).default([])}).strict().default({endpoints:[]}),volumes:p(Nj).max(5).default([]),integrations:c({requiredLeases:p(jj).max(20).default([])}).strict().default({requiredLeases:[]}),permissions:$j,inputs:c({schema:Hj.default({type:"object"}),env:p(zj).max(100).default([])}).strict().default({schema:{type:"object"},env:[]}),artifacts:c({paths:p($l).max(100).default([])}).strict().default({paths:[]}),network:c({egress:b(["restricted","allow","block"]).default("restricted")}).strict().default({egress:"restricted"})}).strict().superRefine((e,t)=>{Vj(e,t),Gh(t,e.volumes.flatMap(n=>n.name?[n.name]:[]),"volume names must be unique","volumes"),Kj(e,t),Wj(e,t),Gj(e,t),Zj(e,t)}),Fj=c({path:r(),message:r(),code:r()});function BY(e){return[{kind:"start",name:"start",...e.start,artifactPaths:Ep(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:Ep(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:Ep(t,e)}))]}function ik(e){return!e.includes("\0")&&!e.startsWith("/")&&!e.split(/[\\/]+/).some(t=>t===".."||t==="")}function Gh(e,t,n,a){const o=new Set;for(const i of t){if(o.has(i)){e.addIssue({code:qn.custom,path:[a],message:n});return}o.add(i)}}function Vj(e,t){const n=["start",...e.actions.map(a=>a.name),...e.services.map(a=>a.name)];Gh(t,n,"start, action, and service names must be unique","actions")}function Kj(e,t){const n=Tp(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=Tp(i),l=Tp(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(!ik(d)){t.addIssue({code:qn.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:qn.custom,path:["inputs","schema","properties",o,"x-openpond-upload","targetPath"],message:"upload target references an undeclared volume"})}}function Wj(e,t){Gh(t,e.inputs.env.map(n=>n.name),"env input names must be unique","inputs")}function Gj(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:qn.custom,path:["mcp","endpoints",o,"service"],message:`app MCP service does not exist: ${i.service}`});continue}s.has(i.port)||t.addIssue({code:qn.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:qn.custom,path:["mcp","endpoints",o,"port"],message:`app MCP port ${i.port} is not declared on start or services`})}}function Zj(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:qn.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:qn.custom,path:["schedules",o,"target","name"],message:`schedule service target does not exist: ${m}`})}}}function Tp(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Ep(e,t){return e.artifactPaths.length>0?e.artifactPaths:t.artifacts.paths}const Jj=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:de().optional()}).passthrough(),Yj=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(Jj).optional().default([]),truncated:A().optional()}).passthrough(),Mp=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(),Qj=c({schemaVersion:S(1),source:S("openpond.yaml"),manifestName:r(),manifestVersion:r(),manifestUseCase:r(),manifestDescription:r(),manifestPath:r(),manifestHash:r(),inputSchema:re(r(),de()).default({}),env:p(c({name:r(),required:A(),secret:A(),description:r().nullable()}).passthrough()).default([]),start:Mp,actions:p(Mp).default([]),services:p(Mp).default([]),defaultActionName:r().nullable(),updatedAt:r()}).passthrough(),Xj=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:Qj.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:Yj.nullable().optional()}),eO=c({detected:A(),rootPath:r(),manifestPath:r(),manifestHash:r().nullable().optional().default(null),manifest:re(r(),de()).nullable().optional().default(null),normalizedManifest:Bj.nullable().optional().default(null),valid:A().optional().default(!1),diagnostics:p(Fj).optional().default([])}),tO=c({appId:r(),appName:r(),gitOwner:r().nullable(),gitRepo:r().nullable(),gitHost:r().nullable(),defaultBranch:r().nullable(),linkedAt:r()}),sk=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()}),nO=b(["github_repo","internal_repo","template","manual"]),aO=c({id:r(),teamId:r(),name:r(),slug:r().nullable().optional().default(null),sourceType:nO.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)}),oO=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:eO.nullable().optional().default(null),linkedOpenPondApp:tO.nullable().optional().default(null),linkedSandboxProject:sk.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:sk.nullable().optional(),preferredSandboxAgentId:r().nullable().optional(),hiddenFromDefaultSidebar:A().optional()});const rO=["connected_app_search","connected_app_read","connected_app_write"],jp="https://openpond.ai",Zh=["slack","google","github","turnkey","x","microsoft_teams","mcp"],Jh={slack:[Ft("slack.channel.bind","Bind channels","Bind Slack channels or threads to OpenPond profiles.","setup",!1),Ft("slack.message.ingest","Ingest messages","Ingest Slack channel or thread activity into OpenPond context.","setup",!1)],microsoft_teams:[Ft("microsoft_teams.channel.bind","Bind channels","Bind Teams channels or chats to OpenPond profiles.","setup",!1),Ft("microsoft_teams.message.ingest","Ingest messages","Ingest Teams channel or chat activity into OpenPond context.","setup",!1)],google:[Ft("google.drive.file.read","Read Drive files","Find and read Google Drive files.","read",!0),Ft("google.drive.file.write","Write Drive files","Create or update approved Google Drive files.","write",!0),Ft("google.docs.read","Read Docs","Read Google Docs content and structure.","read",!0),Ft("google.docs.write","Edit Docs","Apply approved Google Docs edits.","write",!0),Ft("google.comments.read","Read comments","Read Google file comments.","read",!0),Ft("google.comments.write","Write comments","Create or resolve approved Google comments.","write",!0)],github:[Ft("github.repo.read","Read repositories","Read repository metadata and file context.","read",!0),Ft("github.issue.read","Read issues","Read GitHub issues and comments.","read",!0),Ft("github.issue.write","Update issues","Create or update approved GitHub issue content.","write",!0),Ft("github.pull_request.read","Read pull requests","Read pull request metadata, diffs, checks, and reviews.","read",!0),Ft("github.pull_request.write","Update pull requests","Create approved comments or pull request updates.","write",!0)],turnkey:[Ft("turnkey.wallets.read","Read Agent Wallet","Read the connected OpenPond Agent Wallet address and metadata.","read",!0),Ft("turnkey.balances.read","Read wallet balances","Read balances for the connected OpenPond Agent Wallet.","read",!0),Ft("turnkey.activities.read","Read wallet activity","Read recent Turnkey activity for the connected OpenPond Agent Wallet.","read",!0)],x:[Ft("x.profile.read","Read profile","Read the connected X profile.","read",!0),Ft("x.search.read","Search X","Search public X posts when granted.","read",!0),Ft("x.mentions.read","Read mentions","Read mentions for the connected X account.","read",!0),Ft("x.post.write","Post","Create approved X posts.","write",!0),Ft("x.reply.write","Reply","Create approved X replies.","write",!0)],mcp:[Ft("mcp.tool.discover","Discover tools","Discover team-scoped MCP tools.","tooling",!1),Ft("mcp.tool.call","Call tools","Call approved MCP tools through the team endpoint.","tooling",!1)]},Yh={slack:[],microsoft_teams:[],google:[Dt("google.drive.search","search","Search Drive","Search Google Drive files by grounded query.",["google.drive.file.read"]),Dt("google.drive.read_file","read","Read Drive file","Read Drive file metadata or exported content by stable ref.",["google.drive.file.read"],{requiredKeys:["ref"]}),Dt("google.docs.read","read","Read Google Doc","Read Google Docs content and structure by stable ref.",["google.docs.read"],{requiredKeys:["ref"]}),Dt("google.comments.read","read","Read comments","Read comments for a grounded Google file ref.",["google.comments.read"],{requiredKeys:["ref"]}),Dt("google.docs.update","write","Update Google Doc","Apply an explicitly approved Google Docs edit and return readback verification.",["google.docs.write"],{requiredKeys:["ref","patch"]}),Dt("google.comments.create","write","Create comment","Create an explicitly approved Google file comment and return readback verification.",["google.comments.write"],{requiredKeys:["ref","body"]}),Dt("google.comments.resolve","write","Resolve comment","Resolve an explicitly approved Google comment and return readback verification.",["google.comments.write"],{requiredKeys:["ref","commentId"]})],github:[Dt("github.repo.search","search","Search repositories","Search accessible repositories by owner, name, or topic.",["github.repo.read"]),Dt("github.issue.search","search","Search issues","Search accessible GitHub issues.",["github.issue.read"]),Dt("github.pull_request.search","search","Search pull requests","Search accessible GitHub pull requests.",["github.pull_request.read"]),Dt("github.repo.read","read","Read repository","Read grounded repository metadata or file context.",["github.repo.read"],{requiredKeys:["ref"]}),Dt("github.issue.read","read","Read issue","Read a grounded GitHub issue and comments.",["github.issue.read"],{requiredKeys:["ref"]}),Dt("github.pull_request.read","read","Read pull request","Read a grounded pull request, checks, reviews, or diff summary.",["github.pull_request.read"],{requiredKeys:["ref"]}),Dt("github.issue.create","write","Create issue","Create an explicitly approved GitHub issue and return readback verification.",["github.issue.write"],{requiredKeys:["repo","title","body"]}),Dt("github.issue.comment","write","Comment on issue","Create an explicitly approved GitHub issue comment and return readback verification.",["github.issue.write"],{requiredKeys:["ref","body"]}),Dt("github.issue.update","write","Update issue","Apply an explicitly approved issue metadata/content update and return readback verification.",["github.issue.write"],{requiredKeys:["ref"]}),Dt("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"]}),Dt("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:[Dt("turnkey.wallets.read","read","Read Agent Wallet","Read the address and metadata for the connected OpenPond Agent Wallet.",["turnkey.wallets.read"]),Dt("turnkey.balances.read","read","Read wallet balances","Read supported-network balances for the connected OpenPond Agent Wallet.",["turnkey.balances.read"]),Dt("turnkey.activities.read","read","Read wallet activity","Read recent Turnkey activity for the connected OpenPond Agent Wallet.",["turnkey.activities.read"])],x:[Dt("x.profile.read","read","Read profile","Read the connected X account profile.",["x.profile.read"]),Dt("x.post.read","read","Read post","Read a public X post by stable ref, status URL, or post id.",["x.search.read"],{requiredKeys:["ref"]}),Dt("x.search.posts","search","Search recent posts","Search public X posts from the X recent-search window by grounded query.",["x.search.read"]),Dt("x.mentions.search","search","Search mentions","Search mentions for the connected X account.",["x.mentions.read"]),Dt("x.mention.read","read","Read mention","Read a grounded mention or post ref.",["x.mentions.read"],{requiredKeys:["ref"]}),Dt("x.post.create","write","Create post","Create an explicitly approved X post and return readback verification.",["x.post.write"],{requiredKeys:["text"]}),Dt("x.reply.create","write","Create reply","Create an explicitly approved X reply and return readback verification.",["x.reply.write"],{requiredKeys:["inReplyToRef","text"]})],mcp:[]},iO={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
|
+
`)},FY=Zh.map(e=>{const t=ck(e),n=iO[e];return{...t,provider:e,body:n,sourceHash:`connected-app-skill:${e}:${CO(n)}`,charCount:n.length}});function sO(e){const t=Qh(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=xO(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=cO(e);return s.ok?{ok:!0,request:e}:s}function lO(e){const t=uu(e);return t?Yh[t]:[]}function cO(e){const t=pO(e.args),n=lO(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=hO(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 dO=[{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"}],du=dO,uO=Zh.map(e=>{const t=du.filter(a=>a.providerFamily===e),n=t[0];return{id:e,label:Il(e),shortLabel:n.shortLabel,category:n.category,icon:n.icon,description:n.description,setupSurfaces:t,capabilities:Jh[e],skills:yO(e),tools:SO(e),operations:Yh[e],leasePolicy:kO(e)}});function lk(e){const t=mO(e);return t?du.find(n=>n.id===t)??null:null}function Qh(e){const t=uu(e);return t?uO.find(n=>n.id===t)??null:null}function VY(e){const t=lk(e.appId),n=vO(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 mO(e){const t=e?.trim().toLowerCase().replace(/[-\s]+/g,"_");return t?t==="teams"||t==="microsoft"?"microsoft_teams":du.some(n=>n.id===t)?t:null:null}function uu(e){const t=e?.trim().toLowerCase().replace(/[-\s]+/g,"_");return t?t==="teams"||t==="microsoft"?"microsoft_teams":Zh.includes(t)?t:lk(t)?.providerFamily??null:null}function Op(e={}){const t=wO(e.connections??[]);return du.map(n=>{const a=Qh(n.providerFamily),o=n.statusSource==="integration_connection"?t.filter(l=>l.provider===n.providerFamily):[],i=o.some(l=>l.status==="active"),s=IO(n,i);return{...n,providerLabel:a.label,setupSurfaceLabel:bO(n.setupSurface),status:s,statusLabel:_O(n,s,o),connections:o,connected:i,capabilities:Qb(n,a.capabilities),capabilityLabels:Qb(n,a.capabilities).map(l=>l.label),leasePolicy:a.leasePolicy}})}function Ft(e,t,n,a,o){return{id:e,label:t,description:n,access:a,leaseable:o}}function Dt(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 pO(e){return fO(e.operation)}function fO(e){return typeof e=="string"&&e.trim()?e.trim():null}function hO(e,t){return t==="write"?gO(e.input)?e.input:{}:e}function gO(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function vO(e){const t=e?.trim();if(!t)return jp;try{const n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?jp:(n.pathname="/",n.search="",n.hash="",n.toString())}catch{return jp}}function Il(e){return e==="microsoft_teams"?"Microsoft Teams":e==="mcp"?"OpenPond MCP":e==="x"?"X":e[0].toUpperCase()+e.slice(1)}function bO(e){return e==="native_bot"?"Native app":e==="oauth_connector"?"OAuth connector":e==="wallet_connector"?"Wallet connector":"MCP endpoint"}function yO(e){return[ck(e)]}function ck(e){return{name:`${e}-connected-app`,description:`Use ${Il(e)} safely through connected app tools.`,path:`integration_skills/${e}.md`}}function SO(e){if(e==="mcp")return[];const t=Jh[e],n=Yh[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 ${Il(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 ${Il(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 ${Il(e)} write through a server-owned connected app connector.`,capabilityIds:o,write:!0}),i}function xO(e){return e==="search"?"connected_app_search":e==="read"?"connected_app_read":"connected_app_write"}function kO(e){const t=Jh[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 Qb(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 wO(e){return e.flatMap(t=>{const n=uu(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 IO(e,t){return e.statusSource==="integration_connection"?t?"connected":"disconnected":"setup_available"}function _O(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 CO(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 RO=b(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),PO=b(["search","read","write"]),AO=b(rO);c({provider:RO,operation:PO,toolName:AO,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(),de()).default({})}).strict().superRefine((e,t)=>{const n=sO(e);n.ok||t.addIssue({code:qn.custom,message:n.error})});c({ok:A(),output:r().nullable().optional(),data:de().optional()}).strict();const TO="local_path:";function dk(e){return`${TO}${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 EO=c({path:r(),status:r(),additions:u(),deletions:u(),patch:r(),content:r().nullable().optional().default(null)}),MO=c({appId:r(),repoPath:r(),initialized:A(),dirty:A(),filesChanged:u(),additions:u(),deletions:u(),repoFiles:p(r()).optional().default([]),files:p(EO),error:r().nullable(),updatedAt:r()});c({branch:r().trim().min(1).max(160)});c({path:r().trim().min(1),content:r()});const Xb=c({line:u().int().nonnegative(),character:u().int().nonnegative()}),jO=c({start:Xb,end:Xb}),OO=c({path:r(),range:jO,severity:b(["error","warning","info","hint"]),message:r(),source:r().nullable().optional().default(null),code:r().nullable().optional().default(null)}),uk=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(OO),servers:p(uk),updatedAt:r()});const $O=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:$O.shape.operation,path:r(),results:de(),servers:p(uk),updatedAt:r()});const NO=c({pinned:A().optional(),archived:A().optional(),order:u().optional()}),DO=re(r(),NO),mk=b(["local","sandbox"]),LO=b(["pinned","saved_for_later"]),pk=c({id:r().min(1),workspaceKind:mk,workspaceId:r().min(1),workspaceName:r().min(1),path:r().min(1),status:LO,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(pk)});c({workspaceKind:mk,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 UO(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 KY(e){return["sidebar-file",e.workspaceKind,encodeURIComponent(e.workspaceId),encodeURIComponent(UO(e.path))].join(":")}const HO=c({id:r(),name:r(),type:r(),status:r(),isActive:A().nullable(),price:r().nullable(),currency:r().nullable(),credits:r().nullable()}).passthrough(),zO=c({reachable:A(),authenticated:A().nullable(),apiBase:r(),latencyMs:u(),status:u().nullable(),service:r().nullable(),checkedAt:r(),error:r().nullable()}),qO=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()}),BO=c({handle:r(),baseUrl:r().nullable().optional()}),FO=c({state:b(["signed_out","signed_in","loading","switching","auth_error"]),activeProfile:BO.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:qO.nullable(),products:p(HO),apiHealth:zO.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()}),ey=c({asOf:r().nullable(),refreshing:A(),lastRefreshError:r().nullable(),source:b(["fresh","cache","empty"])}),VO=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()})}),Xh="gpt-5.6-sol",ds="openpond-chat",Gr="openpond",Nl=ds,eg="default",tg="high",mu="ask",Is=ei,ng=b(["default","auto-review","full-access"]),oc=b(["ask","full-access","disabled"]),pu=b(["off","low","medium","high","xhigh","max"]),rc=b(["sandbox_app","local_project","sandbox","sandbox_template"]);b(["openpond"]);const KO=b(["provider_usage","provider_tokenizer","model_family","heuristic"]),WO=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:KO,updatedAtEventId:r().nullable()}),Ef=c({pinned:A().default(!1),projects:A().default(!1),cloudProjects:A().default(!1),chats:A().default(!1),savedForLater:A().default(!0)}),GO=b(["auto","off"]),ZO=b(["typescript","python","rust"]),fk=b(["auto","disabled","custom"]),_o=c({mode:fk.default("auto"),customCommand:r().trim().max(4096).default("")}),Md=c({languageServers:GO.default("auto"),diagnosticsWhileEditing:A().default(!0),checkOnSave:A().default(!0),languages:c({typescript:_o.optional().default(()=>_o.parse({})),python:_o.optional().default(()=>_o.parse({})),rust:_o.optional().default(()=>_o.parse({}))}).optional().default(()=>({typescript:_o.parse({}),python:_o.parse({}),rust:_o.parse({})}))}),JO=c({language:ZO,label:r(),mode:fk,status:b(["found","missing","disabled","error"]),command:r().nullable(),message:r().nullable()});c({settings:Md,languages:p(JO),updatedAt:r()});const YO=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(YO),maxClients:u().int().positive(),idleTimeoutMs:u().int().positive(),updatedAt:r()});const Mf=c({autoEnabled:A().default(!0),triggerPercent:u().int().min(50).max(95).default(85),summaryModel:b(["same_model"]).default("same_model")}),jf=c({defaultModelRef:dn.nullable().default(null),creationMode:b(["defaults","customize"]).default("customize"),autoApproveEvidence:A().default(!1)}),ty=c({defaultChatProvider:Is.default(Gr),defaultChatModel:r().min(1).default(Nl),defaultChatModelRef:dn.nullable().optional(),subagents:Ol.optional().default(()=>Ol.parse({})),codexPermissionMode:ng.default(eg),codexReasoningEffort:pu.default(tg),openPondCommandAccessMode:oc.default(mu),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:Mf.optional().default(()=>Mf.parse({})),training:jf.optional().default(()=>jf.parse({})),sidebarWidth:u().int().min(244).max(560).default(332),diffPanelWidth:u().int().min(320).max(2400).default(560),sidebarSectionsCollapsed:Ef.optional().default(()=>Ef.parse({})),editor:Md.optional().default(()=>Md.parse({}))}),QO="default",hk=[{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.`}],ag=r().trim().min(1).max(120),XO=c({id:ag,name:r(),source:b(["built_in","custom"]).default("custom"),description:r(),content:r()}),ny=c({activeTemplateId:ag.default(QO),customized:A().default(!1),soul:r(),soulPath:r().nullable(),updatedAt:r().nullable(),templates:p(XO).default(()=>[...hk])}),e2=c({id:r(),host:r(),port:u(),startedAt:r(),storePath:r(),version:r(),runtimeVersion:r()}),og=b(["chat","work","development"]);b(["chat","models","console","development"]);const t2="work",Ve=r().trim().min(1).nullable(),Ia=re(r(),de()).default({}),n2=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"]),gk=b(["/create","/edit","openpond extend","create_as_agent","suggest_workflow","local_import","lab_create","lab_improve","training"]),a2=b(["create","improve","import","promote"]),o2=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"]),Kc=b(["always_require_plan_approval","approval_already_granted"]);b(["local_profile","hosted_profile","promote_local_to_hosted","managed_artifact"]);const r2=It("kind",[c({kind:S("local"),sourceAuthority:S("local_profile"),activeProfile:r().trim().min(1).nullable(),repoPath:Ve,sourcePath:Ve,localHead:Ve,confirmationPolicy:Kc.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:Kc.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:Kc.default("always_require_plan_approval")}),c({kind:S("managed_artifact"),sourceAuthority:S("managed_artifact"),activeProfile:r().trim().min(1).nullable(),confirmationPolicy:Kc.default("always_require_plan_approval")})]),i2=c({id:Ve,kind:b(["user","system","automation"]).default("user"),label:Ve}),s2=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()}),bl=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([])}),$i={id:Ve,displayName:Ve},rg=It("kind",[c({kind:S("unselected"),...$i}),c({kind:S("agent"),...$i,defaultActionKey:Ve}),c({kind:S("skill"),...$i,skillName:Ve}),c({kind:S("extension"),...$i,slot:Ve}),c({kind:S("model"),...$i,trainingPlanId:Ve,trainingJobId:Ve,artifactId:Ve}),c({kind:S("configuration"),...$i,key:Ve})]),Of=b(["agent","skill","extension","model","configuration"]),l2=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:Ia}),vk=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:Of,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:Ia}),c2=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:Ia}),d2=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)}),u2=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(c2).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:Ia,createdAt:r().trim().min(1),updatedAt:r().trim().min(1)}),m2=c({id:r().trim().min(1),label:r().trim().min(1),value:r().trim().min(1),description:Ve,metadata:Ia}),p2=c({value:r().trim().min(1),label:Ve,detail:Ve,answeredAt:r().trim().min(1),metadata:Ia}),f2=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(m2).default([]),answer:p2.nullable().default(null),metadata:Ia}),h2=c({schemaVersion:S("openpond.createImprove.workflowCapture.v1"),id:r().trim().min(1),runId:r().trim().min(1),command:gk,objective:r().trim().min(1),conversationExcerpts:bl.shape.conversationExcerpts,attachments:bl.shape.attachments,apps:bl.shape.apps,tools:bl.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:Ia,createdAt:r().trim().min(1)}),bk=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)}),g2=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:bk.nullable().default(null)}),v2=c({id:r().trim().min(1),target:rg,status:b(["draft","authored","checking","evaluated","accepted","rejected","failed"]),git:g2.nullable().default(null),parentCandidateId:Ve.default(null),tasksetRef:vk.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:Ia}),b2=c({id:r().trim().min(1),candidateId:Ve,target:rg,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:Ia}),y2=c({mode:b(["foreground","background"]).default("background"),pauseAllowed:A().default(!0),cancellationAllowed:A().default(!0)}),S2=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)}),x2=c({kind:b(["candidate_authoring","local_apply","hosted_turn","training_job","evaluation","pull_request","release"]),id:r().trim().min(1),status:Ve,metadata:Ia}),k2=c({status:b(["not_requested","pending","released","rejected","rolled_back"]),profileCommit:Ve,profileTag:Ve,releaseReceiptRef:Ve,pullRequest:bk.nullable().default(null),updatedAt:Ve}),ic=c({schemaVersion:S("openpond.createImprove.run.v1"),id:r().trim().min(1),revision:u().int().nonnegative(),operation:a2,surface:n2,command:gk,objective:r().trim().min(1),state:o2,adapter:r2,actor:i2,scope:s2,context:bl,target:rg,evidenceSnapshots:p(l2).default([]),tasksetRef:vk.nullable().default(null),targetSelection:c({status:b(["open","recommended","confirmed"]),preselectedKind:Of.nullable(),confirmedKind:Of.nullable()}).nullable().default(null),plan:u2.nullable(),workflowCapture:h2.nullable(),executionPolicy:y2.default({mode:"background",pauseAllowed:!0,cancellationAllowed:!0}),iterationPolicy:S2.default({mode:"single",maximumAttempts:1,currentAttempt:0}),approvalIds:p(r().trim().min(1)).default([]),questionIds:p(r().trim().min(1)).default([]),questions:p(f2).default([]),candidates:p(v2).default([]),evaluationReceipts:p(b2).default([]),checkRefs:p(r().trim().min(1)).default([]),sourceRefs:p(r().trim().min(1)).default([]),externalExecutionRefs:p(x2).default([]),localProfileCommit:Ve,hostedSourceCommit:Ve,hostedSourceRef:Ve,releaseOutcome:k2.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:Ia,createdAt:r().trim().min(1),updatedAt:r().trim().min(1)}),ao={runId:r().trim().min(1),expectedRevision:u().int().nonnegative(),actionId:r().trim().min(1)};It("type",[c({...ao,type:S("answer_question"),questionId:r().trim().min(1),value:r().trim().min(1)}),c({...ao,type:S("approve_plan")}),c({...ao,type:S("revise_plan"),revision:r().trim().min(1)}),c({...ao,type:S("cancel"),reason:Ve.optional().default(null)}),c({...ao,type:S("pause")}),c({...ao,type:S("resume")}),c({...ao,type:S("open_pull_request"),candidateId:r().trim().min(1)}),c({...ao,type:S("apply_candidate"),candidateId:r().trim().min(1)}),c({...ao,type:S("reject_candidate"),candidateId:r().trim().min(1),reason:Ve.optional().default(null)}),c({...ao,type:S("reconcile_pull_request"),candidateId:r().trim().min(1)})]);c({schemaVersion:S("openpond.createImprove.runList.v1"),runs:p(ic),generatedAt:r().trim().min(1)});function WY(e){const t=d2.safeParse(e?.actionShape);return t.success?t.data:null}const vr=c({source:b(["local","github","openpond_git"]),repositoryId:r().trim().min(1),profileId:r().trim().min(1)}),w2=c({ref:vr,revision:r().nullable(),sourceHash:r()}),_s=re(r(),de()).default({}),ga=u().int().nonnegative(),fu=r().trim().min(1).max(1e5),yk=c({kind:b(["personal","team"]),id:E}).strict(),I2=c({name:E,release:J.nullable(),revision:ga}).strict();c({schemaVersion:S("openpond.harnessWorkspace.v1"),id:E,ownerScope:yk,name:r().trim().min(1).max(240),location:b(["local","hosted"]),sourceRevision:r().trim().min(1).max(500),revision:ga,dirty:A(),currentChannel:I2,createdAt:Ee,updatedAt:Ee,metadata:_s}).strict();const us=b(["runtime","memory","prompt","skill","agent","product","taskset","training"]),Sk=b(["text_instruction","memory","dependency_selection","executable_code","business_logic","financial_logic","permission","connected_app","publication","deployment","training","model_binding","team_or_global"]),xk=c({id:E,route:us,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:Q.nullable(),effects:p(Sk).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=rn(e.content);e.contentHash!==n&&t.addIssue({code:"custom",message:`edit contentHash is ${e.contentHash}; expected ${n}`,path:["contentHash"]})}),kk=c({workspaceId:E,revision:ga,sourceRevision:r().trim().min(1).max(500),channelRevision:ga}).strict(),$o=c({id:E,revision:ga,contentHash:Q}).strict(),_2=c({schemaVersion:S("openpond.harnessTurnSnapshot.v1"),workspaceId:E,workspaceRevision:ga,sourceRevision:r().trim().min(1).max(500),channelName:E,channelRevision:ga,harnessRelease:J,toolCatalogHash:Q.nullable().optional(),overlay:$o.nullable().optional().default(null)}).strict(),C2=c({schemaVersion:S("openpond.harnessRunOverlay.v1"),id:E,runId:E,baseHarnessRelease:J,workspace:kk,revision:ga,status:b(["active","frozen","abandoned"]),edits:p(xk).max(1e3),createdAt:Ee,updatedAt:Ee,metadata:_s}).strict();C2.extend({contentHash:Q}).strict();const wk=c({kind:b(["tool_event","recovery","validation","user_turn","work_output","work_receipt"]),id:E,contentHash:Q.nullable()}).strict(),Ik=c({id:E,kind:b(["dependency","schema","package","file_render","skill","prompt","business_formula","targeted_evaluation","observed_recovery","memory","component_activation"]),description:fu,required:A()}).strict(),R2=c({schemaVersion:S("openpond.harnessImprovementProposal.v1"),id:E,overlay:$o,baseHarnessRelease:J,expectedWorkspace:kk,requestedScope:b(["personal","team","global"]),route:us,risk:b(["low","review","restricted"]),effects:p(Sk).min(1).max(20),evidence:p(wk).min(1).max(1e3),edits:p(xk).min(1).max(1e3),validationPlan:p(Ik).min(1).max(100),expectedOutcome:fu,createdAt:Ee,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"]})});R2.extend({contentHash:Q}).strict();const P2=c({schemaVersion:S("openpond.harnessTargetedValidationReceipt.v1"),id:E,proposal:J,validationId:E,kind:Ik.shape.kind,status:b(["passed","failed","blocked","skipped"]),summary:fu,evidenceRefs:p(wk).max(1e3),createdAt:Ee,metadata:_s}).strict();P2.extend({contentHash:Q}).strict();const A2=b(["advanced","retained","conflict","rolled_back"]),T2=c({schemaVersion:S("openpond.harnessAdvanceReceipt.v1"),id:E,workspaceId:E,ownerScope:yk,proposal:J.nullable(),expectedWorkspaceRevision:ga,observedWorkspaceRevision:ga,previousChannelRevision:ga,nextChannelRevision:ga,previousRelease:J.nullable(),nextRelease:J.nullable(),validationReceipts:p(J).max(100),decision:A2,reason:fu,rollbackOf:J.nullable(),createdAt:Ee,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"]})});T2.extend({contentHash:Q}).strict();const E2=c({schemaVersion:S("openpond.harnessOverlayMergeReceipt.v1"),id:E,workspaceId:E,baseHarnessRelease:J,leftOverlay:$o,rightOverlay:$o,decision:b(["merged","conflict"]),mergedOverlay:$o.nullable(),conflictTargets:p(r().trim().min(1).max(2e3)).max(1e3),requiresRevalidation:S(!0),createdAt:Ee,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"]})});E2.extend({contentHash:Q}).strict();const No=r().trim().min(1).max(1e5),M2=b(["no_action","harness_maintenance","runtime","product","taskset","model_improvement"]),j2=b(["none","runtime_service","product_team","human_review","evaluation_system","training_system"]),_k=b(["observation","trigger","route_decision","refiner_outcome","proposal","validation","apply_receipt","harness_advance","rollback","work_outcome","taskset","evaluation","training_qualification","model_candidate"]),ig=c({kind:b(["personal","team"]),id:E}).strict(),Ck=c({policy:J,state:b(["authorized","revoked","deleted","expired"]),checkedAt:Ee}).strict(),Dl=c({evidence:J,kind:_k,sourceRef:E,sourcePolicy:Ck,occurrenceKey:Q,occurredAt:Ee}).strict(),O2=c({evidence:J,sourcePolicy:Ck.nullable(),reason:b(["outside_scope","before_watermark","duplicate","resolved","revoked","deleted","expired","sensitive","unverified","budget"])}).strict(),ay=c({cursor:Q,throughCreatedAt:Ee}).strict(),$2=c({fingerprint:Q,recurrenceFamily:r().trim().min(1).max(1e3),statement:No,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"),Rk=b(["harness","runtime","product","retrieval","tools","evaluation","model"]),N2=c({layer:Rk,status:b(["not_applicable","unresolved","resolved","blocked"]),reason:No,evidenceRefs:p(J).max(1e3)}).strict(),D2=c({schemaVersion:S("openpond.harnessEvaluationReviewReceipt.v1"),id:E,ownerScope:ig,workspaceRef:E,harnessRelease:J,previousWatermark:ay.nullable(),nextWatermark:ay,selectedEvidence:p(Dl).max(1e4),excludedEvidence:p(O2).max(1e4),claim:$2.nullable(),classification:M2,triage:p(N2).max(16),reason:No,nextAuthority:j2,maxEstimatedCostUsd:u().finite().nonnegative(),tasksetProposal:J.nullable(),evaluation:J.nullable(),trainingQualification:J.nullable(),policyVersion:E,createdAt:Ee,metadata:_n}).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"})});D2.extend({contentHash:Q}).strict();c({id:E,evidence:J,kind:_k,sourceRef:E,occurredAt:Ee,payload:re(r(),de())}).strict();const L2=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("no_action"),reason:No,ignoredEvidence:p(c({id:E,reason:r().trim().min(1).max(2e3)}).strict()).max(1e3)}).strict(),U2=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("review"),classification:b(["harness_maintenance","runtime","product","taskset"]),selectedEvidenceIds:p(E).min(1).max(1e3),ignoredEvidence:p(c({id:E,reason:r().trim().min(1).max(2e3)}).strict()).max(1e3),recurrenceFamily:r().trim().min(1).max(1e3),statement:No,triageLayer:Rk,expectedOutcome:No,counterevidence:r().trim().max(1e4),confidence:u().min(0).max(1),candidateDisposition:b(["observe","confirm"]).nullable(),reason:No}).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"]})}),H2=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("resolve_candidate"),candidateId:E,candidateFingerprint:Q,selectedEvidenceIds:p(E).min(1).max(1e3),ignoredEvidence:p(c({id:E,reason:r().trim().min(1).max(2e3)}).strict()).max(1e3),confidence:u().min(0).max(1),reason:No}).strict();It("decision",[L2,U2,H2]);c({schemaVersion:S("openpond.harnessEvaluationReviewNavigationDecision.v1"),selectedEvidenceIds:p(E).min(1).max(50),reason:No}).strict();const sc=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(),de()),inputSchemaHash:Q,sideEffect:b(["read","write"]),timeoutMs:u().int().positive().max(36e5)}).strict(),sg=c({id:E,required:A(),scopes:p(r().trim().min(1).max(500)).max(100).default([]),portability:b(["portable","host_adapter","local_only","hosted_only"])}).strict(),z2=c({portable:A(),blockers:p(r().trim().min(1).max(2e3)).max(1e3),localOnlyAssetRefs:p(E).max(1e4),hostPrivateAssetRefs:p(E).max(1e4)}).strict(),q2=c({schemaVersion:S("openpond.agentSnapshot.v2"),id:E,sourceRelease:J.nullable(),instructions:p(ln).max(1e4),skills:p(ln).max(1e4),agents:p(ln).max(1e4),toolDeclarations:p(sc).max(200),capabilityRequirements:p(sg).max(200),dependencyLock:ln,portability:z2,metadata:_n}).strict(),B2=q2.extend({contentHash:Q}).strict(),Pk=c({create:S(!0),reset:S(!0),step:S(!0),collect:S(!0),destroy:S(!0),resetScope:b(["task","attempt"])}).strict(),Ak=c({visibleEvidence:p(E).max(1e3),privilegedEvidence:p(E).max(1e3),privateVerifierIsolation:A()}).strict(),F2=c({schemaVersion:S("openpond.harnessRelease.v2"),id:E,agentSnapshot:J,program:ln,tools:p(sc).max(200),lifecycle:Pk,graderInterface:Ak,files:p(ln).max(1e5),metadata:_n}).strict(),V2=F2.extend({contentHash:Q}).strict(),K2=c({id:E,turn:u().int().nonnegative(),kind:b(["message","tool_call","terminal"]),name:E.nullable(),arguments:re(r(),de()),content:r().max(1e6).nullable()}).strict(),W2=c({actionId:E,turn:u().int().nonnegative(),terminal:A(),output:re(r(),de()),artifactRefs:p(Va).max(1e5)}).strict(),G2=c({sequence:u().int().nonnegative(),type:b(["created","reset","action","observation","terminal","failure","collected","destroyed"]),payloadHash:Q,metadata:_n}).strict();c({schemaVersion:S("openpond.harnessTrace.v1"),manifest:J,taskId:E,seed:r().trim().min(1).max(500),events:p(G2).max(1e6),actions:p(K2).max(1e5),observations:p(W2).max(1e5),terminal:A(),failureClass:tc.nullable(),output:re(r(),de()),contentHash:Q}).strict();const hu=r().trim().min(1).max(1e5),lc=re(r(),de()).default({}),Z2=b(["completed_tool_batch","before_model_step","turn_completed","turn_paused"]),Tk=c({kind:Z2,eventSequence:u().int().nonnegative(),occurredAt:Ee}).strict(),Ek=c({id:E,sequence:u().int().nonnegative().nullable(),contentHash:Q}).strict(),J2=b(["tool_failure","retry","recovery","validation","user_turn","reusable_success","completion_detour"]),Y2=b(["open","recovered","terminal"]),Q2=c({name:r().trim().min(1).max(500),invocationKey:Q}).strict(),X2=c({schemaVersion:S("openpond.improvementObservation.v1"),id:E,runRef:E,turnId:E,harnessRelease:J,overlay:$o.nullable(),eventRefs:p(Ek).min(1).max(100),kind:J2,state:Y2,tool:Q2.nullable(),deterministicClass:r().trim().min(1).max(500).nullable(),summary:hu,createdAt:Ee,metadata:lc}).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"]})});X2.extend({contentHash:Q}).strict();const e$=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(),t$=b(["no_action","route_deterministically","queue_refiner"]),n$=c({schemaVersion:S("openpond.refinementTriggerDecision.v1"),id:E,runRef:E,turnId:E,harnessRelease:J,overlay:$o.nullable(),observations:p(J).max(100),decision:t$,deterministicRoute:us.nullable(),suggestedRoutes:p(us).max(8),reason:hu,deduplicationKey:Q,policy:e$,estimatedMaxCostUsd:u().finite().nonnegative(),pendingPlanCount:u().int().nonnegative(),boundary:Tk,cooldownUntil:Ee.nullable(),createdAt:Ee,metadata:lc}).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"]})});n$.extend({contentHash:Q}).strict();const a$=b(["runtime_service","refiner_model","human_review","evaluation_system","training_system"]),o$=c({schemaVersion:S("openpond.improvementRouteDecision.v1"),id:E,trigger:J,route:us,authority:a$,automatic:A(),reason:hu,createdAt:Ee,metadata:lc}).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"]})});o$.extend({contentHash:Q}).strict();const r$=c({schemaVersion:S("openpond.harnessRefinerOutcome.v1"),id:E,trigger:J,decision:b(["no_action","proposed"]),proposal:J.nullable(),reason:hu,evidenceRefs:p(J).max(100),estimatedCostUsd:u().finite().nonnegative(),createdAt:Ee,metadata:lc}).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"]})});r$.extend({contentHash:Q}).strict();const i$=b(["applied","retained","declined","conflict","rolled_back"]),s$=c({schemaVersion:S("openpond.improvementApplyReceipt.v1"),id:E,proposal:J,beforeOverlay:$o,afterOverlay:$o.nullable(),decision:i$,boundary:Tk,validationRefs:p(J).max(100),outcomeEvidenceRefs:p(Ek).max(1e3),rollbackOf:J.nullable(),createdAt:Ee,metadata:lc}).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"]})});s$.extend({contentHash:Q}).strict();const l$=b(["memory","prompt","skill","agent"]),c$=b(["runtime","product","taskset","training"]),d$=c({id:r().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),text:r().trim().min(1).max(1e4)}).strict(),Mk=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(d$).max(100),allowedProposalRoutes:p(l$).max(4),allowedExternalRoutes:p(c$).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"]})}),oy=c({schemaVersion:S("openpond.refinerRelease.v1"),id:r().trim().min(1).max(240),coreVersion:r().trim().min(1).max(120),coreHash:Q,profile:Mk,profileHash:Q,composedPromptHash:Q,createdAt:Ee,contentHash:Q}).strict(),u$=c({schemaVersion:S("openpond.refinerBinding.v1"),channel:S("active"),revision:u().int().nonnegative(),release:J,updatedAt:Ee}).strict(),m$=c({schemaVersion:S("openpond.refinerTransitionReceipt.v1"),id:r().trim().min(1).max(240),operation:b(["initialize","update","activate","rollback"]),bindingChanged:A(),previousRelease:J.nullable(),nextRelease:J,actor:r().trim().min(1).max(240),reason:r().trim().min(1).max(1e4),authoringSkillHash:Q.nullable(),validation:c({valid:A(),messages:p(r().max(2e3)).max(100)}).strict(),createdAt:Ee,contentHash:Q}).strict(),p$=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v1"),decision:S("no_action"),reason:r().trim().min(1).max(1e4)}).strip(),f$=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(),h$=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"]})}),g$=It("decision",[p$,f$,h$]),v$=g$,lg=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"]})}),b$=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("no_action"),reason:r().trim().min(1).max(1e4)}).strict(),y$=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("route"),route:b(["runtime","product","taskset","training"]),summary:r().trim().min(1).max(2e3),evidenceBasis:lg,expectedOutcome:r().trim().min(1).max(1e4),reason:r().trim().min(1).max(1e4)}).strict(),S$=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:lg,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"]})}),jk=It("decision",[b$,y$,S$]);Nt([v$,jk]);const cg=c({memory:A(),prompt:A(),skill:A(),agent:A()}).strict(),Ok=b(["memory","instruction","skill","agent"]),ry=c({path:r().trim().min(1).max(2e3),kind:Ok,content:r().max(6e4),loaded:A()}).strict(),iy=c({path:r().trim().min(1).max(2e3),kind:Ok,loaded:A()}).strict(),x$=c({capabilities:cg,trigger:re(r(),de()),observations:p(re(r(),de())).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(),de())).max(60),artifacts:p(re(r(),de())).max(30),artifactDiagnostics:p(re(r(),de())).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(),de())).max(3),truncation:c({timelineEventCount:u().int().nonnegative(),includedTimelineEventCount:u().int().nonnegative(),timelineTruncated:A()}).strict()}).strict(),runtimeActivation:c({admittedRelease:J,currentRelease:J,rebasedOntoCurrent:A(),admittedSourceFiles:p(ry).max(100),admittedSourceCatalog:p(iy).max(1e3)}).strict(),sourceFiles:p(ry).max(100),sourceCatalog:p(iy).max(1e3),additionalEvidence:de().nullable().optional()}).strict(),k$=c({id:r().trim().min(1).max(240),revision:u().int().nonnegative(),contentHash:Q}).strict();c({schemaVersion:S("openpond.hostedHarnessRefinerRequest.v2"),requestId:r().trim().min(1).max(240),idempotencyKey:r().trim().min(1).max(240),evidenceHash:Q,harness:c({admittedRelease:J,currentRelease:J,overlay:k$,workspace:c({id:r().trim().min(1).max(240),revision:u().int().nonnegative(),sourceRevision:Q,channelRevision:u().int().nonnegative()}).strict(),capabilities:cg}).strict(),evidence:x$}).strict();const w$=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:Q,admittedRelease:J,currentRelease:J,decision:jk,serviceRevision:r().trim().min(1).max(240),usage:w$}).strict();const I$=r().trim().min(1).max(2e3),dg=r().trim().min(1).max(1e5),_$=b(["create","update","delete"]),C$=b(["memory","prompt","skill","agent"]),R$=b(["runtime","product","taskset","training"]),P$=b(["no_action","routed","applied","retained","failed"]),A$=b(["not_applicable","pending","passed","rejected","failed"]),T$=b(["not_applicable","pending","passed","failed"]),E$=c({schemaVersion:S("openpond.harnessRefinerActivityReceipt.v1"),id:E,runRef:E,turnId:E,result:P$,decision:b(["no_action","route","propose"]).nullable(),route:us.nullable(),operation:_$.nullable(),target:r().trim().min(1).max(2e3).nullable(),summary:I$,evidenceBasis:lg.nullable(),critiqueStatus:A$,validationStatus:T$,trigger:J,outcome:J.nullable(),proposal:J.nullable(),applyReceipt:J.nullable(),inputHarness:J,outputHarness:J.nullable(),createdAt:Ee}).strict().superRefine((e,t)=>{const n=e.result==="applied"||e.result==="retained";e.result==="no_action"?sy(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"||!R$.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"}),sy(t,e,{critiqueStatus:"not_applicable",validationStatus:"not_applicable"})):n?((e.decision!=="propose"||!C$.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"]})});E$.extend({contentHash:Q}).strict();const M$=b(["unresolved","confirmed","resolved","rejected","expired"]),j$=c({kind:b(["applied_change","later_success","manual_rejection","source_revoked","expired"]),reason:dg,evidenceRefs:p(J).max(1e3),resolvedAt:Ee}).strict(),O$=c({schemaVersion:S("openpond.harnessRefinementCandidate.v1"),id:E,ownerScope:ig,workspaceRef:E,fingerprint:Q,recurrenceFamily:r().trim().min(1).max(1e3),statement:dg,status:M$,occurrences:p(Dl).max(1e3),counterevidence:p(Dl).max(1e3),sourceReviews:p(J).min(1).max(100),relatedHarnessReleases:p(J).max(100),firstSeenAt:Ee,lastSeenAt:Ee,lastReviewedAt:Ee,expiresAt:Ee,resolution:j$.nullable(),createdAt:Ee,updatedAt:Ee}).strict().superRefine((e,t)=>{Ur(t,e.occurrences,"occurrences"),Ur(t,e.counterevidence,"counterevidence"),Ur(t,e.sourceReviews,"sourceReviews"),Ur(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"]}),U$(t,e)});O$.extend({contentHash:Q}).strict();const $$=b(["created","merged","rejected","expired","reopened","resolved"]),N$=c({schemaVersion:S("openpond.harnessRefinementCandidateLifecycleReceipt.v1"),id:E,candidateId:E,decision:$$,beforeCandidate:J.nullable(),afterCandidate:J,review:J,addedEvidence:p(Dl).max(1e3),removedEvidence:p(J).max(1e3),reason:dg,createdAt:Ee}).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"]}),Ur(t,e.addedEvidence,"addedEvidence"),Ur(t,e.removedEvidence,"removedEvidence");const n=new Set(e.removedEvidence.map(a=>$f(a)));e.addedEvidence.some(a=>n.has($f(a.evidence)))&&t.addIssue({code:"custom",message:"candidate lifecycle evidence cannot be added and removed together",path:["removedEvidence"]})});N$.extend({contentHash:Q}).strict();const D$=c({schemaVersion:S("openpond.harnessCrossRunRefinementRequest.v1"),id:E,ownerScope:ig,workspaceRef:E,candidate:J,candidateFingerprint:Q,review:J,admittedHarness:J,evidence:p(Dl).min(1).max(1e3),capabilities:cg,deduplicationKey:Q,createdAt:Ee}).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"]}),Ur(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=L$(e);e.deduplicationKey!==n&&t.addIssue({code:"custom",message:`cross-run refinement deduplicationKey is ${e.deduplicationKey}; expected ${n}`,path:["deduplicationKey"]})});D$.extend({contentHash:Q}).strict();function L$(e){return rn({schemaVersion:"openpond.harnessCrossRunRefinementIdentity.v1",workspaceRef:e.workspaceRef,candidateFingerprint:e.candidateFingerprint,admittedHarness:e.admittedHarness})}function sy(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 Ur(e,t,n){const a=t.map(o=>$f(o));new Set(a).size!==a.length&&e.addIssue({code:"custom",message:`${n} references must be unique`,path:[n]})}function $f(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 U$(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 H$=25*1024*1024,z$=c({path:ln.shape.path,base64:r().max(Math.ceil(H$/3)*4)}).strict(),$k=c({schemaVersion:S("openpond.harnessSourcePackage.v1"),agentSnapshot:B2,harnessRelease:V2,files:p(z$).max(1e4)}).strict();$k.extend({contentHash:Q}).strict();$k.extend({schemaVersion:S("openpond.harnessPolicySourcePackage.v1"),contentHash:Q}).strict();c({schemaVersion:S("openpond.harnessSourceSelection.v1"),mode:b(["taskset_owned","selected_release"]),harnessRelease:J,sourcePackageHash:Q.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 Nk=r().regex(/^[a-z][a-z0-9_-]{0,119}$/),Dk=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"),q$=c({id:Nk,label:r().trim().min(1).max(240),description:r().max(4e3),inputSchema:re(r(),de()),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(Dk).max(100)}).strict();c({schemaVersion:S("openpond.profileWorkflows.v1"),workflows:p(q$).max(1e3)}).strict();const B$=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(),de())}).strict();c({schemaVersion:S("openpond.profileWorkflowActions.v1"),actions:p(B$).max(200)}).strict();const F$=c({schemaVersion:S("openpond.profileWorkflowBinding.v1"),profileId:r().trim().min(1).max(240),sourceRevision:r().trim().min(1).max(240),harnessRelease:J,catalogHash:Q,workflowId:Nk}).strict(),V$=c({schemaVersion:S("openpond.profileComponentBinding.v1"),profileId:r().trim().min(1).max(240),sourceRevision:r().trim().min(1).max(240),harnessRelease:J,target:It("kind",[c({kind:S("profile")}).strict(),c({kind:S("skill"),skillPath:Dk}).strict(),c({kind:S("agent_action"),actionId:r().trim().min(1).max(240)}).strict()])}).strict(),ug=Symbol.for("yaml.alias"),K$=Symbol.for("yaml.document"),Vr=Symbol.for("yaml.map"),Lk=Symbol.for("yaml.pair"),mg=Symbol.for("yaml.scalar"),cc=Symbol.for("yaml.seq"),bo=Symbol.for("yaml.node.type"),Cs=e=>!!e&&typeof e=="object"&&e[bo]===ug,gu=e=>!!e&&typeof e=="object"&&e[bo]===K$,Uk=e=>!!e&&typeof e=="object"&&e[bo]===Vr,Mn=e=>!!e&&typeof e=="object"&&e[bo]===Lk,Sn=e=>!!e&&typeof e=="object"&&e[bo]===mg,pg=e=>!!e&&typeof e=="object"&&e[bo]===cc;function sa(e){if(e&&typeof e=="object")switch(e[bo]){case Vr:case cc:return!0}return!1}function On(e){if(e&&typeof e=="object")switch(e[bo]){case ug:case Vr:case mg:case cc:return!0}return!1}const Hk=e=>(Sn(e)||sa(e))&&!!e.anchor,$r=Symbol("break visit"),W$=Symbol("skip children"),_l=Symbol("remove node");function vu(e,t){const n=G$(t);gu(e)?Fi(null,e.contents,n,Object.freeze([e]))===_l&&(e.contents=null):Fi(null,e,n,Object.freeze([]))}vu.BREAK=$r;vu.SKIP=W$;vu.REMOVE=_l;function Fi(e,t,n,a){const o=Z$(e,t,n,a);if(On(o)||Mn(o))return J$(e,a,o),Fi(e,o,n,a);if(typeof o!="symbol"){if(sa(t)){a=Object.freeze(a.concat(t));for(let i=0;i<t.items.length;++i){const s=Fi(i,t.items[i],n,a);if(typeof s=="number")i=s-1;else{if(s===$r)return $r;s===_l&&(t.items.splice(i,1),i-=1)}}}else if(Mn(t)){a=Object.freeze(a.concat(t));const i=Fi("key",t.key,n,a);if(i===$r)return $r;i===_l&&(t.key=null);const s=Fi("value",t.value,n,a);if(s===$r)return $r;s===_l&&(t.value=null)}}return o}function G$(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 Z$(e,t,n,a){if(typeof n=="function")return n(e,t,a);if(Uk(t))return n.Map?.(e,t,a);if(pg(t))return n.Seq?.(e,t,a);if(Mn(t))return n.Pair?.(e,t,a);if(Sn(t))return n.Scalar?.(e,t,a);if(Cs(t))return n.Alias?.(e,t,a)}function J$(e,t,n){const a=t[t.length-1];if(sa(a))a.items[e]=n;else if(Mn(a))e==="key"?a.key=n:a.value=n;else if(gu(a))a.contents=n;else{const o=Cs(a)?"alias":"scalar";throw new Error(`Cannot replace node with ${o} parent`)}}function zk(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 yl(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=yl(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=yl(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=yl(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=yl(e,a,o,i);s===void 0?delete a[o]:s!==i&&(a[o]=s)}return e.call(t,n,a)}function Ba(e,t,n){if(Array.isArray(e))return e.map((a,o)=>Ba(a,String(o),n));if(e&&typeof e.toJSON=="function"){if(!n||!Hk(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 fg{constructor(t){Object.defineProperty(this,bo,{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(!gu(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=Ba(this,"",s);if(typeof o=="function")for(const{count:m,res:d}of s.anchors.values())o(d,m);return typeof i=="function"?yl(i,{"":l},"",l):l}}class Y$ extends fg{constructor(t){super(ug),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=[],vu(t,{Node:(i,s)=>{(Cs(s)||Hk(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||(Ba(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=ud(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(zk(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 ud(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(sa(t)){let a=0;for(const o of t.items){const i=ud(e,o,n);i>a&&(a=i)}return a}else if(Mn(t)){const a=ud(e,t.key,n),o=ud(e,t.value,n);return Math.max(a,o)}return 1}const qk=e=>!e||typeof e!="function"&&typeof e!="object";class on extends fg{constructor(t){super(mg),this.value=t}toJSON(t,n){return n?.keep?this.value:Ba(this.value,t,n)}toString(){return String(this.value)}}on.BLOCK_FOLDED="BLOCK_FOLDED";on.BLOCK_LITERAL="BLOCK_LITERAL";on.PLAIN="PLAIN";on.QUOTE_DOUBLE="QUOTE_DOUBLE";on.QUOTE_SINGLE="QUOTE_SINGLE";function Q$(e,t,n){return n.find(a=>a.identify?.(e)&&!a.format)}function jd(e,t,n){if(gu(e)&&(e=e.contents),On(e))return e;if(Mn(e)){const v=n.schema[Vr].createNode?.(n.schema,null,n);return v.items.push(e),v}(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 Y$(m.anchor);m={anchor:null,node:null},l.set(e,m)}let d=Q$(e,t,s.tags);if(!d){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){const v=new on(e);return m&&(m.node=v),v}d=e instanceof Map?s[Vr]:Symbol.iterator in Object(e)?s[cc]:s[Vr]}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 on(e);return d.default||(h.tag=d.tag),m&&(m.node=h),h}function ly(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 jd(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 X$=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done;class Bk extends fg{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=>On(a)||Mn(a)?a.clone(t):a),this.range&&(n.range=this.range.slice()),n}addIn(t,n){if(X$(t))this.add(n);else{const[a,...o]=t,i=this.get(a,!0);if(sa(i))i.addIn(o,n);else if(i===void 0&&this.schema)this.set(a,ly(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(sa(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&&Sn(i)?i.value:i:sa(i)?i.getIn(o,n):void 0}hasAllNullValues(t){return this.items.every(n=>{if(!Mn(n))return!1;const a=n.value;return a==null||t&&Sn(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 sa(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(sa(i))i.setIn(o,n);else if(i===void 0&&this.schema)this.set(a,ly(this.schema,o,n));else throw new Error(`Expected YAML collection at ${a}. Remaining path: ${o}`)}}}const eN=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Ll(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}const Vi=(e,t,n)=>e.endsWith(`
|
|
125
|
+
`)?Ll(n,t):n.includes(`
|
|
126
|
+
`)?`
|
|
127
|
+
`+Ll(n,t):(e.endsWith(" ")?"":" ")+n,Fk="flow",Nf="block",md="quoted";function bu(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 v=o-t.length;typeof a=="number"&&(a>o-Math.max(2,i)?d.push(0):v=o-a);let y,w,_=!1,R=-1,M=-1,C=-1;n===Nf&&(R=cy(e,R,t.length),R!==-1&&(v=R+m));for(let $;$=e[R+=1];){if(n===md&&$==="\\"){switch(M=R,e[R+1]){case"x":R+=3;break;case"u":R+=5;break;case"U":R+=9;break;default:R+=1}C=R}if($===`
|
|
128
|
+
`)n===Nf&&(R=cy(e,R,t.length)),v=R+t.length+m,y=void 0;else{if($===" "&&w&&w!==" "&&w!==`
|
|
129
|
+
`&&w!==" "){const j=e[R+1];j&&j!==" "&&j!==`
|
|
130
|
+
`&&j!==" "&&(y=R)}if(R>=v)if(y)d.push(y),v=y+m,y=void 0;else if(n===md){for(;w===" "||w===" ";)w=$,$=e[R+=1],_=!0;const j=R>C+1?R-2:M-1;if(h[j])return e;d.push(j),h[j]=!0,v=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[$],k=d[$+1]||e.length;j===0?N=`
|
|
131
|
+
${t}${e.slice(0,k)}`:(n===md&&h[j]&&(N+=`${e[j]}\\`),N+=`
|
|
132
|
+
${t}${e.slice(j+1,k)}`)}return N}function cy(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 yu=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Su=e=>/^(%|---|\.\.\.)/m.test(e);function tN(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 Cl(e,t){const n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;const{implicitKey:a}=t,o=t.options.doubleQuotedMinMultiLineLength,i=t.indent||(Su(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:bu(s,i,md,yu(t,!1))}function Df(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
138
|
+
`)||/[ \t]\n|\n[ \t]/.test(e))return Cl(e,t);const n=t.indent||(Su(e)?" ":""),a="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
139
|
+
${n}`)+"'";return t.implicitKey?a:bu(a,n,Fk,yu(t,!1))}function Ki(e,t){const{singleQuote:n}=t.options;let a;if(n===!1)a=Cl;else{const o=e.includes('"'),i=e.includes("'");o&&!i?a=Df:i&&!o?a=Cl:a=n?Df:Cl}return a(e,t)}let Lf;try{Lf=new RegExp(`(^|(?<!
|
|
140
|
+
))
|
|
141
|
+
+(?!
|
|
142
|
+
|$)`,"g")}catch{Lf=/\n+(?!\n|$)/g}function pd({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 Ki(n,a);const d=a.indent||(a.forceBlockIndent||Su(n)?" ":""),h=s==="literal"?!0:s==="folded"||t===on.BLOCK_FOLDED?!1:t===on.BLOCK_LITERAL?!0:!tN(n,m,d.length);if(!n)return h?`|
|
|
143
|
+
`:`>
|
|
144
|
+
`;let v,y;for(y=n.length;y>0;--y){const k=n[y-1];if(k!==`
|
|
145
|
+
`&&k!==" "&&k!==" ")break}let w=n.substring(y);const _=w.indexOf(`
|
|
146
|
+
`);_===-1?v="-":n===w||_!==w.length-1?(v="+",i&&i()):v="",w&&(n=n.slice(0,-w.length),w[w.length-1]===`
|
|
147
|
+
`&&(w=w.slice(0,-1)),w=w.replace(Lf,`$&${d}`));let R=!1,M,C=-1;for(M=0;M<n.length;++M){const k=n[M];if(k===" ")R=!0;else if(k===`
|
|
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=(R?d?"2":"1":"")+v;if(e&&(j+=" "+l(e.replace(/ ?[\r\n]+/g," ")),o&&o()),!h){const k=n.replace(/\n+/g,`
|
|
149
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${d}`);let P=!1;const T=yu(a,!0);s!=="folded"&&t!==on.BLOCK_FOLDED&&(T.onOverflow=()=>{P=!0});const U=bu(`${N}${k}${w}`,d,Nf,T);if(!P)return`>${j}
|
|
150
|
+
${d}${U}`}return n=n.replace(/\n+/g,`$&${d}`),`|${j}
|
|
151
|
+
${d}${N}${n}${w}`}function nN(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 Ki(i,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return l||h||!i.includes(`
|
|
153
|
+
`)?Ki(i,t):pd(e,t,n,a);if(!l&&!h&&o!==on.PLAIN&&i.includes(`
|
|
154
|
+
`))return pd(e,t,n,a);if(Su(i)){if(m==="")return t.forceBlockIndent=!0,pd(e,t,n,a);if(l&&m===d)return Ki(i,t)}const v=i.replace(/\n+/g,`$&
|
|
155
|
+
${m}`);if(s){const y=R=>R.default&&R.tag!=="tag:yaml.org,2002:str"&&R.test?.test(v),{compat:w,tags:_}=t.doc.schema;if(_.some(y)||w?.some(y))return Ki(i,t)}return l?v:bu(v,m,Fk,yu(t,!1))}function aN(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!==on.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(s.value)&&(l=on.QUOTE_DOUBLE);const m=h=>{switch(h){case on.BLOCK_FOLDED:case on.BLOCK_LITERAL:return o||i?Ki(s.value,t):pd(s,t,n,a);case on.QUOTE_DOUBLE:return Cl(s.value,t);case on.QUOTE_SINGLE:return Df(s.value,t);case on.PLAIN:return nN(s,t,n,a);default:return null}};let d=m(l);if(d===null){const{defaultKeyType:h,defaultStringType:v}=t.options,y=o&&h||v;if(d=m(y),d===null)throw new Error(`Unsupported default string type ${y}`)}return d}function oN(e,t){const n=Object.assign({blockQuote:!0,commentString:eN,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 rN(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(Sn(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 iN(e,t,{anchors:n,doc:a}){if(!a.directives)return"";const o=[],i=(Sn(e)||sa(e))&&e.anchor;i&&zk(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 Od(e,t,n,a){if(Mn(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=On(e)?e:t.doc.createNode(e,{onTagObj:m=>o=m});o??(o=rN(t.doc.schema.tags,i));const s=iN(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):Sn(i)?aN(i,t,n,a):i.toString(t,n,a);return s?Sn(i)||l[0]==="{"||l[0]==="["?`${s} ${l}`:`${s}
|
|
156
|
+
${t.indent}${l}`:l}function sN({key:e,value:t},n,a,o){const{allNullValues:i,doc:s,indent:l,indentStep:m,options:{commentString:d,indentSeq:h,simpleKeys:v}}=n;let y=On(e)&&e.comment||null;if(v){if(y)throw new Error("With simple keys, key nodes cannot have comments");if(sa(e)||!On(e)&&typeof e=="object"){const T="With simple keys, collection cannot be used as a key value";throw new Error(T)}}let w=!v&&(!e||y&&t==null&&!n.inFlow||sa(e)||(Sn(e)?e.type===on.BLOCK_FOLDED||e.type===on.BLOCK_LITERAL:typeof e=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!w&&(v||!i),indent:l+m});let _=!1,R=!1,M=Od(e,n,()=>_=!0,()=>R=!0);if(!w&&!n.inFlow&&M.length>1024){if(v)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&&!v||t==null&&w)return M=`? ${M}`,y&&!_?M+=Vi(M,n.indent,d(y)):R&&o&&o(),M;_&&(y=null),w?(y&&(M+=Vi(M,n.indent,d(y))),M=`? ${M}
|
|
157
|
+
${l}:`):(M=`${M}:`,y&&(M+=Vi(M,n.indent,d(y))));let C,N,$;On(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&&Sn(t)&&(n.indentAtStart=M.length+1),R=!1,!h&&m.length>=2&&!n.inFlow&&!w&&pg(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let j=!1;const k=Od(t,n,()=>j=!0,()=>R=!0);let P=" ";if(y||C||N){if(P=C?`
|
|
158
|
+
`:"",N){const T=d(N);P+=`
|
|
159
|
+
${Ll(T,n.indent)}`}k===""&&!n.inFlow?P===`
|
|
160
|
+
`&&$&&(P=`
|
|
161
|
+
|
|
162
|
+
`):P+=`
|
|
163
|
+
${n.indent}`}else if(!w&&sa(t)){const T=k[0],U=k.indexOf(`
|
|
164
|
+
`),B=U!==-1,D=n.inFlow??t.flow??t.items.length===0;if(B||!D){let W=!1;if(B&&(T==="&"||T==="!")){let se=k.indexOf(" ");T==="&"&&se!==-1&&se<U&&k[se+1]==="!"&&(se=k.indexOf(" ",se+1)),(se===-1||U<se)&&(W=!0)}W||(P=`
|
|
165
|
+
${n.indent}`)}}else(k===""||k[0]===`
|
|
166
|
+
`)&&(P="");return M+=P+k,n.inFlow?j&&a&&a():$&&!j?M+=Vi(M,n.indent,d($)):R&&o&&o(),M}function lN(e,t){(e==="debug"||e==="warn")&&console.warn(t)}const Wc="<<",$p={identify:e=>e===Wc||typeof e=="symbol"&&e.description===Wc,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new on(Symbol(Wc)),{addToJSMap:Vk}),stringify:()=>Wc},cN=(e,t)=>($p.identify(t)||Sn(t)&&(!t.type||t.type===on.PLAIN)&&$p.identify(t.value))&&e?.doc.schema.tags.some(n=>n.tag===$p.tag&&n.default);function Vk(e,t,n){const a=Kk(e,n);if(pg(a))for(const o of a.items)Np(e,t,o);else if(Array.isArray(a))for(const o of a)Np(e,t,o);else Np(e,t,a)}function Np(e,t,n){const a=Kk(e,n);if(!Uk(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 Kk(e,t){return e&&Cs(t)?t.resolve(e.doc,e):t}function Wk(e,t,{key:n,value:a}){if(On(n)&&n.addToJSMap)n.addToJSMap(e,t,a);else if(cN(e,n))Vk(e,t,a);else{const o=Ba(n,"",e);if(t instanceof Map)t.set(o,Ba(a,o,e));else if(t instanceof Set)t.add(o);else{const i=dN(n,o,e),s=Ba(a,i,e);i in t?Object.defineProperty(t,i,{value:s,writable:!0,enumerable:!0,configurable:!0}):t[i]=s}}return t}function dN(e,t,n){if(t===null)return"";if(typeof t!="object")return String(t);if(On(e)&&n?.doc){const a=oN(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)+'..."'),lN(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 hg(e,t,n){const a=jd(e,void 0,n),o=jd(t,void 0,n);return new Do(a,o)}class Do{constructor(t,n=null){Object.defineProperty(this,bo,{value:Lk}),this.key=t,this.value=n}clone(t){let{key:n,value:a}=this;return On(n)&&(n=n.clone(t)),On(a)&&(a=a.clone(t)),new Do(n,a)}toJSON(t,n){const a=n?.mapAsMap?new Map:{};return Wk(n,a,this)}toString(t,n,a){return t?.doc?sN(this,t,n,a):JSON.stringify(this)}}function Gk(e,t,n){return(t.inFlow??e.flow?mN:uN)(e,t,n)}function uN({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 v=!1;const y=[];for(let _=0;_<t.length;++_){const R=t[_];let M=null;if(On(R))!v&&R.spaceBefore&&y.push(""),$d(n,y,R.commentBefore,v),R.comment&&(M=R.comment);else if(Mn(R)){const N=On(R.key)?R.key:null;N&&(!v&&N.spaceBefore&&y.push(""),$d(n,y,N.commentBefore,v))}v=!1;let C=Od(R,h,()=>M=null,()=>v=!0);M&&(C+=Vi(C,i,d(M))),v&&M&&(v=!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 R=y[_];w+=R?`
|
|
167
|
+
${m}${R}`:`
|
|
168
|
+
`}}return e?(w+=`
|
|
169
|
+
`+Ll(d(e),m),l&&l()):v&&s&&s(),w}function mN({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 v=[];for(let _=0;_<e.length;++_){const R=e[_];let M=null;if(On(R))R.spaceBefore&&v.push(""),$d(t,v,R.commentBefore,!1),R.comment&&(M=R.comment);else if(Mn(R)){const N=On(R.key)?R.key:null;N&&(N.spaceBefore&&v.push(""),$d(t,v,N.commentBefore,!1),N.comment&&(d=!0));const $=On(R.value)?R.value:null;$?($.comment&&(M=$.comment),$.commentBefore&&(d=!0)):R.value==null&&N?.comment&&(M=N.comment)}M&&(d=!0);let C=Od(R,m,()=>M=null);d||(d=v.length>h||C.includes(`
|
|
170
|
+
`)),_<e.length-1?C+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(d||(d=v.reduce((N,$)=>N+$.length+2,2)+(C.length+2)>t.options.lineWidth)),d&&(C+=",")),M&&(C+=Vi(C,a,l(M))),v.push(C),h=v.length}const{start:y,end:w}=n;if(v.length===0)return y+w;if(!d){const _=v.reduce((R,M)=>R+M.length+2,2);d=t.options.lineWidth>0&&_>t.options.lineWidth}if(d){let _=y;for(const R of v)_+=R?`
|
|
171
|
+
${i}${o}${R}`:`
|
|
172
|
+
`;return`${_}
|
|
173
|
+
${o}${w}`}else return`${y}${s}${v.join(" ")}${s}${w}`}function $d({indent:e,options:{commentString:t}},n,a,o){if(a&&o&&(a=a.replace(/^\n+/,"")),a){const i=Ll(t(a),e);n.push(i.trimStart())}}function Hr(e,t){const n=Sn(t)?t.value:t;for(const a of e)if(Mn(a)&&(a.key===t||a.key===n||Sn(a.key)&&a.key.value===n))return a}class Li extends Bk{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Vr,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(hg(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;Mn(t)?a=t:!t||typeof t!="object"||!("key"in t)?a=new Do(t,t?.value):a=new Do(t.key,t.value);const o=Hr(this.items,a.key),i=this.schema?.sortMapEntries;if(o){if(!n)throw new Error(`Key ${a.key} already set`);Sn(o.value)&&qk(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=Hr(this.items,t);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(t,n){const o=Hr(this.items,t)?.value;return(!n&&Sn(o)?o.value:o)??void 0}has(t){return!!Hr(this.items,t)}set(t,n){this.add(new Do(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)Wk(n,o,i);return o}toString(t,n,a){if(!t)return JSON.stringify(this);for(const o of this.items)if(!Mn(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})),Gk(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:a,onComment:n})}}class Zk extends Bk{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(cc,t),this.items=[]}add(t){this.items.push(t)}delete(t){const n=Gc(t);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(t,n){const a=Gc(t);if(typeof a!="number")return;const o=this.items[a];return!n&&Sn(o)?o.value:o}has(t){const n=Gc(t);return typeof n=="number"&&n<this.items.length}set(t,n){const a=Gc(t);if(typeof a!="number")throw new Error(`Expected a valid index, not ${t}.`);const o=this.items[a];Sn(o)&&qk(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(Ba(i,String(o++),n));return a}toString(t,n,a){return t?Gk(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(jd(l,void 0,a))}}return i}}function Gc(e){let t=Sn(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}function pN(e,t,n){const{replacer:a}=n,o=new Zk(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(hg(l,m,n))}return o}class gg extends Zk{constructor(){super(),this.add=Li.prototype.add.bind(this),this.delete=Li.prototype.delete.bind(this),this.get=Li.prototype.get.bind(this),this.has=Li.prototype.has.bind(this),this.set=Li.prototype.set.bind(this),this.tag=gg.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(Mn(o)?(i=Ba(o.key,"",n),s=Ba(o.value,i,n)):i=Ba(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=pN(t,n,a),i=new this;return i.items=o.items,i}}gg.tag="tag:yaml.org,2002:omap";class vg extends Li{constructor(t){super(t),this.tag=vg.tag}add(t){let n;Mn(t)?n=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?n=new Do(t.key,null):n=new Do(t,null),Hr(this.items,n.key)||this.items.push(n)}get(t,n){const a=Hr(this.items,t);return!n&&Mn(a)?Sn(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=Hr(this.items,t);a&&!n?this.items.splice(this.items.indexOf(a),1):!a&&n&&this.items.push(new Do(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(hg(s,null,a));return i}}vg.tag="tag:yaml.org,2002:set";new Set("0123456789ABCDEFabcdef");new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()");new Set(",[]{}");new Set(` ,[]{}
|
|
174
|
+
\r `);const Nd=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 fN={type:"object",properties:{},additionalProperties:!1};c({name:r().trim().min(1).max(240).optional(),description:r().max(4e3).optional(),skillPaths:p(Nd).max(100).optional(),assetPaths:p(Nd).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(),de()).default(fN),skillPaths:p(Nd).max(100).default([]),assetPaths:p(Nd).max(100).default([])}).strict();const Jk=b(["openpond.lab"]),Ul=c({id:r(),experience:og.default(t2),provider:Is,modelRef:dn.nullable().optional(),openPondCommandAccessMode:oc.default(mu),systemKind:Jk.nullable().optional(),hiddenFromDefaultSidebar:A().optional(),parentSessionId:r().nullable().optional(),parentTurnId:r().nullable().optional(),subagentRunId:r().nullable().optional(),subagentRoleId:ws.nullable().optional(),subagentDelegationMode:cu.nullable().optional(),title:r(),appId:r().nullable(),appName:r().nullable(),workspaceKind:rc.optional(),workspaceId:r().nullable().optional(),workspaceName:r().nullable().optional(),localProjectId:r().nullable().optional(),cloudProjectId:r().nullable().optional(),cloudTeamId:r().nullable().optional(),currentProfile:vr.nullable().optional(),profileWorkflowBinding:F$.nullable().optional(),profileComponentBinding:V$.nullable().optional(),metadata:re(r(),de()).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:dn.nullable().optional(),prompt:r(),startedAt:r(),completedAt:r().nullable(),status:b(["in_progress","completed","failed","interrupted"]),error:r().nullable(),metadata:re(r(),de()).optional().default({}),createImproveRun:ic.nullable().optional().default(null),profileSnapshot:w2.nullable().optional(),harnessSnapshot:_2.nullable().optional()});const hN=c({id:r(),sessionId:r(),turnId:r().nullable(),providerRequestId:Nt([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()}),gN=c({key:b(["files","diffs","checks","deploys","sources","schedules","tool_runs","logs","app_config"]),label:r(),status:b(["placeholder","available","error"]),summary:r()}),Yk=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:Nt([r().trim().max(191),re(r(),de())]).optional().nullable(),outputSchema:Nt([r().trim().max(191),re(r(),de())]).optional().nullable(),approvalPolicy:re(r(),de()).optional().nullable(),artifactPolicy:re(r(),de()).optional().nullable(),setupRequirements:p(re(r(),de())).optional(),mcp:re(r(),de()).optional().nullable(),schedulePolicy:re(r(),de()).optional().nullable(),trace:re(r(),de()).optional().nullable(),implementation:re(r(),de()).optional().nullable(),invokesModel:A().optional()}),vN=c({command:b(["inspect","build","validate","eval","traces","run"]),status:b(["passed","failed"]),checkedAt:r(),exitCode:u().nullable().optional(),sourceHead:r().nullable().optional()}),bN=c({id:r(),name:r(),path:r(),enabled:A()}),yN=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([])}),SN=c({id:r(),name:r(),path:r(),agentId:r().nullable(),sourcePath:r()}),Qk=c({path:r(),originalPath:r().nullable().optional(),indexStatus:r().nullable(),worktreeStatus:r().nullable(),status:r(),category:b(["added","modified","deleted","renamed","untracked","changed"])}),xN=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(Qk),fileCount:u().int().nonnegative().optional(),error:r().nullable()}),kN=c({actionCount:u(),generatedAt:r().nullable(),manifestPath:r().nullable(),registryPath:r().nullable(),stale:A(),error:r().nullable()}),wN=c({skillCount:u(),generatedAt:r().nullable(),stale:A(),error:r().nullable()}),dy=c({ref:r(),source:b(["action_catalog","source_upload_metadata"]),actionId:r().nullable(),kind:r().nullable(),label:r(),status:r(),required:A(),blocking:A()}),IN=c({status:b(["ready","setup_required","blocked"]),requirementCount:u(),blockingCount:u(),optionalMissingCount:u(),readyCount:u(),requirements:p(dy),blockingRequirements:p(dy)}),_N=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(Qk),fileCount:u().int().nonnegative().optional()}),CN=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()}),RN=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()}),PN=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()}),AN=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()}),TN=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:RN.nullable().optional().default(null),hostedSourceCheck:CN.nullable().optional().default(null),hostedPublish:PN.nullable().optional().default(null),hostedRun:AN.nullable().optional().default(null)}),EN=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()}),Xk=c({mode:b(["none","local"]),repoPath:r().nullable(),activeProfile:r().nullable(),sourcePath:r().nullable(),manifestPath:r().nullable(),agents:p(bN),skills:p(yN).optional().default([]),evals:p(SN).optional().default([]),git:xN.nullable(),catalog:kN,skillCatalog:wN.optional().default({skillCount:0,generatedAt:null,stale:!0,error:null}),actionCatalog:p(Yk),sourceSetupRequirements:p(re(r(),de())),setupGate:IN,diff:_N,hosted:TN.nullable(),summary:EN,lastCheck:vN.nullable(),error:r().nullable()}),MN=c({ref:vr,name:r(),repoPath:r(),sourcePath:r().nullable(),state:Xk}),jN=c({lastUsed:vr.nullable(),profiles:p(MN)});function ON(){return{lastUsed:null,profiles:[]}}function $N(){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 NN=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()}),DN=b(["codex","profile","extension"]);c({skillName:r(),scope:DN,path:r(),byteSize:u().int().nonnegative(),isBinary:A(),content:r().nullable()});const LN=[{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"]}],UN=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())}),ew=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(UN),validationStatus:b(["valid","error"]),validationMessages:p(r())});ew.omit({installedAt:!0,updatedAt:!0,sourcePath:!0}).extend({sourcePath:su()});const HN=c({rootPath:r(),registryPath:r(),extensions:p(ew),error:r().nullable()});c({source:r().trim().min(1),ref:r().trim().min(1).optional()});const zN=c({latestSequence:u().int().nonnegative(),oldestSequence:u().int().nonnegative(),totalEvents:u().int().nonnegative(),limit:u().int().nonnegative(),hasMoreBefore:A()});c({server:e2,account:FO,codex:VO,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:ty.optional().default(()=>ty.parse({})),providers:wb.optional().default(()=>wb.parse({})),personalization:ny.optional().default(()=>ny.parse({soul:hk[0].content,soulPath:null,updatedAt:null})),apps:p(Xj),localProjects:p(oO).optional().default([]),cloudProjects:p(aO).optional().default([]),profile:Xk.optional().default($N),profileLibrary:jN.optional().default(ON),codexPersonalSkills:p(NN).optional().default([]),extensionCatalog:HN.optional().default({rootPath:"",registryPath:"",extensions:[],error:null}),codexHistorySessions:p(Ul).optional().default([]),sidebarAppPreferences:DO,sidebarFileBookmarks:p(pk).optional().default([]),appsError:r().nullable(),appsMeta:ey,accountMeta:ey,sessions:p(Ul),events:p(Ib),eventWindow:zN.optional(),approvals:p(hN),placeholders:p(gN),diagnostics:p(Ib)});const bg=b(["openpond_hosted","local_byok","codex_app_server","unknown"]),tw=b(["provider_usage","codex_context_usage","missing"]),qN=b(["provider_usage_body","provider_response_headers"]),BN=b(["chat_turn","tool_loop","slash_command","create_improve_planner","harness_refiner","context_compaction","subagent","codex_context","other"]),FN=b(["foreground","tool_loop","compaction","subagent","refiner","other"]),nw=b(["user_facing","background","system"]),aw=b(["started","completed","failed","interrupted"]),yg=b(["composer_selection","prompt_parse","server_parser","model_tool","api"]),ow=b(["chat","settings","goal","create_improve","compaction","system"]),rw=b(["direct_chat","tool_loop","slash_command","planner","summary","scan","subagent","other"]),VN=c({surface:ow,workflowKind:rw,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:yg.nullable().default(null),appId:r().trim().min(1).nullable().default(null),workspaceKind:rc.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)}),KN=c({surface:ow.optional(),workflowKind:rw.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:yg.nullable().optional()}).strict(),ti=r().trim().min(1).max(160),WN=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:ti,model:r().trim().min(1),route:bg,source:tw,requestKind:BN,visibility:nw,status:aw,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:qN.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:VN}),iw=c({from:r().trim().min(1),to:r().trim().min(1),bucket:b(["day","all_time"])}),Sg=Nt([S("all"),nw]),xg=b(["all","started","completed","failed","interrupted","missing"]),GN=c({range:b(["7d","30d","90d","all"]).default("30d"),visibility:Sg.default("all"),status:xg.default("all"),provider:ti.optional(),model:r().trim().min(1).optional()});GN.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 ni=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)}),ZN=ni.extend({provider:ti,model:r().trim().min(1),route:bg}),JN=ni.extend({sessionId:r().trim().min(1),title:r().trim().min(1).nullable(),workspaceKind:rc.nullable(),workspaceId:r().trim().min(1).nullable()}),YN=ni.extend({commandName:r().trim().min(1),commandSource:yg.nullable()}),QN=ni.extend({route:bg}),XN=ni.extend({status:aw}),eD=ni.extend({source:tw}),tD=ni.extend({cohort:FN}),nD=c({date:r().trim().min(1),totalTokens:u().int().nonnegative(),requests:u().int().nonnegative(),models:p(c({provider:ti,model:r().trim().min(1),totalTokens:u().int().nonnegative(),requests:u().int().nonnegative()}))}),aD=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:iw,filters:c({visibility:Sg,status:xg,provider:ti.nullable(),model:r().trim().min(1).nullable()}),totals:aD,daily:p(nD),models:p(ZN),threads:p(JN),commands:p(YN),routes:p(QN),statuses:p(XN),sources:p(eD),cohorts:p(tD)});c({generatedAt:r().trim().min(1),range:iw,filters:c({visibility:Sg,status:xg,provider:ti.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(WN)});const oD=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(ti)});c({generatedAt:r().trim().min(1),sessionId:r().trim().min(1),turns:p(oD)});const rD=b(["usage_spike","model_usage_spike","latency_regression","failure_cluster","missing_usage_frames"]);c({type:rD,title:r().trim().min(1),summary:r().trim().min(1),severity:b(["nit","concern","blocker"]),payload:re(r(),de()).default({})});const iD=b(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),sD=b(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),lD=b(["native_bot","oauth_connector","wallet_connector","mcp_endpoint"]),cD=c({kind:S("integration"),provider:iD,appIds:p(sD).min(1).max(4),setupSurfaces:p(lD).min(1).max(4),connectionIds:p(r().trim().min(1)).max(8).optional(),capabilities:p(r().trim().min(1)).max(64).optional()}).strict(),zr={maxAttachments:10,maxAttachmentBytes:12*1024*1024,maxAttachmentBase64Chars:Math.ceil(12*1024*1024*4/3)+16,maxTextChars:2e5},dD=b(["image","text","file"]),uD=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)}),mD=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)}),sw=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(zr.maxAttachmentBytes),kind:dD,lineCount:u().int().nonnegative().max(zr.maxAttachmentBytes+1).optional(),relativePath:r().trim().min(1).max(1024).optional(),text:r().max(zr.maxTextChars).optional(),contentsBase64:r().max(zr.maxAttachmentBase64Chars).optional()}),pD=sw.omit({text:!0,contentsBase64:!0}).extend({imagePreview:uD.optional(),filePreview:mD.optional()});c({experience:og.optional(),provider:Is.default(Gr),modelRef:dn.optional(),openPondCommandAccessMode:oc.optional(),systemKind:Jk.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:cu.nullable().optional(),appId:r().nullable().optional(),appName:r().nullable().optional(),workspaceKind:rc.optional(),workspaceId:r().nullable().optional(),workspaceName:r().nullable().optional(),localProjectId:r().nullable().optional(),cloudProjectId:r().nullable().optional(),cloudTeamId:r().nullable().optional(),currentProfile:vr.nullable().optional(),profileWorkflowBinding:Ul.shape.profileWorkflowBinding,profileComponentBinding:Ul.shape.profileComponentBinding,metadata:re(r(),de()).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:de().optional(),metadata:re(r(),de()).optional(),usageAttribution:KN.optional().nullable(),cwd:r().nullable().optional(),model:r().nullable().optional(),modelRef:dn.optional(),mentionedAppIds:p(r().trim().min(1)).max(8).optional(),mentionedConnectedApps:p(cD).max(8).optional(),openPondActionCatalog:p(Yk).max(100).optional(),attachments:p(sw).max(zr.maxAttachments).optional(),createImproveRun:ic.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:ng.default("default"),codexReasoningEffort:pu.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:dn.optional()});c({experience:og.optional(),provider:Is.optional(),modelRef:dn.nullable().optional(),openPondCommandAccessMode:oc.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:cu.nullable().optional(),appId:r().nullable().optional(),appName:r().nullable().optional(),workspaceKind:rc.optional(),workspaceId:r().nullable().optional(),workspaceName:r().nullable().optional(),localProjectId:r().nullable().optional(),cloudProjectId:r().nullable().optional(),cloudTeamId:r().nullable().optional(),currentProfile:vr.nullable().optional(),metadata:re(r(),de()).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:dn.nullable().optional(),subagents:Ol.optional(),codexPermissionMode:ng.optional(),codexReasoningEffort:pu.optional(),openPondCommandAccessMode:oc.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:Mf.optional(),training:jf.optional(),sidebarWidth:u().int().min(244).max(560).optional(),diffPanelWidth:u().int().min(320).max(2400).optional(),sidebarSectionsCollapsed:Ef.optional(),editor:Md.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(),de()).optional()}).strict();c({activeTemplateId:ag,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:Nt([r(),u()]).nullable(),source:b(["hosted_env","local_file","defaults","missing"]),currentConfig:re(r(),de()).nullable(),defaults:re(r(),de()).nullable(),schema:re(r(),de()).nullable(),error:r().nullable().optional(),updatedAt:r()}).passthrough();const Dd=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:Dd,args:re(r(),de()).optional().default({}),source:b(["ui_button","chat_action","terminal_command","hook"]).default("chat_action")});c({ok:A(),action:Dd,appId:r().nullable().optional(),output:r(),data:de().optional()});const dc=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()}),uc=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()}),lw=c({kind:S("local"),path:r().trim().min(1).max(4096),deviceId:r().trim().min(1).max(200)}),cw=c({kind:S("managed"),fileId:r().trim().min(1).max(200),downloadPath:r().trim().min(1).max(4096)}),fD=c({kind:S("external"),provider:r().trim().min(1).max(120),resourceId:r().trim().min(1).max(500),url:r().url().nullable()}),dw=dc.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",[lw,cw,fD]),validation:p(uc).max(32).default([])}),hD=dc.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(uc).max(32).default([])}),gD=dc.extend({kind:S("deployment"),deploymentId:r().trim().min(1).max(200),url:r().url(),validation:p(uc).max(32).default([])}),vD=dc.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(uc).max(32).default([])}),uw=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(),de()).nullable(),outputSchema:re(r(),de()).nullable(),schedulePolicy:re(r(),de()).nullable()}),mw=c({base:r().trim().min(1).max(200),resources:re(r(),de()),modelPolicy:re(r(),de()).nullable(),setup:re(r(),de()).nullable()}),bD=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}$/)}),yD=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(yD).min(1).max(1e3),totalSizeBytes:u().int().nonnegative()}),manifest:re(r(),de()),actions:p(uw).min(1).max(256),runtimeRequirements:mw,receipts:p(bD).min(2).max(64)});const SD=dc.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(uw).min(1).max(256),runtimeRequirements:mw,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",[lw,cw]),validation:p(uc).max(32).default([])}),GY=It("kind",[dw,hD,gD,vD,SD]);c({outputs:p(dw)});const xD=b(["sandbox_template","sandbox","generic_git","plain_folder"]),kD=b(["sandbox_template"]).nullable();c({productKind:xD,actions:c({files:A(),git:A(),sandboxRuntime:A(),sandboxTemplate:A()}),checks:c({validate:Dd.nullable(),build:Dd.nullable(),postEdit:kD}),ui:c({showSandboxTemplateActions:A(),showSandboxRuntimeActions:A()})});const wD=c({id:r(),name:r(),dnsName:r().nullable(),os:r().nullable(),online:A(),active:A(),isSelf:A(),tailscaleIps:p(r()),lastSeen:r().nullable()}),ID=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(wD)}),_D=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()}),CD=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:ID,serve:_D});c({message:r(),status:CD});const pw=b(["github","openpond_git"]),fw=b(["private","public"]),RD=b(["actions","workflows","instructions","prompts","goals","evals","examples","tasksets","extensions"]),PD=c({agentIds:p(r().trim().min(1)).max(100),skillNames:p(r().trim().min(1)).max(200),optionalContent:p(RD).max(20).default([])}),hw=c({provider:pw,owner:r().trim().min(1).max(191).nullable().optional(),repository:r().trim().min(1).max(191),visibility:fw.default("private")}),AD=c({ref:vr,selection:PD,target:hw}),TD=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(TD),excludedFiles:p(r()),target:hw,replacesExisting:A()});AD.extend({expectedSourceHash:r().trim().min(1),confirmed:S(!0)});c({provider:pw,owner:r(),repository:r(),visibility:fw,remoteUrl:r(),webUrl:r(),revision:r()});const ED=b(["cron","rate"]),gw=b(["queued","running","succeeded","failed","skipped"]),kg=c({id:r(),localProjectId:r(),localProjectName:r(),agentRootPath:r(),agentName:r(),scheduleName:r(),scheduleType:ED,scheduleExpression:r(),timezone:r().nullable(),targetAction:r(),input:re(r(),de()).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:gw.nullable(),lastRunId:r().nullable(),lastError:r().nullable(),createdAt:r(),updatedAt:r()}),vw=c({id:r(),scheduleId:r(),definitionSnapshot:kg.optional(),configurationSnapshot:re(r(),de()).optional(),inputSnapshot:re(r(),de()).optional(),localProjectId:r(),scheduleName:r(),scheduledFor:r(),trigger:b(["schedule","manual"]),status:gw,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(),de()).nullable(),traceArtifactRef:r().nullable(),error:r().nullable(),createdAt:r(),updatedAt:r()});c({schedules:p(kg),scheduler:c({running:A(),nextTickAt:r().nullable(),lastSyncAt:r().nullable(),scanRunning:A()})});c({runs:p(vw)});c({enabled:A().optional()});c({input:re(r(),de()).optional()});c({schedule:kg,run:vw});const MD=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(MD).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"]})}),jD=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(),de()).default({})}),OD=c({id:r(),definitionKey:r(),version:u().int(),name:r(),prompt:r(),modelId:r(),schedules:p(jD)}),$D=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(OD),runs:p($D),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")});Nt([c({enabled:A()}),c({name:r().trim().min(1).max(180),prompt:r().trim().min(1).max(2e4),recurrence:Rs})]);const bw=b(["queued","running","succeeded","failed"]),yw=c({id:r(),sessionId:r(),sessionTitle:r(),sourceTurnId:r().nullable(),name:r(),prompt:r(),profileRef:vr.optional(),profileWorkflowId:r().optional(),profileMigrationError:r().nullable().optional(),recurrence:Rs,enabled:A(),nextRunAt:r().nullable(),lastRunAt:r().nullable(),lastRunStatus:bw.nullable(),lastRunId:r().nullable(),lastError:r().nullable(),scheduledRunCount:u().int().nonnegative(),createdAt:r(),updatedAt:r()}),ND=c({definitionSnapshot:yw.optional(),configurationSnapshot:re(r(),de()).optional(),id:r(),workflowId:r(),sessionId:r(),scheduledFor:r(),trigger:b(["schedule","manual"]),status:bw,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});Nt([c({enabled:A()}),c({name:r().trim().min(1).max(180),prompt:r().trim().min(1).max(2e4),recurrence:Rs})]);c({workflows:p(yw),runs:p(ND),asOf:r()});const wg=re(r(),de());c({userId:r(),role:b(["owner","admin","member"]),name:r(),handle:r().nullable(),image:r().nullable()});const DD=c({userId:r(),role:b(["owner","admin","member"]),name:r(),handle:r().nullable(),image:r().nullable(),lastReadSequence:u().int().nonnegative()}),LD=c({id:r(),messageId:r(),refType:b(["hosted_ai_thread","goal","openpond_session","project","agent_run","message_reply"]),refId:r(),preview:wg,createdAt:r()}),Sw=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:Sw,uploadUrl:r().url().nullable(),uploadHeaders:re(r(),r()),expiresAt:r().nullable()});c({url:r().url(),expiresAt:r()});const Ig=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:wg,editedAt:r().nullable(),deletedAt:r().nullable(),createdAt:r(),refs:p(LD),attachments:p(Sw)}),UD=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(DD),lastMessage:Ig.nullable()});c({thread:UD,messages:p(Ig),hasMoreBefore:A()});c({threadId:r(),mutedAt:r().nullable()});const HD=b(["pending","running","completed","failed","interrupted","cancelled"]),uy=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:HD,partialBody:r().nullable(),userMessageId:r(),assistantMessageId:r().nullable(),errorCode:r().nullable(),cancelledByUserId:r().nullable(),leaseExpiresAt:r().nullable(),heartbeatAt:r().nullable(),createdAt:r(),updatedAt:r()}),zD=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(zD),turns:p(uy),activeTurn:uy.nullable(),createdAt:r(),updatedAt:r()});const xw=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:wg,createdAt:r()});c({events:p(xw),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 _g=re(r(),de()),ya=r().nullable(),qD=b(["draft","published","archived"]),Cg=b(["owner","admin","member"]),kw=b(["active","left"]),ww=b(["mentions","all","none"]),Iw=b(["public_preview","members"]),BD=b(["members","admins"]),FD=c({canPreview:A(),canJoin:A(),canLeave:A(),canRead:A(),canPost:A(),canUpload:A(),canMention:A(),canManage:A(),requiresRulesAcceptance:A(),currentRulesVersionId:r().nullable()}),_w=c({id:r(),communityId:r(),version:u().int().positive(),title:r(),requiresReacceptance:A(),publishedAt:r()}),VD=_w.extend({bodyMarkdown:r(),contentHash:r()}),KD=c({role:Cg,status:kw,notificationMode:ww}),WD=c({id:r(),communityId:r(),userId:r(),role:Cg,status:kw,notificationMode:ww,joinedAt:r(),leftAt:ya,createdAt:r(),updatedAt:r()}),Cw=c({id:r(),slug:r(),displayName:r(),description:r(),imageUrl:r().nullable(),status:qD,visibility:b(["public","private"]),joinPolicy:b(["open","closed"]),historyVisibility:Iw,featuredAt:ya,publishedAt:ya,archivedAt:ya,memberCount:u().int().nonnegative(),membership:KD.nullable(),capabilities:FD,currentRules:_w.nullable()});c({items:p(Cw),nextCursor:r().nullable()});const Rw=c({lastReadSequence:u().int().nonnegative(),lastReadAt:ya.optional(),mutedAt:ya,pinnedAt:ya}),Rg=c({id:r(),communityId:r(),chatThreadId:r().nullable(),slug:r(),displayName:r(),topic:r(),position:u().int().nonnegative(),visibility:Iw,postingPolicy:BD,isDefault:A(),archivedAt:ya,lastMessageSequence:u().int().nonnegative(),unreadCount:u().int().nonnegative(),readState:Rw.nullable()});Cw.omit({currentRules:!0}).extend({currentRules:VD.nullable(),channels:p(Rg),previewMessageLimit:u().int().positive()});const GD=c({id:r(),messageId:r(),refType:b(["hosted_ai_thread","goal","openpond_session","project","agent_run","message_reply"]),refId:r(),preview:_g,createdAt:r()}),Pw=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:ya});c({attachment:Pw,uploadUrl:r().url().nullable(),uploadHeaders:re(r(),r()),expiresAt:ya});c({url:r().url(),expiresAt:r()});const Aw=c({id:r(),threadId:r(),teamId:su(),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:ya,deletedAt:ya,createdAt:r(),refs:p(GD),attachments:p(Pw)});c({messages:p(Aw),hasMoreBefore:A(),channelId:r(),readState:Rw.omit({lastReadAt:!0}).nullable(),preview:A()});const ZD=c({userId:r(),handle:r().nullable(),name:r().nullable(),role:Cg});c({items:p(ZD),nextCursor:r().nullable()});const Tw=c({id:u().int().nonnegative(),communityId:r(),channelId:r(),threadId:r(),type:b(["thread.created","message.created","message.updated","message.deleted","read.updated"]),payload:_g,createdAt:r()});c({events:p(Tw),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:WD,channels:p(Rg)});c({channels:p(Rg)});class Ew extends Error{code;status;constructor(t,n=422,a){super(a?`${t}: ${a}`:t),this.code=t,this.status=n,this.name="LearningDomainError"}}var Mw=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},JD=Mw((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}}),YD=Mw(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var t=JD();t.code='require("ajv/dist/runtime/equal").default',e.default=t}),my=Ot,py={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"}}},QD=Object.prototype.hasOwnProperty,XD=YD().default,kt={validate:Ot};function ia(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:i={}}={}){let s=null,l=0,m=ia.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 v=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=v===l;if(!d)break}else return ia.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"object"}}],!1;return ia.errors=s,l===0}ia.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};function In(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:i={}}={}){let s=null,l=0,m=In.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 In.errors=[{instancePath:t,schemaPath:"#/maxItems",keyword:"maxItems",params:{limit:32}}],!1;if(e.length<1)return In.errors=[{instancePath:t,schemaPath:"#/minItems",keyword:"minItems",params:{limit:1}}],!1;{var d=!0;let h=e.length;for(let v=0;v<h;v++){let y=l;kt.validate(e[v],{instancePath:t+"/"+v,parentData:e,parentDataProperty:v,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 In.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"array"}}],!1;return In.errors=s,l===0}In.evaluated={items:!0,dynamicProps:!1,dynamicItems:!1};var eL={enum:["array","boolean","integer","null","number","object","string"]};function lo(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:i={}}={}){let s=null,l=0,m=lo.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"?(lo.errors=s,l===0):(lo.errors=[{instancePath:t,schemaPath:"#/enum",keyword:"enum",params:{allowedValues:eL.enum}}],!1)}lo.evaluated={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;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))?($t.errors=[{instancePath:t,schemaPath:"#/minimum",keyword:"minimum",params:{comparison:">=",limit:0}}],!1):($t.errors=s,l===0):($t.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"integer"}}],!1)}$t.evaluated={dynamicProps:!1,dynamicItems:!1};function ha(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:i={}}={}){let s=null,l=0,m=ha.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 v=0;v<h;v++){let y=l;if(typeof e[v]!="string")return ha.errors=[{instancePath:t+"/"+v,schemaPath:"#/items/type",keyword:"type",params:{type:"string"}}],!1;var d=y===l;if(!d)break}if(d){let v=e.length,y;if(v>1){let w={};for(;v--;){let _=e[v];if(typeof _=="string"){if(typeof w[_]=="number")return y=w[_],ha.errors=[{instancePath:t,schemaPath:"#/uniqueItems",keyword:"uniqueItems",params:{i:v,j:y}}],!1;w[_]=v}}}}}else return ha.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"array"}}],!1;return ha.errors=s,l===0}ha.evaluated={items:!0,dynamicProps:!1,dynamicItems:!1};function Ot(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:i={}}={}){let s=null,l=0,m=Ot.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 Ot.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:py.type}}],!1;if(l===0&&e&&typeof e=="object"&&!Array.isArray(e)){let w=l;for(let _ in e)if(!QD.call(py.properties,_))return Ot.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 Ot.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 R=l;if(typeof e.$ref!="string")return Ot.errors=[{instancePath:t+"/$ref",schemaPath:"#/properties/%24ref/type",keyword:"type",params:{type:"string"}}],!1;var d=R===l}else var d=!0;if(d){if(e.$comment!==void 0){let M=l;if(typeof e.$comment!="string")return Ot.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;ia(e.$defs,{instancePath:t+"/$defs",parentData:e,parentDataProperty:"$defs",rootData:o,dynamicAnchors:i})||(s=s===null?ia.errors:s.concat(ia.errors),l=s.length);var d=C===l}else var d=!0;if(d){if(e.properties!==void 0){let N=l;ia(e.properties,{instancePath:t+"/properties",parentData:e,parentDataProperty:"properties",rootData:o,dynamicAnchors:i})||(s=s===null?ia.errors:s.concat(ia.errors),l=s.length);var d=N===l}else var d=!0;if(d){if(e.dependentSchemas!==void 0){let $=l;ia(e.dependentSchemas,{instancePath:t+"/dependentSchemas",parentData:e,parentDataProperty:"dependentSchemas",rootData:o,dynamicAnchors:i})||(s=s===null?ia.errors:s.concat(ia.errors),l=s.length);var d=$===l}else var d=!0;if(d){if(e.allOf!==void 0){let j=l;In(e.allOf,{instancePath:t+"/allOf",parentData:e,parentDataProperty:"allOf",rootData:o,dynamicAnchors:i})||(s=s===null?In.errors:s.concat(In.errors),l=s.length);var d=j===l}else var d=!0;if(d){if(e.anyOf!==void 0){let k=l;In(e.anyOf,{instancePath:t+"/anyOf",parentData:e,parentDataProperty:"anyOf",rootData:o,dynamicAnchors:i})||(s=s===null?In.errors:s.concat(In.errors),l=s.length);var d=k===l}else var d=!0;if(d){if(e.oneOf!==void 0){let P=l;In(e.oneOf,{instancePath:t+"/oneOf",parentData:e,parentDataProperty:"oneOf",rootData:o,dynamicAnchors:i})||(s=s===null?In.errors:s.concat(In.errors),l=s.length);var d=P===l}else var d=!0;if(d){if(e.prefixItems!==void 0){let T=l;In(e.prefixItems,{instancePath:t+"/prefixItems",parentData:e,parentDataProperty:"prefixItems",rootData:o,dynamicAnchors:i})||(s=s===null?In.errors:s.concat(In.errors),l=s.length);var d=T===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 me=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=me===l}else var d=!0;if(d){if(e.contains!==void 0){let Te=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=Te===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 V=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=V===l}else var d=!0;if(d){if(e.propertyNames!==void 0){let Re=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=Re===l}else var d=!0;if(d){if(e.type!==void 0){let be=e.type,ce=l,ye=l,ne=!1,ge=l;lo(be,{instancePath:t+"/type",parentData:e,parentDataProperty:"type",rootData:o,dynamicAnchors:i})||(s=s===null?lo.errors:s.concat(lo.errors),l=s.length);var v=ge===l;ne=ne||v;let xe=l;if(l===xe)if(Array.isArray(be))if(be.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=be.length;for(let ae=0;ae<we;ae++){let Se=l;lo(be[ae],{instancePath:t+"/type/"+ae,parentData:be,parentDataProperty:ae,rootData:o,dynamicAnchors:i})||(s=s===null?lo.errors:s.concat(lo.errors),l=s.length);var h=Se===l;if(!h)break}if(h){let ae=be.length,Se;if(ae>1){e:for(;ae--;)for(Se=ae;Se--;)if(XD(be[ae],be[Se])){let ze={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf/1/uniqueItems",keyword:"uniqueItems",params:{i:ae,j:Se}};s===null?s=[ze]:s.push(ze),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 v=xe===l;if(ne=ne||v,ne)l=ye,s!==null&&(ye?s.length=ye:s=null);else{let we={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf",keyword:"anyOf",params:{}};return s===null?s=[we]:s.push(we),l++,Ot.errors=s,!1}var d=ce===l}else var d=!0;if(d){if(e.enum!==void 0){let ce=e.enum,ye=l;if(l===ye)if(Array.isArray(ce)){if(ce.length<1)return Ot.errors=[{instancePath:t+"/enum",schemaPath:"#/properties/enum/minItems",keyword:"minItems",params:{limit:1}}],!1}else return Ot.errors=[{instancePath:t+"/enum",schemaPath:"#/properties/enum/type",keyword:"type",params:{type:"array"}}],!1;var d=ye===l}else var d=!0;if(d){if(e.title!==void 0){let ye=l;if(typeof e.title!="string")return Ot.errors=[{instancePath:t+"/title",schemaPath:"#/properties/title/type",keyword:"type",params:{type:"string"}}],!1;var d=ye===l}else var d=!0;if(d){if(e.description!==void 0){let ne=l;if(typeof e.description!="string")return Ot.errors=[{instancePath:t+"/description",schemaPath:"#/properties/description/type",keyword:"type",params:{type:"string"}}],!1;var d=ne===l}else var d=!0;if(d){if(e.examples!==void 0){let ge=l;if(!Array.isArray(e.examples))return Ot.errors=[{instancePath:t+"/examples",schemaPath:"#/properties/examples/type",keyword:"type",params:{type:"array"}}],!1;var d=ge===l}else var d=!0;if(d){if(e.readOnly!==void 0){let xe=l;if(typeof e.readOnly!="boolean")return Ot.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 Ot.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 Ot.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 ae=e.multipleOf,Se=l;if(l===Se)if(typeof ae=="number"&&isFinite(ae)){if(ae<=0||isNaN(ae))return Ot.errors=[{instancePath:t+"/multipleOf",schemaPath:"#/properties/multipleOf/exclusiveMinimum",keyword:"exclusiveMinimum",params:{comparison:">",limit:0}}],!1}else return Ot.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,ze=l;if(!(typeof Se=="number"&&isFinite(Se)))return Ot.errors=[{instancePath:t+"/maximum",schemaPath:"#/properties/maximum/type",keyword:"type",params:{type:"number"}}],!1;var d=ze===l}else var d=!0;if(d){if(e.exclusiveMaximum!==void 0){let ze=e.exclusiveMaximum,Qe=l;if(!(typeof ze=="number"&&isFinite(ze)))return Ot.errors=[{instancePath:t+"/exclusiveMaximum",schemaPath:"#/properties/exclusiveMaximum/type",keyword:"type",params:{type:"number"}}],!1;var d=Qe===l}else var d=!0;if(d){if(e.minimum!==void 0){let Qe=e.minimum,We=l;if(!(typeof Qe=="number"&&isFinite(Qe)))return Ot.errors=[{instancePath:t+"/minimum",schemaPath:"#/properties/minimum/type",keyword:"type",params:{type:"number"}}],!1;var d=We===l}else var d=!0;if(d){if(e.exclusiveMinimum!==void 0){let We=e.exclusiveMinimum,nt=l;if(!(typeof We=="number"&&isFinite(We)))return Ot.errors=[{instancePath:t+"/exclusiveMinimum",schemaPath:"#/properties/exclusiveMinimum/type",keyword:"type",params:{type:"number"}}],!1;var d=nt===l}else var d=!0;if(d){if(e.maxLength!==void 0){let nt=l;$t(e.maxLength,{instancePath:t+"/maxLength",parentData:e,parentDataProperty:"maxLength",rootData:o,dynamicAnchors:i})||(s=s===null?$t.errors:s.concat($t.errors),l=s.length);var d=nt===l}else var d=!0;if(d){if(e.minLength!==void 0){let qe=l;$t(e.minLength,{instancePath:t+"/minLength",parentData:e,parentDataProperty:"minLength",rootData:o,dynamicAnchors:i})||(s=s===null?$t.errors:s.concat($t.errors),l=s.length);var d=qe===l}else var d=!0;if(d){if(e.maxItems!==void 0){let Ze=l;$t(e.maxItems,{instancePath:t+"/maxItems",parentData:e,parentDataProperty:"maxItems",rootData:o,dynamicAnchors:i})||(s=s===null?$t.errors:s.concat($t.errors),l=s.length);var d=Ze===l}else var d=!0;if(d){if(e.minItems!==void 0){let He=l;$t(e.minItems,{instancePath:t+"/minItems",parentData:e,parentDataProperty:"minItems",rootData:o,dynamicAnchors:i})||(s=s===null?$t.errors:s.concat($t.errors),l=s.length);var d=He===l}else var d=!0;if(d){if(e.maxContains!==void 0){let L=l;$t(e.maxContains,{instancePath:t+"/maxContains",parentData:e,parentDataProperty:"maxContains",rootData:o,dynamicAnchors:i})||(s=s===null?$t.errors:s.concat($t.errors),l=s.length);var d=L===l}else var d=!0;if(d){if(e.minContains!==void 0){let O=l;$t(e.minContains,{instancePath:t+"/minContains",parentData:e,parentDataProperty:"minContains",rootData:o,dynamicAnchors:i})||(s=s===null?$t.errors:s.concat($t.errors),l=s.length);var d=O===l}else var d=!0;if(d){if(e.maxProperties!==void 0){let z=l;$t(e.maxProperties,{instancePath:t+"/maxProperties",parentData:e,parentDataProperty:"maxProperties",rootData:o,dynamicAnchors:i})||(s=s===null?$t.errors:s.concat($t.errors),l=s.length);var d=z===l}else var d=!0;if(d){if(e.minProperties!==void 0){let X=l;$t(e.minProperties,{instancePath:t+"/minProperties",parentData:e,parentDataProperty:"minProperties",rootData:o,dynamicAnchors:i})||(s=s===null?$t.errors:s.concat($t.errors),l=s.length);var d=X===l}else var d=!0;if(d){if(e.uniqueItems!==void 0){let fe=l;if(typeof e.uniqueItems!="boolean")return Ot.errors=[{instancePath:t+"/uniqueItems",schemaPath:"#/properties/uniqueItems/type",keyword:"type",params:{type:"boolean"}}],!1;var d=fe===l}else var d=!0;if(d){if(e.required!==void 0){let Me=l;ha(e.required,{instancePath:t+"/required",parentData:e,parentDataProperty:"required",rootData:o,dynamicAnchors:i})||(s=s===null?ha.errors:s.concat(ha.errors),l=s.length);var d=Me===l}else var d=!0;if(d){if(e.dependentRequired!==void 0){let Le=e.dependentRequired,et=l;if(l===et)if(Le&&typeof Le=="object"&&!Array.isArray(Le))for(let st in Le){let mt=l;ha(Le[st],{instancePath:t+"/dependentRequired/"+st.replace(/~/g,"~0").replace(/\//g,"~1"),parentData:Le,parentDataProperty:st,rootData:o,dynamicAnchors:i})||(s=s===null?ha.errors:s.concat(ha.errors),l=s.length);var y=mt===l;if(!y)break}else return Ot.errors=[{instancePath:t+"/dependentRequired",schemaPath:"#/properties/dependentRequired/type",keyword:"type",params:{type:"object"}}],!1;var d=et===l}else var d=!0;if(d){if(e.contentEncoding!==void 0){let et=l;if(typeof e.contentEncoding!="string")return Ot.errors=[{instancePath:t+"/contentEncoding",schemaPath:"#/properties/contentEncoding/type",keyword:"type",params:{type:"string"}}],!1;var d=et===l}else var d=!0;if(d)if(e.contentMediaType!==void 0){let et=l;if(typeof e.contentMediaType!="string")return Ot.errors=[{instancePath:t+"/contentMediaType",schemaPath:"#/properties/contentMediaType/type",keyword:"type",params:{type:"string"}}],!1;var d=et===l}else var d=!0}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}return Ot.errors=s,l===0}Ot.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};const fy="https://json-schema.org/draft/2020-12/schema",tL=1048576,nL=32768,aL=new Set(["properties","$defs","dependentSchemas"]),oL=new Set(["allOf","anyOf","oneOf","prefixItems"]),rL=new Set(["items","additionalProperties","not","if","then","else","contains","unevaluatedProperties","unevaluatedItems","propertyNames"]);function Go(e,t=tL){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 Pg(e){try{return iL(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 iL(e){if(Go(e,nL),Sl(e,e,new Set,0,{remaining:2048}),!my(e)){const t=my.errors?.[0];throw new Error(`Task schema ${t?.instancePath||"/"} violates ${t?.keyword??"schema"}.`)}}function Sl(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!==fy)throw new Error(`Task schemas must use ${fy}.`);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 v=h.replaceAll("~1","/").replaceAll("~0","~");if(!d||typeof d!="object"||!Object.hasOwn(d,v))throw new Error(`Task schema reference ${m} is missing.`);d=d[v]}Sl(d,t,i,a+1,o)}else if(aL.has(l)){if(!m||typeof m!="object"||Array.isArray(m))throw new Error(`Invalid schema map ${l}.`);for(const d of Object.values(m))Sl(d,t,i,a+1,o)}else if(oL.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)Sl(d,t,i,a+1,o)}else rL.has(l)&&Sl(m,t,i,a+1,o)}const sL=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:Q,responseHash:Q,inputTokens:u().int().nonnegative().nullable(),outputTokens:u().int().nonnegative().nullable(),costUsd:u().finite().nonnegative().nullable()}).strict(),lL=c({schemaVersion:S("openpond.graderEvidence.v1"),graderId:E,graderVersion:r().trim().min(1).max(100),score:u().min(0).max(1).nullable(),passed:A(),rewardEligible:A(),failureClass:tc.nullable(),feedback:p(r().max(2e4)).max(1e3),visibleEvidenceRefs:p(E).max(1e4),privilegedEvidenceRefs:p(E).max(1e4),modelJudgeReceipt:sL.optional()}).strict(),cL=lL.extend({contentHash:Q}).strict();c({score:u().min(0).max(1).nullable(),passed:A(),rewardEligible:A(),failureClass:tc.nullable(),gradingStatus:b(["scored","unscorable","not_configured"])}).strict();const hy=r().trim().min(1).max(240),dL=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."),xu=c({schemaVersion:S("openpond.tasksetMetricPolicy.v1"),primaryMetric:hy,aggregation:b(["mean_score","pass_rate","weighted_mean","custom"]),missingReward:b(["zero","exclude"]),taskWeights:re(hy,u().positive().max(1e6)).optional(),customAggregator:c({module:dL,exportName:r().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),contentHash:Q,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."})}),uL=c({schemaVersion:S("openpond.tasksetMetricResult.v1"),runManifest:J,tasksetRelease:J,policy:xu,policyHash:Q,receiptRefs:p(J).min(1).max(1e6),includedCount:u().int().nonnegative(),missingRewardCount:u().int().nonnegative(),excludedCount:u().int().nonnegative(),value:u().min(0).max(1).nullable()}).strict(),mL=uL.extend({contentHash:Q}).strict(),Zo=b(["train","validation","test","frozen_eval"]),pL=c({path:r().trim().min(1).max(2e3).refine(hL),mediaType:r().trim().min(1).max(200),schemaRef:ln.nullable().default(null),maxBytes:u().int().positive().max(25e7).nullable().default(null),metadata:_n}).strict(),fL=c({policyVisibleFields:p(E).max(1e3).default([]),privilegedFields:p(E).max(1e3).default([]),hiddenGraderRefs:p(E).max(1e3).default([]),connectedAppScopes:p(E).max(100).default([])}).strict(),jw=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(),ku=c({id:E,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)}),Ow=ku.extend({kind:b(["content","schema","artifact","runtime_event","state"]),config:re(r(),de())}).strict(),$w=ku.extend({kind:S("model_judge"),rubricRef:ln,calibrationStatus:b(["pending","passed","failed"]),model:c({providerId:E,modelId:E,revision:r().trim().min(1).max(500).nullable()}).strict().optional(),temperature:u().min(0).max(2).optional()}).strict(),Nw=b(["isolated_javascript","sandbox_process"]),Dw=ku.extend({kind:S("custom_verifier"),runtime:Nw.optional(),verifierRef:ln,exportName:r().trim().min(1).max(240).optional(),timeoutMs:u().int().positive().max(3e5),networkPolicy:S("none")}).strict(),Lw=ku.extend({kind:S("human"),rubricRef:ln,reviewerRole:r().trim().min(1).max(500)}).strict(),Uw=Nt([Ow,$w,Dw,Lw]),Ag=c({id:E,clusterKey:E,split:Zo,input:re(r(),de()),expectedOutput:re(r(),de()).nullable(),policyVisibleContext:re(r(),de()).default({}),privilegedContextRef:E.nullable(),artifactRefs:p(ln).max(1e3).default([]),requiredOutputs:p(pL).max(1e3).optional(),tags:p(E).max(100).default([])}).strict(),Hw=c({schemaVersion:S("openpond.tasksetRelease.v2"),id:E,revision:u().int().positive(),policy:fL,environment:jw,environmentRelease:c({id:E,contentHash:Q}).strict().optional(),tools:p(sc).max(200),capabilities:p(sg).max(200),tasks:p(Ag).min(1).max(1e6),graders:p(Uw).min(1).max(1e3),verifierSetRelease:c({id:E,contentHash:Q}).strict().optional(),metrics:xu.optional(),metadata:_n}).strict(),zw=Hw.extend({contentHash:Q}).strict();function hL(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}const Zc={id:!0,version:!0,weight:!0,hardGate:!0,rewardEligible:!0,privileged:!0},gL=Nt([Ow.omit(Zc),$w.omit(Zc),Dw.omit(Zc),Lw.omit(Zc),c({kind:S("learned_model"),modelVersion:J,inputContract:ln}).strict()]),qw=c({schemaVersion:S("openpond.rewardRelease.v1"),id:E,revision:u().int().positive(),name:r().trim().min(1).max(500),description:r().max(1e4),implementation:gL,rawScore:c({minimum:u().finite(),maximum:u().finite()}).strict(),assets:p(ln).max(1e3),fixtureSetRef:ln.optional(),calibrationCheckRef:J.extend({revision:u().int().positive()}).optional()}).strict().superRefine((e,t)=>{if(e.fixtureSetRef&&(e.fixtureSetRef.visibility!=="verifier"||!e.assets.some(n=>rn(n)===rn(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=Pg(e.implementation.config.jsonSchema);n.valid||t.addIssue({code:"custom",path:["implementation","config","jsonSchema"],message:n.issues[0].message})}}),wu=qw.safeExtend({contentHash:Q}).strict(),mc=J.extend({revision:u().int().positive()}).strict(),vL=It("kind",[c({kind:S("identity")}).strict(),c({kind:S("linear"),minimum:u().finite(),maximum:u().finite(),direction:b(["higher","lower"])}).strict()]),bL=c({graderId:E,reward:mc,role:b(["training","evaluation"]),normalization:vL,weight:u().nonnegative().max(1e3),required:A(),hardGate:A(),privileged:A(),fixtureRefs:p(J).max(1e3)}).strict(),yL=c({schemaVersion:S("openpond.rewardBinding.v1"),id:E,revision:u().int().positive(),name:r().trim().min(1).max(500).optional(),description:r().max(1e4).optional(),recipeRef:mc.optional(),sources:p(bL).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."})}),Iu=yL.safeExtend({contentHash:Q}).strict(),SL=c({graderId:E,reward:mc,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(Q).max(1e3),graderEvidence:cL.optional(),message:r().max(2e4).nullable()}).strict(),xL=c({schemaVersion:S("openpond.rewardComposition.v1"),binding:mc,taskHash:Q,outputHash:Q,results:p(SL).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(),Ld=xL.extend({contentHash:Q}).strict();function ZY(e){Go(e);const t=qw.parse(e);return wu.parse({...t,contentHash:rn(t)})}const kL=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(),wL=c({id:E,requestHash:Q,reservedUsd:u().finite().positive(),status:b(["reserved","settled","not_dispatched"]),response:kL.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."})}),Bw=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(),Ht=re(r(),Wr()),xt=mc,or=r().max(2e3).refine(e=>e===""||e.startsWith("/")&&!/~(?![01])/u.test(e),"Use an RFC 6901 JSON pointer."),IL=c({schemaVersion:S("openpond.taskDefinition.v1"),id:E,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:E,inputSchema:re(r(),de()),outputSchema:re(r(),de()),requiredOutputs:Ag.shape.requiredOutputs,contextRequirements:p(r().trim().min(1).max(2e3)).max(100).optional(),rewardBinding:xt,harness:J.nullable(),execution:Hw.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=Pg(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."})}),_u=IL.safeExtend({contentHash:Q}).strict(),_L=c({schemaVersion:S("openpond.taskSourceMapping.v1"),exampleId:or,attemptId:or,occurredAt:or,input:or,observedOutput:or.nullable(),expected:or.nullable(),evaluatorContext:or.nullable(),familyKey:or,split:Zo}).strict(),CL=c({modelId:E,packageHash:Q,taskset:xt,batch:xt,rewardBinding:xt}).strict(),RL=c({schemaVersion:S("openpond.learningSource.v1"),id:E,revision:u().int().positive(),name:r().trim().min(1).max(500),kind:b(["direct","benchmark","work","opentelemetry","provider"]),taskDefinition:xt,enabled:A(),allowedSplits:p(Zo).min(1).max(4),mapping:_L.nullable(),adapterVersion:r().trim().min(1).max(200).nullable(),reviewOrigin:CL.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."})}),Tg=RL.safeExtend({contentHash:Q}).strict(),PL=c({schemaVersion:S("openpond.taskExample.v1"),sourceId:E,idempotencyKey:E,taskDefinition:xt,exampleId:E,attemptId:E,occurredAt:Ee,familyKey:E.nullable(),split:Zo,input:Ht,observedOutput:Ht.nullable(),expected:Ht.nullable(),evaluatorContext:Ht.nullable(),assets:p(ln).max(1e3),requiredOutputs:Ag.shape.requiredOutputs,provenance:c({sourceRecordRef:r().max(2e3).nullable(),mappingHash:Q.nullable()}).strict()}).strict(),AL=c({schemaVersion:S("openpond.taskEvidence.v1"),id:E,revision:u().int().positive(),source:xt,submission:PL,supersedes:xt.nullable(),correctionFeedbackId:E.nullable(),receivedAt:Ee}).strict(),Cu=AL.extend({contentHash:Q}).strict(),TL=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."})}),EL=c({schemaVersion:S("openpond.taskFeedback.v1"),sourceId:E,idempotencyKey:E,exampleId:E,attemptId:E,expectedEvidenceHash:Q.nullable(),occurredAt:Ee,kind:b(["outcome","target_correction","ground_truth_correction","input_correction","family_resolution"]),value:Ht,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=TL.safeParse(e.value);if(!n.success)for(const a of n.error.issues)t.addIssue({code:"custom",path:["value",...a.path],message:a.message})}),Fw=c({schemaVersion:S("openpond.taskFeedbackRecord.v1"),id:E,submission:EL,status:b(["pending_example","pending_review","applied","superseded","rejected"]),evidence:xt.nullable(),createdAt:Ee,revision:u().int().positive(),submittedBy:c({id:E,role:b(["editor","reviewer","source"]),sourceId:E.nullable()}).strict().nullable().default(null),review:c({actorId:E,decision:xt.nullable(),note:r().max(2e4),resolvedAt:Ee}).strict().nullable().default(null)}).strict(),ML=c({schemaVersion:S("openpond.taskAdmissionDecision.v1"),id:E,revision:u().int().positive(),evidence:xt,supersedes:xt.nullable(),actor:c({kind:b(["human","qualified_policy"]),id:E,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:Ht.nullable(),grade:Ld.nullable(),targetGrade:Ld.nullable(),note:r().max(2e4),decidedAt:Ee}).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."})}),Eg=ML.safeExtend({contentHash:Q}).strict(),jL=c({schemaVersion:S("openpond.taskBatch.v1"),id:E,revision:S(1),taskDefinition:xt,rewardBinding:xt,purpose:b(["supervised_training","reward_training","evaluation"]),examples:p(c({evidence:xt,decision:xt,familyKey:E,inputHash:Q,split:Zo}).strict()).min(1).max(1e4),sealedAt:Ee,sealedBy:E}).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)}}),Vw=jL.safeExtend({contentHash:Q}).strict(),OL=c({schemaVersion:S("openpond.learningPolicy.v1"),id:E,revision:u().int().positive(),modelProjectId:E,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:J.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(),Bw.extend({kind:S("nightly")}).strict(),c({kind:S("upstream_accepted"),modelProjectId:E}).strict()]),trainingParent:J,teacher:J.nullable(),training:c({method:b(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),recipe:J,retentionEvaluation:J,replayBatches:p(J).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:J.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."})}),$L=OL.safeExtend({contentHash:Q}).strict(),NL=c({iterationId:E,iterationRevision:u().int().positive(),candidate:J,decision:xt,decidedAt:Ee}).strict(),DL=b(["waiting_for_data","waiting_for_review","ready","dispatching","training","evaluating","candidate_ready","accepted","rejected","paused","failed","cancelling","cancelled","completed_without_candidate"]),LL=c({schemaVersion:S("openpond.learningIteration.v1"),id:E,revision:u().int().positive(),policy:xt,status:DL,triggerIdentity:E,batch:xt.nullable(),sourceWatermarks:re(E,u().int().nonnegative()),trainingParent:J,trainingParentSelection:NL.nullable().optional(),teacher:J.nullable(),upstreamEvent:J.nullable(),trainingJob:J.nullable(),evaluationJob:J.nullable(),candidateVersion:J.nullable(),candidateDecision:xt.nullable().default(null),candidateDecisionAt:Ee.nullable().optional(),dispatchId:E,retryCount:u().int().nonnegative(),spendUsd:u().nonnegative(),failure:c({code:E,message:r().max(2e4)}).strict().nullable(),createdAt:Ee,updatedAt:Ee}).strict(),UL=c({schemaVersion:S("openpond.taskGradeRun.v1"),id:E,revision:u().int().positive(),evidence:xt,binding:xt,target:b(["observed","proposed_target"]),output:Ht,status:b(["queued","running","completed","failed","cancelling","cancelled"]),composition:Ld.nullable(),leaseOwner:E.nullable(),leaseExpiresAt:Ee.nullable(),attemptCount:u().int().nonnegative(),timeoutMs:u().int().min(100).max(3e5),maximumSpendUsd:u().nonnegative().max(1e3),judgeCalls:p(wL).max(1e4).optional(),requestedBy:E.optional(),failure:r().max(2e4).nullable(),createdAt:Ee,updatedAt:Ee}).strict();Nt([_u,wu,Iu,Tg,Cu,Fw,Eg,Vw,$L,LL,UL]);function HL(e){return xt.parse({id:e.id,revision:e.revision,contentHash:e.contentHash})}function JY(e,t){return e.id===t.id&&e.revision===t.revision&&e.contentHash===t.contentHash}function YY(e){return Go(e,16777216),{...e,contentHash:rn(e)}}function QY(e){const{contentHash:t,...n}=e;if(Go(n,16777216),rn(n)!==t)throw new Ew("learning_content_hash_mismatch",422)}const Kw=c({schemaVersion:S("openpond.learningTextAsset.v1"),id:E,revision:S(1),asset:ln,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!==Hh(e.text)&&t.addIssue({code:"custom",path:["asset","contentHash"],message:"Asset source does not match its SHA-256."})}),Ru=Kw.safeExtend({contentHash:Q}).strict();function XY(e){Go(e);const{text:t,...n}=e,a=Hh(t),o=`asset-${a}-${rn(n).slice(0,16)}`,i=Kw.parse({schemaVersion:"openpond.learningTextAsset.v1",id:o,revision:1,asset:{...n,id:o,contentHash:a,sizeBytes:new TextEncoder().encode(t).byteLength},text:t});return Ru.parse({...i,contentHash:rn(i)})}function eQ(e,t){const{contentHash:n,...a}=Ru.parse(e);if(rn(a)!==n||rn(a.asset)!==rn(t))throw new Ew("learning_asset_reference_mismatch",409);return a.text}const za={bytes:5*1024*1024,records:1e3,files:100,messages:2e3},Ww=b(["json","jsonl","csv","hermes","openclaw"]),zL=c({path:r().min(1).max(500),text:r()}).strict(),Mg=c({id:r().min(1).max(200),familyKey:r().min(1).max(200),split:Zo,kind:b(["task","attempt"]),input:Ht,observedOutput:Ht.nullable(),expected:Ht.nullable(),sourceId:r().min(1).max(2e3),sourceHash:r().length(64),occurredAt:r().datetime().nullable(),metadata:Ht,warnings:p(r().max(2e3)).max(100),needsContext:A()}).strict(),Gw=c({schemaVersion:S("openpond.taskIntakePreview.v1"),format:Ww,contentHash:r().length(64),records:p(Mg).max(za.records),issues:p(c({file:r(),row:u().int().positive().nullable(),message:r()}).strict()).max(1e3)}).strict();function Ud(e,t){return`${e}-${rn(t)}`}function Zw(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 qL(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>za.records+1)throw new Error("CSV exceeds the 1,000-record limit.")};for(let h=0;h<e.length;h++){const v=e[h];if(o)v==='"'&&e[h+1]==='"'?(a+='"',h++):v==='"'?(o=!1,i=!0):a+=v;else if(v===",")s();else if(v===`
|
|
175
|
+
`||v==="\r")v==="\r"&&e[h+1]===`
|
|
176
|
+
`&&h++,l();else if(v==='"'&&!a&&!i)o=!0;else{if(i||v==='"')throw new Error("CSV has an invalid quoted field.");a+=v}}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,v)=>{if(h.length!==m.length)throw new Error(`CSV record ${v+2} has a different number of columns from its header.`);return Object.fromEntries(m.map((y,w)=>[y,h[w]]).filter(([,y])=>y!==""))})}function tQ(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 Jw(e){return e.startsWith("\uFEFF")?e.slice(1):e}const Yw=c({role:r().min(1),content:Wr().nullable().optional()}).catchall(Wr()),BL=c({id:r().min(1),messages:p(Yw).min(1).max(za.messages),lineage_session_ids:p(r()).optional(),parent_session_id:r().nullable().optional()}).catchall(Wr());function FL(e){const t=BL.parse(e),n=t.lineage_session_ids?.[0]??t.parent_session_id??t.id,{messages:a,segments:o,...i}=t;return Qw("hermes",t.id,n,t.messages,{sourceHash:rn(e),metadata:{session:i},warnings:["Imported session context and tools need review before this can become an executable task."]})}const VL=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(Ht).optional()}).catchall(Wr()),KL=c({traceSchema:S("openclaw-trajectory"),schemaVersion:S(1),traceId:r(),sessionId:r(),seq:u().int().nonnegative(),type:r(),ts:r()}).catchall(Wr()),WL=c({header:Ht.nullable(),leafId:r().nullable(),entries:p(c({id:r().min(1),type:r().min(1),parentId:r().nullable().optional(),message:Yw.optional()}).catchall(Wr())).max(za.messages)}).strict();function GL(e){const t=l=>{const m=e.find(d=>d.path===l);if(!m)throw new Error(`OpenClaw bundle is missing ${l}.`);return Jw(m.text)},n=VL.parse(JSON.parse(t("manifest.json"))),a=WL.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=>KL.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 Qw("openclaw",n.sessionId,n.sessionId,s,{sourceHash:rn(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 Qw(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),v=h.filter(R=>R.role==="assistant").at(-1),y=a[l],w=y.entryId??y.message_id??y.id??rn({start:l,request:y}),_={id:Ud(e,[t,w]),familyKey:Ud(e,n),split:"train",kind:"attempt",input:{request:y.content??null,messages:a.slice(0,l+1)},observedOutput:v?{response:v.content??null,messages:h}:null,expected:null,sourceId:`${e}:${t}:${String(w)}`,sourceHash:o.sourceHash,occurredAt:Zw(v?.timestamp??y.timestamp),metadata:o.metadata,warnings:[...o.warnings,...v?[]:["No assistant response was recorded for this request."]],needsContext:!0};if(Go(_),s+=new TextEncoder().encode(JSON.stringify(_)).length,s>za.bytes)throw new Error("Expanded history exceeds the 5 MiB preview limit. Export a smaller session selection.");return Mg.parse(_)})}const ZL=c({instruction:r().trim().min(1).max(1e5),context:Nt([r(),Ht]).optional(),reference:Nt([r(),Ht]).optional(),labels:Nt([r(),p(r()),Ht]).optional(),id:r().min(1).max(200).optional(),familyKey:r().min(1).max(200).optional(),split:Zo.optional()}).strict(),JL=c({input:Ht,observedOutput:Ht.nullable().optional(),expectedOutput:Ht.nullable().optional(),id:r().min(1).max(200).optional(),familyKey:r().min(1).max(200).optional(),split:Zo.optional(),occurredAt:r().datetime().optional(),labels:Ht.optional()}).strict();function YL(e){const t=Ww.parse(e.format),n=p(zL).min(1).max(za.files).parse(e.files);if(n.reduce((d,h)=>d+new TextEncoder().encode(h.text).length,0)>za.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,v){try{const y=v();if(a.length+y.length>za.records)throw new Error("Import exceeds the 1,000-record limit.");const w=new Map(i),_=new Map(s);let R=0;for(const M of y){Go(M);const C=rn(M),N=w.get(M.id);if(N&&N!==C)throw new Error("The same record identity has different content in this upload.");N||(R+=new TextEncoder().encode(JSON.stringify(M)).length),w.set(M.id,C);for(const $ of[`family:${M.familyKey}`,`input:${rn(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+R>za.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,rn(M));for(const[M,C]of _)s.set(M,C);l+=R}catch(y){o.push({file:d,row:h,message:y instanceof $E?`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,()=>GL(n));else for(const d of n){const h=Jw(d.text);if(t==="jsonl"||t==="hermes"){for(const[v,y]of h.split(/\r?\n/u).entries())if(y.trim()){if(o.length>=za.records)break;m(d.path,v+1,()=>t==="hermes"?FL(JSON.parse(y)):[gy(JSON.parse(y))])}}else{let v;try{const y=t==="csv"?qL(h):JSON.parse(h);v=Array.isArray(y)?y:[y]}catch(y){m(d.path,null,()=>{throw y});continue}if(v.length>za.records){m(d.path,null,()=>{throw new Error("Import exceeds the 1,000-record limit.")});continue}v.forEach((y,w)=>m(d.path,w+(t==="csv"?2:1),()=>[gy(y)]))}}return Gw.parse({schemaVersion:"openpond.taskIntakePreview.v1",format:t,contentHash:rn({format:t,files:n}),records:a,issues:o.slice(0,1e3)})}function gy(e){const t=Nt([ZL,JL]).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??Ud("family",a),l=t.id??Ud("task",{input:a,expected:o,observedOutput:i});return Mg.parse({id:l,familyKey:s,split:t.split??"train",kind:i?"attempt":"task",input:a,expected:o,observedOutput:i,sourceId:l,sourceHash:rn(e),occurredAt:n?null:Zw(t.occurredAt),metadata:t.labels===void 0?{}:{importedLabels:t.labels,labelOrigin:"unverified_import"},warnings:[],needsContext:!1})}const Hl=r().trim().min(1).max(240),sr=r().regex(/^[a-f0-9]{64}$/),QL=c({id:Hl,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:J}).strict().optional(),dataset:J,evaluator:J,executionHash:sr,populationHash:sr,metric:Hl,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."})}),XL=c({schemaVersion:S("openpond.acceptancePlan.v1"),id:Hl,revision:u().int().positive(),checks:p(QL).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."})}),eU=XL.safeExtend({contentHash:sr}),tU=c({runId:Hl,artifact:J,checkHash:sr,populationHash:sr,scoredPopulationHash:sr,executionHash:sr,evaluator:J,metric:Hl,expectedCount:u().int().positive(),scoredCount:u().int().nonnegative(),score:u().finite().nullable(),status:b(["pending","running","completed","failed","cancelled"]),evidenceHash:sr}).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."})}),lr=r().trim().min(1).max(240),jg=r().regex(/^[a-f0-9]{64}$/),Hd=bx(),vy=u().finite().nonnegative(),nU=new Set(["completed","failed","cancelled","budget_exhausted"]),aU=c({schemaVersion:S("openpond.acceptanceGroupManifest.v1"),id:lr,teamId:lr,trainingJob:J,baseline:J,candidate:J,plan:eU,maximumParallelAttempts:u().int().min(1).max(8),createdAt:Hd}).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."})}),oU=aU.safeExtend({contentHash:jg}),rU=c({id:lr,checkId:lr,subject:b(["baseline","candidate"]),ordinal:u().int().positive(),dispatchId:lr,state:b(["queued","dispatching","running","grading","cleaning","completed","failed","cancelled","budget_exhausted"]),artifact:J,checkHash:jg,measurement:tU.nullable(),executionReceipt:J.nullable(),reusedFrom:c({group:J,attemptId:lr}).strict().nullable(),spendUsd:vy,reservedUsd:vy,cleanupComplete:A(),accountingComplete:A(),failureCode:lr.nullable(),createdAt:Hd,updatedAt:Hd}).strict().superRefine((e,t)=>{Date.parse(e.updatedAt)<Date.parse(e.createdAt)&&t.addIssue({code:"custom",message:"Attempt timestamps are reversed."}),nU.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."})}),iU=c({schemaVersion:S("openpond.acceptanceGroupSnapshot.v1"),manifest:oU,revision:u().int().positive(),state:b(["queued","running","blocked","cancelling","cleaning","completed","failed","cancelled","budget_exhausted"]),attempts:p(rU).max(2e3),failureCode:lr.nullable(),updatedAt:Hd}).strict(),sU=iU.extend({contentHash:jg});var Zr=xt.shape.id,zl=r().regex(/^[a-f0-9]{64}$/),lU=c({scopeId:Zr,modelId:Zr}).strict(),cU=c({schemaVersion:S("openpond.modelTasksetAuthoring.v1"),owner:lU,root:xt,parent:xt}).strict(),nQ=c({schemaVersion:S("openpond.modelTasksetDraftRequest.v1"),operationId:Zr,modelId:Zr,expectedModelRevision:u().int().positive(),sourcePackageHash:zl}).strict(),dU=c({schemaVersion:S("openpond.modelTasksetDraftPreparation.v1"),draftId:Zr,requestHash:zl,sourcePackageHash:zl,sourceTasksetRef:xt,tasksetId:Zr,tasksetRevision:u().int().positive(),lineage:cU,authoringGraph:S("bound").optional()}).strict(),Pu=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."),Xw=c({path:Pu,sizeBytes:u().int().nonnegative(),writable:A()}).strict(),e1=c({encoding:b(["utf8","base64"]),data:r().max(8e6)}).strict(),uU=Xw.extend({contentHash:zl,content:e1}).strict();c({draftId:Zr,expectedDraftRevision:u().int().positive(),path:Pu,expectedFileHash:zl.nullable(),content:e1.nullable()}).strict();var mU=Bw.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."})}),pU=67108864,Uf=524288,xl=class extends Error{code;constructor(e,t){super(t),this.name="OpenPondProtocolError",this.code=e}};function t1(e){return JSON.stringify(Hf(e))}function fU(e){return new TextEncoder().encode(t1(e)).byteLength}async function hU(e){const t=new TextEncoder().encode(t1(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 gU(e,t,n){const a=fU(e);if(a>t)throw new xl("payload_too_large",`${n} is ${a} bytes; the maximum is ${t} bytes.`)}function Hf(e){if(e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number"){if(!Number.isFinite(e))throw new xl("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=>Hf(t));if(typeof e=="object"){const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)throw new xl("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 xl("non_json_value",`Canonical JSON cannot contain ${typeof o} at ${a}.`);n[a]=Hf(o)}return n}throw new xl("non_json_value",`Canonical JSON cannot contain ${typeof e}.`)}var Mt=r().trim().min(1).max(500),co=r().regex(/^[a-f0-9]{64}$/),Sa=r().datetime({offset:!0}),Ct=c({id:Mt,contentHash:co}).strict(),Lo=Ct.extend({revision:u().int().positive()}).strict(),ai=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(),n1=b(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),a1=c({schemaVersion:r().regex(/^openpond\.[A-Za-z0-9]+Recipe\.v\d+$/),method:n1,parameterization:b(["lora","full"])}).catchall(de()),vU=c({profileProjectId:Mt,sourceRevision:r().regex(/^[a-f0-9]{40,64}$/),harnessRelease:Ct}).strict(),bU=c({profileProjectId:Mt,sourceRevision:r().regex(/^[a-f0-9]{40,64}$/),catalogHash:co,definitionId:Mt,harnessRelease:Ct,tasksetRelease:Ct}).strict(),o1=c({tasksetRef:Lo.nullable().default(null),evaluationTasksetRef:Lo.nullable().optional(),profileSource:vU.nullable().optional(),profileEvaluation:bU.nullable().optional(),rewardBindingRef:Lo.nullable().optional(),tasksetRelease:Ct.nullable().default(null),harnessRelease:Ct.nullable().default(null),baseModel:ai.nullable().default(null),method:n1.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:a1.nullable().default(null),preferredMaximumSpendUsd:u().nonnegative().nullable().default(null),preferredRetentionDays:u().int().nonnegative().nullable().default(null)}).strict(),Og=o1.omit({managedGpuRequirement:!0}),yU=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:co,syncedSourceRevision:u().int().positive(),syncedAt:Sa,tasksets:p(c({localTasksetId:Mt,localTasksetHash:co.nullable().default(null),releaseId:Mt,releaseRevision:u().int().positive(),releaseHash:co,packageHash:co.nullable().default(null),hostedTasksetId:Mt,syncedAt:Sa}).strict()).max(1e4).default([])}).strict(),SU=c({localTasksetId:Mt,releaseId:Mt,releaseRevision:u().int().positive(),releaseHash:co,state:b(["syncing","synced","sync_failed"]),hostedTasksetId:Mt.nullable().default(null),lastAttemptAt:Sa,syncedAt:Sa.nullable().default(null),lastError:r().trim().min(1).max(5e3).nullable().default(null)}).strict(),r1=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:ai.nullable(),defaultDestinationId:Mt.nullable(),trainingSetup:o1,hosted:yU.nullable().default(null),tasksetSyncs:p(SU).max(1e4).default([]),createdAt:Sa,updatedAt:Sa}).strict(),i1=r1.pick({id:!0,profileId:!0,name:!0,objective:!0,defaultBaseModel:!0,defaultDestinationId:!0,trainingSetup:!0}),xU=c({schemaVersion:S("openpond.modelProjectSave.v1"),operationId:Mt,expectedRevision:u().int().nonnegative(),project:i1,learning:mU.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."})}),s1=c({schemaVersion:S("openpond.modelProjectConfigurationCheck.v1"),configurationHash:co,projectId:Mt,expectedRevision:u().int().nonnegative(),checkedAt:Sa,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:ai}).strict();function kU(e){try{Go(e,Uf)}catch{throw new CU(400,{schemaVersion:"openpond.modelProjectApiError.v2",code:"model_configuration_json_invalid",message:"Model configuration must be bounded JSON data.",retryable:!1,requestId:null,details:{}})}return xU.parse(e)}async function wU(e,t,n){Go(e,Uf);const a=i1.parse(e);gU(a,Uf,"Model configuration");const o=await hU({project:a,expectedRevision:t});return kU({schemaVersion:"openpond.modelProjectSave.v1",operationId:`model-save:${o}`,expectedRevision:t,project:a})}var IU=c({schemaVersion:S("openpond.hostedModelProjectSync.v2"),portableProjectId:Mt,name:r().trim().min(1).max(200),objective:r().trim().max(5e3).nullable(),defaultBaseModel:ai.nullable(),defaultDestinationId:Mt.nullable(),trainingSetup:Og,sourceRevision:u().int().positive(),sourceUpdatedAt:Sa,expectedEtag:co.nullable().default(null)}).strict(),l1=c({id:Mt,teamId:Mt,portableProjectId:Mt,name:r().trim().min(1).max(200),objective:r().trim().max(5e3).nullable(),defaultBaseModel:ai.nullable(),defaultDestinationId:Mt.nullable(),trainingSetup:Og,sourceRevision:u().int().positive(),sourceUpdatedAt:Sa,revision:u().int().positive(),etag:co,createdAt:Sa,updatedAt:Sa}).strict(),_U=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:Sa}).strict();c({project:l1,resources:p(_U).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(),de()).default({})}).strict();var CU=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}},RU=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),PU=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 AU(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(RU),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=oo(N,7)^oo(N,18)^N>>>3,k=oo($,17)^oo($,19)^$>>>10;l[C]=l[C-16]+j+l[C-7]+k>>>0}let d=s[0],h=s[1],v=s[2],y=s[3],w=s[4],_=s[5],R=s[6],M=s[7];for(let C=0;C<64;C+=1){const N=w&_^~w&R,$=d&h^d&v^h&v,j=oo(d,2)^oo(d,13)^oo(d,22),k=oo(w,6)^oo(w,11)^oo(w,25),P=M+k+N+PU[C]+l[C]>>>0,T=j+$>>>0;M=R,R=_,_=w,w=y+P>>>0,y=v,v=h,h=d,d=P+T>>>0}s[0]=s[0]+d>>>0,s[1]=s[1]+h>>>0,s[2]=s[2]+v>>>0,s[3]=s[3]+y>>>0,s[4]=s[4]+w>>>0,s[5]=s[5]+_>>>0,s[6]=s[6]+R>>>0,s[7]=s[7]+M>>>0}return Array.from(s,m=>m.toString(16).padStart(8,"0")).join("")}function oo(e,t){return e>>>t|e<<32-t}var TU=2e3,c1=25e7,Fe=r().trim().min(1).max(240),Ye=r().regex(/^[a-f0-9]{64}$/),wt=r().datetime({offset:!0}),Au=re(r(),de()).default({}),Je=c({id:Fe,contentHash:Ye}).strict(),EU=Je.extend({revision:u().int().positive()}).strict(),ur=c({id:Fe,path:r().trim().min(1).max(TU).refine($U),contentHash:Ye,sizeBytes:u().int().nonnegative().max(c1),mediaType:r().trim().min(1).max(200),visibility:b(["policy","verifier","host_private"])}).strict(),MU=c({id:Fe,contentHash:Ye,mediaType:r().trim().min(1).max(200).nullable().default(null),sizeBytes:u().int().nonnegative().max(c1).nullable().default(null)}).strict(),jU=b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]);function OU(e){return`${JSON.stringify(zf(e),null,2)}
|
|
177
|
+
`}function d1(e){return AU(e)}function Kr(e){return d1(OU(e))}function $U(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function zf(e){return Array.isArray(e)?e.map(zf):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,zf(n)]))}var NU=b(["memory","prompt","skill","agent"]),DU=b(["runtime","product","taskset","training"]),LU=c({id:r().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),text:r().trim().min(1).max(1e4)}).strict(),UU=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(LU).max(100),allowedProposalRoutes:p(NU).max(4),allowedExternalRoutes:p(DU).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:Ye,profile:UU,profileHash:Ye,composedPromptHash:Ye,createdAt:wt,contentHash:Ye}).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:Ye.nullable(),validation:c({valid:A(),messages:p(r().max(2e3)).max(100)}).strict(),createdAt:wt,contentHash:Ye}).strict();var HU=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(),qU=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"]})}),BU=It("decision",[HU,zU,qU]),FU=BU,$g=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"]})}),VU=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("no_action"),reason:r().trim().min(1).max(1e4)}).strict(),KU=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("route"),route:b(["runtime","product","taskset","training"]),summary:r().trim().min(1).max(2e3),evidenceBasis:$g,expectedOutcome:r().trim().min(1).max(1e4),reason:r().trim().min(1).max(1e4)}).strict(),WU=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:$g,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"]})}),u1=It("decision",[VU,KU,WU]);Nt([FU,u1]);var Ng=c({memory:A(),prompt:A(),skill:A(),agent:A()}).strict(),m1=b(["memory","instruction","skill","agent"]),by=c({path:r().trim().min(1).max(2e3),kind:m1,content:r().max(6e4),loaded:A()}).strict(),yy=c({path:r().trim().min(1).max(2e3),kind:m1,loaded:A()}).strict(),GU=c({capabilities:Ng,trigger:re(r(),de()),observations:p(re(r(),de())).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(),de())).max(60),artifacts:p(re(r(),de())).max(30),artifactDiagnostics:p(re(r(),de())).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(),de())).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(by).max(100),admittedSourceCatalog:p(yy).max(1e3)}).strict(),sourceFiles:p(by).max(100),sourceCatalog:p(yy).max(1e3),additionalEvidence:de().nullable().optional()}).strict(),ZU=c({id:r().trim().min(1).max(240),revision:u().int().nonnegative(),contentHash:Ye}).strict();c({schemaVersion:S("openpond.hostedHarnessRefinerRequest.v2"),requestId:r().trim().min(1).max(240),idempotencyKey:r().trim().min(1).max(240),evidenceHash:Ye,harness:c({admittedRelease:Je,currentRelease:Je,overlay:ZU,workspace:c({id:r().trim().min(1).max(240),revision:u().int().nonnegative(),sourceRevision:Ye,channelRevision:u().int().nonnegative()}).strict(),capabilities:Ng}).strict(),evidence:GU}).strict();var JU=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:Ye,admittedRelease:Je,currentRelease:Je,decision:u1,serviceRevision:r().trim().min(1).max(240),usage:JU}).strict();const YU=c({adapterId:E,placement:b(["local","remote","colocated","provider_native"]),runtimeVersion:r().trim().min(1).max(200),capabilityReceipt:Q}).strict(),QU=c({maxTurns:u().int().positive().max(1e5),timeoutMs:u().int().positive().max(864e5),maxOutputBytes:u().int().positive().max(25e7),maximumSpendUsd:u().nonnegative().nullable()}).strict(),XU=c({schemaVersion:S("openpond.runManifest.v1"),id:E,harnessRelease:J,tasksetRelease:J,model:zh,runtimeTarget:YU,limits:QU,approval:c({id:E,contentHash:Q}).strict().nullable(),createdAt:Ee,metadata:_n}).strict();XU.extend({contentHash:Q}).strict();const eH=c({schemaVersion:S("openpond.attemptReceipt.v1"),id:E,runManifest:J,taskId:E,seed:r().trim().min(1).max(500),terminal:A(),failureClass:tc.nullable(),outputHash:Q.nullable(),traceHash:Q,artifactRefs:p(Va).max(1e5),graderEvidenceRefs:p(Va).max(1e4),startedAt:Ee,completedAt:Ee,latencyMs:u().int().nonnegative(),costUsd:u().nonnegative().nullable(),legacyAttemptRef:E.nullable().default(null),metadata:_n}).strict();eH.extend({contentHash:Q}).strict();const tH=c({schemaVersion:S("openpond.evaluationResult.v1"),id:E,runManifest:J,harnessRelease:J,tasksetRelease:J,model:zh,receiptRefs:p(J).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(tc,u().int().nonnegative()),authoredMetric:mL.optional(),metadata:_n}).strict(),nH=tH.extend({contentHash:Q}).strict(),aH=c({schemaVersion:S("openpond.harnessCompatibility.v1"),id:E,baseHarnessRelease:J,candidateHarnessRelease:J,tasksetRelease:J,environmentHash:Q,toolContractHash:Q,policyHash:Q,graderInterfaceHash:Q,metadata:_n}).strict();aH.extend({contentHash:Q}).strict();const Dg=b(["scored","unscorable"]),Tu=b(["policy","environment","collector","verifier","provider","host","user","scheduler"]),p1=b(["completed","policy_failure","incomplete_output","task_deadline","environment_failure","collector_failure","verifier_failure","provider_failure","host_failure","infrastructure_timeout","cancelled"]),oH=c({schemaVersion:S("openpond.environmentRelease.v1"),id:E,revision:u().int().positive(),contract:jw,actionSchemaRef:ln.nullable(),observationSchemaRef:ln.nullable(),stateSchemaRef:ln.nullable(),artifactCollection:c({maxArtifacts:u().int().positive().max(1e5),maxTotalBytes:u().int().positive().max(1e10)}).strict(),adapterConformanceHashes:re(E,Q),metadata:_n}).strict(),Lg=oH.extend({contentHash:Q}).strict(),rH=b(["collected","missing","skipped","failed"]),Sy=b(["not_requested","passed","failed"]),iH=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:Va.nullable(),status:rH,parseStatus:Sy,schemaStatus:Sy,errorCode:E.nullable(),failureOwner:Tu.nullable(),evidenceRefs:p(Va).max(1e4),metadata:_n}).strict(),sH=c({schemaVersion:S("openpond.artifactManifest.v1"),id:E,attemptRef:J,entries:p(iH).max(1e5),createdAt:Ee,metadata:_n}).strict();sH.extend({contentHash:Q}).strict();const lH=c({schemaVersion:S("openpond.verifierSetRelease.v1"),id:E,revision:u().int().positive(),graders:p(Uw).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(J).max(1e4),metadata:_n}).strict(),Ug=lH.extend({contentHash:Q}).strict(),cH=c({verifierId:E,verifierVersion:r().trim().min(1).max(100),status:Dg,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:Tu.nullable(),feedback:p(r().max(2e4)).max(1e3),visibleEvidenceRefs:p(Va).max(1e4),privilegedEvidenceRefs:p(Va).max(1e4),metadata:_n}).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"]})}),f1=c({schemaVersion:S("openpond.rewardReceipt.v1"),id:E,attemptRef:J,verifierSetRef:J,artifactManifestRef:J,status:Dg,reward:u().min(0).max(1).nullable(),learningEligible:A(),passed:A(),outcomeClass:p1,failureOwner:Tu.nullable(),components:p(cH).min(1).max(1e4),visibleEvidenceRefs:p(Va).max(1e5),privilegedEvidenceRefs:p(Va).max(1e5),supersedes:J.nullable(),createdAt:Ee,metadata:_n}).strict();function h1(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"]})}f1.superRefine(h1);f1.extend({contentHash:Q}).strict().superRefine(h1);const g1=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"})}),dH=c({id:E,environmentRelease:J,status:b(["completed","failed","timed_out","cancelled"]),startedAt:Ee,completedAt:Ee,traceRefs:p(Va).max(1e4),metadata:_n}).strict(),uH=c({receiptRef:J,status:Dg,value:u().min(0).max(1).nullable(),learningEligible:A(),passed:A(),outcomeClass:p1,failureOwner:Tu.nullable(),components:re(E,u().min(0).max(1).nullable())}).strict(),v1=c({schemaVersion:S("openpond.canonicalRolloutRecord.v1"),id:E,attemptRef:J,artifactManifestRef:J,tasksetRelease:J,environmentRelease:J,verifierSetRelease:J,harnessRelease:J,taskId:E,split:Zo,model:zh,seed:r().trim().min(1).max(500),reward:uH,traceRef:Va,optimizerSample:g1.nullable(),environmentExecutions:p(dH).min(1).max(1e5),startedAt:Ee,completedAt:Ee,metadata:_n}).strict();function b1(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."})}v1.superRefine(b1);c({...v1.shape,contentHash:Q}).strict().superRefine(b1);const mH=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."),y1=Nt([su(),r().max(262144),u().finite(),c({integer:mH}).strict(),c({blobBase64:r().max(349528).regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/)}).strict()]),xy=r().min(1).max(128).refine(e=>!e.includes("\0")),pH=c({tables:p(c({name:xy,columns:p(c({name:xy,type:b(["INTEGER","REAL","TEXT","BLOB"])}).strict()).min(1).max(128),rows:p(p(y1).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."})}}),ky=c({schemaVersion:S("openpond.sqlExecution.v1"),snapshot:pH,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(y1).max(128)).max(4096)}).strict(),c({status:S("rejected"),code:b(["invalid_query","multiple_statements","result_too_large","memory_limit"])}).strict()]);const Jc=c({scope:b(["input","initialState","state","arguments"]),path:p(r().min(1).max(256)).max(16)}).strict(),wy={id:r().min(1).max(128),operation:b(["step","collect"]),toolName:r().min(1).max(500).optional(),timeoutMs:u().int().min(1).max(2e4)},fH=It("kind",[c({...wy,kind:S("sqlite.v1"),sql:Jc,snapshot:Jc,maxRows:ky.shape.maxRows,maxResultBytes:ky.shape.maxResultBytes}).strict(),c({...wy,kind:S("javascript.v1"),source:Jc,cases:Jc,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."})}),hH=c({schemaVersion:S("openpond.javascriptEnvironment.v1"),id:r().trim().min(1).max(500),revision:u().int().positive(),module:ln.refine(e=>e.visibility==="host_private","Environment code belongs to the execution owner."),tools:p(sc).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(fH).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)=>{Pg(a.inputSchema).valid||t.addIssue({code:"custom",path:["tools",o,"inputSchema"],message:"Environment tools require a supported JSON schema."}),a.inputSchemaHash!==rn(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."})})}),gH=hH.safeExtend({contentHash:r().regex(/^[a-f0-9]{64}$/)});b(["create","reset","step","collect","destroy"]);c({state:re(r(),de()),observation:re(r(),de())}).strict();r().regex(/^[a-f0-9]{64}$/);var vH=c({environment:Lg,verifierSet:Ug,javascript:gH}).strict();c({actions:p(c({name:r().min(1).max(64),arguments:re(r(),de())}).strict()).max(1e3)}).strict();var bH=c({environment:Lg,verifierSet:Ug}).strict(),yH=c({scopeId:r().trim().min(1).max(500),modelId:r().trim().min(1).max(500)}).strict();c({schemaVersion:S("openpond.modelTasksetDerivation.v1"),owner:yH,root:Lo,parent:Lo}).strict();var SH=c({taskset:zw,taskDefinition:_u,rewardBinding:Iu,rewards:p(wu).min(1).max(100),assets:p(Ru).max(1e3),executionResources:bH.optional(),execution:vH.optional(),instructionMode:S("per_task").optional()}).strict(),xH=c({batch:Vw,evidence:p(Cu).min(1).max(1e4),decisions:p(Eg).min(1).max(1e4),sources:p(Tg).min(1).max(1e4),assets:p(Ru).max(1e3)}).strict(),kH=64*1024*1024,wH=c({asset:ur,base64:r().max(Math.ceil(kH/3)*4)}).strict(),IH=SH.omit({taskset:!0,executionResources:!0}),_H=c({schemaVersion:S("openpond.tasksetPackage.v1"),taskset:zw,environment:Lg,verifierSet:Ug,files:p(wH).max(1e4),modelResources:IH.optional(),learningResources:xH.optional()}).strict(),qf=_H.extend({contentHash:r().regex(/^[a-f0-9]{64}$/)}).strict(),ms=r().trim().min(1).max(500),CH=r().regex(/^[a-f0-9]{64}$/),Bf=c({id:ms,revision:u().int().positive(),contentHash:CH}).strict(),RH=c({schemaVersion:S("openpond.hostedTasksetSummary.v1"),id:ms,teamId:ms,release:Bf,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:ms.optional(),limit:u().int().min(1).max(100).default(30),modelProjectId:ms.optional()}).strict();c({items:p(RH).max(100),nextCursor:ms.nullable()}).strict();c({code:r().min(1),message:r().min(1)}).strict();var Eo=r().trim().min(1).max(500),fd=r().regex(/^[a-f0-9]{64}$/),PH=IU.pick({portableProjectId:!0,name:!0,objective:!0,defaultBaseModel:!0,defaultDestinationId:!0,sourceRevision:!0,sourceUpdatedAt:!0}).extend({trainingSetup:Og.omit({tasksetRef:!0,rewardBindingRef:!0,tasksetRelease:!0})}).strict();c({schemaVersion:S("openpond.tasksetPackagePublication.v1"),operationId:Eo,modelProjectId:Eo,expectedProjectEtag:fd.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:qf,modelConfiguration:PH.optional(),evaluationPackage:qf.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&&Kr(e.modelConfiguration.trainingSetup.evaluationTasksetRef)===Kr(HL(e.evaluationPackage.taskset)),"Evaluation package must match the selected immutable evaluation in Model configuration.");c({schemaVersion:S("openpond.tasksetPackageReceipt.v1"),teamId:Eo,modelProjectId:Eo,operationId:Eo,taskset:Bf,packageHash:fd,hostedTasksetId:Eo,projectEtag:fd,project:l1.optional(),selection:b(["select","attach"]).optional(),evaluation:c({taskset:Bf,packageHash:fd,hostedTasksetId:Eo}).strict().optional()}).strict();c({schemaVersion:S("openpond.tasksetPackageReadback.v1"),teamId:Eo,modelProjectId:Eo,package:qf}).strict();var S1=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(),de()),inputSchemaHash:Ye,sideEffect:b(["read","write"]),timeoutMs:u().int().positive().max(36e5)}).strict(),AH=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(),TH=c({portable:A(),blockers:p(r().trim().min(1).max(2e3)).max(1e3),localOnlyAssetRefs:p(Fe).max(1e4),hostPrivateAssetRefs:p(Fe).max(1e4)}).strict(),EH=c({schemaVersion:S("openpond.agentSnapshot.v2"),id:Fe,sourceRelease:Je.nullable(),instructions:p(ur).max(1e4),skills:p(ur).max(1e4),agents:p(ur).max(1e4),toolDeclarations:p(S1).max(200),capabilityRequirements:p(AH).max(200),dependencyLock:ur,portability:TH,metadata:Au}).strict(),MH=EH.extend({contentHash:Ye}).strict(),jH=c({create:S(!0),reset:S(!0),step:S(!0),collect:S(!0),destroy:S(!0),resetScope:b(["task","attempt"])}).strict(),OH=c({visibleEvidence:p(Fe).max(1e3),privilegedEvidence:p(Fe).max(1e3),privateVerifierIsolation:A()}).strict(),$H=c({schemaVersion:S("openpond.harnessRelease.v2"),id:Fe,agentSnapshot:Je,program:ur,tools:p(S1).max(200),lifecycle:jH,graderInterface:OH,files:p(ur).max(1e5),metadata:Au}).strict(),NH=$H.extend({contentHash:Ye}).strict(),DH=c({id:Fe,turn:u().int().nonnegative(),kind:b(["message","tool_call","terminal"]),name:Fe.nullable(),arguments:re(r(),de()),content:r().max(1e6).nullable()}).strict(),LH=c({actionId:Fe,turn:u().int().nonnegative(),terminal:A(),output:re(r(),de()),artifactRefs:p(MU).max(1e5)}).strict(),UH=c({sequence:u().int().nonnegative(),type:b(["created","reset","action","observation","terminal","failure","collected","destroyed"]),payloadHash:Ye,metadata:Au}).strict();c({schemaVersion:S("openpond.harnessTrace.v1"),manifest:Je,taskId:Fe,seed:r().trim().min(1).max(500),events:p(UH).max(1e6),actions:p(DH).max(1e5),observations:p(LH).max(1e5),terminal:A(),failureClass:jU.nullable(),output:re(r(),de()),contentHash:Ye}).strict();var HH=25*1024*1024,zH=c({path:ur.shape.path,base64:r().max(Math.ceil(HH/3)*4)}).strict(),x1=c({schemaVersion:S("openpond.harnessSourcePackage.v1"),agentSnapshot:MH,harnessRelease:NH,files:p(zH).max(1e4)}).strict();x1.extend({contentHash:Ye}).strict();x1.extend({schemaVersion:S("openpond.harnessPolicySourcePackage.v1"),contentHash:Ye}).strict();c({schemaVersion:S("openpond.harnessSourceSelection.v1"),mode:b(["taskset_owned","selected_release"]),harnessRelease:Je,sourcePackageHash:Ye.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 Uo=r().trim().min(1).max(1e5),qH=b(["no_action","harness_maintenance","runtime","product","taskset","model_improvement"]),BH=b(["none","runtime_service","product_team","human_review","evaluation_system","training_system"]),k1=b(["observation","trigger","route_decision","refiner_outcome","proposal","validation","apply_receipt","harness_advance","rollback","work_outcome","taskset","evaluation","training_qualification","model_candidate"]),Hg=c({kind:b(["personal","team"]),id:Fe}).strict(),w1=c({policy:Je,state:b(["authorized","revoked","deleted","expired"]),checkedAt:wt}).strict(),ql=c({evidence:Je,kind:k1,sourceRef:Fe,sourcePolicy:w1,occurrenceKey:Ye,occurredAt:wt}).strict(),FH=c({evidence:Je,sourcePolicy:w1.nullable(),reason:b(["outside_scope","before_watermark","duplicate","resolved","revoked","deleted","expired","sensitive","unverified","budget"])}).strict(),Iy=c({cursor:Ye,throughCreatedAt:wt}).strict(),VH=c({fingerprint:Ye,recurrenceFamily:r().trim().min(1).max(1e3),statement:Uo,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"),I1=b(["harness","runtime","product","retrieval","tools","evaluation","model"]),KH=c({layer:I1,status:b(["not_applicable","unresolved","resolved","blocked"]),reason:Uo,evidenceRefs:p(Je).max(1e3)}).strict(),WH=c({schemaVersion:S("openpond.harnessEvaluationReviewReceipt.v1"),id:Fe,ownerScope:Hg,workspaceRef:Fe,harnessRelease:Je,previousWatermark:Iy.nullable(),nextWatermark:Iy,selectedEvidence:p(ql).max(1e4),excludedEvidence:p(FH).max(1e4),claim:VH.nullable(),classification:qH,triage:p(KH).max(16),reason:Uo,nextAuthority:BH,maxEstimatedCostUsd:u().finite().nonnegative(),tasksetProposal:Je.nullable(),evaluation:Je.nullable(),trainingQualification:Je.nullable(),policyVersion:Fe,createdAt:wt,metadata:Au}).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"})});WH.extend({contentHash:Ye}).strict();c({id:Fe,evidence:Je,kind:k1,sourceRef:Fe,occurredAt:wt,payload:re(r(),de())}).strict();var GH=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("no_action"),reason:Uo,ignoredEvidence:p(c({id:Fe,reason:r().trim().min(1).max(2e3)}).strict()).max(1e3)}).strict(),ZH=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:Uo,triageLayer:I1,expectedOutcome:Uo,counterevidence:r().trim().max(1e4),confidence:u().min(0).max(1),candidateDisposition:b(["observe","confirm"]).nullable(),reason:Uo}).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"]})}),JH=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("resolve_candidate"),candidateId:Fe,candidateFingerprint:Ye,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:Uo}).strict();It("decision",[GH,ZH,JH]);c({schemaVersion:S("openpond.harnessEvaluationReviewNavigationDecision.v1"),selectedEvidenceIds:p(Fe).min(1).max(50),reason:Uo}).strict();var Ps=re(r(),de()).default({}),va=u().int().nonnegative(),Eu=r().trim().min(1).max(1e5),_1=c({kind:b(["personal","team"]),id:Fe}).strict(),YH=c({name:Fe,release:Je.nullable(),revision:va}).strict();c({schemaVersion:S("openpond.harnessWorkspace.v1"),id:Fe,ownerScope:_1,name:r().trim().min(1).max(240),location:b(["local","hosted"]),sourceRevision:r().trim().min(1).max(500),revision:va,dirty:A(),currentChannel:YH,createdAt:wt,updatedAt:wt,metadata:Ps}).strict();var ps=b(["runtime","memory","prompt","skill","agent","product","taskset","training"]),C1=b(["text_instruction","memory","dependency_selection","executable_code","business_logic","financial_logic","permission","connected_app","publication","deployment","training","model_binding","team_or_global"]),R1=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:Ye.nullable(),effects:p(C1).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=Kr(e.content);e.contentHash!==n&&t.addIssue({code:"custom",message:`edit contentHash is ${e.contentHash}; expected ${n}`,path:["contentHash"]})}),P1=c({workspaceId:Fe,revision:va,sourceRevision:r().trim().min(1).max(500),channelRevision:va}).strict(),Ho=c({id:Fe,revision:va,contentHash:Ye}).strict();c({schemaVersion:S("openpond.harnessTurnSnapshot.v1"),workspaceId:Fe,workspaceRevision:va,sourceRevision:r().trim().min(1).max(500),channelName:Fe,channelRevision:va,harnessRelease:Je,toolCatalogHash:Ye.nullable().optional(),overlay:Ho.nullable().optional().default(null)}).strict();var QH=c({schemaVersion:S("openpond.harnessRunOverlay.v1"),id:Fe,runId:Fe,baseHarnessRelease:Je,workspace:P1,revision:va,status:b(["active","frozen","abandoned"]),edits:p(R1).max(1e3),createdAt:wt,updatedAt:wt,metadata:Ps}).strict();QH.extend({contentHash:Ye}).strict();var A1=c({kind:b(["tool_event","recovery","validation","user_turn","work_output","work_receipt"]),id:Fe,contentHash:Ye.nullable()}).strict(),T1=c({id:Fe,kind:b(["dependency","schema","package","file_render","skill","prompt","business_formula","targeted_evaluation","observed_recovery","memory","component_activation"]),description:Eu,required:A()}).strict(),XH=c({schemaVersion:S("openpond.harnessImprovementProposal.v1"),id:Fe,overlay:Ho,baseHarnessRelease:Je,expectedWorkspace:P1,requestedScope:b(["personal","team","global"]),route:ps,risk:b(["low","review","restricted"]),effects:p(C1).min(1).max(20),evidence:p(A1).min(1).max(1e3),edits:p(R1).min(1).max(1e3),validationPlan:p(T1).min(1).max(100),expectedOutcome:Eu,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"]})});XH.extend({contentHash:Ye}).strict();var ez=c({schemaVersion:S("openpond.harnessTargetedValidationReceipt.v1"),id:Fe,proposal:Je,validationId:Fe,kind:T1.shape.kind,status:b(["passed","failed","blocked","skipped"]),summary:Eu,evidenceRefs:p(A1).max(1e3),createdAt:wt,metadata:Ps}).strict();ez.extend({contentHash:Ye}).strict();var tz=b(["advanced","retained","conflict","rolled_back"]),nz=c({schemaVersion:S("openpond.harnessAdvanceReceipt.v1"),id:Fe,workspaceId:Fe,ownerScope:_1,proposal:Je.nullable(),expectedWorkspaceRevision:va,observedWorkspaceRevision:va,previousChannelRevision:va,nextChannelRevision:va,previousRelease:Je.nullable(),nextRelease:Je.nullable(),validationReceipts:p(Je).max(100),decision:tz,reason:Eu,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"]})});nz.extend({contentHash:Ye}).strict();var az=c({schemaVersion:S("openpond.harnessOverlayMergeReceipt.v1"),id:Fe,workspaceId:Fe,baseHarnessRelease:Je,leftOverlay:Ho,rightOverlay:Ho,decision:b(["merged","conflict"]),mergedOverlay:Ho.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"]})});az.extend({contentHash:Ye}).strict();var Mu=r().trim().min(1).max(1e5),pc=re(r(),de()).default({}),oz=b(["completed_tool_batch","before_model_step","turn_completed","turn_paused"]),E1=c({kind:oz,eventSequence:u().int().nonnegative(),occurredAt:wt}).strict(),M1=c({id:Fe,sequence:u().int().nonnegative().nullable(),contentHash:Ye}).strict(),rz=b(["tool_failure","retry","recovery","validation","user_turn","reusable_success","completion_detour"]),iz=b(["open","recovered","terminal"]),sz=c({name:r().trim().min(1).max(500),invocationKey:Ye}).strict(),lz=c({schemaVersion:S("openpond.improvementObservation.v1"),id:Fe,runRef:Fe,turnId:Fe,harnessRelease:Je,overlay:Ho.nullable(),eventRefs:p(M1).min(1).max(100),kind:rz,state:iz,tool:sz.nullable(),deterministicClass:r().trim().min(1).max(500).nullable(),summary:Mu,createdAt:wt,metadata:pc}).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"]})});lz.extend({contentHash:Ye}).strict();var cz=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(),dz=b(["no_action","route_deterministically","queue_refiner"]),uz=c({schemaVersion:S("openpond.refinementTriggerDecision.v1"),id:Fe,runRef:Fe,turnId:Fe,harnessRelease:Je,overlay:Ho.nullable(),observations:p(Je).max(100),decision:dz,deterministicRoute:ps.nullable(),suggestedRoutes:p(ps).max(8),reason:Mu,deduplicationKey:Ye,policy:cz,estimatedMaxCostUsd:u().finite().nonnegative(),pendingPlanCount:u().int().nonnegative(),boundary:E1,cooldownUntil:wt.nullable(),createdAt:wt,metadata:pc}).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"]})});uz.extend({contentHash:Ye}).strict();var mz=b(["runtime_service","refiner_model","human_review","evaluation_system","training_system"]),pz=c({schemaVersion:S("openpond.improvementRouteDecision.v1"),id:Fe,trigger:Je,route:ps,authority:mz,automatic:A(),reason:Mu,createdAt:wt,metadata:pc}).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"]})});pz.extend({contentHash:Ye}).strict();var fz=c({schemaVersion:S("openpond.harnessRefinerOutcome.v1"),id:Fe,trigger:Je,decision:b(["no_action","proposed"]),proposal:Je.nullable(),reason:Mu,evidenceRefs:p(Je).max(100),estimatedCostUsd:u().finite().nonnegative(),createdAt:wt,metadata:pc}).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"]})});fz.extend({contentHash:Ye}).strict();var hz=b(["applied","retained","declined","conflict","rolled_back"]),gz=c({schemaVersion:S("openpond.improvementApplyReceipt.v1"),id:Fe,proposal:Je,beforeOverlay:Ho,afterOverlay:Ho.nullable(),decision:hz,boundary:E1,validationRefs:p(Je).max(100),outcomeEvidenceRefs:p(M1).max(1e3),rollbackOf:Je.nullable(),createdAt:wt,metadata:pc}).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"]})});gz.extend({contentHash:Ye}).strict();c({provider:Fe,model:Fe,revision:r().trim().min(1).max(500).nullable().default(null),artifactHash:Ye.nullable().default(null),tokenizerRevision:r().trim().min(1).max(500).nullable().default(null),chatTemplateHash:Ye.nullable().default(null)}).strict();var vz=["openpond","codex","anthropic","openai","xai","google","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],bz=b(vz),j1=c({providerId:bz,modelId:r().trim().min(1).max(300)}),yz=r().trim().min(1).max(2e3),zg=r().trim().min(1).max(1e5),Sz=b(["create","update","delete"]),xz=b(["memory","prompt","skill","agent"]),kz=b(["runtime","product","taskset","training"]),wz=b(["no_action","routed","applied","retained","failed"]),Iz=b(["not_applicable","pending","passed","rejected","failed"]),_z=b(["not_applicable","pending","passed","failed"]),Cz=c({schemaVersion:S("openpond.harnessRefinerActivityReceipt.v1"),id:Fe,runRef:Fe,turnId:Fe,result:wz,decision:b(["no_action","route","propose"]).nullable(),route:ps.nullable(),operation:Sz.nullable(),target:r().trim().min(1).max(2e3).nullable(),summary:yz,evidenceBasis:$g.nullable(),critiqueStatus:Iz,validationStatus:_z,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"?_y(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"||!kz.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"}),_y(t,e,{critiqueStatus:"not_applicable",validationStatus:"not_applicable"})):n?((e.decision!=="propose"||!xz.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"]})});Cz.extend({contentHash:Ye}).strict();var Rz=b(["unresolved","confirmed","resolved","rejected","expired"]),Pz=c({kind:b(["applied_change","later_success","manual_rejection","source_revoked","expired"]),reason:zg,evidenceRefs:p(Je).max(1e3),resolvedAt:wt}).strict(),Az=c({schemaVersion:S("openpond.harnessRefinementCandidate.v1"),id:Fe,ownerScope:Hg,workspaceRef:Fe,fingerprint:Ye,recurrenceFamily:r().trim().min(1).max(1e3),statement:zg,status:Rz,occurrences:p(ql).max(1e3),counterevidence:p(ql).max(1e3),sourceReviews:p(Je).min(1).max(100),relatedHarnessReleases:p(Je).max(100),firstSeenAt:wt,lastSeenAt:wt,lastReviewedAt:wt,expiresAt:wt,resolution:Pz.nullable(),createdAt:wt,updatedAt:wt}).strict().superRefine((e,t)=>{qr(t,e.occurrences,"occurrences"),qr(t,e.counterevidence,"counterevidence"),qr(t,e.sourceReviews,"sourceReviews"),qr(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"]}),Oz(t,e)});Az.extend({contentHash:Ye}).strict();var Tz=b(["created","merged","rejected","expired","reopened","resolved"]),Ez=c({schemaVersion:S("openpond.harnessRefinementCandidateLifecycleReceipt.v1"),id:Fe,candidateId:Fe,decision:Tz,beforeCandidate:Je.nullable(),afterCandidate:Je,review:Je,addedEvidence:p(ql).max(1e3),removedEvidence:p(Je).max(1e3),reason:zg,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"]}),qr(t,e.addedEvidence,"addedEvidence"),qr(t,e.removedEvidence,"removedEvidence");const n=new Set(e.removedEvidence.map(a=>Ff(a)));e.addedEvidence.some(a=>n.has(Ff(a.evidence)))&&t.addIssue({code:"custom",message:"candidate lifecycle evidence cannot be added and removed together",path:["removedEvidence"]})});Ez.extend({contentHash:Ye}).strict();var Mz=c({schemaVersion:S("openpond.harnessCrossRunRefinementRequest.v1"),id:Fe,ownerScope:Hg,workspaceRef:Fe,candidate:Je,candidateFingerprint:Ye,review:Je,admittedHarness:Je,evidence:p(ql).min(1).max(1e3),capabilities:Ng,deduplicationKey:Ye,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"]}),qr(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=jz(e);e.deduplicationKey!==n&&t.addIssue({code:"custom",message:`cross-run refinement deduplicationKey is ${e.deduplicationKey}; expected ${n}`,path:["deduplicationKey"]})});Mz.extend({contentHash:Ye}).strict();function jz(e){return Kr({schemaVersion:"openpond.harnessCrossRunRefinementIdentity.v1",workspaceRef:e.workspaceRef,candidateFingerprint:e.candidateFingerprint,admittedHarness:e.admittedHarness})}function _y(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 qr(e,t,n){const a=t.map(o=>Ff(o));new Set(a).size!==a.length&&e.addIssue({code:"custom",message:`${n} references must be unique`,path:[n]})}function Ff(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 Oz(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 O1=r().regex(/^[a-z][a-z0-9_-]{0,119}$/),$1=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"),$z=c({id:O1,label:r().trim().min(1).max(240),description:r().max(4e3),inputSchema:re(r(),de()),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($1).max(100)}).strict();c({schemaVersion:S("openpond.profileWorkflows.v1"),workflows:p($z).max(1e3)}).strict();var Nz=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(),de())}).strict();c({schemaVersion:S("openpond.profileWorkflowActions.v1"),actions:p(Nz).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:Ye,workflowId:O1}).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:$1}).strict(),c({kind:S("agent_action"),actionId:r().trim().min(1).max(240)}).strict()])}).strict();var zd=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 Dz={type:"object",properties:{},additionalProperties:!1};c({name:r().trim().min(1).max(240).optional(),description:r().max(4e3).optional(),skillPaths:p(zd).max(100).optional(),assetPaths:p(zd).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(),de()).default(Dz),skillPaths:p(zd).max(100).default([]),assetPaths:p(zd).max(100).default([])}).strict();var xa=r().trim().min(1).max(240),zo=r().trim().min(1),fr=r().trim().min(8).max(256),N1=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."),br=b(["train","validation","test","frozen_eval"]),Lz=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"])}),Uz=c({schemaVersion:S("openpond.datasetSemanticSchema.v1"),fields:p(Lz).min(1).max(1e4),schemaHash:fr}),Hz=c({id:xa,split:br,path:N1,contentHash:fr,schemaHash:fr,sizeBytes:u().int().nonnegative(),rowCount:u().int().positive(),rowGroupCount:u().int().positive()}),qg=c({schemaVersion:S("openpond.datasetArtifact.v1"),id:xa,tasksetId:xa,tasksetRevision:u().int().positive(),contentHash:fr,format:S("parquet"),schema:Uz,shards:p(Hz).min(1).max(1e5),rowCount:u().int().positive(),splitCounts:re(br,u().int().nonnegative()),sourceReceiptRefs:p(xa).min(1).max(1e5),mappingHash:fr,qualityReportHash:fr,createdAt:zo}),zz=c({schemaVersion:S("openpond.datasetArtifactSummary.v1"),artifactId:xa,tasksetId:xa,tasksetRevision:u().int().positive(),format:S("parquet"),rowCount:u().int().positive(),splitCounts:re(br,u().int().nonnegative()),sizeBytes:u().int().nonnegative(),contentHash:fr,available:A(),unavailableReason:r().trim().min(1).max(2e3).nullable(),createdAt:zo}),qz=c({schemaVersion:S("openpond.datasetCatalogItem.v1"),tasksetId:xa,tasksetRevision:u().int().positive(),artifactId:xa.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(br,u().int().nonnegative()),sizeBytes:u().int().nonnegative().nullable(),available:A(),unavailableReason:r().trim().min(1).max(2e3).nullable(),createdAt:zo,updatedAt:zo});c({schemaVersion:S("openpond.datasetCatalog.v1"),profileId:xa,datasets:p(qz),generatedAt:zo});c({schemaVersion:S("openpond.datasetArtifactRegistry.v1"),manifest:qg,profileId:xa,storageRoot:r().trim().min(1).max(4e3),relativeManifestPath:N1,available:A(),unavailableReason:r().trim().min(1).max(2e3).nullable(),verifiedAt:zo.nullable(),createdAt:zo,updatedAt:zo});c({split:br.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:xa,tasksetRevision:u().int().positive(),artifactHash:fr,split:br.nullable(),rows:p(re(r(),de())).max(100),nextCursor:r().max(2e3).nullable(),totalRows:u().int().nonnegative(),returnedRows:u().int().nonnegative()});var Bz=c({schemaVersion:S("openpond.datasetStorageSettings.v1"),datasetStorePath:r().trim().min(1).max(4e3),updatedAt:zo}),Fz=c({id:xa,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:Bz,storageRoots:p(Fz)});c({datasetStorePath:r().trim().min(1).max(4e3)});var ns=r().trim().min(1).max(240),Vz=r().trim().min(1),fs=r().trim().min(8).max(256),Kz=re(r(),de()).default({}),Wz=r().trim().min(7).max(256),Gz=b(["pending","approved","review","blocked"]),ju=c({id:ns,profileId:ns,title:r().trim().min(1).max(500),sourceHash:fs,occurredAt:Vz,licensingStatus:Gz,secretScanStatus:b(["pending","passed","blocked"]),piiScanStatus:b(["pending","passed","review","blocked"]),metadata:Kz}),Zz=ju.extend({schemaVersion:S("openpond.huggingFaceDatasetSource.v1"),kind:S("huggingface"),repositoryId:r().trim().regex(/^[^/\s]+\/[^/\s]+$/).max(500),repositoryUrl:r().url().max(2e3),revision:Wz,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)}),Jz=ju.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)}),Yz=ju.extend({schemaVersion:S("openpond.generatedDatasetSource.v1"),kind:S("generated"),generatorId:ns,generatorVersion:r().trim().min(1).max(200),seed:u().int(),generatorHash:fs}),Qz=ju.extend({schemaVersion:S("openpond.learningBatchDatasetSource.v1"),kind:S("learning_batch"),batch:c({id:ns,revision:u().int().positive(),contentHash:fs}).strict(),taskDefinition:c({id:ns,revision:u().int().positive(),contentHash:fs}).strict(),admittedBy:ns}),Xz=It("kind",[Zz,Jz,Yz,Qz]),eq=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(),de()),actionSchemaHash:Ye,agentRelease:Je,implementationHash:Ye,runtimeBindingId:Fe,capabilityReceiptHash:Ye,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),Bg=r().trim().min(1),tq=r().trim().min(8).max(256),Fg=r().trim().regex(/^[a-f0-9]{64}$/),nq=r().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),Wa=re(r(),de()).default({}),Ou=Rt.nullable();function fc(e){const t=e.trim().replaceAll("\\","/");return!t||t.startsWith("/")||t==="."||t===".."?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function aq(e){const t=e.trim();return t.length>0&&t!=="."&&t!==".."&&!t.includes("/")&&!t.includes("\\")&&!t.includes("\0")}var hs=br,D1=b(["general","benchmark"]),L1=c({schemaVersion:S("openpond.tasksetBenchmark.v1"),definitionId:Rt,releaseId:Rt,releaseHash:Fg,managedReleasePath:r().trim().min(1).max(1e3).refine(fc,"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:Wa}),U1=c({schemaVersion:S("openpond.tasksetPreferenceComparisonBinding.v1"),releaseId:Rt,releaseHash:Fg,publishedAt:Bg,metadata:Wa}),oq=c({status:b(["pending","granted","denied","revoked"]),scope:b(["metadata_only","selected_turns","full_session"]),grantedBy:Ou,grantedAt:Bg.nullable(),purpose:S("task_authoring_and_evaluation")}),H1=c({schemaVersion:S("openpond.trainingSource.v1"),id:Rt,profileId:Rt,sessionId:Rt,turnIds:p(Rt).max(1e3).default([]),workspaceId:Ou,sourceHash:tq,clusterKey:Rt,title:r().trim().min(1).max(500),occurredAt:Bg,consent:oq,connectedAppIds:p(Rt).max(100).default([]),secretScanStatus:b(["pending","passed","blocked"]),piiScanStatus:b(["pending","passed","review","blocked"]),licensingStatus:b(["pending","approved","review","blocked"]),metadata:Wa}),z1=Nt([H1,Xz]),Vg=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([])}),rq=c({id:Rt,sourceRefId:Rt,artifactRef:r().trim().min(1).max(4e3).refine(fc,"Task asset references must be safe relative paths."),fileName:r().trim().min(1).max(500).refine(aq,"Task asset file names must not contain path separators."),mediaType:r().trim().min(1).max(200),sha256:Fg,sizeBytes:u().int().nonnegative().max(25e7),split:hs,metadata:Wa}),iq=c({path:r().trim().min(1).max(1e3).refine(fc,"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:Wa}),Kg=c({schemaVersion:S("openpond.taskData.v1"),id:Rt,clusterKey:Rt,split:hs,input:re(r(),de()),expectedOutput:re(r(),de()).nullable(),policyVisibleContext:re(r(),de()).default({}),privilegedContextRef:Ou,sourceRefs:p(Rt).min(1).max(100),assets:p(rq).max(1e3).optional(),resourceRefs:p(Rt).max(1e3).optional(),requiredOutputs:p(iq).max(100).optional(),tags:p(Rt).max(100).default([]),metadata:Wa}),sq=c({id:Rt,kind:b(["file","catalog","configuration","code_module"]),path:r().trim().min(1).max(1e3).refine(fc,"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:Wa}),As=c({id:Rt,taskId:Ou,sourceRefs:p(Rt).min(1).max(100),artifactRef:Rt,approved:A(),confidence:u().min(0).max(1),metadata:Wa}),q1=As.extend({kind:S("demonstration"),prompt:r().max(1e5).nullable().default(null),response:r().max(2e5).nullable().default(null)}),B1=As.extend({kind:S("preference"),prompt:r().max(1e5),chosen:r().max(2e5),rejected:r().max(2e5),rationale:r().max(1e5).nullable().default(null)}),F1=As.extend({kind:S("correction"),original:r().max(2e5),corrected:r().max(2e5),rationale:r().max(1e5).nullable().default(null)}),V1=As.extend({kind:S("feedback"),feedback:r().max(1e5),polarity:b(["positive","negative","mixed","neutral"])}),K1=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()}),W1=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",[q1,B1,F1,V1,K1,W1]);var G1=c({demonstrations:p(q1).max(1e5).default([]),preferences:p(B1).max(1e5).default([]),corrections:p(F1).max(1e5).default([]),feedback:p(V1).max(1e5).default([]),rewards:p(K1).max(1e5).default([]),labels:p(W1).max(1e5).default([])}),Z1=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(eq).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(sq).max(1e4).optional(),metadata:Wa}),Wg=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([])}),$u=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:Wa}),lq=$u.extend({kind:b(["content","schema","file","diff","test","runtime_event","state"]),config:re(r(),de())}),cq=$u.extend({kind:S("model_judge"),rubric:r().trim().min(1).max(5e4),judge:j1,calibrationFixtureRefs:p(Rt).min(1).max(500),calibrationStatus:b(["pending","passed","failed"]),temperature:u().min(0).max(2).default(0)}),dq=$u.extend({kind:S("human"),rubric:r().trim().min(1).max(5e4),reviewerRole:r().trim().min(1).max(500)}),uq=$u.extend({kind:S("custom_verifier"),runtime:Nw.optional(),module:r().trim().min(1).max(1e3).refine(fc,"Custom verifier modules must use a safe relative path."),exportName:nq,timeoutMs:u().int().positive().max(3e5),networkPolicy:S("none")}),Nu=Nt([lq,cq,dq,uq]),Gg=b(["positive","negative","boundary","adversarial","prompt_injection","infrastructure_failure"]),J1=c({id:Rt,taskId:Rt,label:Gg,output:re(r(),de()),infrastructureError:r().trim().min(1).max(1e4).nullable(),expectedPassed:A(),expectedRewardEligible:A(),metadata:Wa}),uo=r().trim().min(1).max(240),Bl=r().trim().min(1),qd=r().trim().min(8).max(256),Y1=re(r(),de()).default({}),mq=uo.nullable(),pq=b(["draft","awaiting_disclosure_approval","awaiting_materialization_approval","materializing","validating","needs_review","baselining","ready","blocked","failed","archived"]),Q1=b(["demonstrations","preferences","verifiable_reward","rubric","discovery"]),Un=r().trim().max(1e5),X1=It("kind",[c({kind:S("demonstrations"),behavior:Un,examples:p(c({id:uo,prompt:Un,response:Un})).max(1e3).default([])}),c({kind:S("preferences"),preference:Un,pairs:p(c({id:uo,prompt:Un,chosen:Un,rejected:Un,rationale:Un})).max(1e3).default([])}),c({kind:S("verifiable_reward"),task:Un,rules:p(c({id:uo,points:u().finite(),condition:Un})).max(1e3).default([]),otherwisePoints:u().finite().default(0)}),c({kind:S("rubric"),task:Un,criteria:p(c({id:uo,label:r().trim().max(500),description:Un})).max(1e3).default([]),positiveExample:Un,negativeExample:Un,boundaryExample:Un})]),fq=c({path:r().trim().min(1).max(1e3),role:b(["environment","verifier","fixture"]),content:r().max(25e4)}),eI=c({primaryMethod:b(["sft","dpo","grpo","ppo","sdft","opsd","sdpo"]),bootstrap:c({method:S("sft"),purpose:S("trajectory_bootstrap"),demonstrationRefs:p(uo).min(1).max(1e5),limitations:p(r().trim().min(1).max(5e3)).min(1).max(100)}).nullable()}),tI=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"]),hq=c({method:b(["sft","dpo","grpo","ppo"]),status:b(["recommended","compatible","needs_dataset_work"]),reasonCodes:p(tI).default([]),reasons:p(r().trim().min(1).max(5e3)).default([])}),Cy=c({code:uo,message:r().trim().min(1).max(5e3),path:r().trim().max(2e3).nullable()}),nI=c({schemaVersion:S("openpond.tasksetReadiness.v1"),tasksetId:uo,tasksetHash:qd,ready:A(),recommendedMethod:b(["none","retrieval","sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),trainingPath:eI.nullable().default(null),methodReadiness:p(hq).default([]),compatibleDestinationClasses:p(b(["export","custom","hosted_managed"])),blockers:p(Cy).default([]),advisories:p(Cy).default([]),warnings:p(r().trim().min(1).max(5e3)).default([]),generatedAt:Bl}),aI=c({attempt:u().int().positive(),summary:r().trim().min(1).max(5e3),createdAt:Bl}),gq=c({schemaVersion:S("openpond.taskAuthoringProvenance.v1"),model:j1.nullable(),modelConfig:Y1,skillHash:qd,promptTemplateVersion:r().trim().min(1).max(200),buildIntent:Q1.default("demonstrations"),buildSpecification:X1.nullable().default(null),evidenceHashes:p(qd).max(1e5),tasksetSdkVersion:r().trim().min(1).max(100),sourceCommit:r().trim().min(1).max(256).nullable(),repairHistory:p(aI).max(1e3),createdAt:Bl}),Ry=c({schemaVersion:S("openpond.taskset.v1"),id:uo,revision:u().int().positive().default(1),profileId:uo,profileRelease:EU.nullable().optional(),createImproveRunId:mq.default(null),name:r().trim().min(1).max(500),objective:r().trim().max(2e4),purpose:D1.default("general"),benchmark:L1.nullable().default(null),preferenceComparison:U1.nullable().default(null),status:pq,sourceRefs:p(z1).min(1).max(1e5),datasetArtifact:qg.nullable().optional(),policy:Vg,environment:Z1,capabilities:Wg,metrics:xu.optional(),tasks:p(Kg).max(1e6),graders:p(Nu).min(1).max(1e3),graderFixtures:p(J1).max(1e5),learningSignals:G1,authoringProvenance:gq,readiness:nI.nullable(),contentHash:qd,createdAt:Bl,updatedAt:Bl,metadata:Y1}).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 vq(e){return e.schemaVersion==="openpond.trainingSource.v1"}var Wi=r().trim().min(1).max(240),Py=r().trim().min(1),bq=r().trim().min(8).max(256),yq=r().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),Sq=re(r(),de()).default({});function Ay(e){const t=e.trim().replaceAll("\\","/");return!t||t.startsWith("/")||t==="."||t===".."?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}var oI=Kg.extend({sourceRefs:p(Wi).max(100).default([])}),rI=b(["draft","validating","needs_review","published"]),xq=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:Wi,label:r().trim().min(1).max(500),description:r().trim().max(1e4),weight:u().nonnegative().max(1e3)})).max(100)}),kq=c({mode:b(["text","structured_json","artifacts"]),jsonSchema:re(r(),de()).nullable(),renderer:c({module:r().trim().min(1).max(1e3).refine(Ay,"Renderer modules must use a safe relative path."),exportName:yq,configRef:r().trim().min(1).max(1e3).refine(Ay,"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"]})}),fo=c({schemaVersion:S("openpond.tasksetDraft.v1"),id:Wi,revision:u().int().positive(),profileId:Wi,modelScope:c({modelId:Wi,expectedModelRevision:u().int().positive(),source:dU.optional()}).strict().nullable().default(null),name:r().trim().max(500),objective:r().trim().max(2e4),purpose:D1.default("general"),benchmark:L1.nullable().default(null),preferenceComparison:U1.nullable().default(null),status:rI,sourceRefs:p(z1).max(1e5).default([]),datasetArtifact:qg.nullable().optional(),policy:Vg,environment:Z1,output:kq.default({mode:"text",jsonSchema:null,renderer:null}),capabilities:Wg,metrics:xu,review:xq,tasks:p(oI).max(1e6).default([]),graders:p(Nu).max(1e3).default([]),graderFixtures:p(J1).max(1e5).default([]),learningSignals:G1,publishedTasksetRef:c({id:Wi,revision:u().int().positive(),contentHash:bq}).nullable(),createdAt:Py,updatedAt:Py,metadata:Sq}).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"]})}),wq=6e6,Iq=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 _q(e){const t=Pu.parse(e);return!Iq.has(t)&&!t.startsWith("source-artifacts/")}function Ty(e,t){const n=_q(e);if(t.byteLength>wq)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)?Ey(t):{encoding:"utf8",data:o}}catch{a=Ey(t)}return{path:e,writable:n,content:a,sizeBytes:t.byteLength,contentHash:d1(t)}}function Ey(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 My=64*1024*1024,iI=r().regex(/^[a-f0-9]{64}$/),Cq=c({path:Pu,contentHash:iI,sizeBytes:u().int().nonnegative().max(My),base64:r().max(My)}).strict(),Rq=c({schemaVersion:S("openpond.tasksetDraftWorkspace.v1"),draft:fo,files:p(Cq).max(1e4)}).strict();Rq.extend({contentHash:iI}).strict();var as=r().trim().min(1).max(240),Pq=Ct.extend({revision:u().int().positive()}).strict(),Aq=Pq.extend({teamId:as,jobId:as,plan:Ct,baseline:Ct,candidate:Ct,state:sU.shape.state,updatedAt:r().datetime()}).strict();c({schemaVersion:S("openpond.trainingAcceptanceGroupPage.v1"),teamId:as,jobId:as,groups:p(Aq).max(100),nextCursor:as.nullable()}).strict();c({cursor:as.optional(),limit:u().int().min(1).max(100).default(25)}).strict();var ba=r().trim().min(1).max(191),Fl=r().regex(/^[a-f0-9]{64}$/),Tq=c({schemaVersion:S("openpond.trainingPreparationRequest.v1"),teamId:ba,operationId:ba,projectId:ba.nullable(),configuration:c({id:ba,expectedRevision:u().int().positive(),expectedEtag:Fl}).strict(),batch:Lo,name:r().trim().min(1).max(191),maximumSpendUsd:u().finite().positive().max(1e6)}).strict(),Eq=c({schemaVersion:S("openpond.trainingPreparationPlan.v1"),id:ba,creatorUserId:ba,request:Tq,requestHash:Fl,source:Ax(()=>lI),submissionHash:Fl,createdAt:r().datetime({offset:!0})}).strict(),Mq=Eq.extend({contentHash:Fl}).strict(),jq=c({schemaVersion:S("openpond.trainingPreparationReceipt.v1"),plan:Mq,revision:u().int().positive(),state:b(["prepared","submitted","cancelled"]),jobId:ba.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:ba,planHash:Fl,expectedRevision:u().int().positive()}).strict();c({projectId:ba.optional(),state:b(["prepared","submitted","cancelled"]).optional(),afterId:ba.optional(),limit:u().int().min(1).max(100).default(25)}).strict();c({schemaVersion:S("openpond.trainingPreparationPage.v1"),teamId:ba,items:p(jq).max(100),nextCursor:ba.nullable()}).strict();c({schemaVersion:S("openpond.trainingHarnessSourcePublication.v1"),harnessRelease:Je,sourcePackageHash:r().regex(/^[a-f0-9]{64}$/),sizeBytes:u().int().positive().max(pU)}).strict();p(c({id:r().trim().min(1)}).catchall(de())).min(1).max(1e3);c({binding:Iu,rewards:p(wu).min(1).max(100)}).strict();var Oq=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:Lo,tasks:p(Oq).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 En=r().trim().min(1).max(500),la=r().regex(/^[a-f0-9]{64}$/),Fa=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:de(),contentHash:la}).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:la,sizeBytes:u().int().positive(),createdAt:Fa}).strict();var sI=b(["reward_model_train","policy_optimize"]),$q=b(["queued","admitting","provisioning","running","stopping","cancelling","succeeded","failed","cancelled"]),Nq=c({id:En,version:r().trim().min(1).max(200).nullable().default(null),required:A().default(!0)}).strict(),lI=c({modelProject:c({id:En,portableProjectId:En,revision:u().int().positive(),contentHash:la}).strict(),harnessRunManifest:Ct,harnessRelease:Ct,taskset:Lo,tasksetRelease:Ct,evaluation:c({taskset:Lo,dataset:Ct}).strict().nullable().optional(),dataset:Ct,evidenceSets:p(Ct).max(1e4)}).strict(),Dq=c({kind:S("reward_model_train"),baseModel:ai,preferenceDatasetRelease:Ct,processorRelease:Ct,recipe:c({schemaVersion:S("openpond.rewardModelRecipe.v1"),method:S("reward_model"),parameterization:S("lora_with_scalar_head")}).catchall(de())}).strict(),Lq=c({kind:S("deterministic"),grader:Ct,composer:Ct.nullable().default(null)}).strict(),Uq=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:la,executionReceipt:Ct}).strict(),processorRelease:Ct,rewardComposerRelease:Ct}).strict(),Hq=c({kind:S("policy_optimize"),baseModel:ai,recipe:a1,rewardSource:It("kind",[Lq,Uq]),resumeFrom:Ct.nullable().default(null)}).strict(),zq=It("kind",[Dq,Hq]),qq=c({approvalHash:la,approvedAt:Fa,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:lI,job:zq,requestedCapabilities:p(Nq).max(1e3),placementObjective:b(["fast","balanced","economical"]),budget:c({maximumSpendUsd:u().nonnegative(),maximumWallSeconds:u().int().positive()}).strict(),approval:qq,contentHash:la}).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 Bq=c({schemaVersion:S("openpond.trainingJob.v2"),id:En,teamId:En,kind:sI,modelProjectId:En,portableProjectId:En,sourceProjectRevision:u().int().positive(),submissionHash:la,state:$q,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:Fa,updatedAt:Fa,completedAt:Fa.nullable()}).strict();c({schemaVersion:S("openpond.trainingJobPage.v2"),jobs:p(Bq).max(1e3),nextCursor:r().trim().min(1).max(2e3).nullable()}).strict();c({schemaVersion:S("openpond.trainingJobEvent.v2"),id:En,jobId:En,sequence:u().int().nonnegative(),type:En,phase:r().trim().min(1).max(200),message:r().trim().min(1).max(5e3).nullable(),data:re(r(),de()).default({}),createdAt:Fa}).strict();c({schemaVersion:S("openpond.trainingJobLog.v2"),jobId:En,sequence:u().int().nonnegative(),level:b(["debug","info","warning","error"]),message:r().max(2e4),createdAt:Fa}).strict();c({expectedVersion:u().int().nonnegative()}).strict();var Fq=c({schemaVersion:S("openpond.trainingJobOutput.v2"),id:En,jobId:En,kind:b(["checkpoint","adapter","scorer","metrics","evaluation","trace","receipt"]),artifactRef:r().trim().min(1).max(2e3),contentHash:la,sizeBytes:u().int().nonnegative(),metadata:re(r(),de()).default({}),createdAt:Fa}).strict(),Vq=c({schemaVersion:S("openpond.trainingExecutionReceipt.v2"),id:En,teamId:En,jobId:En,submissionHash:la,manifestHash:la,recipeHash:la,capabilityHash:la,runtimeRelease:Ct,inputs:p(Ct).max(1e4),outputs:p(Ct).max(1e4),spendUsd:u().nonnegative(),durationSeconds:u().nonnegative(),cleanupComplete:A(),issuer:En,issuedAt:Fa,signature:r().trim().min(1).max(1e4).nullable()}).strict();c({schemaVersion:S("openpond.trainingJobOutputs.v2"),outputs:p(Fq).max(1e4),receipt:Vq.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(),de()).default({})}).strict();c({schemaVersion:S("openpond.trainingCapabilities.v2"),capabilityHash:la,jobKinds:p(sI),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:Fa,expiresAt:Fa}).strict();var ho=fo.shape.id,Ka=u().int().positive(),Jr=r().regex(/^[a-f0-9]{64}$/),oi={teamId:ho,modelId:ho};c({schemaVersion:S("openpond.tasksetDraftCreate.v1"),operationId:ho,modelId:ho,expectedModelRevision:Ka,name:fo.shape.name}).strict();c({schemaVersion:S("openpond.tasksetDraftSourceDescriptor.v1"),...oi,expectedModelRevision:Ka,sourcePackageHash:Jr}).strict();c({schemaVersion:S("openpond.tasksetDraftReadback.v1"),...oi,draft:fo,workspaceHash:Jr,projectEtag:Jr}).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 Kq=c({id:ho,revision:Ka,name:fo.shape.name,status:rI,updatedAt:fo.shape.updatedAt,sourceTasksetRef:xt.nullable()}).strict();c({schemaVersion:S("openpond.tasksetDraftList.v1"),...oi,drafts:p(Kq).max(100),nextCursor:r().min(1).max(2e3).nullable()}).strict();c({expectedDraftRevision:Ka,draft:fo}).strict();c({expectedDraftRevision:Ka,expectedModelRevision:Ka}).strict();var Wq=c({expectedDraftRevision:Ka,expectedWorkspaceHash:Jr}).strict();c({schemaVersion:S("openpond.tasksetDraftValidation.v1"),...oi,draftId:ho,draftRevision:Ka,workspaceHash:Jr,valid:A(),issues:p(c({code:r().min(1),severity:b(["warning","error"]),message:r(),path:r().nullable()}).strict()),packageHash:Jr.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.");Wq.extend({operationId:ho,expectedPackageHash:Jr,expectedTasksetRef:xt}).strict();c({schemaVersion:S("openpond.tasksetDraftFileList.v1"),...oi,draftId:ho,draftRevision:Ka,files:p(Xw).max(10020)}).strict();c({schemaVersion:S("openpond.tasksetDraftFileReadback.v1"),...oi,draftId:ho,draftRevision:Ka,file:uU}).strict();c({schemaVersion:S("openpond.tasksetDraftDeletion.v1"),...oi,draftId:ho,revision:Ka,deleted:S(!0)}).strict();fo.shape.id;u().int().positive();var Oo=r().trim().min(1).max(500),Gq=c({projectId:Oo.optional(),tasksetId:Oo.optional(),draftId:Oo.optional(),taskId:Oo.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(),Zq=c({id:Oo,method:b(["code","judge","human"]),required:A()}),cI=c({tasksetId:Oo,tasksetName:r(),tasksetRevision:u().int().positive(),tasksetHash:r(),taskId:Oo,ordinal:u().int().nonnegative(),title:r(),description:r(),split:r(),scoring:p(Zq),configuration:b(["configured","needs_reward","needs_checks"]),draftId:Oo.nullable().default(null),modelId:Oo.nullable().default(null)}),Jq=c({items:p(cI).max(100),nextCursor:r().nullable()});function aQ(e,t){if(YL({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})=>Ty(s,new TextEncoder().encode(i.text))),Ty(`${n}/manifest.json`,new TextEncoder().encode(JSON.stringify(o)))]}function oQ(e,t,n){const a=Gw.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=oI.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&&Kr(d)!==Kr(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:${Kr(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 fo.parse({...e,tasks:o})}const Yn=r().trim().min(1).max(240),mr=r().trim().min(1),dI=re(r(),de()).default({}),uI=b(["nominated","needs_review","approved_for_creation","creating","needs_task_review","baselining","ready_for_export","rejected","dismissed","retired","blocked"]),mI=b(["no_training","prompting","retrieval","sft","preference","grpo_rft","sdft_opsd","sdpo","agentic_rl"]),Yq=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:mr,signature:r().trim().min(1).max(2e3),summary:r().trim().min(1).max(5e3),confidence:u().min(0).max(1),consented:A(),metadata:dI}),Qq=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)}),Xq=c({tactic:mI,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"])}),pI=c({schemaVersion:S("openpond.taskCandidate.v1"),id:Yn,profileId:Yn,status:uI,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(Yq).min(1).max(1e5),scorecard:Qq,recommendation:Xq,mergedIntoId:Yn.nullable(),createdAt:mr,updatedAt:mr,metadata:dI}),Du=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(pI),generatedAt:mr,config:Du});c({status:uI.optional(),mergeIntoId:Yn.nullable().optional()});c({profileId:Yn,sourceIds:p(Yn).max(1e5).default([]),sessionIds:p(Yn).max(1e5).default([]),config:Du.optional()});const eB=c({schemaVersion:S("openpond.taskMinerRun.v1"),id:Yn,profileId:Yn,status:b(["queued","running","cancelling","cancelled","succeeded","failed"]),config:Du,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:mr,startedAt:mr.nullable(),completedAt:mr.nullable(),updatedAt:mr});var tB=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(),nB=c({declarationId:Fe,leaseRef:r().trim().min(8).max(1e3),audience:tB.shape.audience,expiresAt:wt}).strict(),Zg=c({adapterId:Fe,placement:b(["local","remote","colocated","provider_native"]),capabilityReceipt:Ye,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:Ye}).strict().nullable()}).strict(),Jg=c({adapterId:Fe,kind:b(["local","ssh","managed","custom"]),deviceOrPool:r().trim().min(1).max(1e3),capabilityReceipt:Ye,provider:Fe.nullable()}).strict(),Yg=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:Ye}).strict(),aB=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:Ye.nullable(),tokenizerRevision:r().trim().min(1).max(500),chatTemplateHash:Ye}).strict(),recipe:c({method:r().trim().min(1).max(100),version:r().trim().min(1).max(200),configHash:Ye}).strict(),runtimeTarget:Zg,computeTarget:Jg,engine:Yg,resolvedBundleHash:Ye,secretLeaseRefs:p(nB).max(1e3),approval:c({approvalHash:Ye,approvedAt:wt,maximumSpendUsd:u().nonnegative().nullable()}).strict(),createdAt:wt}).strict(),oB=aB.extend({contentHash:Ye}).strict(),rB=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:Ye,sizeBytes:u().int().nonnegative()}).strict()).max(1e5)}).strict();rB.extend({contentHash:Ye}).strict();var fI=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 ht=r().trim().min(1).max(240),Qn=r().trim().min(1),gs=r().trim().min(8).max(256),Qg=re(r(),de()).default({}),mo=ht.nullable(),iB=b(["slash_train","session_menu","bulk_selection","training_page","task_candidate"]),sB=b(["defaults","customize"]),lB=b(["automated","manual"]);c({schemaVersion:S("openpond.trainingSourceEstimate.v1"),sessionId:ht,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:ht,title:r().trim().min(1).max(500),updatedAt:Qn})).max(500).default([])});const cB=c({sessionId:ht,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(cB)});const Xg=b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]),dB=c({graderId:ht.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"])}),uB=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:zt,sourceTasksetId:ht,graders:p(Nu).max(1e3),runtime:uB.nullable(),sources:p(dB).max(1e3),unavailableReason:r().max(2e3).nullable()});const mB=c({id:ht,taskIndex:u().int().nonnegative(),label:Gg,output:re(r(),de()),infrastructureError:r().trim().min(1).max(1e4).nullable(),expectedPassed:A(),expectedRewardEligible:A(),metadata:Qg}),pB=c({schemaVersion:S("openpond.taskAttempt.v1"),id:ht,tasksetId:ht,taskId:ht,split:hs,attempt:u().int().nonnegative(),seed:u().int(),modelRef:dn.nullable(),startedAt:Qn,completedAt:Qn,output:re(r(),de()),runtimeEventRefs:p(ht).max(1e4).default([]),artifactRefs:p(ht).max(1e4).default([]),privilegedOutcomeRef:mo,infrastructureError:r().trim().min(1).max(1e4).nullable(),costUsd:u().nonnegative().nullable(),latencyMs:u().int().nonnegative(),userInterventions:u().int().nonnegative().default(0),metadata:Qg}),fB=c({schemaVersion:S("openpond.taskAttemptArtifact.v1"),id:ht,tasksetId:ht,taskId:ht,attemptId:ht,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:Qg}),hB=c({graderId:ht,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(ht).max(1e4).default([]),judge:dn.nullable().optional().default(null),calibrationStatus:b(["not_applicable","pending","passed","failed"])}),gB=c({schemaVersion:S("openpond.gradeResult.v1"),id:ht,attemptId:ht,graderSetHash:gs,score:u().min(0).max(1).nullable(),passed:A(),components:p(hB).min(1).max(1e3),failureClass:Xg.nullable(),feedback:p(r().trim().min(1).max(2e4)).max(1e3).default([]),rewardEligible:A(),rewardComposition:Ld.optional(),createdAt:Qn});b(["stable_hash_top_n","rft_easy_curriculum_v1"]);const vB=c({schemaVersion:S("openpond.graderAuditReport.v1"),id:ht,tasksetId:ht,tasksetHash:gs,fixtureRefs:p(ht).min(1).max(1e5),gradeRefs:p(ht).min(1).max(1e5),passed:A(),hackingChecksPassed:A(),leakageChecksPassed:A(),infrastructureSafetyPassed:A(),failures:p(c({fixtureId:ht,label:Gg,gradeId:ht,reason:r().trim().min(1).max(5e3)})).max(1e5),createdAt:Qn}),bB=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(ht).max(100).default([]),intervention:mI,trainingEligible:A(),rationale:p(r().trim().min(1).max(5e3)).min(1).max(100),confidence:u().min(0).max(1)}),yB=c({id:ht,sourceId:ht,sourceTurnId:mo,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)}),SB=c({schemaVersion:S("openpond.taskDesignProposal.v1"),id:ht,name:r().trim().min(1).max(500),objective:r().trim().min(1).max(2e4),diagnosis:bB.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:Wg.shape.taskKind,sourceIds:p(ht).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(Nu).max(1e3).default([]),graderFixtures:p(mB).max(1e5).default([]),generatedFiles:p(fq).max(1e3).default([]),proposedExamples:p(yB).max(1e5).default([]),proposedMethod:nI.shape.recommendedMethod,trainingPath:eI.nullable().default(null),policy:Vg,warnings:p(r().trim().min(1).max(5e3)).default([]),createdAt:Qn}),xB=5;function rQ(e,t="New model"){const n=e?.trim().split(/\s+/).filter(Boolean)??[];return n.length===0?t:n.slice(0,xB).join(" ")}const hc=c({schemaVersion:S("openpond.baseModelPreference.v1"),modelId:ht,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:mo,source:b(["managed","local","builtin"])}),kB=c({schemaVersion:S("openpond.taskCreationRequest.v1"),id:ht,profileId:ht,surface:iB,mode:sB,entryMode:lB.default("manual"),resourceIntent:b(["workproduct","dataset"]).default("workproduct"),buildIntent:Q1.default("demonstrations"),buildSpecification:X1.nullable().default(null),objective:r().trim().min(1).max(2e4).nullable(),methodHint:b(["sft","dpo","grpo","ppo"]).nullable().default(null),preferredBaseModelId:ht.nullable().default(null),preferredBaseModel:hc.nullable().default(null),sourceIds:p(ht).max(1e5),candidateId:mo,analysisModel:dn.nullable(),analysisReasoningEffort:pu.nullable().default(null),createImproveRunId:mo.default(null),targetIntent:c({kind:b(["agent","skill","extension","model","configuration"]).nullable(),id:mo,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(ht).max(1e5),providerModel:dn.nullable(),approvalId:mo,approvedAt:Qn.nullable()}).default({status:"not_required",content:"raw_excerpts",sourceIds:[],providerModel:null,approvalId:null,approvedAt:null}),createdAt:Qn}),hI=c({schemaVersion:S("openpond.taskCreationSnapshot.v1"),id:ht,request:kB,state:b(["planning","awaiting_disclosure_approval","awaiting_questions","recommendation_ready","awaiting_materialization_approval","materializing","validating","ready","blocked","failed","cancelled"]),proposal:SB.nullable(),materializedTasksetId:mo,disclosureApprovalId:mo,materializationApprovalId:mo,blockingQuestions:p(c({id:ht,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:ht,role:b(["user","assistant","system","tool"]),text:r().max(1e5),createdAt:Qn})).max(1e4).default([]),repairHistory:p(aI).max(1e3).default([]),blockedReason:r().trim().min(1).max(1e4).nullable(),createdAt:Qn,updatedAt:Qn});c({schemaVersion:S("openpond.taskCreationTranscript.v1"),creationId:ht,profileId:ht,messages:hI.shape.transcript,updatedAt:Qn});const Gi=r().trim().min(1).max(240),hd=r().trim().min(1),Vf=r().trim().min(8).max(256),gI=re(r(),de()).default({}),wB=b(["created","inspecting","awaiting_source_review","awaiting_mapping","awaiting_materialization_approval","materializing","validating","ready","cancelling","cancelled","failed"]),vI=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()}),IB=c({path:r().trim().min(1).max(1e3),logicalType:r().trim().min(1).max(500),nullable:A(),sampleValues:p(de()).max(5)}),_B=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()}),CB=c({schemaVersion:S("openpond.huggingFaceDatasetInspection.v1"),id:Gi,locator:vI,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(_B).min(1).max(1e4),columns:p(IB).min(1).max(1e4),previewRows:p(re(r(),de())).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:Vf.nullable()})).max(1e5),inspectedAt:hd,metadata:gI}),RB=b(["row_id","cluster_id","prompt","messages","demonstration","chosen","rejected","expected_output","privileged_context","reward","feedback","tag","metadata"]),PB=c({sourcePath:r().trim().min(1).max(1e3),target:RB,transform:b(["identity","string","json","messages","numeric","math_final_answer"]),policy:b(["visible","privileged","metadata"]),required:A()}),bI=c({schemaVersion:S("openpond.datasetImportMapping.v1"),sourceSchemaHash:Vf,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(PB).min(1).max(1e4),nullPolicy:b(["reject","drop","preserve"]),invalidRowPolicy:b(["reject_import","drop_with_receipt"]),splitPolicy:c({seed:u().int(),assignments:re(r(),br),validationPercent:u().min(0).max(100),frozenEvalPercent:u().min(0).max(100)}),importerVersion:r().trim().min(1).max(200),mappingHash:Vf}),AB=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()}),TB=c({schemaVersion:S("openpond.datasetImportJob.v1"),id:Gi,profileId:Gi,sourceKind:b(["huggingface","uploaded_file"]),status:wB,locator:vI.nullable(),inspection:CB.nullable(),mapping:bI.nullable(),progress:AB,targetStorageRoot:r().trim().min(1).max(4e3).nullable(),tasksetId:Gi.nullable(),tasksetRevision:u().int().positive().nullable(),artifactId:Gi.nullable(),error:r().trim().min(1).max(2e4).nullable(),cancellationRequested:A(),createdAt:hd,updatedAt:hd,completedAt:hd.nullable(),metadata:gI});c({profileId:Gi,url:r().trim().min(1).max(2e3)});c({name:r().trim().min(1).max(500),objective:r().trim().min(1).max(2e4),mapping:bI,targetStorageRoot:r().trim().min(1).max(4e3).nullable(),licenseApproved:A().default(!1)});const rr=E.nullable(),Co=u().int().nonnegative(),EB=r().regex(/^[a-f0-9]{40}$/),MB=c({name:r().trim().min(1).max(160),startedAt:Ee,completedAt:Ee,durationMs:u().nonnegative(),clock:b(["monotonic","provider","wall"]),outcome:b(["succeeded","failed","cancelled"])}).strict(),jB=c({schemaVersion:S("openpond.correlatedTelemetryReceipt.v1"),stage:b(["training","evaluation","deployment","inference"]),correlation:c({modelRunId:rr,modelVersionId:rr,policyVersion:Co.nullable(),taskId:rr,rolloutGroupId:rr,providerResourceId:rr,deploymentId:rr,inferenceRequestId:rr}).strict(),spans:p(MB).max(1e4),usage:c({promptTokens:Co.nullable(),generatedTokens:Co.nullable(),gpuSeconds:u().nonnegative().nullable(),workerActiveSeconds:u().nonnegative().nullable(),optimizerSteps:Co.nullable(),rolloutGroups:Co.nullable(),successfulTrajectories:Co.nullable(),failedTrajectories:Co.nullable(),peakGpuMemoryBytes:Co.nullable(),peakGpuUtilizationPercent:u().min(0).max(100).nullable()}).strict(),resource:c({provider:E,resourceIds:p(E).max(1e3),gpuType:r().trim().min(1).max(300).nullable(),gpuCount:Co.nullable(),baseProfileId:rr,baseRepository:r().trim().min(1).max(512).nullable(),baseRevision:EB.nullable(),adapterContentHash:Q.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:Ee,contentHash:Q}).strict(),hn=r().trim().min(1).max(240),qo=r().regex(/^[a-f0-9]{64}$/),cr=r().datetime({offset:!0}),yn=c({id:hn,contentHash:qo}).strict(),OB=yn.extend({revision:u().int().positive()}).strict(),yI=c({providerId:hn,modelId:r().trim().min(1).max(300)}).strict(),Lu=b(["correction","sibling_verification","cumulative_known","development","retained","frozen_final","training_eligible"]),$B=c({taskId:hn,taskContentHash:qo,panelRole:Lu,passLabel:hn.nullable(),optimizerEligible:A(),criticalInvariantIds:p(hn).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."})}),NB=c({schemaVersion:S("openpond.continualBenchIssuePacket.v1"),id:hn,revision:u().int().positive(),contentHash:qo,familyId:hn,familyLabel:r().trim().min(1).max(500),severity:b(["low","medium","high","critical"]),cases:p($B).min(2).max(1e4),duplicateEvidence:yn,leakageEvidence:yn,priorExposureEvidence:yn,observedAt:cr,reviewedAt:cr,queuedAt:cr.nullable(),runAt:cr.nullable(),createdBy:hn,createdAt:cr}).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."})}),DB=c({id:hn,role:Lu,passLabel:hn.nullable(),taskset:OB,familyIds:p(hn).min(1).max(1e5),taskCount:u().int().positive().max(1e6),sealedAt:cr}).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."})}),Dp=It("kind",[c({kind:S("base_model"),id:hn,revision:r().trim().min(1).max(500),contentHash:qo}).strict(),c({kind:S("model_version"),id:hn,contentHash:qo}).strict(),c({kind:S("external_reference"),id:hn,model:yI,providerRevision:r().trim().min(1).max(500),contentHash:qo}).strict()]),LB=c({scheduleEntryId:hn,ordinal:u().int().nonnegative(),label:hn,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(hn).min(1).max(1e3),optimizerGroupsPerTask:u().int().positive().max(1e3),trajectoriesPerGroup:u().int().min(4).max(1e3)}).strict(),UB=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(),HB=c({schemaVersion:S("openpond.continualBenchmarkProtocol.v1"),id:hn,revision:u().int().positive(),contentHash:qo,ownerId:hn,createdAt:cr,sealedAt:cr,creationReceipt:yn,predecessorSeries:c({id:hn,revision:u().int().positive(),contentHash:qo}).strict().nullable(),scenarioPack:yn,issueFamilyLedger:yn,issuePacketRelease:yn,panels:p(DB).min(6).max(1e4),grader:yn,judge:c({release:yn,rubricRelease:yn,calibrationRelease:yn,model:yI}).strict().nullable(),policies:c({base:Dp,master:Dp.nullable(),externalReferences:p(Dp).min(1).max(20)}).strict(),invariants:c({systemPromptHash:qo,toolSchema:yn,application:yn,harness:yn,runtime:yn,workerImage:yn,autoRefiner:c({enabled:A(),release:yn.nullable()}).strict()}).strict(),schedule:p(LB).min(1).max(1e3),evaluation:c({seeds:p(u().int()).min(3).max(100),repetitions:u().int().min(3).max(20),powerRule:yn,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:UB}).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."})}),zB=b(["draft","active","completed","archived"]),qB=b(["draft","ready","queued","running","candidate","accepted","rejected","no_signal","failed","cancelled"]),SI=b(["seed","daily_residual","rank_candidate","weekly_rollup","full_refresh"]),BB=b(["base_model","previous_release","seed_release","accepted_daily_head","accepted_seed"]),FB=b(["seed_taskset","nightly_selection","daily_cohort_union","eligible_task_pool"]),VB=b(["live_client","evaluation_attempt","replay_evidence","manual"]),KB=c({id:E,ordinal:u().int().nonnegative(),label:r().trim().min(1).max(100),role:SI,parentRule:BB,taskSource:FB,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."})}),WB=c({id:E,version:u().int().positive(),requireCheckpoint:A(),requireAppliedOptimizerUpdate:A(),minimumCurrentCohortMeanImprovement:u().finite(),maximumRetainedMeanRegression:u().finite().nonnegative(),blockCriticalInvariantRegression:A(),automaticDailyAdvancement:A()}).strict(),GB=c({schemaVersion:S("openpond.modelComparisonSeries.v1"),id:E,profileId:E,modelProjectId:E,name:r().trim().min(1).max(500),objective:r().trim().min(1).max(2e4),status:zB,revision:u().int().positive(),productionBinding:c({role:S("chat_manual"),roleTargetId:E}).strict(),baseModel:c({id:E,revision:r().trim().min(1).max(256)}).strict(),seedTaskset:zt,eligibleTaskPool:zt,evaluationTasksets:c({development:zt,retained:zt,frozenFinal:zt}).strict(),grader:J,benchmarkProtocol:HB.nullable().default(null),automaticEvaluation:c({enabled:A()}).strict().default({enabled:!1}),residualProfile:c({profileId:E,serializedEnvelopeRank:u().int().positive().max(1024),maximumEnabledRank:u().int().positive().max(1024),topology:S("uniform_block_masked")}).strict(),schedule:p(KB).min(1).max(1e3),scheduleSealedAt:Ee.nullable(),advancementPolicy:WB,executionPolicy:c({startWhenReady:S(!1)}).strict(),acceptedSeedEntryId:E.nullable(),acceptedDailyHeadEntryId:E.nullable(),promotedBindingId:E.nullable(),createdBy:E,createdAt:Ee,updatedAt:Ee}).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."})}),xI=c({source:VB,taskIds:p(E).min(1).max(1e5),observedFrom:Ee,observedTo:Ee,reviewedAt:Ee,reviewedBy:E,sourceTaskset:zt}).strict(),ZB=xI.extend({derivedFamilyKeys:p(E).min(1).max(1e5),familyDerivation:c({algorithm:E,sourceTasksetHash:Q}).strict(),selectionHash:Q}).strict(),kI=It("kind",[c({kind:S("base_model"),id:E,revision:r().trim().min(1).max(256)}).strict(),c({kind:S("model_version"),id:E,contentHash:Q}).strict()]),JB=c({id:E,branchOrdinal:u().int().nonnegative(),rank:u().int().positive().max(1024),offsetStart:u().int().nonnegative(),offsetEnd:u().int().positive(),optimizationRole:b(["frozen","trainable"]),artifactLineageId:E.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."})}),YB=c({disposition:b(["advance","hold","no_signal"]),policy:c({id:E,version:u().int().positive()}).strict(),reasonCodes:p(E).min(1).max(100),summary:r().trim().min(1).max(5e3),decidedBy:E,decidedAt:Ee}).strict(),QB=c({evaluationRunId:E,modelVersionId:E,taskset:zt,grader:J,cohortRole:b(["current","correction","sibling_verification","cumulative_known","development","retained","prior_disclosed","frozen_final"]),panelId:E.nullable().default(null),protocol:c({id:E,revision:u().int().positive(),contentHash:Q}).strict().nullable().default(null)}).strict(),XB=c({attemptOrdinal:u().int().positive(),trainingPlanId:E.nullable(),modelRunId:E.nullable(),terminalStatus:b(["failed","cancelled"]),queuedAt:Ee.nullable(),startedAt:Ee.nullable(),completedAt:Ee}).strict(),vs=c({seriesId:E,entryId:E,scheduleEntryId:E,ordinal:u().int().nonnegative(),releaseHash:Q}).strict(),eF=c({schemaVersion:S("openpond.modelComparisonSeriesEntry.v1"),id:E,seriesId:E,profileId:E,modelProjectId:E,scheduleEntryId:E,releaseHash:Q,ordinal:u().int().nonnegative(),label:r().trim().min(1).max(100),role:SI,branch:b(["daily","rank_candidate","weekly_rollup","full_refresh"]),status:qB,parent:kI,taskset:zt,sourceTasksets:p(zt).min(1).max(1e3),taskSelection:ZB.nullable(),trainableRank:u().int().positive().max(1024),serializedEnvelopeRank:u().int().positive().max(1024),enabledCumulativeRank:u().int().positive().max(1024),trainableBlockId:E,residualBlocks:p(JB).min(1).max(1024),attemptOrdinal:u().int().positive().default(1),priorRunAttempts:p(XB).max(100).default([]),trainingPlanId:E.nullable(),modelRunId:E.nullable(),modelVersionId:E.nullable(),evaluations:p(QB).max(1e5),decision:YB.nullable(),promotionBindingId:E.nullable(),queuedAt:Ee.nullable(),startedAt:Ee.nullable(),completedAt:Ee.nullable(),createdAt:Ee,updatedAt:Ee}).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:E,scheduleEntryId:E,taskSelection:xI.nullable(),expectedSeriesRevision:u().int().positive()}).strict();const tF=b(["base_reference","lora_adapter"]),wI=c({baseModel:c({source:S("huggingface"),repoId:E,revision:r().regex(/^[a-f0-9]{40}$/),configHash:Q,tokenizerHash:Q,licenseId:E,gated:A()}).strict(),processor:c({repository:E,revision:r().regex(/^[a-f0-9]{40}$/),configHash:Q}).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."})}),nF=c({schemaVersion:S("openpond.modelVersion.v1"),id:E,modelId:E,profileId:E,version:u().int().nonnegative(),kind:tF,status:b(["available","failed"]),baseModel:hc,taskset:zt,comparisonSeriesEntry:vs.nullable().optional(),evaluationTasksetRef:zt.nullable().optional(),releaseGraph:c({resolvedBundleHash:Q,profileRelease:zt,harnessRelease:J,agentRelease:J.nullable(),grader:c({id:E,contentHash:Q}).strict()}).strict(),artifactLineageId:E.nullable(),adapterStatus:b(["not_trained","trained"]),createdAt:Ee,contentHash:Q}).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."})}),aF=c({schemaVersion:S("openpond.rewardModelVersion.v1"),id:E,modelId:E,profileId:E,version:u().int().positive(),role:S("reward"),status:b(["available","failed"]),scope:b(["synthetic_smoke","human_preference"]),baseModel:hc,runtime:wI.nullable().default(null),taskset:zt,preferenceDatasetRelease:J,releaseGraph:c({resolvedBundleHash:Q,profileRelease:zt,harnessRelease:J,grader:c({id:E,contentHash:Q}).strict()}).strict(),artifacts:c({checkpoint:J.extend({objectRef:r().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/),files:p(c({path:r().trim().min(1).max(512),sizeBytes:u().int().positive(),sha256:Q}).strict()).min(4).max(128)}).strict(),adapter:J,scalarHead:J,bucketHead:J.nullable(),processorRelease:J}).strict(),qualificationReport:J.nullable(),createdAt:Ee,contentHash:Q}).strict(),oF=c({schemaVersion:S("openpond.rewardModelRunReceipt.v1"),provider:E,providerRunId:E,resolvedBundleHash:Q,finalCheckpoint:J.extend({objectRef:r().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/)}).strict(),adapter:J,scalarHead:J,bucketHead:J.nullable(),processorRelease:J,optimizerEvidence:J,managedExecutionReceipt:J.nullable().default(null),parameterDeltaHash:Q,cleanup:c({computeReleased:A(),providerTerminalObserved:A()}).strict(),contentHash:Q}).strict(),rF=UM(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:E,rewardModelId:E,rewardModelVersionId:E.nullable(),profileId:E,role:S("reward"),scope:b(["synthetic_smoke","human_preference"]),status:b(["prepared","running","succeeded","failed","cancelled"]),taskset:zt,tasksetRelease:J,preferenceDatasetRelease:J,recipeRelease:J,destinationId:E,quote:c({maximumSpendUsd:u().positive(),hourlyCostUsd:u().nonnegative().nullable()}).strict(),managedRunId:E.nullable(),progress:c({completedSteps:u().int().nonnegative(),totalSteps:u().int().positive(),latestLoss:u().finite().nullable()}).strict(),receipt:oF.nullable(),qualificationReport:J.nullable(),accruedSpendUsd:u().nonnegative().nullable(),failureOwner:b(["authoring","admission","provider","runner","artifact","qualification","cleanup"]).nullable(),failure:r().trim().min(1).max(5e3).nullable(),startedAt:Ee,completedAt:Ee.nullable(),updatedAt:Ee}).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."})}),iF=c({schemaVersion:S("openpond.modelRunReceipt.v1"),provider:E,providerRunId:E,assignmentHash:Q,resultHash:Q,transcriptHash:Q,traceHash:Q.nullable(),resolvedBundleHash:Q,artifactPath:r().trim().min(1).max(2e3),cleanup:c({computeReleased:A(),tunnelClosed:A()}).strict(),telemetry:jB.nullable().default(null),contentHash:Q}).strict(),ir=c({inputTokens:u().int().nonnegative(),outputTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative(),costUsd:u().nonnegative().nullable()}).strict(),jy=r().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),ev=c({phase:b(["baseline","adaptation","candidate_adaptation","candidate"]),taskId:E,attemptId:E,sessionId:E.nullable(),turnId:E.nullable(),passed:A(),score:u().min(0).max(1).nullable(),failureClass:Xg.nullable(),inputTokens:u().int().nonnegative(),outputTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative(),latencyMs:u().int().nonnegative(),costUsd:u().nonnegative().nullable(),startedAt:Ee}).strict(),Oy=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(),II=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:Oy,heldOut:Oy}).strict()}).strict(),tv=c({baseline:ir,adaptation:ir,candidateAdaptation:ir,candidate:ir,refiner:ir,grader:ir}).strict(),sF=c({usage:tv,observedSpendUsd:u().nonnegative(),attempts:p(ev).max(1e4)}).strict(),lF=c({id:E,contentHash:Q,artifactPath:r().trim().min(1).max(2e3)}).strict(),cF=c({schemaVersion:S("openpond.modelEvaluationReceipt.v1"),benchmarkId:E,resultManifest:c({id:E,contentHash:Q,artifactPath:r().trim().min(1).max(2e3)}).strict(),stages:c({baseline:J,adaptation:J,refiner:J,candidateAdaptation:J,candidate:J,comparison:J}).strict(),usage:tv,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:II.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:J,lineage:c({adaptationEvidenceHash:Q,refinerInputHash:Q,refinerOutcomeHash:Q,validationHash:Q,applyReceiptHash:Q,candidateRelease:J,valid:A()}).strict(),invalidReasons:p(r().trim().min(1).max(2e3)).max(100),attempts:p(ev).max(1e4).default([]),terminalClassification:b(["improved","no_improvement","regressed","inconclusive","cancelled","infrastructure_failure"]),profileGit:c({ref:r().trim().min(1).max(2e3),commit:jy,baseCommit:jy}).strict().nullable(),contentHash:Q}).strict(),dF=c({schemaVersion:S("openpond.modelEvaluationStopReceipt.v1"),benchmarkId:E,terminalClassification:S("inconclusive"),stopReason:b(["candidate_harness_unchanged","candidate_lineage_invalid"]),reason:r().trim().min(1).max(5e3),stoppedAfter:S("refiner"),baselineHarness:J,candidateHarness:J,refiner:c({id:E,contentHash:Q,outcomeCount:u().int().nonnegative()}).strict(),usage:tv,budget:c({maximumSpendUsd:u().nonnegative(),observedSpendUsd:u().nonnegative(),enforced:A()}).strict(),evidenceSnapshot:J,attempts:p(ev).max(1e4),contentHash:Q}).strict(),$y=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."})}),uF=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:E.nullable(),model:dn.nullable()}).strict(),taskset:zt,grader:J,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:$y.nullable()}).strict(),judge:c({judgeModel:dn,judgeRelease:J,rubricRelease:J,calibrationRelease:J,score:u().min(0).max(100),scoreCi95:$y,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:E.nullable().default(null),taskId:E,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:Q.nullable(),traceHash:Q.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:Xg.nullable()}).strict()).max(1e5),usage:c({policy:ir.nullable(),judge:ir.nullable(),observedSpendUsd:u().nonnegative().nullable(),evaluationGpuSeconds:u().nonnegative().nullable().default(null)}).strict(),managedServing:c({jobId:E,terminalState:b(["completed","cancelled","failed","budget_exhausted"]),sourcePolicyVersion:u().int().nonnegative(),sourceAdapterSha256:Q.nullable(),servedPolicyVersion:u().int().nonnegative().nullable(),servedAdapterSha256:Q.nullable(),accruedSpendUsd:u().nonnegative(),cleanupAttestationHash:Q,resourceCount:u().int().nonnegative(),activeResourceCount:S(0)}).strict().nullable().default(null),evidenceSnapshot:c({id:E,contentHash:Q,artifactPath:r().trim().min(1).max(2e3)}).strict(),completedAt:Ee,contentHash:Q}).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."})}),mF=c({benchmarkId:S("harness-refiner"),model:dn,upstreamModel:c({providerId:E,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:Ee,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(E).min(1).max(1e5),attemptCount:u().int().positive()}).strict()).length(4)}).strict(),pF=c({benchmarkId:S("model-comparison"),target:c({kind:b(["base_model","model_version","external_reference"]),label:r().trim().min(1).max(300),modelVersionId:E.nullable(),model:dn.nullable()}).strict(),grader:J,judge:c({model:dn,release:J,rubricRelease:J,calibrationRelease:J,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:E,protocol:c({id:E,revision:u().int().positive(),contentHash:Q}).strict()}).strict().nullable().default(null),panel:c({id:E,role:b(["correction","sibling_verification","cumulative_known","development","retained","frozen_final"]),passLabel:E.nullable()}).strict().nullable().default(null),comparisonPair:c({entryId:E,parent:kI,candidateModelVersionId:E}).strict().nullable().default(null),attemptPlan:p(c({stage:S("comparison"),split:r().trim().min(1).max(100),taskIds:p(E).min(1).max(1e5),attemptCount:u().int().positive()}).strict()).length(1)}).strict(),fF=Nt([mF,pF]),hF=c({schemaVersion:S("openpond.modelRun.v1"),id:E,modelId:E,modelVersionId:E.nullable(),profileId:E,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:E.nullable(),taskset:zt,comparisonSeriesEntry:vs.nullable().optional(),evaluationTasksetRef:zt.nullable().optional(),harnessRelease:J.nullable().optional(),quote:c({maximumSpendUsd:u().nonnegative(),hourlyCostUsd:u().nonnegative().nullable()}).strict().nullable(),evaluation:fF.nullable().default(null),evaluationProgress:c({stage:b(["baseline","adaptation","refiner","candidate_adaptation","candidate","comparison"]),completedAttempts:u().int().nonnegative(),totalAttempts:u().int().positive(),accounting:sF.nullable().default(null),evidenceSnapshot:lF.nullable().default(null)}).strict().nullable().default(null),reward:c({raw:u(),components:re(r(),u())}).strict().nullable(),receipt:Nt([iF,cF,dF,uF]).nullable(),adapterArtifactLineageId:E.nullable(),failure:r().trim().min(1).max(5e3).nullable(),startedAt:Ee,completedAt:Ee.nullable(),updatedAt:Ee}).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 iQ(e){const t=new Map;for(const _ of e.attempts){const R=`${_.phase}\0${_.taskId}`,M=t.get(R);(!M||_.startedAt>M.startedAt||_.startedAt===M.startedAt&&_.attemptId>M.attemptId)&&t.set(R,_)}const n=[...t.values()],a=[["adaptation","adaptation","candidate_adaptation"],["held_out","baseline","candidate"]].flatMap(([_,R,M])=>{const C=new Map(n.filter(N=>N.phase===M).map(N=>[N.taskId,N]));return n.filter(N=>N.phase===R).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=(_,R)=>({targetTaskCount:R,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((_,R)=>_+R.baseline.totalTokens,0),h=a.reduce((_,R)=>_+R.refined.totalTokens,0),v=h-d,y=a.length===i;return{summary:II.parse({target:"all_tasks_lower",...m,baselineTokens:d,refinedTokens:h,tokenDelta:v,tokenDeltaPercent:d>0?v/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 gF=b(["measuring","up_to_date","needs_attention"]),vF=b(["fixed","retained","regressed","unresolved","unavailable"]),Ny=c({evaluationRunId:E,attemptKey:E,artifactPath:r().trim().min(1).max(2e3),jsonPointer:r().trim().min(1).max(1e3),transcriptHash:Q.nullable(),traceHash:Q.nullable()}).strict(),Kf=c({level:S(.95),lower:u().finite(),upper:u().finite()}).strict(),bF=c({panelId:E,panelRole:Lu,passLabel:E.nullable(),taskset:zt,attempted:u().int().nonnegative(),available:u().int().nonnegative(),passed:u().int().nonnegative(),strictSuccess:u().min(0).max(1).nullable(),strictSuccessCi95:Kf.nullable(),judgeScore:u().min(0).max(100).nullable(),judgeScoreCi95:Kf.nullable()}).strict(),yF=c({schemaVersion:S("openpond.modelCurrencySnapshot.v1"),id:E,contentHash:Q,seriesId:E,protocol:c({id:E,revision:u().int().positive(),contentHash:Q}).strict(),entryId:E,passLabel:E,parent:It("kind",[c({kind:S("base_model"),id:E,revision:r().trim().min(1).max(500)}).strict(),c({kind:S("model_version"),id:E,contentHash:Q}).strict()]),candidate:c({kind:S("model_version"),id:E,contentHash:Q}).strict(),sources:c({evaluationRunIds:p(E).max(1e5),attemptIds:p(E).max(1e6),tasksets:p(zt).max(1e4),grader:J,judge:J.nullable(),calibration:J.nullable()}).strict(),matches:p(c({key:E,panelId:E,panelRole:Lu,taskId:E,issueFamilyId:E,seed:u().int(),repetition:u().int().nonnegative(),classification:vF,parentPassed:A().nullable(),candidatePassed:A().nullable(),parentAttempt:Ny.nullable(),candidateAttempt:Ny.nullable()}).strict()).max(1e6),taskIds:c({fixed:p(E).max(1e6),retained:p(E).max(1e6),regressed:p(E).max(1e6),unresolved:p(E).max(1e6),unavailable:p(E).max(1e6)}).strict(),panels:p(bF).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:Kf.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:J}).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:Q,toolSchema:J,application:J,harness:J,runtime:J,grader:J,autoRefinerEnabled:A()}).strict(),evidenceState:gF,evidenceReasons:p(E).max(100),projectedAt:Ee}).strict(),gd=It("kind",[c({kind:S("base_model"),id:E,revision:r().trim().min(1).max(500),label:r().trim().min(1).max(300)}).strict(),c({kind:S("model_version"),id:E,label:r().trim().min(1).max(300)}).strict(),c({kind:S("captured_model"),id:E,label:r().trim().min(1).max(300)}).strict()]),Rl=Nt([c({source:S("evaluation_run").default("evaluation_run"),evaluationRunId:E,attemptId:E,modelLabel:r().trim().min(1).max(300).nullable().default(null),modelVersionId:E.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:E.nullable().default(null),response:de().refine(e=>e!==void 0,"An imported model response is required."),reward:u().finite().nullable().default(null),components:re(r(),u().finite()).default({})}).strict()]),SF=Nt([c({taskId:E,target:gd,attempt:Rl}).strict(),c({taskId:E,target:b(["base","current"]).default("current"),attempt:Rl}).strict(),c({taskId:E,target:b(["base","current"]).default("current"),evaluationRunId:E,attemptId:E,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:E,seriesId:E,scheduleEntryId:E,dayOrdinal:u().int().positive().max(1e4),sourceTaskset:zt,taskIds:p(E).min(1).max(1e3),observedAttempts:p(SF).max(1e3).default([]),sourceFileName:r().trim().min(1).max(500).nullable().default(null),availableAt:Ee}).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}:${wF(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 xF=c({schemaVersion:S("openpond.continualLearningDailyBatch.v1"),id:E,seriesId:E,scheduleEntryId:E,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:zt,tasks:p(c({taskId:E,taskContentHash:Q,familyKey:E,disposition:b(["include","defer","exclude"]).nullable(),oracleReview:b(["pending","confirmed","needs_correction"]),note:r().trim().max(2e3),observedAttempt:Rl.nullable(),baselineAttempt:Rl.nullable().default(null),responses:p(c({target:gd,attempt:Rl}).strict()).max(100).default([]),stagedAt:Ee.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(gd).max(100).default([]),runs:p(c({target:gd,runId:E}).strict()).max(100).default([]),baselineRunId:E.nullable(),currentRunId:E.nullable(),currentPolicy:It("kind",[c({kind:S("base_model"),id:E}).strict(),c({kind:S("model_version"),id:E}).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:E.nullable(),reviewedAt:Ee.nullable(),availableAt:Ee,revision:u().int().positive(),createdAt:Ee,updatedAt:Ee}).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=>_I(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."})}),kF=c({schemaVersion:S("openpond.continualBenchIssueReview.v1"),id:E,seriesId:E,scheduleEntryId:E,passLabel:E,packet:NB,splitManifest:c({id:E,contentHash:Q}).strict(),decisions:p(c({taskId:E,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:E.nullable(),reviewedAt:Ee.nullable(),revision:u().int().positive(),createdAt:Ee,updatedAt:Ee}).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 _I(e){return`${e.kind}:${e.id}`}function wF(e){return typeof e=="string"?e:_I(e)}const Ua=r().trim().min(1).max(240),pa=r().trim().min(8).max(256),CI=b(["grpo","dapo","gspo-token"]),Vl=c({id:Ua,revision:r().trim().min(1).max(256),tokenizerRevision:r().trim().min(1).max(256),chatTemplateHash:pa}),IF=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()}),_F=c({method:S("grpo"),groupSize:u().int().min(2).max(128),normalization:S("group_standardized"),advantageEpsilon:u().positive().max(.01).default(1e-8),loss:CI,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:fI}),RI=c({method:S("ppo"),valueModel:Vl,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)}),CF=It("method",[_F,RI]),PI=c({rewardModelVersion:c({id:Ua,contentHash:pa}).strict(),qualificationReport:c({id:Ua,contentHash:pa}).strict().nullable().default(null),evaluationReferences:p(c({id:Ua,contentHash:pa}).strict()).max(1e3).default([]),checkpoint:c({id:Ua,contentHash:pa,objectRef:r().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/),files:p(c({path:r().trim().min(1).max(512),sizeBytes:u().int().positive(),sha256:pa}).strict()).min(4).max(128)}).strict(),runtime:wI,processorRelease:c({id:Ua,contentHash:pa}).strict(),rewardComposerRelease:c({id:Ua,contentHash:pa}).strict(),executionReceipt:c({id:Ua,contentHash:pa}).strict()}).strict(),AI=c({schemaVersion:S("openpond.policyOptimization.v1"),policyModel:Vl,referenceModel:Vl,dataset:c({tasksetId:Ua,tasksetHash:pa,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:Ua,version:r().trim().min(1).max(256),toolContractHash:pa}),reward:c({graderId:Ua,graderHash:pa,learnedPreference:PI.nullable().default(null)}),kl:c({coefficient:u().nonnegative().nullable(),referenceConstraint:S("fixed_reference")}),budgets:IF,checkpointEverySteps:u().int().positive(),seed:u().int(),evaluationSplit:S("frozen_eval"),optimizer:CF}),Ae=r().trim().min(1).max(240),Pt=r().trim().min(1),ft=r().trim().min(8).max(256),gc=re(r(),de()).default({}),TI=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)}),RF=TI.parse({}),PF=c({schemaVersion:S("openpond.managedAdapterServingProjection.v1"),teamId:Ae.nullable().default(null),source:S("sandbox_managed_rl"),sourceRef:Ae,canonicalArtifactId:Ae.nullable(),canonicalArtifactState:b(["imported_unvalidated","evaluating","promotable","rejected","deleted"]).nullable(),canonicalDeploymentId:Ae.nullable(),canonicalDeploymentState:b(["requested","deploying","ready","degraded","deleting","deleted","failed"]).nullable(),state:b(["pending","imported","ready","failed"]),customerBindingAllowed:A().default(!1),artifactContentHash:ft.nullable().default(null),baseProfileId:Ae.nullable().default(null),publishedAt:Pt.nullable(),lastSyncedAt:Pt,lastError:r().trim().min(1).max(5e3).nullable()});function sQ(e){const t=e.managedServing;return!!(t?.source==="sandbox_managed_rl"&&t.canonicalArtifactState==="promotable"&&t.customerBindingAllowed)}function EI(e){return e.state==="ready"&&e.canonicalArtifactState==="promotable"&&e.canonicalDeploymentState==="ready"&&e.customerBindingAllowed&&!!e.teamId&&!!e.canonicalArtifactId&&!!e.canonicalDeploymentId}function lQ(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"&&EI(t)&&t.canonicalArtifactId&&t.canonicalDeploymentId?{kind:"sandbox_customer_binding",evaluationArtifactId:null,canonicalArtifactId:t.canonicalArtifactId,canonicalDeploymentId:t.canonicalDeploymentId}:null}function cQ(e){const t=e.managedServing;return t?EI(t)&&t.canonicalArtifactId&&t.canonicalDeploymentId?{kind:"sandbox_serving",canonicalArtifactId:t.canonicalArtifactId,canonicalDeploymentId:t.canonicalDeploymentId}:null:{kind:"source_artifact",canonicalArtifactId:null,canonicalDeploymentId:null}}const nv="openpond.crossSystemOperations.v1",dQ="1.0.0",MI="openpond.crossSystemTools.v1",AF=["search_crm","query_billing","search_support","run_python"],TF=b(["train","validation","frozen_eval"]),EF=b(["easy","medium","hard"]),MF=b(["renewal_risk_v2"]);b(["renewal_exposure","collections_prioritization","invoice_reconciliation","sla_escalation","contract_billing_mismatch"]);c({seed:u().int().nonnegative(),split:TF,difficulty:EF,scenarioProfile:MF.optional()});const Lp={anyOf:[{type:"string",minLength:1,maxLength:256},{type:"null"}],default:null},Up={type:"integer",minimum:1,maximum:50,default:25},jI=[{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:Lp,limit:Up}}},{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:Lp,limit:Up}}},{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:Lp,limit:Up}}},{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}}}}],vc=BF({schemaVersion:MI,tools:jI}),jF=[`Use only the four registered synthetic Cross-System Operations tools. Contract ${vc}.`,"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(" "),OF=15;function $F(e="auto"){return[jF,"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: ${OF}.`,`Registered tool signatures: ${jI.map(NF).join("; ")}`].join(`
|
|
178
|
+
`)}$F();function NF(e){const t=Bd(e.parameters),n=Bd(t.properties),a=OI(t.required),o=Object.fromEntries(a.map(i=>[i,vd(n[i])]));return`${e.name}(${JSON.stringify(o)})`}function vd(e){const t=Bd(e),n=Wf(t.anyOf);if(n.length)return n.map(vd).join("|");const a=Wf(t.enum);if(a.length)return a.join("|");if(t.type==="array")return[vd(t.items)];if(t.type==="object"){const o=Bd(t.properties),i=OI(t.required);return Object.fromEntries(i.map(s=>[s,vd(o[s])]))}return typeof t.type=="string"?t.type:"unknown"}function Bd(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Wf(e){return Array.isArray(e)?e:[]}function OI(e){return Wf(e).filter(t=>typeof t=="string")}const Fd=b(AF),DF=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:Fd,arguments:re(r(),de())}),c({kind:S("tool_result"),turn:u().int().nonnegative(),callId:r().trim().min(1).max(240),name:Fd,ok:A(),result:de(),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)})]),LF=c({schemaVersion:S(nv),id:r().trim().min(1).max(240),worldId:r().trim().min(1).max(240),taskId:r().trim().min(1).max(240),toolContractHash:S(vc),modelRef:c({providerId:r().trim().min(1),modelId:r().trim().min(1)}).nullable(),status:b(["completed","budget_exhausted","cancelled","infrastructure_failure"]),steps:p(DF).max(1e3),startedAt:r().trim().min(1),completedAt:r().trim().min(1),infrastructureError:r().trim().min(1).max(2e4).nullable(),metadata:re(r(),de()).default({})}),UF=c({schemaVersion:S(nv),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:de().nullable(),feedback:p(r().trim().min(1).max(5e3)).max(100)}),HF=c({id:r().trim().min(1).max(240),type:S("function"),function:c({name:Fd,arguments:r().max(2e4)})}),$I=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(HF).max(4).optional()});c({schemaVersion:S(nv),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(vc),approval:c({status:S("approved"),approvedBy:r().trim().min(1).max(240),approvedAt:r().trim().min(1)}),messages:p($I).min(3).max(1e3)});const zF=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(Fd).min(1).max(100),toolCallCount:u().int().positive(),messageCount:u().int().min(3),reward:u().min(0).max(1.15),messages:p($I).min(3).max(1e3)}),qF=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(vc),status:b(["ready_for_review","approved"]),approval:qF.nullable(),tasks:p(zF).min(1).max(100)});function BF(e){const t=Gf(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`${MI}:${Dy(n)}${Dy(a)}`}function Gf(e){return Array.isArray(e)?`[${e.map(Gf).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${Gf(n)}`).join(",")}}`:JSON.stringify(e)}function Dy(e){return(e>>>0).toString(16).padStart(8,"0")}const FF=c({schemaVersion:S("openpond.singleTurnPolicyTrajectory.v1"),id:Ae,taskId:Ae,status:b(["completed","infrastructure_failure"]),promptHash:ft,responseText:r().max(2e6),infrastructureError:r().trim().min(1).max(1e4).nullable(),startedAt:Pt,completedAt:Pt,metadata:gc}),VF=c({schemaVersion:S("openpond.ppoTrajectory.v1"),id:Ae,taskId:Ae,policyModelId:Ae,referenceModelId:Ae,valueModelId:Ae,steps:p(c({index:u().int().nonnegative(),observationHash:ft,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}),KF=c({schemaVersion:S("openpond.exactAnswerVerifierResult.v1"),outcome:b(["correct","incorrect","parse_failure","infrastructure_failure"]),graderSetHash:ft,score:u().min(0).max(1).nullable(),passed:A(),rewardEligible:A(),expectedAnswerHash:ft,extractedAnswer:r().max(2e4).nullable(),feedback:p(r().trim().min(1).max(2e4)).max(1e3)}),WF=c({schemaVersion:S("openpond.rolloutTrajectoryReceipt.v1"),id:Ae,jobId:Ae,planId:Ae,tasksetId:Ae,tasksetHash:ft,taskId:Ae,split:S("train"),correlationId:Ae,provider:Ae,providerTrace:c({invocationId:Ae,experimentId:Ae,rolloutId:Ae,runId:Ae,rowId:Ae}),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:Ae,version:r().trim().min(1).max(256),worldId:Ae,worldHash:ft,toolContractHash:ft}),policy:c({modelId:Ae,checkpointId:Ae.nullable(),completionParametersHash:ft}),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:Nt([LF,FF,VF]).nullable(),verifier:Nt([UF,KF]).nullable(),providerStatus:re(r(),de()).default({}),receivedAt:Pt,startedAt:Pt.nullable(),completedAt:Pt.nullable(),updatedAt:Pt}),uQ="dataset-exact-answer",mQ="dataset-exact-answer-v1",pQ="no-tools-v1",yr=b(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),Uu=b(["lora","full"]),ri=b(["openpond_managed"]),GF=c({schemaVersion:S("openpond.sftRecipe.v1"),method:S("sft"),parameterization:S("lora"),baseModel:c({id:Ae,revision:r().trim().min(1).max(256),tokenizerRevision:r().trim().min(1).max(256),chatTemplateHash:ft}),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(Ae).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:Ae,input:re(r(),de()),expectedOutput:re(r(),de()),tags:p(Ae).max(100).default([])});c({id:Ae,prompt:r().min(1).max(5e5),chosen:r().min(1).max(5e5),rejected:r().min(1).max(5e5),sourceRefs:p(Ae).min(1).max(1e4)});c({id:Ae,input:re(r(),de()),tags:p(Ae).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:Ae,revision:r().trim().min(1).max(256),tokenizerRevision:r().trim().min(1).max(256),processorRevision:r().trim().min(1).max(256),chatTemplateHash:ft}).strict(),tasksetRelease:J,preferenceDatasetRelease:J,processorRelease:J,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(Ae).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 ZF=c({schemaVersion:S("openpond.rftRecipe.v1"),method:S("grpo"),parameterization:S("lora"),baseModel:c({id:Ae,revision:r().trim().min(1).max(256),tokenizerRevision:r().trim().min(1).max(256),chatTemplateHash:ft}),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:fI}),loss:c({method:CI.default("grpo"),klBeta:u().min(0).nullable().default(null)}).default({method:"grpo",klBeta:null}),reward:c({graderId:Ae,graderHash:ft,environmentId:Ae,environmentVersion:r().trim().min(1).max(256),toolContractHash:ft,learnedPreference:PI.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:AI.nullable().default(null),continuation:c({schemaVersion:S("openpond.crossJobContinuationRequest.v1"),parentArtifact:J,sourceArtifact:c({jobId:Ae,artifactId:Ae,checkpointId:Ae,contentHash:ft}).strict(),optimizerMode:b(["continue","reset"])}).strict().optional()}),JF=c({schemaVersion:S("openpond.dpoRecipe.v1"),method:S("dpo"),parameterization:S("lora"),policyModel:Vl,referenceModel:Vl,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(Ae).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:ft,invalidationHash:ft}),resourceLimits:c({cpuThreads:u().int().positive().max(256),memoryBytes:u().int().positive(),wallTimeMs:u().int().positive()})}),YF=c({schemaVersion:S("openpond.ppoRecipe.v1"),method:S("ppo"),parameterization:S("lora"),policyOptimization:AI.extend({optimizer:RI}),lora:c({rank:u().int().positive().max(256),alpha:u().positive().max(1024),dropout:u().min(0).max(1),targetModules:p(Ae).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:Ae.nullable(),policyHash:ft,referenceHash:ft,valueModelHash:ft,optimizerStateHash:ft.nullable()}),resourceLimits:c({cpuThreads:u().int().positive().max(256),memoryBytes:u().int().positive(),wallTimeMs:u().int().positive()})}),QF=c({schemaVersion:S("openpond.unsupportedRecipe.v1"),method:yr.exclude(["sft","dpo","grpo","ppo"]),parameterization:Uu,unsupportedReason:r().trim().min(1).max(5e3)}),NI=Nt([GF,JF,ZF,YF,QF]),XF=c({schemaVersion:S("openpond.trainingDestinationCapabilities.v1"),destinationId:ri,available:A(),methods:p(yr),parameterizations:p(Uu),modelAllowlist:p(Ae).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}),e4=c({destinationId:ri,available:A(),methods:p(yr),parameterizations:p(Uu),nonProduction:A(),unavailableReason:r().trim().min(1).max(5e3).nullable()}),t4=c({schemaVersion:S("openpond.baseModelCandidate.v1"),selectionKey:Ae,label:r().trim().min(1).max(500),sourceLabel:r().trim().min(1).max(500),preference:hc,available:A(),nonProduction:A(),unavailableReason:r().trim().min(1).max(5e3).nullable(),methods:p(yr),executionOptions:p(e4).min(1)}),n4=c({code:Ae,severity:b(["warning","error"]),path:r().trim().max(2e3).nullable(),message:r().trim().min(1).max(5e3)}),a4=c({schemaVersion:S("openpond.trainingCompatibility.v1"),compatible:A(),destinationId:ri,tasksetId:Ae,recipeMethod:yr,issues:p(n4),checkedAt:Pt}),o4=Nt([tI,b(["destination_unavailable","destination_method_unsupported","destination_model_unsupported","destination_parameterization_unsupported","experimental_destination"])]);c({method:yr,state:b(["recommended","compatible","needs_dataset_work","destination_unavailable","experimental_destination"]),reasonCodes:p(o4).default([]),reasons:p(r().trim().min(1).max(5e3)).default([]),destinationId:ri.nullable().default(null)});b(["small","standard","custom","small_experiment"]);const r4=r1,DI=c({schemaVersion:S("openpond.trainingPlan.v1"),id:Ae,modelId:Ae,tasksetId:Ae,tasksetHash:ft,comparisonSeriesEntry:vs.nullable().optional(),evaluationTasksetRef:zt.nullable().optional(),harnessRelease:J.nullable().optional(),modelImprovementQualification:J.nullable().optional(),destinationId:ri,recipe:NI,environmentPlacement:b(["none","local","remote","colocated","provider_native"]),compatibility:a4,dataPolicy:c({exportApproved:A(),approvedSourceIds:p(Ae),retentionDays:u().int().nonnegative().nullable(),region:r().trim().min(1).max(200).nullable()}),estimatedCostUsd:u().nonnegative().nullable(),createdAt:Pt,contentHash:ft}),i4=c({path:r().trim().min(1).max(2e3),sha256:ft,sizeBytes:u().int().nonnegative(),role:b(["manifest","task_data","grader","environment","recipe","policy","provenance"])}),av=c({schemaVersion:S("openpond.trainingBundle.v1"),id:Ae,planId:Ae,tasksetId:Ae,tasksetHash:ft,recipeHash:ft,files:p(i4).min(1).max(1e6),totalSizeBytes:u().int().nonnegative(),sourceIds:p(Ae),excludedSourceIds:p(Ae),containsRawChats:S(!1),containsSecrets:S(!1),containsHiddenGraderAssets:S(!1),createdAt:Pt,contentHash:ft});c({schemaVersion:S("openpond.trainingBundleExport.v1"),manifest:av,files:p(c({path:r().trim().min(1).max(2e3),sha256:ft,sizeBytes:u().int().nonnegative(),encoding:S("base64"),content:r()})).min(1),contentHash:ft});c({schemaVersion:S("openpond.trainingPreparedStart.v1"),plan:DI,bundle:av,approvalActor:Ae.nullable(),preparedAt:Pt});c({schemaVersion:S("openpond.trainingApproval.v1"),evaluationTasksetRef:zt.nullable().optional(),id:Ae,planId:Ae,bundleHash:ft,harnessRelease:J.nullable().optional(),modelImprovementQualification:J.nullable().optional(),destinationId:ri,modelId:Ae,method:yr,parameterization:Uu,maximumCostUsd:u().nonnegative().nullable(),approvedBy:Ae,approvedAt:Pt});c({schemaVersion:S("openpond.trainingJobSourceSnapshot.v1"),evaluationTasksetRef:zt.nullable().optional(),modelProjectId:Ae,sourceProjectRevision:u().int().positive(),profileId:Ae,taskset:c({id:Ae,revision:u().int().positive(),contentHash:ft}).strict(),tasksetRelease:J,harnessRelease:J,baseModel:hc,method:yr}).strict();const s4=b(["queued","starting","running","cancelling","cancelled","succeeded","failed","reconciling"]),LI=c({schemaVersion:S("openpond.trainingJob.v1"),id:Ae,planId:Ae,bundleHash:ft,approvalId:Ae,destinationId:ri,status:s4,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:gc}),l4=c({schemaVersion:S("openpond.trainingJobEvent.v1"),id:Ae,jobId:Ae,sequence:u().int().nonnegative(),type:b(["queued","start","progress","metric","checkpoint","cancel","complete","failure","reconcile"]),timestamp:Pt,payload:gc}),c4=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()}),d4=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()}),u4=c({schemaVersion:S("openpond.managedTrainingRunEvidence.v2"),provider:Ae,providerRunId:Ae,state:Ae,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:Ae,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:Ae,policyVersion:u().int().nonnegative(),sha256:ft.nullable(),sizeBytes:u().int().nonnegative().nullable()}).nullable(),movement:c({adapterDeltaNorm:u().nonnegative().nullable()}),evaluations:p(c({reference:c({id:Ae,contentHash:ft}).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:Ae.nullable(),artifactId:Ae.nullable()}),syncedAt:Pt}),Ly=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()}),Uy=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:Ae,score:u().min(0).max(1).nullable(),passed:A(),feedback:r().trim().max(2e4).nullable()})).max(1e3)}),m4=c({taskId:Ae,input:re(r(),de()),baseOutput:re(r(),de()).nullable(),trainedOutput:re(r(),de()).nullable(),baseGrade:Uy.nullable(),trainedGrade:Uy.nullable()}),p4=c({schemaVersion:S("openpond.trainingEvaluationSummary.v1"),jobId:Ae,tasksetId:Ae,base:Ly,trained:Ly,meanScoreDelta:u().min(-1).max(1).nullable(),examples:p(m4).max(1e6)});c({schemaVersion:S("openpond.trainingRunDetail.v1"),job:LI,events:p(l4),stepMetrics:p(c4),policyMetrics:p(d4).default([]),managedEvidence:u4.nullable().default(null),evaluation:p4.nullable(),generatedAt:Pt});const f4=c({schemaVersion:S("openpond.trainingArtifact.v1"),id:Ae,jobId:Ae,kind:b(["adapter","checkpoint","metrics","log","manifest","evaluation"]),path:r().trim().min(1).max(4e3),sha256:ft,sizeBytes:u().int().nonnegative(),baseModelId:Ae.nullable(),baseModelRevision:r().trim().min(1).max(256).nullable(),tokenizerRevision:r().trim().min(1).max(256).nullable(),chatTemplateHash:ft.nullable(),nonProduction:A(),createdAt:Pt,metadata:gc}),h4=c({schemaVersion:S("openpond.modelArtifactLineage.v1"),id:Ae,modelId:Ae,artifactId:Ae,jobId:Ae,tasksetId:Ae,tasksetHash:ft,graderHash:ft,planHash:ft,bundleHash:ft,recipeHash:ft,workerVersion:r().trim().min(1).max(256),trainerVersion:r().trim().min(1).max(256),importedAt:Pt,frozenEvaluationArtifactId:Ae.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:TI.default(RF),managedServing:PF.nullable().default(null)}),g4=b(["chat_manual","agent","extension","authoring_optimizer"]),v4=c({schemaVersion:S("openpond.modelBinding.v1"),id:Ae,profileId:Ae,role:g4,roleTargetId:Ae,modelArtifactLineageId:Ae,tasksetId:Ae,evaluationArtifactId:Ae.nullable(),status:b(["active","rolled_back"]),priorBindingId:Ae.nullable(),rollbackTargetBindingId:Ae.nullable(),promotedBy:Ae,promotedAt:Pt,rolledBackAt:Pt.nullable(),metadata:gc});c({schemaVersion:S("openpond.trainingActivity.v1"),profileId:Ae,active:A(),activeCounts:c({jobs:u().int().nonnegative(),creations:u().int().nonnegative(),minerRuns:u().int().nonnegative(),datasetImports:u().int().nonnegative()}),revision:ft,generatedAt:Pt});c({schemaVersion:S("openpond.tasksetOperationalState.v1"),tasksetId:Ae,attempts:p(pB),artifacts:p(fB),grades:p(gB),evaluationResults:p(nH).default([]),generatedAt:Pt});const b4=c({schemaVersion:S("openpond.trainingState.v1"),profileId:Ae,sources:p(H1),creations:p(hI),tasksetDrafts:p(fo).default([]),tasksets:p(Ry),benchmarkRuns:p(ip()).default([]),benchmarkComparisons:p(ip()).default([]),datasetImports:p(TB).default([]),datasetArtifacts:p(zz).default([]),graderAuditReports:p(vB),evaluationResults:p(ip()).default([]),candidates:p(pI),minerConfig:Du,minerRuns:p(eB).default([]),modelProjects:p(r4).default([]),modelVersions:p(nF).default([]),modelRuns:p(hF).default([]),comparisonSeries:p(GB).default([]),comparisonSeriesEntries:p(eF).default([]),modelCurrencySnapshots:p(yF).default([]),continualBenchIssueReviews:p(kF).default([]),continualLearningDailyBatches:p(xF).default([]),rewardModelVersions:p(aF).default([]),rewardModelRuns:p(rF).default([]),modelTasksets:p(Ry).default([]),plans:p(DI),bundles:p(av),jobs:p(LI),artifacts:p(f4),models:p(h4),rolloutReceipts:p(WF).default([]),modelBindings:p(v4).default([]),destinations:p(XF),baseModelCandidates:p(t4).default([]),activityRevision:ft.optional(),generatedAt:Pt}),y4=b(["trajectory","reward","demonstration","preference","correction","critique","targeted_feedback","grader_evidence","infrastructure_failure"]),S4=c({datasetRelease:J,harnessRelease:J,evidenceSetRelease:J.nullable(),profileRelease:J.nullable(),model:c({source:r().trim().min(1).max(200),revision:r().trim().min(1).max(500),artifactHash:Q.nullable()}).strict(),environmentHash:Q,graderHash:Q,toolContractHash:Q,verificationReceiptHash:Q.nullable()}).strict(),Jo=c({schemaVersion:S("openpond.learningSignal.v1"),id:E,taskId:E.nullable(),episodeId:E.nullable(),policyVersion:u().int().nonnegative().nullable(),lineage:S4,approved:A(),verifier:b(["deterministic","model_judge","human","none"]),createdAt:Ee,contentHash:Q,metadata:re(r(),de()).default({})}).strict(),x4=Jo.extend({kind:S("trajectory"),payload:c({traceRef:r().trim().min(1).max(2e3),traceHash:Q,terminal:A(),failureClass:b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),optimizerSample:g1.nullable().optional()}).strict()}).strict(),k4=Jo.extend({kind:S("reward"),payload:c({reward:u().finite(),components:re(r(),u().finite()),eligible:A(),graderEvidenceRefs:p(E).max(1e3)}).strict()}).strict(),w4=Jo.extend({kind:S("demonstration"),payload:c({prompt:r().max(5e5),response:r().max(1e6)}).strict()}).strict(),I4=Jo.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(),_4=Jo.extend({kind:S("correction"),payload:c({original:r().max(1e6),corrected:r().max(1e6),rationale:r().max(5e5).nullable()}).strict()}).strict(),C4=Jo.extend({kind:S("critique"),payload:c({response:r().max(1e6),critique:r().max(5e5),severity:b(["note","warning","error"])}).strict()}).strict(),R4=Jo.extend({kind:S("targeted_feedback"),payload:c({turnIndex:u().int().nonnegative(),target:b(["reasoning","tool","answer","policy"]),feedback:r().max(5e5)}).strict()}).strict(),P4=Jo.extend({kind:S("grader_evidence"),payload:c({graderId:E,score:u().finite().nullable(),passed:A(),privilegedArtifactRefs:p(r().trim().min(1).max(2e3))}).strict()}).strict(),A4=Jo.extend({kind:S("infrastructure_failure"),approved:S(!1),verifier:S("none"),payload:c({code:E,phase:E,retryable:A(),rewardEligible:S(!1)}).strict()}).strict(),UI=It("kind",[x4,k4,w4,I4,_4,C4,R4,P4,A4]);c({schemaVersion:S("openpond.learningSignalBatch.v1"),manifestId:E,manifestHash:Q,sequence:u().int().nonnegative(),signals:p(UI).min(1).max(1e5),contentHash:Q}).strict();const T4=c({id:E,turn:u().int().nonnegative(),kind:b(["message","tool_call","terminal"]),name:E.nullable(),arguments:re(r(),de()),content:r().max(1e6).nullable(),contentHash:Q}).strict(),E4=c({actionId:E,turn:u().int().nonnegative(),terminal:A(),output:re(r(),de()),artifactRefs:p(r().trim().min(1).max(2e3)),contentHash:Q}).strict(),M4=c({sequence:u().int().nonnegative(),type:b(["created","reset","action","observation","terminal","graded","feedback","failure","collected","destroyed"]),timestamp:Ee,payloadHash:Q,metadata:re(r(),de()).default({})}).strict(),Hy=c({graderId:E,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:Q}).strict();c({schemaVersion:S("openpond.harnessRunTrace.v1"),manifest:J,taskId:E,seed:r().trim().min(1).max(500),events:p(M4).max(1e6),actions:p(T4).max(1e5),observations:p(E4).max(1e5),graderEvidence:p(Hy).max(1e4),learningSignals:p(UI).max(1e5),terminal:A(),failureClass:Hy.shape.failureClass,artifactHash:Q,contentHash:Q}).strict();const j4=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"),O4=b(["instruction","skill","skill_resource","agent","workflow","dependency_lock","program","asset"]),$4=c({id:E,kind:O4,path:j4,parentId:E.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($4).min(2).max(1e5),toolDeclarations:p(sc).max(200),capabilityRequirements:p(sg).max(200),lifecycle:Pk,graderInterface:Ak,runtimeProtocol:r().trim().min(1).max(500),metadata:re(r(),de()).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:u$,currentRelease:oy,releases:p(oy),transitions:p(m$)}).strict();c({profile:Mk,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:J,reason:r().trim().min(1).max(1e4),actor:r().trim().min(1).max(240).default("local-user")}).strict();const N4=c({schemaVersion:S("openpond.trainingEngineCapabilities.v1"),adapterId:E,available:A(),methods:p(r().trim().min(1).max(100)),signalKinds:p(y4),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:Q,checkedAt:Ee,unavailableReason:r().trim().min(1).max(5e3).nullable()}).strict(),D4=c({schemaVersion:S("openpond.computeTargetCapabilities.v1"),adapterId:E,kind:b(["local","ssh","managed","custom"]),provider:E.nullable(),available:A(),devices:p(c({id:E,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:Q,checkedAt:Ee,unavailableReason:r().trim().min(1).max(5e3).nullable()}).strict(),L4=c({schemaVersion:S("openpond.harnessRuntimeCapabilities.v1"),adapterId:E,available:A(),placements:p(b(["local","remote","colocated","provider_native"])),lifecycle:p(b(["create","reset","step","grade","collect","destroy"])),deterministicReplay:A(),privilegedIsolation:A(),capabilityReceipt:Q,checkedAt:Ee,unavailableReason:r().trim().min(1).max(5e3).nullable()}).strict();c({schemaVersion:S("openpond.resolvedTrainingPlan.v1"),manifest:oB,recipe:NI,runtime:Zg,compute:Jg,engine:Yg,execution:c({trainingPlanId:E,approvalId:E}).strict().nullable(),maximumSpendUsd:u().nonnegative().nullable(),approvalHash:Q,contentHash:Q}).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:E,valid:A(),issues:p(c({code:E,path:r().trim().max(2e3).nullable(),message:r().trim().min(1).max(5e3)}).strict()),capabilityReceipt:Q,planHash:Q,createdAt:Ee,contentHash:Q}).strict();c({runId:E,adapterId:E,protocolVersion:b(["openpond.training.v2","adapter.native.v1"]).default("adapter.native.v1"),routeFamily:b(["training_v2","adapter_native"]).default("adapter_native"),routeId:E.optional(),providerJobId:r().trim().min(1).max(1e3).nullable(),tenantId:E.optional(),leaseId:E.nullable(),manifestHash:Q.optional(),inputBundleHash:Q.optional(),createdAt:Ee}).strict();c({runId:E,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:Ee,errorCode:E.nullable()}).strict();c({runId:E,manifestHash:Q,artifacts:p(c({kind:b(["checkpoint","adapter","metrics","trace","evaluation","receipt"]),objectRef:r().trim().min(1).max(2e3),sha256:Q,sizeBytes:u().int().nonnegative(),metadata:re(r(),de()).optional()}).strict()),contentHash:Q}).strict();const Zf=b(["ready","model_download_required","compute_setup_required","provider_managed","unsupported"]),U4=c({id:E,label:r().trim().min(1).max(500),description:r().trim().min(1).max(2e3),destinationId:E,computeAdapterId:E,runtimeAdapterId:E,engineAdapterId:E,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:ei,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(),H4=c({selectionKey:E,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:Q.nullable(),modelAssetId:E.nullable(),expectedBytes:u().int().nonnegative().nullable(),cached:A(),known:A(),searchResolved:A(),computeAdapterIds:p(E),engineAdapterIds:p(E),preparationState:Zf,reason:r().trim().min(1).max(5e3).nullable(),compatibilities:p(c({targetId:E,methods:p(r().trim().min(1).max(100)),state:Zf,reason:r().trim().min(1).max(5e3).nullable()}).strict())}).strict();c({schemaVersion:S("openpond.trainingCatalog.v1"),models:p(H4).max(1e5),engines:p(N4),compute:p(D4),runtimes:p(L4),targets:p(U4),generatedAt:Ee,contentHash:Q}).strict();c({schemaVersion:S("openpond.trainingPreparationPlan.v1"),modelRunId:E,state:Zf,reason:r().trim().min(1).max(5e3).nullable(),runtime:Zg.nullable(),compute:Jg.nullable(),engine:Yg.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:Q}).strict();const ov=32e3,z4=b(["steer","message","followup","queued","result"]),q4=b(["pending","included","resolved","cancelled","rejected"]),HI=c({id:r().min(1),sequence:u().int().nonnegative(),sessionId:r().min(1),senderSessionId:r().min(1).nullable(),senderKind:b(["user","task","runtime"]),kind:z4,body:r().trim().min(1).max(ov),payload:re(r(),de()).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:q4,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(ov)}).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(ov)}).strict(),c({action:S("steer"),expectedRevision:u().int().positive(),expectedTurnId:r().trim().min(1)}).strict()]);const B4=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(HI),waits:p(B4)});function F4(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 V4(e){return Math.min(500*2**Math.max(0,e),1e4)}async function K4(e,t,n,a){zI(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),qy(h,t,n),d=s.indexOf(`
|
|
181
|
+
|
|
182
|
+
`)}}!a?.aborted&&s.trim()&&qy(s,t,n)}function zI(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 W4(e,t,n,a,o={}){const i=new AbortController,s=o.fetchImpl??fetch,l=o.reconnectDelayMs??V4;let m=zy(o.afterSequence),d=!1;return(async()=>{let h=0;for(;!i.signal.aborted;)try{const v=F4(e,i.signal,m),y=await s(v.url,v.init);if(zI(y),d=!0,h=0,await K4(y,w=>{const _=zy(w.sequence);_>0&&_<=m||(_>0&&(m=_),t(w))},a,i.signal),d=!1,i.signal.aborted)break;throw new Error("event stream ended")}catch(v){if(d=!1,i.signal.aborted)break;n(v),await G4(l(h),i.signal),h+=1}})().catch(()=>{}),{close(){i.abort()},isOpen(){return d}}}function zy(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0?e:0}function qy(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 G4(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 Z4 extends Error{constructor(t,n){super(t),this.status=n,this.name="ApiRequestError"}status}function By(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 Fy=new WeakMap,Vy=new WeakMap,Yc=new WeakMap;let J4=0;async function q(e,t,n){if(t==="/v1/preferences"&&typeof n?.body=="string"){const o=(Yc.get(e)??Promise.resolve()).catch(()=>{}).then(()=>Ky(e,t,n));Yc.set(e,o);try{return await o}finally{Yc.get(e)===o&&Yc.delete(e)}}return Ky(e,t,n)}async function Ky(e,t,n){const a=++J4;if(t==="/v1/preferences"&&typeof n?.body=="string"){const m=Fy.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 Z4(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>=(Vy.get(e)??0)&&(Fy.set(e,l),Vy.set(e,a)),s}function fQ(e){const t=new URL("/v1/terminal",e.serverUrl);return t.protocol=t.protocol==="https:"?"wss:":"ws:",t.toString()}function hQ(e){return["openpond-terminal",`openpond-token.${Q4(e.token)}`]}function Y4(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 Q4(e){return Y4(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function X4(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 e5={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"})},t5={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?${n5(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 n5(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 a5={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?"":X4(i.file.contentsBase64)}}},o5={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)})},r5={connectedAppStatus:(e,t={})=>{const n=By(t);return n.set("status",t.status??"all"),q(e,`/v1/connected-apps/status${n.size>0?`?${n.toString()}`:""}`)},integrationConnections:(e,t={})=>{const n=By(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})})},i5={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)})},s5={sandbox:(e,t)=>q(e,`/v1/sandboxes/${encodeURIComponent(t)}`)},l5={...r5,...i5,...s5,...o5,...a5},c5={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`)},rv="openpond-app-server-url",Kl="openpond-app-token",d5=750;function qI(){return window.location.protocol!=="http:"&&window.location.protocol!=="https:"?null:window.location.origin&&window.location.origin!=="null"?window.location.origin:null}function Jf(e){const t=e.getItem(rv)?.trim(),n=e.getItem(Kl)?.trim();return t&&n?{serverUrl:t,token:n}:null}function Vd(e){if(!e)return null;try{const t="__openpond_storage_probe__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return null}}function Ni(e,t){e.setItem(rv,t.serverUrl),e.setItem(Kl,t.token)}function Wy(e,t){const n=Jf(e);n?.serverUrl!==t.serverUrl||n.token!==t.token||(e.removeItem(rv),e.removeItem(Kl))}function u5(){const e=window.__OPENPOND_WEB_CONNECTION__,t=e?.serverUrl?.trim(),n=e?.token?.trim();return t&&n?{serverUrl:t,token:n}:null}function m5(){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()||qI();return!a||!n?null:{serverUrl:a,token:n}}function p5(){window.location.hash&&window.history.replaceState(null,"",`${window.location.pathname}${window.location.search}`)}function Qc(e,t){t&&(e.some(n=>n.serverUrl===t.serverUrl&&n.token===t.token)||e.push(t))}function f5(){const e=[],t=Vd(window.sessionStorage),n=Vd(window.localStorage),a=qI(),o=t?.getItem(Kl)??n?.getItem(Kl);return Qc(e,null),Qc(e,a&&o?{serverUrl:a,token:o.trim()}:null),Qc(e,t?Jf(t):null),Qc(e,n?Jf(n):null),e}async function Hp(e){const t=new AbortController,n=window.setTimeout(()=>t.abort(),d5);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 h5(){if(window.openpond)return window.openpond.getConnection();const e=Vd(window.sessionStorage),t=Vd(window.localStorage),n=m5();if(n&&await Hp(n.serverUrl))return t&&Ni(t,n),e&&Ni(e,n),p5(),{...n,platform:navigator.platform};const a=u5();if(a&&await Hp(a.serverUrl))return t&&Ni(t,a),e&&Ni(e,a),{...a,platform:navigator.platform};const o=f5();for(const i of o){if(await Hp(i.serverUrl))return t&&Ni(t,i),e&&Ni(e,i),{...i,platform:navigator.platform};e&&Wy(e,i),t&&Wy(t,i)}throw new Error("No reachable OpenPond app server. Start `openpond ui` again and open the full printed URL.")}const Y={...c5,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=Gy(t),a=n.size?`?${n.toString()}`:"";return q(e,`/v1/usage${a}`)},usageRecords:(e,t={})=>{const n=Gy(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`),...e5,...l5,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({})}),...t5,resolveApproval:(e,t,n)=>q(e,`/v1/approvals/${t}`,{method:"POST",body:JSON.stringify(n)})};function Gy(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 g5=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),v5=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,a)=>a?a.toUpperCase():n.toLowerCase()),Zy=e=>{const t=v5(e);return t.charAt(0).toUpperCase()+t.slice(1)},BI=(...e)=>e.filter((t,n,a)=>!!t&&t.trim()!==""&&a.indexOf(t)===n).join(" ").trim(),b5=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var y5={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 S5=g.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:a,className:o="",children:i,iconNode:s,...l},m)=>g.createElement("svg",{ref:m,...y5,width:t,height:t,stroke:e,strokeWidth:a?Number(n)*24/Number(t):n,className:BI("lucide",o),...!i&&!b5(l)&&{"aria-hidden":"true"},...l},[...s.map(([d,h])=>g.createElement(d,h)),...Array.isArray(i)?i:[i]]));const dt=(e,t)=>{const n=g.forwardRef(({className:a,...o},i)=>g.createElement(S5,{ref:i,iconNode:t,className:BI(`lucide-${g5(Zy(e))}`,`lucide-${e}`,a),...o}));return n.displayName=Zy(e),n};const x5=[["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"}]],k5=dt("activity",x5);const w5=[["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"}]],I5=dt("archive-restore",w5);const _5=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],C5=dt("arrow-left",_5);const R5=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}]],FI=dt("bookmark",R5);const P5=[["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"}]],VI=dt("bookmark-x",P5);const A5=[["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"}]],Jy=dt("book-open-text",A5);const T5=[["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"}]],zp=dt("boxes",T5);const E5=[["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"}]],M5=dt("calendar-clock",E5);const j5=[["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"}]],KI=dt("chart-column-stacked",j5);const O5=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Ao=dt("check",O5);const $5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],Yf=dt("circle-check",$5);const N5=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Wo=dt("chevron-down",N5);const D5=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Yr=dt("chevron-right",D5);const L5=[["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"}]],U5=dt("circle-alert",L5);const H5=[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]],Hu=dt("cloud",H5);const z5=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],q5=dt("credit-card",z5);const B5=[["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"}]],F5=dt("download",B5);const V5=[["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"}]],qp=dt("external-link",V5);const K5=[["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"}]],W5=dt("file-output",K5);const G5=[["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"}]],iv=dt("file-text",G5);const Z5=[["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"}]],WI=dt("folder",Z5);const J5=[["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"}]],GI=dt("folder-git-2",J5);const Y5=[["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"}]],Q5=dt("git-branch",Y5);const X5=[["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"}]],e3=dt("github",X5);const t3=[["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"}]],ZI=dt("earth",t3);const n3=[["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"}]],a3=dt("circle-question-mark",n3);const o3=[["path",{d:"M2 5h20",key:"1fs1ex"}],["path",{d:"M6 12h12",key:"8npq4p"}],["path",{d:"M9 19h6",key:"456am0"}]],r3=dt("list-filter",o3);const i3=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],s3=dt("loader-circle",i3);const l3=[["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"}]],c3=dt("maximize-2",l3);const d3=[["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"}]],zu=dt("message-square",d3);const u3=[["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"}]],bc=dt("ellipsis",u3);const m3=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],JI=dt("panel-left",m3);const p3=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],Qf=dt("panel-right",p3);const f3=[["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"}]],sv=dt("pin",f3);const h3=[["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"}]],lv=dt("pin-off",h3);const g3=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],v3=dt("plus",g3);const b3=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],y3=dt("power",b3);const S3=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],x3=dt("search",S3);const k3=[["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"}]],YI=dt("settings",k3);const w3=[["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"}]],QI=dt("shapes",w3);const I3=[["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"}]],_3=dt("shield",I3);const C3=[["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"}]],qu=dt("square-pen",C3);const R3=[["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"}]],XI=dt("square-terminal",R3);const P3=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],Yy=dt("user-round",P3);const A3=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],yc=dt("x",A3);function T3({platform:e}){return!Bu()||cv(e)?null:x.jsxs("div",{className:"window-controls","aria-label":"Window controls",children:[x.jsx("button",{type:"button",className:"window-control minimize",title:"Minimize",onClick:()=>{Bp("minimize")},children:x.jsx(Wo,{size:14})}),x.jsx("button",{type:"button",className:"window-control maximize",title:"Maximize",onClick:()=>{Bp("toggleMaximize")},children:x.jsx(c3,{size:12})}),x.jsx("button",{type:"button",className:"window-control close",title:"Close",onClick:()=>{Bp("close")},children:x.jsx(yc,{size:13})})]})}function cv(e){const t=e?.toLowerCase()??"";return t==="darwin"||t.includes("mac")}function Bu(){if(typeof window>"u")return!1;const e=window.openpond;return!!(e?.minimizeWindow||e?.toggleMaximizeWindow||e?.closeWindow)}async function Bp(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 E3({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:v}){const[y,w]=g.useState(!1),[_,R]=g.useState(""),M=g.useRef(null),[C,N]=g.useState();g.useLayoutEffect(()=>{if(!y||!h)return;function P(){const T=M.current?.getBoundingClientRect();if(!T)return;const U=window.innerHeight-T.bottom-12,B=T.top-12,D=U<180&&B>U;N({position:"fixed",left:Math.max(12,T.left),width:Math.min(T.width,window.innerWidth-24),minWidth:0,maxWidth:"calc(100vw - 24px)",right:"auto",top:D?"auto":T.bottom+5,bottom:D?window.innerHeight-T.top+5:"auto",maxHeight:Math.max(80,Math.min(320,D?B-5:U-5)),overflowY:"auto",zIndex:1e3})}return P(),window.addEventListener("resize",P),window.addEventListener("scroll",P,!0),()=>{window.removeEventListener("resize",P),window.removeEventListener("scroll",P,!0)}},[y,h]);const $=t.find(P=>P.value===e)??t[0],j=_.trim().toLowerCase(),k=j?t.filter(P=>[P.label,P.shortLabel,P.description].some(T=>T?.toLowerCase().includes(j))):t;return g.useEffect(()=>{if(!y){R("");return}function P(U){M.current?.contains(U.target)||w(!1)}function T(U){U.key==="Escape"&&w(!1)}return document.addEventListener("pointerdown",P),document.addEventListener("keydown",T),()=>{document.removeEventListener("pointerdown",P),document.removeEventListener("keydown",T)}},[y]),x.jsxs("div",{className:`dropdown-select ${o??""} ${a?"compact":""} ${s==="top"?"open-up":""}`,"data-tooltip":m,ref:M,children:[x.jsxs("button",{type:"button",className:`dropdown-trigger ${y?"active":""}`,disabled:n,"aria-label":l,"aria-haspopup":"menu","aria-expanded":y,onClick:()=>w(P=>!P),children:[i,x.jsx("span",{children:$?.shortLabel??$?.label??e}),x.jsx(Wo,{size:14})]}),y&&x.jsxs("div",{className:"dropdown-menu",role:"menu",style:h?C:void 0,children:[d?x.jsxs("label",{className:"dropdown-search",onClick:P=>P.stopPropagation(),children:[x.jsxs("span",{className:"sr-only",children:["Search ",l]}),x.jsx("input",{autoFocus:!0,placeholder:`Search ${l.toLowerCase()}`,value:_,onChange:P=>R(P.target.value)})]}):null,k.map(P=>x.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":P.value===e,disabled:P.disabled,className:[P.value===e?"selected":"",P.separatorBefore?"separator-before":"",P.icon?"with-icon":""].filter(Boolean).join(" "),onClick:()=>{P.disabled||(v(P.value),R(""),w(!1))},children:[x.jsxs("span",{children:[P.icon==="plus"?x.jsx(v3,{size:13}):null,x.jsx("span",{children:P.label})]}),P.description&&x.jsx("small",{children:P.description})]},P.value)),k.length?null:x.jsx("div",{className:"dropdown-empty",children:"No matches"})]})]})}const M3=[{destination:"walkthroughs",icon:Jy,label:"Walkthroughs"},{destination:"external",icon:Jy,label:"Docs",url:"https://openpond.ai/docs"},{destination:"external",icon:iv,label:"Blog",url:"https://openpond.ai/blog"},{destination:"external",icon:q5,label:"Pricing",url:"https://openpond.ai/pricing"},{destination:"external",icon:ZI,label:"Web app",url:"https://openpond.ai/sandboxes"},{destination:"external",icon:e3,label:"GitHub",url:"https://github.com/openpond/openpond"},{destination:"external",icon:zu,label:"Submit issue",url:"https://github.com/openpond/openpond/issues/new/choose"}];function j3({onOpenWalkthroughs:e,walkthroughsActive:t}){const[n,a]=g.useState(!1),o=g.useRef(null);return g.useEffect(()=>{if(!n)return;function i(l){o.current?.contains(l.target)||a(!1)}function s(l){l.key==="Escape"&&a(!1)}return document.addEventListener("pointerdown",i),document.addEventListener("keydown",s),()=>{document.removeEventListener("pointerdown",i),document.removeEventListener("keydown",s)}},[n]),x.jsxs("div",{className:"sidebar-help-menu",ref:o,children:[x.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:x.jsx(a3,{size:17})}),n?x.jsx("div",{className:"sidebar-help-popover",role:"menu","aria-label":"Help",children:M3.map(i=>{const s=i.icon,l=x.jsxs(x.Fragment,{children:[x.jsx(s,{size:15}),x.jsx("span",{children:i.label})]});return i.destination==="walkthroughs"?x.jsx("button",{"aria-current":t?"page":void 0,className:"sidebar-help-item",onClick:()=>{a(!1),e()},role:"menuitem",type:"button",children:l},i.label):x.jsx("a",{className:"sidebar-help-item",href:i.url,onClick:m=>{m.preventDefault(),a(!1),O3(i.url)},rel:"noreferrer",role:"menuitem",target:"_blank",children:l},i.label)})}):null]})}async function O3(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-help",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const gQ=[{value:"chat",label:"Chat"},{value:"work",label:"Work"}],Fp=[{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 e_(e){return e==="chat"?"New chat":"New task"}const Xf=["get-started","models","tasks","tasksets","labeling","rewards","evaluations","runs","versions","serving"],$3={"get-started":"Get started",models:"Models",tasks:"Tasks",tasksets:"Tasksets",labeling:"Labeling",rewards:"Rewards",evaluations:"Runs",runs:"Runs",versions:"Versions",serving:"Serving"},N3={tasks:["drafts"],tasksets:["drafts","formats","batches"],rewards:["scorers","combined"],evaluations:["results","review","comparisons"],runs:["series","new"]},D3={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 po(e="models",t=null,n={}){return e==="evaluations"&&n.collection==="review"?po("labeling",t,{...n,collection:"default"}):{page:e,modelId:e==="get-started"?null:t,collection:e==="evaluations"?"results":"default",resourceId:null,detailTab:null,query:"",after:null,...n}}function dv(e){const t=e.pathname.split("/").filter(Boolean);if(t[0]!=="models")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]&&!Xf.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(!Xf.includes(i)||o==="models"||a&&i==="get-started")return null;let s=i==="evaluations"?"results":"default";if(N3[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)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&&!D3[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"].includes(R))||[...d.keys()].some(R=>d.getAll(R).length!==1))return null;const h=d.get("source");if(h!==null&&(i!=="labeling"&&(i!=="evaluations"||s!=="review")||!h.trim()||h.length>500))return null;const v=d.get("model");if(a&&v&&a!==v)return null;const y=a??v;if(i==="get-started"&&d.size!==0)return null;const w=d.get("q")??"",_=d.get("after");return y!==null&&(!y.trim()||y.length>500)||w.length>1e3||_!==null&&(!_.trim()||_.length>2e3)?null:po(i,y,{collection:s,resourceId:l,detailTab:m,query:w,after:_,...h!==null?{sourceId:h}:{}})}function Fu(e){const t=["/models"];if(e.modelId&&t.push(encodeURIComponent(e.modelId)),e.page==="evaluations"&&e.collection==="review")return Fu(po("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.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 L3(e,t){return po(e.page,t,{collection:e.collection==="new"||e.collection==="drafts"?"default":e.collection})}function vQ(e,t,n=null){return{...e,resourceId:t,detailTab:n,after:null}}const Kd=new Set,eh=new Set,U3=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"]),th={apps:"/apps",outputs:"/outputs",projects:"/projects",scheduled:"/workflows","get-started":"/get-started"};let nh=!1,ah="",bd=null,t_=null,Wl="",Ha=0,ul=null,Pl=!1,Vp=null,yd=!1;function uv(e){const t=dv(e);if(t)return{kind:"models",route:t};const n=e.pathname.split("/").filter(Boolean);if(n[0]==="models")return{kind:"models_unavailable",pathname:e.pathname,search:e.search??""};if(n[0]==="settings"&&n.length===2&&U3.has(n[1])){const o=mv(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(th).find(o=>th[o]===e.pathname);return a?{kind:"view",view:a}:null}function n_(e){if(e.kind==="models")return Fu(e.route);if(e.kind==="models_unavailable")return`${e.pathname}${e.search}`;if(e.kind==="settings"){const t=mv(e.returnTo??null);return`/settings/${e.section}${t?`?${new URLSearchParams({returnTo:t})}`:""}`}return e.kind==="chat"?e.sessionId?`/chat/${encodeURIComponent(e.sessionId)}`:"/chat/new":th[e.view]}function H3(e){const t=e?.kind==="settings"?mv(e.returnTo??null):null;if(t){const n=new URL(t,"https://local.openpond.invalid"),a=dv(n);if(a)return{kind:"models",route:a}}return{kind:"chat",sessionId:null}}function mv(e){if(!e||e.length>6e3||!e.startsWith("/models")||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=dv(t);return n?Fu(n):null}function Sc(){return`${window.location.pathname}${window.location.search}`}function pv(){if(typeof window>"u")return;const e=nh?Wl:Sc();e!==ah&&(ah=e,bd=uv(new URL(e,window.location.origin)),t_=bd?.kind==="models"?bd.route:null)}function a_(){ah="",pv();for(const e of eh)e()}async function fv(e){if(yd)return!1;yd=!0;try{for(const t of[...Kd].reverse())if(!await t(e))return!1;return!0}finally{yd=!1}}function hv(e){return{...window.history.state,openpondNavigationIndex:e}}async function z3(){const e=Sc(),t=typeof window.history.state?.openpondNavigationIndex=="number"?window.history.state.openpondNavigationIndex:Ha-1;if(ul&&t===Ha){const a=ul;ul=null,a();return}if(Vp===t||Kd.size===0){Vp=null,Wl=e,Ha=t,window.history.replaceState(hv(Ha),"",e),a_();return}if(t===Ha)return;if(Pl||yd){ul??=()=>{},window.history.go(Ha-t);return}Pl=!0;const n=t-Ha;try{await new Promise(a=>{ul=a,window.history.go(-n)}),await fv(e)&&(Vp=t,window.history.go(n))}finally{Pl=!1}}function gv(){if(nh||typeof window>"u")return;const e=uv(window.location);Wl=e?n_(e):Sc(),Ha=typeof window.history.state?.openpondNavigationIndex=="number"?window.history.state.openpondNavigationIndex:0,window.history.replaceState(hv(Ha),"",Wl),window.addEventListener("popstate",z3),nh=!0}function o_(e){return eh.add(e),gv(),()=>{eh.delete(e)}}function bQ(e){return Kd.add(e),gv(),()=>{Kd.delete(e)}}async function yQ(e){!Pl&&await fv(Sc())&&e()}function q3(){return g.useSyncExternalStore(o_,()=>(pv(),t_),()=>null)}function B3(){return g.useSyncExternalStore(o_,()=>(pv(),bd),()=>null)}async function en(e,t="push"){if(typeof window>"u"||(gv(),Pl))return!1;if(e.kind==="settings"&&!e.returnTo){const a=uv(window.location),o=a?.kind==="models"?Fu(a.route):a?.kind==="settings"?a.returnTo:void 0;o&&(e={...e,returnTo:o})}const n=n_(e);return Sc()===n?!0:await fv(n)?(t==="push"&&Ha++,window.history[t==="replace"?"replaceState":"pushState"](hv(Ha),"",n),Wl=n,a_(),!0):!1}function os(e,t="push"){return en({kind:"models",route:e},t)}function F3({experience:e="work",beginNewChat:t}){return x.jsx("div",{className:"sidebar-new-task",children:x.jsxs("button",{className:"nav-command nav-command-new-task",type:"button",onClick:()=>{en({kind:"chat",sessionId:null}),t(null)},children:[x.jsx(qu,{size:18}),x.jsx("span",{children:e_(e)})]})})}function V3({productArea:e="chat",setSectionMenuOpen:t,setSelectedAppId:n,setSelectedProjectId:a,setSelectedSessionId:o,setView:i,view:s,modelProjects:l=[],modelTrainingActivityByProjectId:m={}}){const d=q3(),h=d?.modelId??null,v=d?.page??"models";function y(){n(null),a(null),o(null),t(null)}async function w(C){await os(po(C,h))&&(y(),i("labs"))}async function _(C){await os(L3(d??po(),C||null))&&(y(),i("labs"))}async function R(C){await en({kind:"view",view:C})&&(y(),i(C))}const M=h?m[h]??null:null;return x.jsxs("nav",{className:"sidebar-nav","aria-label":"Primary",children:[e==="models"?x.jsxs(x.Fragment,{children:[x.jsxs("div",{className:"sidebar-model-project-picker",children:[x.jsx("span",{className:"sidebar-nav-group-label",children:"Model"}),x.jsx(E3,{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)}})]}),Xf.filter(C=>C!=="tasksets"&&C!=="evaluations").map(C=>{const N={"get-started":zp,models:k5,tasks:zp,tasksets:zp,labeling:Yf,rewards:_3,evaluations:Yf,runs:KI,versions:Q5,serving:Hu}[C];return x.jsxs("button",{className:`nav-command ${s==="labs"&&(v===C||C==="runs"&&v==="evaluations")?"active":""}`,"aria-current":s==="labs"&&(v===C||C==="runs"&&v==="evaluations")?"page":void 0,type:"button",onClick:()=>{w(C)},children:[x.jsx(N,{size:16}),x.jsx("span",{children:$3[C]}),C==="runs"&&M?x.jsx("span",{className:"sidebar-running-dot","aria-label":M.label}):null]},C)})]}):null,e==="chat"?x.jsxs(x.Fragment,{children:[x.jsxs("button",{className:`nav-command nav-command-prominent ${s==="scheduled"?"active":""}`,"aria-label":"Workflows",type:"button",onClick:()=>{R("scheduled")},children:[x.jsx(M5,{size:18}),x.jsx("span",{children:"Workflows"})]}),x.jsxs("button",{className:`nav-command nav-command-prominent ${s==="outputs"?"active":""}`,"aria-label":"Outputs",type:"button",onClick:()=>{R("outputs")},children:[x.jsx(W5,{size:18}),x.jsx("span",{children:"Outputs"})]}),x.jsxs("button",{className:`nav-command nav-command-prominent ${s==="apps"?"active":""}`,"aria-label":"Apps",type:"button",onClick:()=>{R("apps")},children:[x.jsx(QI,{size:18}),x.jsx("span",{children:"Apps"})]}),x.jsxs("button",{className:`nav-command nav-command-prominent ${s==="projects"?"active":""}`,"aria-label":"Projects",type:"button",onClick:()=>{R("projects")},children:[x.jsx(GI,{size:18}),x.jsx("span",{children:"Projects"})]})]}):null]})}function K3({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"),en({kind:"view",view:"get-started"})}return x.jsx("nav",{className:"sidebar-utility-nav","aria-label":"Resources",children:x.jsx(j3,{onOpenWalkthroughs:s,walkthroughsActive:i==="get-started"})})}const r_=rp({chatMode:b(["chat","work"]).optional(),notificationMode:b(["all","direct_mentions","none"]).optional(),learningNoticeDismissed:A().optional(),sidebarVisibility:rp({showCodexChats:A(),onlyRunningTasks:A()}).optional(),scheduledWorkView:b(["calendar","list"]).optional(),editorControlsVisible:A().optional(),voiceNoticeAcknowledged:A().optional(),lessonProgress:re(r().min(1).max(200),rp({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()}),oh={"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"},rh=new Set;let Al=null,Bo=null,qa={},Gl={},Kp=!1,Sd=0,rs=null,Qy=0;const W3="openpond-client-choices-changed";function vv(){rh.forEach(e=>e()),typeof window<"u"&&window.dispatchEvent(new Event(W3))}function G3(){return rs}function Z3(e){return rh.add(e),()=>{rh.delete(e)}}function xc(e){const t=g.useRef(e);t.current=e,g.useEffect(()=>Z3(()=>t.current()),[])}async function Xy(e){const t=++Qy,n=await q(e,"/v1/configuration");if(n.clientState?.revision===null){const o=J3();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!==Qy)return;const a=Al?.serverUrl!==e.serverUrl||Al?.token!==e.token||Bo?.owner!==n.clientState?.owner;a&&(Sd++,qa={},Gl={},rs=null),Al=e,(a||(n.clientState?.revision??0)>=(Bo?.revision??0))&&(Bo=n.clientState),vv()}async function bv(){if(Kp||!Al||!Bo||!Object.keys(qa).length)return;Kp=!0;const e=qa,t=Al,n=Bo.owner,a=Sd;qa={},Gl=e;try{const o=await q(t,"/v1/configuration",{method:"POST",body:JSON.stringify({action:"client-state",owner:n,patch:e})});a===Sd&&(Bo=o,rs=null)}catch(o){a===Sd&&(qa={...e,...qa},rs=`Preference changes have not been saved. ${o instanceof Error?o.message:String(o)}`)}finally{Gl={},Kp=!1,vv(),!rs&&Object.keys(qa).length&&bv()}}function SQ(){rs=null,bv()}const kc={getItem(e){const t=oh[e];if(!t)return null;const n={...Bo?.value,...Gl,...qa}[t];return n===void 0?null:typeof n=="string"?n:JSON.stringify(n)},setItem(e,t){if(!Bo)return;const n=oh[e];if(!n)throw new Error("Unregistered client preference.");let a;try{a=JSON.parse(t)}catch{a=t}const o=r_.parse({[n]:a});JSON.stringify({...Bo.value,...Gl,...qa}[n])!==JSON.stringify(o[n])&&(qa={...qa,...o},vv(),bv())}};function J3(){const e={},t=[];if(typeof window>"u")return{patch:e,keys:t};for(const[n,a]of Object.entries(oh))try{const o=window.localStorage.getItem(n);if(o===null)continue;let i;try{i=JSON.parse(o)}catch{i=o}const s=r_.safeParse({[a]:i});s.success&&(Object.assign(e,s.data),t.push(n))}catch{}return{patch:e,keys:t}}const xd=5,An=15,ih=10,Et={defaultChatProvider:Gr,subagents:fj(),codexPermissionMode:eg,codexReasoningEffort:tg,openPondCommandAccessMode:mu,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:""}}}},xQ={activeTemplateId:"default",customized:!1,soul:"",soulPath:null,updatedAt:null,templates:[]},i_=[{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"}],Wp=[{value:"openpond",label:"OpenPond Chat"},{value:"codex",label:"OpenAI Codex",description:"Codex login"}],Y3=["openai","xai","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],Q3=["openpond","codex",...Y3],s_=new Set(Q3),l_=[{value:Xh,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"}],kQ=[{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."}],sh=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"xhigh",label:"Extra High",shortLabel:"Extra High"}],X3=[{value:"off",label:"Off"},...sh,{value:"max",label:"Max"}],wQ=[{value:"ask",label:"Ask",description:"Ask before running shell commands."},{value:"full-access",label:"Full access",description:"Run shell commands without approval prompts."}],IQ=[{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 yv(e){return e.kind==="local"}function e6(e){return e.kind==="cloud"}function yt(e,t){return`${e}:${t}`}function c_(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 Br(e){return`${e.type}:${e.id}`}function Wd(e){const t=e.currentTarget.getBoundingClientRect();return e.clientY<t.top+t.height/2?"before":"after"}function Gd(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 e0(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function t6(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 Sv(e,t){return e?.statuses?.[t]??null}function d_(e,t){return e?.providers?.[t]??null}function xv(e,t){return e?.modelCaches?.[t]??null}function n6(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 a6(e){return e==="openpond"?i_:e==="codex"||e==="openai"?l_:[]}function o6(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 CQ(e){return s_.has(e)}function lh(e,t={}){if(!e)return t.localOnly,Wp;const n=t.includeUnavailable??!1,a=t.enabledOnly??!1,o=[];for(const i of qh){if(!s_.has(i)||t.localOnly&&i==="openpond")continue;const s=Sv(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:Wp}function Zl(e,t){const a=(xv(t,e)?.models??[]).filter(l=>e!=="openpond"||l.id!==ds).map(n6),o=d_(t,e),i=[...o?.modelOverrides??[],o?.defaultModel].filter(l=>!!l?.trim()&&(e!=="openpond"||l!==ds)).map(l=>({value:l,label:l})),s=e==="openpond"&&a.length>0?[]:a6(e);return o6([...a,...i,...s])}function u_(e,t,n){if(e!=="openpond")return sh;const a=xv(n,e)?.models.find(i=>i.id===t)?.capabilities;if(!a?.reasoningEfforts.length)return sh;const o=new Set(a.reasoningEfforts);return X3.filter(i=>o.has(i.value))}function r6(e,t,n){const a=u_(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 i6(e,t,n,a){return u_(e,t,a).some(o=>o.value===n)?n:r6(e,t,a)}function s6(e,t,n){if(e==="codex"||e==="openai")return!0;const a=t.trim();if(!a)return!1;const o=xv(n,e)?.models.find(i=>i.id===a);return o?!!o.capabilities.reasoning:Zl(e,n).some(i=>i.value===a&&/\breasoning\b/i.test(i.description??""))}function Zd(e,t){const n=d_(t,e)?.defaultModel?.trim();if(n)return n;const a=Sv(t,e)?.defaultModel?.trim();if(a)return a;const o=Zl(e,t)[0]?.value?.trim();return o||(e==="codex"?Xh:e==="openpond"?ds:"")}function Sr(e,t,n){const a=t?.trim();if(e==="codex"&&(a==="codex-default"||a==="gpt-5.5"))return Xh;const o=Zl(e,n);return a&&o.some(i=>i.value===a)||a&&e!=="codex"&&o.length===0&&!n?a:Zd(e,n)}function m_(e,t){const n=e.modelRef?.providerId??e.provider;return{provider:n,model:Sr(n,e.modelRef?.modelId,t)}}function kv(e,t,n){return Sr(e,t,n)||void 0}function La(e,t,n){const a=kv(e,t,n);return a?{providerId:e,modelId:a}:void 0}function t0(e){return e==="full-access"?{approvalPolicy:"never",sandbox:"danger-full-access"}:{approvalPolicy:"on-request",sandbox:"workspace-write"}}function fa(e){const t=e?.defaultChatProvider??Et.defaultChatProvider;return{defaultChatProvider:t,defaultChatModel:Sr(t,e?.defaultChatModel),subagents:Ol.parse(e?.subagents??Et.subagents),codexPermissionMode:e?.codexPermissionMode??Et.codexPermissionMode,codexReasoningEffort:e?.codexReasoningEffort??Et.codexReasoningEffort,openPondCommandAccessMode:e?.openPondCommandAccessMode??Et.openPondCommandAccessMode,defaultBranchPrefix:p_(e?.defaultBranchPrefix),defaultNewProjectDirectory:e?.defaultNewProjectDirectory??Et.defaultNewProjectDirectory,defaultTeamId:e?.defaultTeamId?.trim()||null,advancedWorkspaceControls:e?.advancedWorkspaceControls??Et.advancedWorkspaceControls,steerActiveResponses:e?.steerActiveResponses??Et.steerActiveResponses,contextCompaction:{autoEnabled:e?.contextCompaction?.autoEnabled??Et.contextCompaction.autoEnabled,triggerPercent:e?.contextCompaction?.triggerPercent??Et.contextCompaction.triggerPercent,summaryModel:e?.contextCompaction?.summaryModel??Et.contextCompaction.summaryModel},training:{defaultModelRef:e?.training?.defaultModelRef??Et.training.defaultModelRef,creationMode:e?.training?.creationMode??Et.training.creationMode,autoApproveEvidence:e?.training?.autoApproveEvidence??Et.training.autoApproveEvidence},sidebarWidth:e?.sidebarWidth??Et.sidebarWidth,diffPanelWidth:e?.diffPanelWidth??Et.diffPanelWidth,sidebarSectionsCollapsed:{pinned:e?.sidebarSectionsCollapsed?.pinned??Et.sidebarSectionsCollapsed.pinned,projects:e?.sidebarSectionsCollapsed?.projects??Et.sidebarSectionsCollapsed.projects,cloudProjects:e?.sidebarSectionsCollapsed?.cloudProjects??Et.sidebarSectionsCollapsed.cloudProjects,chats:e?.sidebarSectionsCollapsed?.chats??Et.sidebarSectionsCollapsed.chats,savedForLater:e?.sidebarSectionsCollapsed?.savedForLater??Et.sidebarSectionsCollapsed.savedForLater},editor:{languageServers:e?.editor?.languageServers??Et.editor.languageServers,diagnosticsWhileEditing:e?.editor?.diagnosticsWhileEditing??Et.editor.diagnosticsWhileEditing,checkOnSave:e?.editor?.checkOnSave??Et.editor.checkOnSave,languages:{typescript:{mode:e?.editor?.languages?.typescript?.mode??Et.editor.languages.typescript.mode,customCommand:e?.editor?.languages?.typescript?.customCommand??Et.editor.languages.typescript.customCommand},python:{mode:e?.editor?.languages?.python?.mode??Et.editor.languages.python.mode,customCommand:e?.editor?.languages?.python?.customCommand??Et.editor.languages.python.customCommand},rust:{mode:e?.editor?.languages?.rust?.mode??Et.editor.languages.rust.mode,customCommand:e?.editor?.languages?.rust?.customCommand??Et.editor.languages.rust.customCommand}}}}}function p_(e){const t=e?.trim()??Et.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 RQ(e,t){return e==="openpond"?"OpenPond Chat":Sv(t,e)?.displayName??(e==="codex"?"OpenAI Codex":e)}function PQ(e,t,n){if(n){const a=Zl(n,t).find(o=>o.value===e);if(a)return a.label}if(t)for(const a of qh){const o=Zl(a,t).find(i=>i.value===e);if(o)return o.label}return[...i_,...l_].find(a=>a.value===e)?.label??e}function l6(e,t){return t==="chat"?e.filter(n=>n.experience==="chat"):e.filter(n=>n.experience==="work"||n.experience==="development")}function c6(e){return e.experience==="chat"?"Chat":"Work"}const wv="taskDraft";function f_(e){if(e?.experience!=="work")return null;const t=e.metadata?.[wv];if(!t||typeof t!="object"||Array.isArray(t))return null;const n=t.prompt;return typeof n=="string"&&n.trim()?n:null}function Jl(e){return f_(e)!==null}function d6(e){return(e.split(/\r?\n/u).map(n=>n.trim()).find(Boolean)||"Task draft").slice(0,64)}function Gp(e,t,n=new Date().toISOString()){const a={version:1,prompt:t,savedAt:n};return{...e??{},[wv]:a}}function u6(e){const t={...e??{}};return delete t[wv],t}function Zi(e){const t=Xc(e.metadata?.trainingTasksetId)??Xc(e.metadata?.tasksetId);return t?{id:t,name:Xc(e.metadata?.trainingTasksetName)??Xc(e.metadata?.tasksetName)??m6(t)}:null}function m6(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 Xc(e){return typeof e=="string"&&e.trim()?e.trim():null}const p6="codex_history_";function Lt(e){return!!e?.startsWith(p6)}function h_(e){const t=[],n=new Set;for(const a of e)for(const o of[a.workspacePath,a.path]){const i=Vu(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 f6(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=g_(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"||!v_(e))return null;const o=Vu(e.cwd);if(!o)return null;for(const i of n)if(Iv(o,i.path))return i.projectId;return null}function n0(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=g_(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"||!v_(e))return null;const o=Vu(e.cwd);if(!o)return null;for(const i of n)if(Iv(o,i.path))return yt("local",i.projectId);return null}function g_(e,t){const n=Vu(e);if(!n)return null;for(const a of t)if(Iv(n,a.path))return a.projectId;return null}function v_(e){return e.workspaceKind==="local_project"||e.provider==="codex"||Lt(e.id)}function Vu(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 Iv(e,t){const n=a0(e),a=a0(t);return n===a||n.startsWith(`${a}/`)}function a0(e){return/^[A-Z]:\//.test(e)?e.toLowerCase():e}const o0=[{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"}],h6=[{value:"recent",label:"Recent first"},{value:"manual",label:"Manual order"}];function r0(e){const t=[];if(e.filter==="done")t.push(...e.doneSessions.filter(o=>!Zi(o)));else if(e.filter==="all")t.push(...e.activeSessions.filter(o=>!Zi(o)),...e.doneSessions.filter(o=>!Zi(o)));else if(e.filter==="tasksets")t.push(...e.activeSessions.filter(o=>i0(o,e.selectedTasksetId)),...e.doneSessions.filter(o=>i0(o,e.selectedTasksetId)));else for(const o of e.activeSessions)Zi(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=>kd(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)=>l0(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:l0(o,i)})}function kd(e,t){return t.showCodexChats===!1&&(e.provider==="codex"||Lt(e.id))?!1:!t.onlyRunningTasks||t.inProgressSessionIds.has(e.id)}function i0(e,t){const n=Zi(e);return!!(n&&(!t||n.id===t))}function g6(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 s0(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 l0(e,t,n=null){const a=Tl(e),o=Tl(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 Tl(e){return e.pinned&&!e.savedForLater&&!e.archived}const ed={showCodexChats:!0,onlyRunningTasks:!1},b_="openpond.sidebar-task-visibility.v1";function c0(e=y_()){try{const t=e?.getItem(b_);if(!t)return ed;const n=JSON.parse(t);return{showCodexChats:typeof n.showCodexChats=="boolean"?n.showCodexChats:ed.showCodexChats,onlyRunningTasks:typeof n.onlyRunningTasks=="boolean"?n.onlyRunningTasks:ed.onlyRunningTasks}}catch{return ed}}function d0(e,t=y_()){try{t?.setItem(b_,JSON.stringify(e))}catch{}}function y_(){return typeof window>"u"?null:kc}function S_(e){return`${e.kind}:${e.id}`}function Yl(e,t){return!!(e&&t&&e.kind===t.kind&&e.id===t.id)}function v6(e){return{kind:"session",id:e}}function b6(e){return{kind:"project",id:e}}function y6(e){return{kind:"draft",id:e}}function S6(e){return e.selectedSessionId?v6(e.selectedSessionId):e.selectedProjectId?b6(e.selectedProjectId):y6(e.selectedAppId?`app:${e.selectedAppId}`:"new-chat")}function x6(e){if(!e.previousScope||e.previousScope.kind!=="draft"||e.activeScope.kind!=="session")return[...e.tabs];if(Yl(e.previousScope,e.activeScope))return[...e.tabs];const t=e.now??Date.now();return e.tabs.map(n=>Yl(n.scope,e.previousScope)?{...n,scope:e.activeScope,updatedAt:t}:n)}function AQ(e,t){return e.filter(n=>Yl(n.scope,t))}function TQ(e,t){return!!(e&&Yl(e.scope,t))}function k6(e){const t={};for(const n of e){const a=S_(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=I6(o.status,n.status,n.commandStatus),t[a]=o}return t}function w6(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 I6(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 x_(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=C6(e),i=t?.linkedCloudSourceKnown===!1&&!!e.headCommit;return o?a.push(o):i?a.push("upload required"):e.diverged?(e.ahead>0&&a.push(pr("ahead",e.ahead)),e.behind>0&&a.push(pr("behind",e.behind)),a.push("diverged")):(e.ahead>0&&a.push(pr("ahead",e.ahead)),e.behind>0&&a.push(pr("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 k_(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),v=R6(n);return v?`${i} / ${v}`:h?`${i} / upload required`:`${i} / ${d||!m?"needs sync":"setup ready"}`}function _6(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(w_(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 C6(e){return e.linkedSourceHeadCommit?e.divergedFromLinkedSource?"diverged":e.aheadOfLinkedSource>0?pr("local ahead",e.aheadOfLinkedSource):e.behindLinkedSource>0?pr("cloud ahead",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"sync unknown":null:null}function R6(e){return e?.linkedSourceHeadCommit?e.dirty?"local dirty files not in cloud":e.divergedFromLinkedSource?"diverged from local":e.aheadOfLinkedSource>0?pr("cloud behind local",e.aheadOfLinkedSource):e.behindLinkedSource>0?pr("cloud ahead local",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"source check unavailable":"synced":null}function pr(e,t){return`${e} by ${w_(t)}`}function w_(e){return`${e} commit${e===1?"":"s"}`}function P6({size:e=14,className:t}){return x.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:[x.jsx("path",{d:"M12 13v8"}),x.jsx("path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242"}),x.jsx("path",{d:"m8 17 4-4 4 4"})]})}function I_({kind:e,linkedCloud:t=!1,open:n=!1,className:a,baseSize:o=15}){const i=e==="cloud"?"cloud":n?"folder-open":"folder";return x.jsx("span",{className:["project-kind-icon",e,t?"linked-cloud":"",a??""].filter(Boolean).join(" "),"aria-hidden":"true",children:x.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"?x.jsx(E6,{}):n?x.jsx(T6,{}):x.jsx(A6,{}),t&&e==="local"?x.jsx(M6,{}):null]})})}function A6(){return x.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 T6(){return x.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 E6(){return x.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 M6(){return x.jsxs("g",{className:"project-kind-icon-cloud-badge",children:[x.jsx("circle",{cx:"18",cy:"17",r:"5"}),x.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 ch=mR();function j6({title:e,pinned:t,savedForLater:n,archived:a,onRename:o,onTogglePin:i,onToggleSaveForLater:s,onDockRight:l,onArchive:m}){const d=g.useRef(null),h=g.useRef(null),[v,y]=g.useState(null),w=[...o?[{label:"Rename",Icon:qu,action:o}]:[],{label:t?"Unpin":"Pin",Icon:t?lv:sv,action:i},...s?[{label:n?"Return to active":"Save for later",Icon:n?VI:FI,action:s}]:[],...l?[{label:"Open in right panel",Icon:Qf,action:l}]:[],{label:a?"Reopen":"Mark done",Icon:a?I5:Ao,action:m}];function _(R=!1){y(null),R&&d.current?.focus()}return g.useEffect(()=>{if(!v)return;h.current?.querySelector("button")?.focus();const R=C=>{!h.current?.contains(C.target)&&!d.current?.contains(C.target)&&y(null)},M=()=>y(null);return document.addEventListener("pointerdown",R),window.addEventListener("resize",M),()=>{document.removeEventListener("pointerdown",R),window.removeEventListener("resize",M)}},[v]),x.jsxs(x.Fragment,{children:[x.jsx("div",{className:`sidebar-row-actions sidebar-task-menu-trigger${v?" is-open":""}`,children:x.jsx("button",{ref:d,type:"button",className:"sidebar-row-action","aria-label":`More actions for task ${e}`,"aria-haspopup":"menu","aria-expanded":!!v,draggable:!1,onDoubleClick:R=>R.stopPropagation(),onClick:R=>{if(R.stopPropagation(),v){_(!0);return}const M=R.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:x.jsx(bc,{size:16})})}),v&&ch.createPortal(x.jsx("div",{ref:h,role:"menu","aria-label":`Actions for ${e}`,className:"sidebar-task-menu",style:v,onClick:R=>R.stopPropagation(),onDoubleClick:R=>R.stopPropagation(),onBlur:R=>{R.currentTarget.contains(R.relatedTarget)||_()},onKeyDown:R=>{R.stopPropagation();const M=Array.from(R.currentTarget.querySelectorAll("button")),C=M.indexOf(document.activeElement);if(R.key==="Escape"&&(R.preventDefault(),_(!0)),["ArrowDown","ArrowUp","Home","End"].includes(R.key)){R.preventDefault();const N=R.key==="Home"?0:R.key==="End"?M.length-1:(C+(R.key==="ArrowDown"?1:-1)+M.length)%M.length;M[N]?.focus()}},children:w.map(({label:R,Icon:M,action:C},N)=>x.jsxs("button",{type:"button",role:"menuitem",className:N===w.length-1?"task-menu-done":void 0,onClick:()=>{_(!0),C()},children:[x.jsx(M,{size:15}),R]},R))}),document.body)]})}function O6({session:e,onSave:t,onClose:n}){const[a,o]=g.useState(e.title),i=g.useRef(null);g.useEffect(()=>{const m=i.current;m&&(m.focus(),m.select())},[]),g.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 x.jsx("div",{className:"git-dialog-backdrop rename-chat-backdrop",role:"presentation",onMouseDown:n,children:x.jsxs("section",{className:"git-dialog rename-chat-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"rename-chat-title",onMouseDown:m=>m.stopPropagation(),children:[x.jsx("h2",{id:"rename-chat-title",children:"Rename chat"}),x.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"}),x.jsxs("div",{className:"git-dialog-footer",children:[x.jsx("button",{type:"button",className:"git-dialog-secondary",onClick:n,children:"Cancel"}),x.jsx("button",{type:"button",className:"git-dialog-primary",autoFocus:!0,onClick:s,disabled:!a.trim(),children:"Save"})]})]})})}const $6=24;function N6({title:e}){const t=g.useRef(e),[n,a]=g.useState(e);return g.useEffect(()=>{const o=t.current;if(t.current=e,!e){a("");return}if(o||window.matchMedia("(prefers-reduced-motion: reduce)").matches){a(e);return}const i=Array.from(e);let s=0;a("");const l=window.setInterval(()=>{s+=1,a(i.slice(0,s).join("")),s>=i.length&&window.clearInterval(l)},$6);return()=>window.clearInterval(l)},[e]),x.jsx("span",{className:"sidebar-task-title-text","aria-label":e||"New task",children:n||"New task"})}const D6=2650,L6=304,U6=260,H6=new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric"}),z6=new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit"}),q6=new Intl.DateTimeFormat("en-US",{dateStyle:"medium",timeStyle:"short"});function B6(){return{animationDelay:`${-(Date.now()%D6)}ms`}}function F6(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 Zp({label:e,actions:t,actionsVisible:n=!1,className:a,titleAccessory:o,children:i,collapsed:s=!1,titleActive:l=!1,onTitleClick:m,onToggleCollapsed:d}){return x.jsxs("section",{className:["sidebar-section",a,n?"actions-visible":""].filter(Boolean).join(" "),children:[x.jsxs("div",{className:"section-header",children:[x.jsxs("div",{className:"section-title-row",children:[m?x.jsxs("div",{className:"section-title-combo",children:[x.jsx("button",{type:"button",className:`section-title-link${l?" active":""}`,onClick:m,children:x.jsx("span",{children:e})}),d&&x.jsx("button",{type:"button",className:"section-chevron-button","aria-label":`${s?"Expand":"Collapse"} ${e}`,"aria-expanded":!s,onClick:d,children:s?x.jsx(Yr,{size:13}):x.jsx(Wo,{size:13})})]}):d?x.jsxs("button",{type:"button",className:"section-title-button","aria-label":`${s?"Expand":"Collapse"} ${e}`,"aria-expanded":!s,onClick:d,children:[x.jsx("span",{children:e}),s?x.jsx(Yr,{size:13}):x.jsx(Wo,{size:13})]}):x.jsx("span",{children:e}),o]}),t&&x.jsx("div",{className:"section-actions",children:t})]}),!s&&x.jsx("div",{className:"sidebar-section-body",children:i})]})}function u0({children:e,expanded:t=!1,onClick:n}){return x.jsx("button",{type:"button",className:"sidebar-show-more",onClick:n,children:e??(t?"Show less":"Show more")})}function Jp({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:v,projectLabel:y,ariaDescribedBy:w,childSessionCount:_=0,childSessionsExpanded:R=!1,onSelect:M,onToggleChildSessions:C,onTogglePin:N,onToggleSaveForLater:$,onDockRight:j,onArchive:k,onDragStart:P,onDragEnd:T,onDragOver:U,onDrop:B,onRename:D}){const[W,se]=g.useState(!1),me=d?.status==="queued",Te=d?.tone==="active"&&!me,ke=(h?.activeCount??0)>0,V=_>0&&!!C,Re=o&&!V,be=ke||Te||!me&&(m??e.status==="active"),ce=ke&&h?h.label:Te&&d?K6(d):"Running",ye=["sidebar-task-row",Jl(e)?"is-draft":"",be?"has-running-dot":""].filter(Boolean).join(" "),ne=g.useMemo(B6,[]),ge=x.jsx(j6,{title:e.title,pinned:!!e.pinned,savedForLater:!!e.savedForLater,archived:a,onRename:D?()=>se(!0):void 0,onTogglePin:N,onToggleSaveForLater:$,onDockRight:j,onArchive:k}),xe=x.jsxs(_v,{selected:t,dataSessionId:e.id,dragging:s,iconless:Re,nested:i,placeholder:l,className:ye||void 0,ariaExpanded:V?R:void 0,ariaDescribedBy:w,onSelect:M,onDragStart:P,onDragEnd:T,onDragOver:U,onDrop:B,onDoubleClick:D?()=>se(!0):void 0,children:[Re?null:V?x.jsx("button",{type:"button",className:"sidebar-child-toggle","data-tooltip":R?"Hide subagent conversations":"Show subagent conversations","aria-label":`${R?"Hide":"Show"} ${_} subagent ${_===1?"conversation":"conversations"}`,"aria-expanded":R,onClick:we=>{we.stopPropagation(),C?.()},children:R?x.jsx(Wo,{size:13}):x.jsx(Yr,{size:13})}):n??x.jsx(zu,{size:15}),x.jsx("span",{className:"row-label-shell",title:y||void 0,children:x.jsx("span",{className:"sidebar-session-title-line",children:x.jsx("span",{className:"row-label sidebar-task-title","data-overflowing":"false",onPointerEnter:F6,children:x.jsx(N6,{title:e.title})})})}),x.jsxs("div",{className:"row-meta",children:[x.jsxs("span",{className:"row-meta-status",children:[v?x.jsx(__,{indicator:v}):null,be?x.jsx("span",{className:`sidebar-running-dot${ke?" subagent":Te?" goal":""}`,style:ne,"aria-label":ce}):null]}),ge]})]}),De=W&&D?x.jsx(O6,{session:e,onSave:we=>D(e,we),onClose:()=>se(!1)}):null;return x.jsxs(x.Fragment,{children:[xe,De]})}function V6({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,v=`${e.workspaceName} · ${e.path}`;return x.jsxs(_v,{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?x.jsx(iv,{size:15}):x.jsx(U5,{size:15}),x.jsx("span",{className:"row-label-shell",title:v,children:x.jsx("span",{className:"row-label",children:h})}),x.jsx("div",{className:"row-meta",children:x.jsxs("div",{className:"sidebar-row-actions",children:[x.jsx(Jd,{label:e.status==="pinned"?"Unpin file":"Pin file",onClick:o,children:e.status==="pinned"?x.jsx(lv,{size:13}):x.jsx(sv,{size:13})}),x.jsx(Jd,{label:e.status==="saved_for_later"?"Remove from Save for later":"Save file for later",onClick:i,children:e.status==="saved_for_later"?x.jsx(VI,{size:13}):x.jsx(FI,{size:13})})]})})]})}function K6(e){return e.actionLabel}function W6({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:v,onNewChat:y,onMoveToCloud:w,onWorkspaceTargetSelect:_,onTogglePin:R,onRemove:M,onDragStart:C,onDragEnd:N,onDragOver:$,onDrop:j}){const[k,P]=g.useState(!1),T=g.useRef(null),[U,B]=g.useState({}),D=!!w||!!M,W=e==="local"&&l!==!1&&!!t.linkedSandboxProject?.projectId,se=g.useCallback(()=>{if(typeof window>"u")return;const ke=T.current?.getBoundingClientRect();if(!ke)return;const V=Math.max(12,window.innerWidth-L6-12),Re=Math.max(12,window.innerHeight-U6),be=Math.max(12,Math.min(ke.right+10,V)),ce=Math.max(12,Math.min(ke.top-4,Re)),ye={"--sidebar-project-locations-left":`${Math.round(be)}px`,"--sidebar-project-locations-top":`${Math.round(ce)}px`};B(ne=>ne["--sidebar-project-locations-left"]===ye["--sidebar-project-locations-left"]&&ne["--sidebar-project-locations-top"]===ye["--sidebar-project-locations-top"]?ne:ye)},[]),me=g.useCallback(()=>{se(),v()},[v,se]);function Te(){P(!1)}return x.jsxs("div",{ref:T,className:["sidebar-project-row-shell",k?"project-menu-open":""].filter(Boolean).join(" "),onFocusCapture:se,onPointerEnter:se,children:[x.jsxs(_v,{selected:a,placeholder:d,className:["sidebar-project-row",k?"project-menu-open":""].filter(Boolean).join(" "),ariaExpanded:i?o:void 0,onSelect:me,onDragStart:C,onDragEnd:N,onDragOver:$,onDrop:j,children:[x.jsx(I_,{kind:e,linkedCloud:W,open:e==="local"&&o,className:"sidebar-row-icon",baseSize:15}),x.jsx("span",{className:"row-label-shell",children:x.jsxs("span",{className:"sidebar-project-title-line",children:[x.jsx("span",{className:"row-label",children:t.name}),x.jsx(G6,{value:t.updatedAt}),i?x.jsx("span",{className:"sidebar-project-caret","aria-hidden":"true",children:o?x.jsx(Wo,{size:13}):x.jsx(Yr,{size:13})}):null]})}),x.jsxs("div",{className:"row-meta",children:[x.jsx("span",{className:"row-meta-status",children:h?x.jsx(__,{indicator:h}):null}),x.jsxs("div",{className:"sidebar-row-actions",children:[x.jsx(Jd,{label:n?"Unpin project":"Pin project",onClick:R,children:n?x.jsx(lv,{size:13}):x.jsx(sv,{size:13})}),D&&x.jsx(lV,{open:k,onToggleOpen:()=>P(ke=>!ke)}),x.jsx(Jd,{label:"New task",onClick:y,children:x.jsx(qu,{size:13})})]})]})]}),x.jsx(J6,{kind:e,project:t,workspaceState:s,cloudLinkTrusted:l,cloudLinkWarning:m,onWorkspaceTargetSelect:_,style:U}),k&&x.jsx(cV,{onClose:Te,onMoveToCloud:w?()=>{Te(),w()}:void 0,onRemove:()=>{Te(),M()}})]})}function G6({value:e}){const t=Z6(e);if(!t||!e)return null;const n=new Date(e);return x.jsx("time",{className:"sidebar-row-updated-at",dateTime:e,title:`Last updated ${q6.format(n)}`,children:t})}function Z6(e,t=new Date){if(!e)return null;const n=new Date(e);if(Number.isNaN(n.getTime()))return null;const a=z6.format(n);return n.getFullYear()===t.getFullYear()&&n.getMonth()===t.getMonth()&&n.getDate()===t.getDate()?a:`${H6.format(n)} ${a}`}function __({indicator:e}){return x.jsx("span",{className:`sidebar-terminal-indicator ${e.status}`,"data-tooltip":e.label,"aria-label":e.label,title:e.label,children:x.jsx(XI,{size:13})})}function J6({kind:e,project:t,workspaceState:n,cloudLinkTrusted:a,cloudLinkWarning:o,onWorkspaceTargetSelect:i,style:s}){const l=X6(e,t,n,a,o);return x.jsxs("aside",{className:"sidebar-project-locations-popover","aria-label":`${t.name} status`,style:s,children:[x.jsx("div",{className:"sidebar-project-locations-title",children:t.name}),x.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=x.jsxs(x.Fragment,{children:[x.jsx("span",{className:["sidebar-project-location-icon",m.key].filter(Boolean).join(" "),"aria-hidden":"true",children:m.icon}),x.jsx("span",{className:"sidebar-project-location-copy",children:x.jsx(Y6,{value:m.value})})]});return m.actionTarget?x.jsx("button",{type:"button",className:d,"data-workspace-target":m.actionTarget,disabled:m.disabled||!i,title:m.disabledReason??void 0,onClick:v=>{v.stopPropagation(),!m.disabled&&i?.(m.actionTarget)},children:h},m.key):x.jsx("div",{className:d,children:h},m.key)})})]})}function Y6({value:e}){const t=Q6(e);return x.jsxs("span",{className:"sidebar-project-location-value","aria-label":e,children:[t.branch?x.jsxs(x.Fragment,{children:[x.jsx("span",{className:"sidebar-project-location-branch",children:t.branch}),x.jsx("span",{className:"sidebar-project-location-separator","aria-hidden":"true",children:"/"})]}):null,x.jsx("span",{className:"sidebar-project-location-status",children:t.status})]})}function Q6(e){const n=e.indexOf(" / ");return n===-1?{branch:null,status:e}:{branch:e.slice(0,n),status:e.slice(n+3)}}function X6(e,t,n,a=!0,o=null){return e==="cloud"?tV(t):eV(t,n,a,o)}function eV(e,t,n=!0,a=null){const o=nV(e,t,n),i=aV(t),s=rV(e,n),l=n===!1&&a;return[{key:"local",value:o,tone:i?"attention":"local",icon:e.source==="git"?x.jsx(GI,{size:13}):x.jsx(WI,{size:13}),actionTarget:"local"},{key:"cloud",value:l||(s?iV(e,t,n):"not in cloud"),tone:l?"attention":"cloud",icon:x.jsx(Hu,{size:13}),actionTarget:s?"cloud":"upload_cloud"}]}function tV(e){return[{key:"cloud",value:sV(e),tone:e.syncedAt?"cloud":"attention",icon:x.jsx(Hu,{size:13}),actionTarget:"cloud"}]}function nV(e,t,n){const a=oV(e,t);return t?t.error?`${a} / status unavailable`:t.initialized?x_(t,{branch:e.linkedSandboxProject?.defaultBranch??null,linkedCloudSourceKnown:e.linkedSandboxProject?.projectId&&n?!!e.linkedSandboxProject.lastUploadedCommit||!t.headCommit:!0}):`${a} / not checked out`:`${a} / available`}function aV(e){return!!(e?.dirty||(e?.changedFilesCount??0)>0||(e?.untrackedFilesCount??0)>0)}function oV(e,t){return t?.currentBranch??t?.defaultBranch??e.linkedSandboxProject?.defaultBranch??"local"}function rV(e,t=!0){return!!(t&&e.linkedSandboxProject?.projectId||e.linkedOpenPondApp?.appId)}function iV(e,t,n){return k_(e,null,t,{cloudLinkTrusted:n})}function sV(e){const t=e.defaultBranch??"main",n=e.syncedAt?"setup ready":"needs setup";return`${t} / ${n}`}function lV({open:e,onToggleOpen:t}){return x.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:x.jsx(bc,{size:13})})}function cV({onClose:e,onMoveToCloud:t,onRemove:n}){return x.jsxs(x.Fragment,{children:[x.jsx("button",{type:"button",className:"sidebar-project-menu-backdrop","aria-label":"Close project actions",onClick:a=>{a.stopPropagation(),e()}}),x.jsxs("div",{className:"section-menu-popover sidebar-project-row-popover",role:"menu",children:[t&&x.jsxs("button",{type:"button",role:"menuitem",onClick:a=>{a.stopPropagation(),t()},children:[x.jsx(P6,{size:13}),x.jsx("span",{children:"Move to Cloud"})]}),x.jsxs("button",{type:"button",role:"menuitem",onClick:a=>{a.stopPropagation(),n()},children:[x.jsx(yc,{size:13}),x.jsx("span",{children:"Remove from Projects"})]})]})]})}function _v({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:v,onDragEnd:y,onDragOver:w,onDrop:_,onDoubleClick:R}){const M=!!v;return x.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:R,onKeyDown:C=>{C.target===C.currentTarget&&(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),h())},onDragStart:v,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 Jd({children:e,label:t,onClick:n}){return x.jsx("button",{type:"button",className:"sidebar-row-action","data-tooltip":t,"aria-label":t,onClick:a=>{a.stopPropagation(),n()},children:e})}function dV({filter:e,groupByProject:t,noun:n,onFilterChange:a,onGroupByProjectChange:o,onOnlyRunningTasksChange:i,onShowCodexChatsChange:s,onTasksetChange:l,onSortChange:m,onlyRunningTasks:d,openMenu:h,setOpenMenu:v,showCodexChats:y,sort:w,selectedTasksetId:_,tasksets:R}){const M=g.useRef(null),[C,N]=g.useState(!1),j=R.find(T=>T.id===_)?.name??o0.find(T=>T.value===e)?.label??"Active",k=h==="tasks-filter",P=h==="chats";return g.useEffect(()=>{if(!k&&!P)return;function T(U){M.current?.contains(U.target)||v(null)}return document.addEventListener("pointerdown",T),()=>document.removeEventListener("pointerdown",T)},[k,v,P]),x.jsxs("div",{className:"sidebar-task-list-controls",ref:M,children:[x.jsxs("div",{className:"section-menu",children:[x.jsx("button",{type:"button",className:`section-icon ${P?"active":""}`,"aria-label":`${n==="tasks"?"Task":"Chat"} list options`,"aria-haspopup":"menu","aria-expanded":P,onClick:()=>v(T=>T==="chats"?null:"chats"),children:x.jsx(bc,{size:14})}),P?x.jsxs("div",{className:"section-menu-popover",role:"menu","aria-label":`${n==="tasks"?"Task":"Chat"} list options`,children:[x.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":y,onClick:()=>s(!y),children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:y?x.jsx(Ao,{size:13}):null}),x.jsx("span",{children:"Show Codex chats, including pinned"})]}),x.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":d,onClick:()=>i(!d),children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:d?x.jsx(Ao,{size:13}):null}),x.jsxs("span",{children:["Only running ",n,", including pinned"]})]}),n==="tasks"?x.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":t,onClick:()=>o(!t),children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:t?x.jsx(Ao,{size:13}):null}),x.jsx("span",{children:"Group by project"})]}):null,h6.map(T=>x.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":w===T.value,onClick:()=>{m(T.value),v(null)},children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:w===T.value?x.jsx(Ao,{size:13}):null}),x.jsx("span",{children:T.label})]},T.value))]}):null]}),x.jsxs("div",{className:"section-menu",children:[x.jsx("button",{type:"button",className:`section-icon ${k?"active":""}`,"aria-label":`Filter ${n}: ${j}`,"aria-haspopup":"menu","aria-expanded":k,onClick:()=>v(T=>T==="tasks-filter"?null:"tasks-filter"),children:x.jsx(r3,{size:14})}),k?x.jsx("div",{className:"section-menu-popover",role:"menu","aria-label":`Filter ${n}`,children:o0.map(T=>x.jsxs(g.Fragment,{children:[T.value==="tasksets"?x.jsxs("button",{type:"button",role:"menuitem","aria-expanded":C,onClick:()=>N(U=>!U),children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:C?x.jsx(Wo,{size:13}):x.jsx(Yr,{size:13})}),x.jsx("span",{children:T.label})]}):x.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":e===T.value,onClick:()=>{a(T.value),v(null)},children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e===T.value?x.jsx(Ao,{size:13}):null}),x.jsx("span",{children:T.label})]}),T.value==="tasksets"&&C?x.jsxs(x.Fragment,{children:[x.jsxs("button",{className:"section-menu-taskset-option",type:"button",role:"menuitemradio","aria-checked":e==="tasksets"&&!_,onClick:()=>{l(null),v(null)},children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&!_?x.jsx(Ao,{size:13}):null}),x.jsx("span",{children:"All Tasksets"})]}),R.map(U=>x.jsxs("button",{className:"section-menu-taskset-option",type:"button",role:"menuitemradio","aria-checked":e==="tasksets"&&_===U.id,onClick:()=>{l(U.id),v(null)},children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&_===U.id?x.jsx(Ao,{size:13}):null}),x.jsx("span",{children:U.name}),x.jsx("span",{className:"section-menu-option-count","aria-hidden":"true",children:U.chatCount})]},U.id))]}):null]},T.value))}):null]})]})}function uV({onAddProject:e,onViewProjects:t}){const[n,a]=g.useState(!1),o=g.useRef(null),i=g.useRef(null);return g.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]),x.jsxs(x.Fragment,{children:[x.jsxs("div",{className:"section-menu",ref:o,onKeyDown:s=>{s.key==="Escape"&&(s.stopPropagation(),a(!1),i.current?.focus())},children:[x.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:x.jsx(bc,{size:14})}),n?x.jsxs("div",{className:"section-menu-popover",role:"menu","aria-label":"Project options",children:[x.jsx("button",{type:"button",role:"menuitem",onClick:()=>{a(!1),t()},children:"View all projects"}),x.jsx("button",{type:"button",role:"menuitem",onClick:()=>{a(!1),e()},children:"Add project"})]}):null]}),x.jsx("button",{type:"button",className:"section-icon",onClick:e,"aria-label":"Add project",title:"Add project",children:"+"})]})}const mV=240,pV=36;function fV(e,t,n=!1){const a=Math.max(12,t.width-mV-12),o=Math.max(12,t.height-pV-(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 hV({detail:e,onClose:t}){if(g.useEffect(()=>{if(!e||typeof window>"u")return;const o=l=>{l.key==="Escape"&&t()};let i=!1;const s=window.requestAnimationFrame(()=>{window.addEventListener("scroll",t,!0),i=!0});return window.addEventListener("keydown",o),()=>{window.cancelAnimationFrame(s),window.removeEventListener("keydown",o),i&&window.removeEventListener("scroll",t,!0)}},[e,t]),!e)return null;const n=new Date(e.updatedAt),a=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(n);return x.jsxs("aside",{id:e.descriptionId,className:"sidebar-task-detail-popover",style:e.style,role:"tooltip","aria-label":`Last updated for ${e.title}`,children:[x.jsx("time",{dateTime:e.updatedAt,children:a}),e.folderName?x.jsxs("div",{className:"sidebar-task-detail-folder",children:[x.jsx(WI,{size:13,"aria-hidden":"true"}),x.jsx("span",{children:e.folderName})]}):null]})}function gV({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,"-")}`,v=a==="draft"?iv:zu,[y,w]=g.useState(!1),_=!!(s||l||m);return x.jsxs("section",{className:"sidebar-task-project-group",children:[x.jsxs("div",{className:`sidebar-task-project-group-header-shell${y?" menu-open":""}`,children:[x.jsxs("button",{type:"button",className:"sidebar-task-project-group-header","aria-controls":h,"aria-expanded":t,onClick:()=>{w(!1),i()},children:[d?x.jsx(I_,{kind:d.kind,linkedCloud:!!(d.kind==="local"&&d.project.linkedSandboxProject?.projectId),open:d.kind==="local"&&t,className:"sidebar-task-project-group-icon",baseSize:14}):x.jsx(v,{className:"sidebar-task-project-group-icon",size:14,"aria-hidden":"true"}),x.jsx("span",{className:"sidebar-task-project-group-name",children:o}),x.jsx("span",{className:"sidebar-task-project-group-caret","aria-hidden":"true",children:t?x.jsx(Wo,{size:13}):x.jsx(Yr,{size:13})})]}),d&&_?x.jsxs("div",{className:"sidebar-task-project-group-actions",children:[l||m?x.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(R=>!R),children:x.jsx(bc,{size:13})}):null,s?x.jsx("button",{type:"button",className:"sidebar-row-action","data-tooltip":"New task","aria-label":"New task",onClick:s,children:x.jsx(qu,{size:13})}):null]}):null,y?x.jsxs(x.Fragment,{children:[x.jsx("button",{type:"button",className:"sidebar-task-project-group-menu-backdrop","aria-label":"Close project actions",onClick:()=>w(!1)}),x.jsxs("div",{className:"section-menu-popover sidebar-task-project-group-menu",role:"menu",children:[l?x.jsx("button",{type:"button",role:"menuitem",onClick:()=>{w(!1),l()},children:x.jsx("span",{children:"Open project"})}):null,m?x.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{w(!1),m()},children:[x.jsx(yc,{size:13}),x.jsx("span",{children:"Remove from Projects"})]}):null]})]}):null]}),t?x.jsx("div",{id:h,className:"sidebar-task-project-group-content",children:e}):null]})}const vV={},bV=new Map,yV=new Map;function SV(e,t){return Math.min(Math.max(e,An)+ih,t)}function xV(e,t){const n=Math.max(An,Math.min(e,t));if(n<=An)return An;const a=Math.ceil((n-An)/ih);return Math.max(An,An+(a-1)*ih)}function kV(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 wV({activeSessions:e,archiveSession:t,archivedSessions:n,chatRowsVisibleCount:a,childSessionRowsByParentId:o={},cloudProjectRows:i,beginProjectChat:s,onAddProject:l,commitTaskDrop:m,commitTaskPreviewDrop:d,dockSessionRight:h,experience:v="work",goalRuntimeBySessionId:y=bV,localProjectRows:w,openSidebarFile:_,pinnedCollapsed:R,pinnedRows:M,previewTaskDrop:C,previewPinnedDrop:N,projectRows:$,renameSession:j,restoreSession:k,runningSessionIds:P,sectionMenuOpen:T,selectedProjectId:U,selectedSessionId:B,setChatRowsVisibleCount:D,setSectionMenuOpen:W,setSelectedAppId:se,setSelectedProjectId:me,setSelectedSessionId:Te,setView:ke,sidebarProjectIdBySessionId:V,startTaskDrag:Re,startPinnedDrag:be,subagentRuntimeBySessionId:ce=yV,taskDragSessionId:ye,taskPreviewSessionIds:ne,terminalSummaries:ge=vV,toggleSessionPinned:xe,toggleSessionSavedForLater:De,view:we,clearTaskDrag:ae,removeProject:Se,toggleProjectPinned:ze,onTogglePinnedCollapsed:Qe,setSidebarFileStatus:We,commitPinnedDrop:nt,commitPinnedPreviewDrop:qe,clearSidebarDrag:Ze,dragItem:He}){const[L,O]=g.useState("active"),[z,X]=g.useState("recent"),[fe,Me]=g.useState(!0);g.useEffect(()=>{v!=="chat"&&Me(!0)},[v]);const[Le,et]=g.useState({work:!1,chat:!0}),[Xe,st]=g.useState({work:!1,chat:!1}),mt=v==="chat"?"chat":"work",Oe=Le[mt],[Ge,f]=g.useState(c0);xc(()=>f(c0()));const{onlyRunningTasks:H,showCodexChats:Z}=Ge,[le,ee]=g.useState(null),[F,I]=g.useState(()=>new Set),[G,ie]=g.useState(()=>new Map),[te,oe]=g.useState(null);g.useEffect(()=>{U&&et(K=>K[mt]?{...K,[mt]:!1}:K)},[mt,U]);const ue=v==="chat"?"chats":"tasks",pe=$??[...w,...i],Ie=g.useMemo(()=>new Map(pe.map(K=>[K.id,K.project.name])),[pe]),je=g.useMemo(()=>new Map(pe.map(K=>[K.id,K])),[pe]),Ne=g.useMemo(()=>{const K=new Set(P);for(const Ue of e){const _e=y.get(Ue.id),Be=ce.get(Ue.id);(_e?.tone==="active"&&_e.status!=="queued"||(Be?.activeCount??0)>0||ut(Ue.id)?.status==="running")&&K.add(Ue.id)}return K},[e,y,P,ce,ge]),$e=g.useMemo(()=>r0({activeSessions:e,doneSessions:n,filter:"all",inProgressSessionIds:Ne,sort:"manual"}),[e,n,Ne]),at=g.useMemo(()=>r0({activeSessions:e,doneSessions:n,filter:L,inProgressSessionIds:Ne,onlyRunningTasks:H,selectedTasksetId:le,previewSessionIds:ne,showCodexChats:Z,sort:z}),[e,n,Ne,H,le,Z,L,ne,z]),pt=g.useMemo(()=>{const K=new Map;for(const Ue of[...e,...n]){if(!kd(Ue,{inProgressSessionIds:Ne,onlyRunningTasks:H,showCodexChats:Z}))continue;const _e=Zi(Ue);if(!_e)continue;const Be=K.get(_e.id);Be?Be.chatCount+=1:K.set(_e.id,{..._e,chatCount:1})}return[...K.values()].sort((Ue,_e)=>Ue.name.localeCompare(_e.name))},[e,n,Ne,H,Z]),sn=g.useMemo(()=>M.filter(K=>K.type!=="session"||kd(K.session,{inProgressSessionIds:Ne,onlyRunningTasks:H,showCodexChats:Z})),[Ne,H,M,Z]),At=g.useMemo(()=>at.filter(K=>!Tl(K)),[at]),nn=g.useMemo(()=>At.slice(0,Math.max(An,a)),[a,At]),un=g.useMemo(()=>{const K=kV(nn,Ue=>{if(Jl(Ue))return{key:"draft",label:"Drafts",projectId:null,project:null,kind:"draft"};const _e=V[Ue.id],Be=lt(Ue)??"Work";return{key:_e?`project:${_e}`:`projectless:${Be}`,label:Be,projectId:_e??null,project:_e?je.get(_e)??null:null,kind:_e?"project":"projectless"}});for(const Ue of pe)K.some(_e=>_e.projectId===Ue.id)||K.push({key:`project:${Ue.id}`,label:Ue.project.name,projectId:Ue.id,project:Ue,kind:"project",sessions:[]});return K},[pe,Ie,je,V,nn]),mn=nn.length<At.length,qt=nn.length>An,_a=g.useMemo(()=>new Set(un.filter(K=>K.sessions.some(Ue=>Ue.id===B||Ne.has(Ue.id))).map(K=>K.key)),[un,Ne,B]),Cn=$e.filter(K=>!Tl(K)).map(K=>K.id),Tt=nn.map(K=>K.id),Wt=JSON.stringify(Object.entries(o).filter(([K,Ue])=>Ue.length>0&&(ce.get(K)?.activeCount??0)>0).flatMap(([K,Ue])=>Ue.map(_e=>[K,_e.id])).sort(([K,Ue],[_e,Be])=>K.localeCompare(_e)||Ue.localeCompare(Be)));g.useEffect(()=>{const K=JSON.parse(Wt);if(K.length===0)return;const Ue=new Set(K.map(([_e])=>_e));I(_e=>[...Ue].every(Be=>_e.has(Be))?_e:new Set([..._e,...Ue]))},[Wt]);function ut(K){return w6(ge[S_({kind:"session",id:K})])}function lt(K){if(Jl(K))return"Draft";const Ue=V[K.id];return Ue?Ie.get(Ue)??K.workspaceName??"Project":c6(K)}function Fn(K){en({kind:"chat",sessionId:K.id}),Te(K.id);const Ue=V[K.id]??null;se(Ue?null:K.appId),me(Ue),ke("chat")}function Gt(K){return(o[K.id]??[]).filter(Ue=>kd(Ue,{inProgressSessionIds:Ne,onlyRunningTasks:H,showCodexChats:Z}))}function Ca(K,Ue){return F.has(K.id)||Ue.some(_e=>_e.id===B)}function Ra(K){I(Ue=>{const _e=new Set(Ue);return _e.has(K)?_e.delete(K):_e.add(K),_e})}function Qt(K){const Ue=Gt(K);return Ue.length===0||!Ca(K,Ue)?null:x.jsx("div",{className:"sidebar-child-session-group",children:Ue.map(_e=>x.jsx(Jp,{session:_e,selected:we==="chat"&&B===_e.id,hideIcon:!0,nested:!0,running:Ne.has(_e.id),goalRuntime:y.get(_e.id)??null,subagentRuntime:ce.get(_e.id)??null,terminalIndicator:ut(_e.id),projectLabel:lt(K),onSelect:()=>Fn(_e),onTogglePin:()=>xe(_e),onToggleSaveForLater:()=>De(_e),onDockRight:()=>h(_e),onArchive:()=>_e.archived?k(_e):t(_e),onRename:j},_e.id))})}function pn(K,Ue){if(typeof window>"u")return;const _e=Tl(K)?lt(K):null;oe({descriptionId:`sidebar-task-detail-${K.id}`,sessionId:K.id,title:K.title,updatedAt:K.updatedAt,folderName:_e,style:fV(Ue.getBoundingClientRect(),{width:window.innerWidth,height:window.innerHeight},!!_e)})}function rt(K,Ue={}){const _e=K.archived,Be=ye===K.id,vt=Gt(K),kn="sidebar-session-group",Xt=z==="manual"?{onDragStart:Ke=>Re(Ke,{allSessionIds:Cn,visibleSessionIds:Tt,sessionId:K.id}),onDragEnd:ae,onDragOver:Ke=>{Be||C(Ke,K.id)},onDrop:Ke=>{Be?d():m(Ke,K.id)}}:{};return x.jsxs("div",{className:kn,onPointerEnter:Ke=>pn(K,Ke.currentTarget),onPointerLeave:()=>oe(null),onFocusCapture:Ke=>pn(K,Ke.currentTarget),onBlurCapture:Ke=>{Ke.currentTarget.contains(Ke.relatedTarget)||oe(null)},children:[x.jsx(Jp,{session:K,selected:!_e&&we==="chat"&&B===K.id,archived:_e,hideIcon:!0,placeholder:Be,running:Ne.has(K.id),goalRuntime:y.get(K.id)??null,subagentRuntime:ce.get(K.id)??null,terminalIndicator:ut(K.id),projectLabel:Ue.projectLabel===void 0?lt(K):Ue.projectLabel,metadataPresentation:Ue.metadataPresentation,ariaDescribedBy:te?.sessionId===K.id?te.descriptionId:void 0,childSessionCount:vt.length,childSessionsExpanded:Ca(K,vt),onToggleChildSessions:()=>Ra(K.id),onSelect:()=>{oe(null),_e&&k(K),Fn(K)},onTogglePin:()=>xe(K),onToggleSaveForLater:()=>De(K),onDockRight:()=>h(K),onArchive:()=>_e?k(K):t(K),onRename:j,...Xt}),Be?null:Qt(K)]},K.id)}function xn(K){K!=="tasksets"&&ee(null),O(K),D(An)}function Pa(K){ee(K),O("tasksets"),D(An)}function Aa(K){X(K),D(An)}function ea(){D(K=>SV(K,At.length))}function Ta(){D(K=>xV(K,At.length))}function Nn(K){const Ue={id:K.id,type:K.type};return{onDragStart:_e=>be(_e,Ue),onDragEnd:Ze,onDragOver:_e=>N(_e,Ue),onDrop:_e=>{He?.id===K.id&&He.type===K.type?qe():nt(_e,Ue)}}}function yo(K){const Ue=Nn(K),_e=He?.id===K.id&&He.type===K.type;if(K.type==="project"){const vt=K.item;return x.jsx(W6,{kind:vt.kind,project:vt.project,pinned:!0,selected:we==="chat"&&U===vt.id,expanded:!1,disclosure:!1,placeholder:_e,onSelect:()=>{se(null),me(vt.id),Te(null),ke("chat")},onNewChat:()=>s(vt.id),onTogglePin:()=>ze(vt),onRemove:()=>Se(vt),...Ue},K.key)}if(K.type==="file")return x.jsx(V6,{file:K.file,placeholder:_e,onSelect:()=>_(K.file),onTogglePin:()=>We(K.file,"none"),onToggleSaveForLater:()=>We(K.file,"saved_for_later"),...Ue},K.key);const Be=K.session;return x.jsx("div",{onPointerEnter:vt=>pn(Be,vt.currentTarget),onPointerLeave:()=>oe(null),onFocusCapture:vt=>pn(Be,vt.currentTarget),onBlurCapture:vt=>{vt.currentTarget.contains(vt.relatedTarget)||oe(null)},children:x.jsx(Jp,{ariaDescribedBy:te?.sessionId===Be.id?te.descriptionId:void 0,session:Be,selected:we==="chat"&&B===Be.id,hideIcon:!0,placeholder:_e,running:Ne.has(Be.id),goalRuntime:y.get(Be.id)??null,subagentRuntime:ce.get(Be.id)??null,terminalIndicator:ut(Be.id),projectLabel:lt(Be),metadataPresentation:"flyout",onSelect:()=>{oe(null),Fn(Be)},onTogglePin:()=>xe(Be),onToggleSaveForLater:()=>De(Be),onDockRight:()=>h(Be),onArchive:()=>t(Be),onRename:j,...Ue})},K.key)}function Ea(K){const Ue=_a.has(K.key)||G.get(K.key)!==!1;return x.jsx(gV,{expanded:Ue,groupKey:K.key,kind:K.kind,label:K.label,onToggle:()=>{ie(_e=>{const Be=new Map(_e);return Be.set(K.key,!Ue),Be})},onNewTask:K.project?()=>s(K.project.id):void 0,onOpenProject:K.project?()=>{se(null),me(K.project.id),Te(null),ke("chat")}:void 0,onRemoveProject:K.project?()=>Se(K.project):void 0,project:K.project,children:K.sessions.map(_e=>rt(_e,{metadataPresentation:"flyout",projectLabel:K.label}))},K.key)}return x.jsxs("div",{className:"sidebar-sections",children:[sn.length>0?x.jsx(Zp,{label:"Pinned",className:"sidebar-pinned-section",collapsed:R,onToggleCollapsed:Qe,children:sn.map(yo)}):null,x.jsx(Zp,{label:"Projects",className:`sidebar-projects-section${v!=="chat"?" development":""}`,collapsed:Oe,onToggleCollapsed:()=>et(K=>({...K,[mt]:!K[mt]})),actions:x.jsx(uV,{onAddProject:l,onViewProjects:()=>{(async()=>await en({kind:"view",view:"projects"})&&(se(null),me(null),Te(null),ke("projects")))()}}),children:un.filter(K=>K.kind==="project").map(K=>Ea(v==="chat"||!fe?{...K,sessions:[]}:K))}),x.jsxs(Zp,{label:v==="chat"?"Chat":"Work",className:"sidebar-task-section sidebar-ordinary-section",collapsed:Xe[mt],onToggleCollapsed:()=>st(K=>({...K,[mt]:!K[mt]})),actionsVisible:T==="chats"||T==="tasks-filter"||L!=="active"||H||!Z,actions:x.jsx(dV,{filter:L,groupByProject:fe,noun:ue,onFilterChange:xn,onGroupByProjectChange:Me,onOnlyRunningTasksChange:K=>{f(Ue=>{const _e={...Ue,onlyRunningTasks:K};return d0(_e),_e}),D(An)},onShowCodexChatsChange:K=>{f(Ue=>{const _e={...Ue,showCodexChats:K};return d0(_e),_e}),D(An)},onTasksetChange:Pa,onSortChange:Aa,onlyRunningTasks:H,openMenu:T,setOpenMenu:W,showCodexChats:Z,sort:z,selectedTasksetId:le,tasksets:pt}),children:[(v==="chat"||!fe?nn:nn.filter(K=>!V[K.id])).map(K=>rt(K)),At.length===0&&sn.length===0?x.jsx("div",{className:"empty-row",children:g6(L,ue)}):null,At.length>An&&(mn||qt)?x.jsxs("div",{className:"sidebar-pagination-controls","aria-label":`Showing ${nn.length} of ${At.length} ${ue}`,children:[mn?x.jsx(u0,{onClick:ea,children:"Show more"}):null,qt?x.jsx(u0,{onClick:Ta,children:"Show less"}):null]}):null]}),x.jsx(hV,{detail:te,onClose:()=>oe(null)})]})}const IV="/";function Jn(e){return`${IV}${e.replace(/^\.?\//,"")}`}const _V=Jn("openpond-icon.png"),CV=Jn("openpond-wordlogo-white.png"),EQ=Jn("tutorials/what-is-an-openpond-agent-poster.png"),MQ=Jn("tutorials/what-is-an-openpond-agent.vtt"),jQ=Jn("tutorials/how-to-make-an-agent-poster.png"),OQ=Jn("tutorials/how-to-make-an-agent.vtt");function $Q(e){return Jn(`tutorials/how-to-make-an-agent-${e}-poster.png`)}function NQ(e){return Jn(`tutorials/how-to-make-an-agent-${e}.vtt`)}const m0={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 DQ(e){return m0[e]??m0.mcp}function RV({value:e,onChange:t}){const[n,a]=g.useState(!1),o=g.useRef(null),i=g.useRef(null),s=g.useRef(null),l=g.useRef(null),m=Fp.find(y=>y.value===e)??Fp[0];g.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]),g.useLayoutEffect(()=>{n&&l.current&&p0(s.current,l.current),l.current=null},[n]);const d=y=>{if(n){p0(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"))},v=y=>{const w=C_(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 R=y.key==="ArrowDown"?1:-1,M=_<0?0:(_+R+w.length)%w.length;w[M]?.focus()};return x.jsxs("div",{className:"sidebar-experience-menu",ref:o,children:[x.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:[x.jsx("img",{className:"sidebar-wordmark",src:CV,alt:""}),x.jsx("span",{className:"sidebar-experience-label",children:m.label}),x.jsx(Wo,{size:13,"aria-hidden":"true"})]}),n?x.jsx("div",{ref:s,className:"sidebar-experience-popover",role:"menu","aria-label":"Choose product",onKeyDown:v,children:Fp.map(y=>{const w=y.value===e;return x.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:[x.jsxs("span",{children:[x.jsx("strong",{children:y.label}),x.jsx("small",{children:y.description})]}),w?x.jsx(Ao,{size:14,"aria-hidden":"true"}):null]},y.value)})}):null]})}function C_(e){return e?Array.from(e.querySelectorAll('[role="menuitemradio"]')):[]}function p0(e,t){const n=C_(e);(t==="first"?n[0]:n.at(-1))?.focus()}function PV(...e){for(const t of e){const n=t?.trim();if(n)return n}return null}function AV(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"?PV(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 TV({account:e,open:t,organizations:n,selectedTeamId:a,onOpenActivity:o,onOpenChange:i,onOpenSettings:s,onSelectTeam:l,onLogOut:m}){const[d,h]=g.useState(null),[v,y]=g.useState(!1),w=g.useRef(null),_=g.useMemo(()=>AV(e),[e]),R=_.label.trim().slice(0,1).toUpperCase(),M=n.find(C=>C.teamId===a)??n[0]??null;return g.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]),x.jsxs("div",{className:"user-auth-footer",ref:w,children:[x.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:[x.jsx("span",{className:"user-auth-avatar","aria-hidden":"true",children:_.image?x.jsx("img",{src:_.image,alt:""}):R?x.jsx("span",{children:R}):x.jsx(Yy,{size:16})}),x.jsx("span",{className:"user-auth-name",children:_.label})]}),t?x.jsxs("div",{className:"user-auth-menu",role:"menu","aria-label":"Account",children:[x.jsxs("div",{className:"user-auth-menu-header",children:[x.jsx("span",{className:"user-auth-menu-avatar","aria-hidden":"true",children:_.image?x.jsx("img",{src:_.image,alt:""}):R?x.jsx("span",{children:R}):x.jsx(Yy,{size:17})}),x.jsx("span",{className:"user-auth-menu-identity",children:x.jsx("strong",{children:_.label})})]}),n.length>0&&l?x.jsxs("label",{className:"user-auth-team-picker",children:[x.jsx(QI,{size:15,"aria-hidden":"true"}),x.jsx("span",{className:"user-auth-team-picker-label",children:"Team"}),x.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=>x.jsx("option",{value:C.teamId,children:C.displayName},C.teamId))})]}):null,x.jsx("div",{className:"user-auth-menu-divider"}),o?x.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",onClick:()=>{i(!1),o()},children:[x.jsx(KI,{size:15}),x.jsx("span",{children:"Activity"})]}):null,x.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",onClick:()=>{i(!1),s()},children:[x.jsx(YI,{size:15}),x.jsx("span",{children:"Settings"})]}),e?.state==="signed_in"&&m?x.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",disabled:v,onClick:async()=>{y(!0);try{await m(),i(!1)}catch{}finally{y(!1)}},children:[x.jsx(y3,{size:15}),x.jsx("span",{children:v?"Logging out…":"Log out"})]}):null]}):null]})}function f0(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 EV(e,t){const n=f0(e),a=f0(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 R_(e){const t=e?.toLowerCase()??"";return t==="darwin"||t.includes("mac")?"mac":t==="linux"||t.includes("linux")?"linux":null}function MV(e){const t=e?.toLowerCase()??"";return t==="arm64"||t==="aarch64"?"arm64":t==="x64"||t==="x86_64"||t==="amd64"?"x64":null}function jV(e,t,n){const a=R_(t),o=MV(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 OV(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(!EV(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=jV(s,e.platform,e.arch);return!l||!o?null:{version:a,releaseUrl:o,assetName:l.name,downloadUrl:l.downloadUrl}}const $V=3600*1e3,NV="https://api.github.com/repos/openpond/openpond/releases/latest";function DV(e){const[t,n]=g.useState({status:"idle",update:null,lastCheckedAt:null}),a=e.currentVersion?.trim()??"",o=e.platform??"",i=e.arch??"",s=e.enabled&&!!a&&!!R_(o);return g.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(NV,{headers:{Accept:"application/vnd.github+json"}});if(!h.ok)throw new Error(`GitHub release check failed: ${h.status}`);const v=await h.json(),y=OV({payload:v,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()},$V);return()=>{l=!0,window.clearInterval(d)}},[i,a,s,o]),t}const P_="openpond.sidebar.continuous-learning.dismissed.v1";function h0(e=A_()){if(!e)return!1;try{return e.getItem(P_)==="true"}catch{return!1}}function LV(e=A_()){if(e)try{e.setItem(P_,"true")}catch{}}function A_(){return typeof window>"u"?null:kc}function UV({connection:e,onOpenSettings:t}){const[n,a]=g.useState(null),[o,i]=g.useState(h0);xc(()=>i(h0()));const s=g.useCallback(async()=>{if(!e){a(null);return}try{a(await Y.harnessHistory(e))}catch{a(null)}},[e]);if(g.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 x.jsxs("section",{className:"sidebar-learning-notice","aria-label":"Continuous learning",children:[x.jsxs("header",{children:[x.jsx("strong",{children:"Continuous learning"}),x.jsxs("div",{className:"sidebar-learning-notice-actions",children:[x.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Open Continuous learning settings",onClick:t,type:"button",children:x.jsx(YI,{size:14})}),x.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Close continuous learning",onClick:()=>{i(!0),LV()},type:"button",children:x.jsx(yc,{size:14})})]})]}),x.jsxs("div",{className:"sidebar-learning-status",children:[x.jsx("strong",{children:"Refiner"}),x.jsx("span",{children:n.backgroundReview.enabled?"On":"Off"})]}),x.jsxs("div",{className:"sidebar-learning-status",children:[x.jsx("strong",{children:"Continuous Review"}),x.jsx("span",{children:m})]})]})}function HV(e){const[t,n]=g.useState(!1),{beginNewChat:a,arch:o,currentVersion:i,experience:s,productArea:l,onProductAreaChange:m,onSidebarResizeStart:d,platform:h,setSectionMenuOpen:v,setSelectedAppId:y,setSelectedProjectId:w,setSelectedSessionId:_,setSidebarOpen:R,setView:M,view:C,modelProjects:N,modelTrainingActivityByProjectId:$}=e,j=g.useCallback(U=>{n(!1),v(U)},[v]),k=g.useCallback(U=>{n(U),U&&v(null)},[v]),P=DV({currentVersion:i,platform:h,arch:o,enabled:Bu()}),T=P.status==="available"?P.update:null;return x.jsxs("aside",{className:"sidebar",children:[x.jsxs("div",{className:"sidebar-toolbar",children:[x.jsx("button",{className:"sidebar-icon","aria-label":"Hide sidebar",onClick:()=>R(!1),children:x.jsx(JI,{size:16})}),x.jsx(RV,{value:l,onChange:m}),T&&x.jsxs("button",{type:"button",className:"sidebar-update-pill",title:`Download OpenPond ${T.version}: ${T.assetName}`,"aria-label":`Download OpenPond ${T.version}`,onClick:()=>{zV(T.downloadUrl)},children:[x.jsx(F5,{size:14}),x.jsx("span",{children:"Update"})]})]}),l==="models"?null:x.jsx(F3,{experience:s,beginNewChat:a}),x.jsxs("div",{className:"sidebar-scroll",children:[l!=="models"&&e.account?.activeProfile&&e.onOpenPonder?x.jsxs("button",{type:"button",className:"sidebar-ponder-entry",onClick:e.onOpenPonder,children:[x.jsx("span",{"aria-hidden":"true",children:"✦"})," Ponder Pal"]}):null,x.jsx(V3,{productArea:l,setSectionMenuOpen:j,setSelectedAppId:y,setSelectedProjectId:w,setSelectedSessionId:_,setView:M,view:C,modelProjects:N,modelTrainingActivityByProjectId:$}),l==="models"?null:x.jsx(wV,{...e,setSectionMenuOpen:j})]}),x.jsxs("div",{className:"sidebar-bottom-stack",children:[l==="models"?null:x.jsx(UV,{connection:e.connection,onOpenSettings:()=>{v(null),en({kind:"settings",section:"harness"})}}),x.jsxs("div",{className:"sidebar-footer-row",children:[x.jsx(TV,{account:e.account,open:t,organizations:e.organizations,selectedTeamId:e.teamChatOrganization?.teamId??null,onOpenChange:k,onOpenActivity:()=>{v(null),en({kind:"settings",section:"usage"})},onOpenSettings:()=>{v(null),en({kind:"settings",section:"account"})},onSelectTeam:e.onSelectTeam,onLogOut:e.onLogOut}),x.jsx(K3,{setSectionMenuOpen:j,setSelectedAppId:y,setSelectedProjectId:w,setSelectedSessionId:_,setView:M,view:C})]})]}),x.jsx("div",{className:"sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",onPointerDown:d})]})}async function zV(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-update",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const qV=[/^(?:(?:type)?error:\s*)?failed to fetch\.?$/i,/^networkerror when attempting to fetch resource\.?$/i,/^load failed\.?$/i];function T_(e,t="Something went wrong."){const a=(e instanceof Error?e.message:String(e??"")).trim();return a?E_(a)?"Couldn’t connect to OpenPond.":a:t}function E_(e){const t=e.trim();return qV.some(n=>n.test(t))}const M_=g.createContext(null);function g0({children:e,showToast:t}){return x.jsx(M_.Provider,{value:t,children:e})}function BV(){return g.useContext(M_)}function v0(e,t={}){const n=BV(),a=g.useRef(null),o=t.enabled??!0,i=t.fallback??"Something went wrong.",s=t.prefix?.trim()??"",l=e==null||e===""?null:`${s}${s?": ":""}${T_(e,i)}`;g.useEffect(()=>{if(!o||!l){a.current=null;return}a.current!==l&&(a.current=l,n?.(l,"error"))},[o,l,n])}function FV({state:e,onClose:t,onOpenBrowserUrl:n,onStart:a}){if(v0(e?.previewError,{prefix:"Upload preview"}),v0(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 x.jsx("div",{className:"git-dialog-backdrop",role:"presentation",children:x.jsxs("section",{className:"git-dialog cloud-setup-dialog",role:"dialog","aria-modal":"true","aria-label":"Set up Cloud coding",children:[x.jsx("button",{className:"git-dialog-close",disabled:o,type:"button",onClick:t,"aria-label":"Close Cloud setup",title:"Close",children:x.jsx(yc,{size:14})}),x.jsx("div",{className:"git-dialog-icon",children:i?x.jsx(Yf,{size:18}):x.jsx(Hu,{size:18})}),x.jsx("h2",{children:i?"Cloud repo ready":"Set up Cloud coding"}),x.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."}),x.jsxs("div",{className:"cloud-setup-summary",children:[x.jsxs("div",{className:"git-dialog-row",children:[x.jsx("span",{children:"Project"}),x.jsx("strong",{children:e.projectName})]}),x.jsxs("div",{className:"git-dialog-row",children:[x.jsx("span",{children:"Source"}),x.jsx("strong",{children:l?"OpenPond Git":"Local project upload"})]}),x.jsxs("div",{className:"git-dialog-row",children:[x.jsx("span",{children:"Branch"}),x.jsx("strong",{children:m?.branch??e.branch??"main"})]}),!l&&x.jsxs("div",{className:"git-dialog-row",children:[x.jsx("span",{children:"Cloud project"}),x.jsx("strong",{children:m?.targetProjectId??e.cloudProjectId??"New on upload"})]})]}),!i&&!l&&x.jsx("div",{className:"cloud-setup-upload-preview",role:"status","aria-live":"polite",children:e.previewLoading?x.jsxs(x.Fragment,{children:[x.jsx("strong",{children:"Calculating upload preview"}),x.jsx("span",{children:"Checking tracked and unignored files before anything is pushed."})]}):e.previewError?x.jsxs(x.Fragment,{children:[x.jsx("strong",{children:"Preview unavailable"}),x.jsx("span",{children:"Close and reopen setup to try the preview again."})]}):m?x.jsxs(x.Fragment,{children:[x.jsx("strong",{children:m.initializedEmptyProject?"Will initialize an empty project":`Will upload ${m.fileCount} files`}),x.jsx("span",{children:b0({byteCount:m.byteCount,skippedCount:m.skippedCount,headCommit:m.headCommit,targetProjectName:m.targetProjectName})})]}):x.jsxs(x.Fragment,{children:[x.jsx("strong",{children:"Upload preview pending"}),x.jsx("span",{children:"File count, byte count, and skipped files will appear here before upload."})]})}),o&&x.jsxs("div",{className:"cloud-setup-progress",role:"status","aria-live":"polite",children:[x.jsx(s3,{className:"cloud-setup-spinner",size:16}),x.jsx("span",{children:"Uploading source to OpenPond Git..."})]}),i&&e.upload&&x.jsxs("div",{className:"cloud-setup-upload-result",children:[x.jsx("strong",{children:e.upload.initializedEmptyProject?"Initialized empty project":`Uploaded ${e.upload.fileCount} files`}),x.jsx("span",{children:b0({byteCount:e.upload.byteCount,skippedCount:e.upload.skippedCount,headCommit:e.upload.headCommit,targetProjectName:e.upload.branch})})]}),i&&e.setupUrl&&x.jsxs("div",{className:"cloud-setup-next",children:[e.projectUrl?x.jsxs("span",{children:["Your repo is ready here:"," ",x.jsxs("a",{href:e.projectUrl,target:"_blank",rel:"noreferrer",onClick:d=>Yp(d,e.projectUrl,n,{newTab:!0}),children:["Project page",x.jsx(qp,{size:13})]})]}):x.jsx("span",{children:"Your repo is ready. Next step:"}),x.jsxs("a",{href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:d=>Yp(d,e.setupUrl,n),children:["Setup the Cloud sandbox",x.jsx(qp,{size:13})]})]}),x.jsxs("div",{className:"git-dialog-footer",children:[x.jsx("button",{className:"git-dialog-secondary",disabled:o,type:"button",onClick:t,children:i?"Done":"Cancel"}),i?e.setupUrl?x.jsxs("a",{className:"git-dialog-primary cloud-setup-primary-link",href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:d=>Yp(d,e.setupUrl,n),children:["Open setup",x.jsx(qp,{size:13})]}):null:x.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 Yp(e,t,n,a={}){!t||!n||(e.preventDefault(),n(t,a))}function VV(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 b0({byteCount:e,skippedCount:t,headCommit:n,targetProjectName:a}){const o=[VV(e),`${t} skipped`],i=KV(n);return i&&o.push(`local ${i}`),o.push(a),o.join(" · ")}function KV(e){const t=e?.trim();return t?t.slice(0,7):null}const WV=g.lazy(()=>Qr(()=>import("./CommandMenu-BN1a4dTn.js"),__vite__mapDeps([0,1,2,3]),import.meta.url).then(e=>({default:e.CommandMenu}))),GV=g.lazy(()=>Qr(()=>import("./SettingsView-ZH2gDC6E.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}))),ZV=g.lazy(()=>Qr(()=>import("./NewProjectDialog-B6E1wWOM.js"),__vite__mapDeps([22,1,2,8,13,23]),import.meta.url).then(e=>({default:e.NewProjectDialog}))),JV=g.lazy(()=>Qr(()=>import("./WorkspaceGitDialogs-DHD-L4Vs.js"),__vite__mapDeps([24,1,2,11,12,25,21]),import.meta.url).then(e=>({default:e.CommitDialog}))),YV=g.lazy(()=>Qr(()=>import("./WorkspaceGitDialogs-DHD-L4Vs.js"),__vite__mapDeps([24,1,2,11,12,25,21]),import.meta.url).then(e=>({default:e.BranchDialog})));function QV({payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:o,onError:i,onToast:s,onBack:l,onOpenSourceSession:m,onStartRefinerAuthoring:d,onAcceptEvaluationReview:h,onOpenSkill:v,onOpenExtension:y,teamChatCurrentUserId:w,teamChatEnabled:_,teamChatNotificationMode:R,teamChatThreads:M,onTeamChatNotificationModeChange:C,onTeamChatThreadMuteChange:N,diffPanelWidth:$,diffPanelResizing:j,diffPanelExpanded:k,onDiffPanelResizeStart:P,onDiffPanelExpandedChange:T}){return x.jsx(g.Suspense,{fallback:null,children:x.jsx(GV,{payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:o,onError:i,onToast:s,onBack:l,onOpenSourceSession:m,onStartRefinerAuthoring:d,onAcceptEvaluationReview:h,onOpenSkill:v,onOpenExtension:y,teamChatCurrentUserId:w,teamChatEnabled:_,teamChatNotificationMode:R,teamChatThreads:M,onTeamChatNotificationModeChange:C,onTeamChatThreadMuteChange:N,diffPanelWidth:$,diffPanelResizing:j,diffPanelExpanded:k,onDiffPanelResizeStart:P,onDiffPanelExpandedChange:T})})}function XV({activeSessions:e,branchDialogName:t,branchDialogOpen:n,commitDialogOpen:a,commitDraft:o,commitIncludeUnstaged:i,commitMessage:s,commitNextStep:l,canPublishOpenPondProject:m,expandProject:d,newProjectBusy:h,newProjectDialogOpen:v,newProjectDirectory:y,newProjectMode:w,newProjectName:_,newProjectPath:R,projectRows:M,query:C,searchOpen:N,visibleWorkspaceDiff:$,visibleWorkspaceState:j,workspaceBusy:k,appDispatch:P,beginNewChat:T,openDefaultsSettingsFromBranchDialog:U,setBranchDialogName:B,setBranchDialogOpen:D,setCommitDialogOpen:W,setCommitDraft:se,setCommitIncludeUnstaged:me,setCommitMessage:Te,setCommitNextStep:ke,setNewProjectDialogOpen:V,setNewProjectName:Re,setNewProjectPath:be,setQuery:ce,setSearchOpen:ye,submitCommitDialog:ne,submitCreateWorkspaceBranch:ge,submitNewProjectDialog:xe}){return x.jsxs(x.Fragment,{children:[N&&x.jsx(g.Suspense,{fallback:null,children:x.jsx(WV,{open:N,query:C,projects:M,sessions:e,onQueryChange:ce,onClose:()=>{ye(!1),ce("")},onNewChat:()=>{ye(!1),ce(""),T()},onOpenProject:De=>{P({type:"selectProject",projectId:De.id}),P({type:"patch",patch:{searchOpen:!1,query:""}}),d(De.id)},onOpenSession:De=>{P({type:"selectSession",sessionId:De.id,appId:De.appId,projectId:De.workspaceKind==="local_project"&&De.workspaceId?yt("local",De.workspaceId):null}),P({type:"patch",patch:{searchOpen:!1,query:""}})}})}),v&&x.jsx(g.Suspense,{fallback:null,children:x.jsx(ZV,{open:v,mode:w,name:_,path:R,directory:y,busy:h,onNameChange:Re,onPathChange:be,onClose:()=>{h||V(!1)},onSubmit:xe})}),a&&x.jsx(g.Suspense,{fallback:null,children:x.jsx(JV,{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:k,canPush:!!j?.remoteUrl,canPublish:m,onMessageChange:Te,onIncludeUnstagedChange:me,onNextStepChange:ke,onDraftChange:se,onClose:()=>{k||W(!1)},onSubmit:ne})}),n&&x.jsx(g.Suspense,{fallback:null,children:x.jsx(YV,{open:n,branchName:t,busy:k,onBranchNameChange:B,onSetPrefix:U,onClose:()=>{k||D(!1)},onSubmit:ge})})]})}function j_({toast:e,onDismiss:t}){if(!e)return null;const n=!!(e.actionLabel&&e.onAction);return x.jsxs("div",{className:`app-toast ${e.tone} ${e.placement??"bottom-right"}`,role:e.tone==="error"?"alert":"status","aria-live":"polite",children:[x.jsx("span",{className:"app-toast-message",children:e.message}),n&&x.jsx("div",{className:"app-toast-actions",children:x.jsx("button",{type:"button","aria-label":e.actionLabel,onClick:()=>{t(),e.onAction?.()},children:e.actionLabel})})]})}const wc=g.createContext(null);function eK({children:e}){const[t,n]=g.useState(null),[a,o]=g.useState(null),i=g.useMemo(()=>({title:t,actions:a,setTitle:n,setActions:o}),[t,a]);return x.jsx(wc.Provider,{value:i,children:e})}function LQ({children:e}){return x.jsx(wc.Provider,{value:null,children:e})}function tK({children:e,className:t=""}){const n=g.useContext(wc);return x.jsx("div",{ref:n?.setTitle,className:`page-chrome-title-target ${t}`,children:e?x.jsx("div",{className:"page-chrome-fallback",children:e}):null})}function nK({className:e=""}){const t=g.useContext(wc);return x.jsx("div",{ref:t?.setActions,className:e})}function UQ({title:e,actions:t,fallback:n,children:a}){const o=g.useContext(wc);return o?x.jsxs(x.Fragment,{children:[o.title?ch.createPortal(x.jsx("div",{className:"page-chrome-title",children:e}),o.title):null,o.actions&&t?ch.createPortal(t,o.actions):null,a]}):n??x.jsxs("header",{children:[e,t]})}async function aK(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 oK({activeView:e,onDiscoverCommunities:t,onOpenTeamChat:n}){return x.jsxs("div",{className:"titlebar-collaboration-actions",children:[x.jsx("button",{type:"button",className:`titlebar-icon${e==="team"?" active":""}`,"aria-label":"Team chat",title:"Team chat",onClick:n,children:x.jsx(zu,{size:16})}),x.jsx("button",{type:"button",className:`titlebar-icon${e==="community"?" active":""}`,"aria-label":"Discover communities",title:"Discover communities",onClick:t,children:x.jsx(ZI,{size:16})})]})}const rK=g.lazy(()=>Qr(()=>import("./WorkspaceEnvironmentMenu-pb6fs4-2.js"),__vite__mapDeps([26,1,2,17,23,5,12,27,25,28]),import.meta.url).then(e=>({default:e.WorkspaceEnvironmentMenu})));function iK({sidebarOpen:e,title:t,conversationId:n,breadcrumbs:a,backAction:o,workspaceName:i,workspaceId:s,busy:l,workspaceState:m,workspaceKind:d,selectedApp:h,selectedProject:v,workspaceDiff:y,managedWorkspace:w,workspaceBusy:_,defaultTeamId:R,showDiffControls:M,diffPanelOpen:C,terminalOpen:N,rightSidebarAvailable:$=!1,rightSidebarOpen:j=!1,onToggleDiffPanel:k,onToggleRightSidebar:P,onOpenSearch:T,onToggleTerminal:U,onRunTerminalCommand:B,onWorkspaceToolAction:D,onOpenCommitDialog:W,onWorkspaceBranchChange:se,onWorkspaceBranchCreate:me,connection:Te,onBootstrap:ke,onOpenSandboxWorkspace:V,onShowSidebar:Re,onOpenTeamChat:be,onDiscoverCommunities:ce,collaborationView:ye=null,platform:ne,showWorkspaceControls:ge=!0}){const xe=y?.filesChanged??0,De=Bu()&&!cv(ne),we=!!(be||ce)||ge||$||De,[ae,Se]=g.useState(null);g.useEffect(()=>{if(!ae)return;const We=()=>Se(null);return window.addEventListener("pointerdown",We),window.addEventListener("blur",We),window.addEventListener("resize",We),()=>{window.removeEventListener("pointerdown",We),window.removeEventListener("blur",We),window.removeEventListener("resize",We)}},[ae]);const ze=We=>{We.preventDefault(),We.stopPropagation();const nt=190,qe=n?76:42;Se({x:Math.min(We.clientX,window.innerWidth-nt-8),y:Math.min(We.clientY,window.innerHeight-qe-8)})},Qe=We=>{aK(We),Se(null)};return x.jsxs("header",{className:"app-titlebar",children:[x.jsxs("div",{className:"titlebar-left",children:[!e&&x.jsx("button",{className:"titlebar-icon",title:"Show sidebar",onClick:Re,children:x.jsx(JI,{size:16})}),o?x.jsx("button",{className:"titlebar-icon",type:"button","aria-label":o.label,title:o.label,onClick:o.onSelect,children:x.jsx(C5,{size:16})}):null,x.jsx(tK,{children:a?.length?x.jsx("nav",{className:"titlebar-breadcrumbs","aria-label":"Breadcrumb",children:a.map((We,nt)=>{const qe=nt===a.length-1;return x.jsxs("div",{className:"titlebar-breadcrumb-item",children:[We.onSelect&&!qe?x.jsx("button",{type:"button",onClick:We.onSelect,children:We.label}):x.jsx("strong",{children:We.label}),!qe&&x.jsx(Yr,{size:14})]},`${We.label}-${nt}`)})}):x.jsxs("div",{className:"titlebar-title",children:[x.jsx("strong",{className:"titlebar-copy-target",title:"Double-click to select; right-click for copy options",onContextMenu:ze,children:t}),i&&x.jsx("span",{children:i})]})})]}),we&&x.jsxs("div",{className:"titlebar-right",children:[x.jsx(nK,{className:"page-chrome-actions"}),x.jsx(oK,{activeView:ye,onDiscoverCommunities:ce,onOpenTeamChat:be}),ge&&x.jsxs("div",{className:"titlebar-actions",children:[x.jsx(g.Suspense,{fallback:null,children:x.jsx(rK,{mode:"topbar",busy:l,workspaceState:m,workspaceId:s,workspaceKind:d,selectedApp:h,selectedProject:v,workspaceBusy:_,defaultTeamId:R,workspaceDiff:y,managedWorkspace:w,showDiffControls:M,diffPanelOpen:C,onToggleDiffPanel:k,onRunTerminalCommand:B,onWorkspaceToolAction:D,onOpenCommitDialog:W,onWorkspaceBranchChange:se,onWorkspaceBranchCreate:me,connection:Te,onBootstrap:ke,onOpenSandboxWorkspace:V})}),x.jsx("button",{type:"button",className:"titlebar-icon",title:"Search chats and projects","aria-label":"Search chats and projects",onClick:T,children:x.jsx(x3,{size:16})}),x.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:x.jsx(XI,{size:16})}),M&&x.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:k,children:x.jsx(Qf,{size:16})})]}),$&&P&&!M?x.jsx("div",{className:"titlebar-actions",children:x.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:P,children:x.jsx(Qf,{size:16})})}):null,x.jsx(T3,{platform:ne})]}),ae&&x.jsxs("div",{className:"titlebar-copy-menu",role:"menu","aria-label":"Conversation title actions",style:{left:ae.x,top:ae.y},onPointerDown:We=>We.stopPropagation(),children:[x.jsx("button",{type:"button",role:"menuitem",onClick:()=>Qe(t),children:"Copy title"}),n&&x.jsx("button",{type:"button",role:"menuitem",onClick:()=>Qe(n),children:"Copy conversation ID"})]})]})}function sK(){const[e,t]=g.useState(null),n=g.useRef(null),a=g.useCallback(i=>new Promise(s=>{n.current?.resolve(!1);const l={...i,cancelLabel:i.cancelLabel??"Cancel",tone:i.tone??"default",resolve:s};n.current=l,t(l)}),[]),o=g.useCallback(i=>{const s=n.current;n.current=null,t(null),s?.resolve(i)},[]);return{confirmAction:a,confirmDialog:e,resolveConfirmDialog:o}}function lK({state:e,onResolve:t}){const n=g.useId(),a=g.useId();if(g.useEffect(()=>{if(!e)return;function i(s){s.key==="Escape"&&t(!1)}return document.addEventListener("keydown",i),()=>document.removeEventListener("keydown",i)},[t,e]),!e)return null;const o=e.tone==="danger"?"git-dialog-primary danger":"git-dialog-primary";return x.jsx("div",{className:"git-dialog-backdrop",role:"presentation",onMouseDown:()=>t(!1),children:x.jsxs("section",{className:"git-dialog project-confirm-dialog",role:"alertdialog","aria-modal":"true","aria-labelledby":n,"aria-describedby":a,onMouseDown:i=>i.stopPropagation(),children:[x.jsx("h2",{id:n,children:e.title}),x.jsx("p",{id:a,children:e.body}),x.jsxs("div",{className:"git-dialog-footer",children:[x.jsx("button",{type:"button",className:"git-dialog-secondary",onClick:()=>t(!1),children:e.cancelLabel}),x.jsx("button",{type:"button",className:o,autoFocus:!0,onClick:()=>t(!0),children:e.confirmLabel})]})]})})}function cK(){const{confirmAction:e,confirmDialog:t,resolveConfirmDialog:n}=sK();return{confirmProjectAction:g.useCallback(o=>e({tone:"danger",...o}),[e]),projectConfirmDialog:t,resolveProjectConfirmDialog:n}}function dK({state:e,onResolve:t}){return x.jsx(lK,{state:e,onResolve:t})}const Yd=new Map,uK=(e,t,n)=>{const a=Yd.get(e)??{commits:0,maxActualDurationMs:0,totalActualDurationMs:0};a.commits+=1,a.maxActualDurationMs=Math.max(a.maxActualDurationMs,n),a.totalActualDurationMs+=n,Yd.set(e,a)};function mK({children:e,id:t}){return x.jsx(g.Profiler,{id:t,onRender:uK,children:e})}typeof window<"u"&&(window.__OPENPOND_RENDER_COMMITS__={get:()=>Object.fromEntries([...Yd.entries()].map(([e,t])=>[e,{...t}])),reset:()=>Yd.clear()});const pK=g.lazy(()=>Qr(()=>import("./MainPane-BdR1K59_.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 fK({className:e,style:t,sidebar:n,topBar:a,mainPane:o,cloudSetup:i,projectConfirm:s,lazyPanels:l,toast:m}){return x.jsx(eK,{children:x.jsxs("div",{className:e,style:t,children:[x.jsx(mK,{id:"sidebar",children:x.jsx(HV,{...n})}),x.jsxs("div",{className:"content-shell",children:[x.jsx(iK,{...a}),x.jsx(g.Suspense,{fallback:x.jsx("main",{className:"main-pane","aria-busy":"true","aria-label":"Loading workspace"}),children:x.jsx(pK,{...o})})]}),x.jsx(FV,{...i}),x.jsx(dK,{...s}),x.jsx(XV,{...l}),x.jsx(j_,{...m})]})})}function hK({settings:e,toast:t}){return x.jsxs(x.Fragment,{children:[x.jsx(QV,{...e}),x.jsx(j_,{...t})]})}const wd="OpenPond".split("");function gK({visibleLetterCount:e=wd.length}){const t=wd.slice(0,Math.max(0,Math.min(e,wd.length)));return x.jsxs("div",{className:"app-splash-lockup",children:[x.jsx("div",{className:"app-splash-mark",children:x.jsx("img",{alt:"OpenPond",className:"app-splash-logo",decoding:"async",src:_V})}),x.jsx("span",{"aria-hidden":"true",className:`app-splash-wordmark${t.length>0?" is-visible":""}`,children:t.map((n,a)=>x.jsx("span",{className:"app-splash-letter",children:n},`${n}-${a}`))})]})}const Qp=wd.length,vK=520,bK=240;function y0(){return typeof window>"u"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function yK({startup:e}){const[t,n]=g.useState(()=>y0()?Qp:0);return g.useEffect(()=>{if(y0()){n(Qp);return}const a=Array.from({length:Qp},(o,i)=>window.setTimeout(()=>n(i+1),vK+bK*i));return()=>{a.forEach(o=>window.clearTimeout(o))}},[]),x.jsxs("main",{className:"app-splash","aria-busy":"true","aria-label":e.label,role:"status",children:[x.jsx(gK,{visibleLetterCount:t}),x.jsx("span",{className:"app-splash-status",children:e.label})]})}const Cv=5e3;function Mo(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 To(e,t,n=Cv){return Id(Mo(e,t),n)}function Id(e,t=Cv){return e.length<=t?e:e.slice(e.length-t)}function SK(e,t,n){return n.length===0?e:{...e,[t]:Mo(e[t]??[],n)}}function xK(e,t){if(t.length===0)return Id(e);if(e.length===0)return Id(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 Id([...n.values()].sort((o,i)=>wK(o,i)).map(({event:o})=>o))}function Qd(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 kK(e){let t=null;for(const n of e)n.sequence!==void 0&&(t===null||n.sequence<t)&&(t=n.sequence);return t}function wK(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 IK(e){const t=e?.trim()||"https://openpond.ai";return new URL("/console",t).toString()}async function _K(e){const t=IK(e),n=window.openpond?.browser;n?.openExternal&&(await n.openExternal({conversationId:"openpond-console",url:t})).ok||window.location.assign(t)}function S0(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 CK(e){return e===null?"unknown":e>=85?"high":e>=65?"medium":"low"}function x0(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 RK(e){return e==="codex"}function PK(e){return e==="openpond"}function O_(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="session.context.updated")continue;const a=WO.safeParse(n.data);if(a.success)return a.data}return null}function $_(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=`${S0(n)} / ${S0(a)} tokens used`;return{usedTokens:n,maxTokens:a,percent:o,summary:i,tokensLabel:s,detail:x0(e.preferences,o),tooltip:`Context window: ${i} ${s}. ${x0(e.preferences,o)}`,tone:CK(o)}}if(RK(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(!PK(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 Rv(e){let t=!1;const n=N_(e);for(let a=e.length-1;a>=0;a-=1){const o=e[a];if(AK(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=Pv(bs(i.goal),Wn(i.provider),n);if(s){const l=Ql(s);return t&&l.tone==="active"?null:l}}if(i.kind==="goal_context"){const s=L_(o.output??"",Wn(i.provider)??"codex",n);if(s){const l=Ql(s);return t&&l.tone==="active"?null:l}}}}return null}function Xd(e){const t=N_(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=Pv(bs(o.goal),Wn(o.provider),t);if(!i)continue;const s=Ql(i);return s.tone==="active"?s:null}if(o.kind==="goal_context"){const i=L_(a.output??"",Wn(o.provider)??"codex",t);if(!i)continue;const s=Ql(i);return s.tone==="active"?s:null}}}return null}function Xp(e){const t=bs(bs(e)?.codexGoalRuntime),n=Pv(t,Wn(t?.provider)??"codex");if(!n)return null;const a=Ql(n);return a.tone==="active"?a:null}function AK(e){return e?.name==="turn.completed"||e?.name==="turn.interrupted"||e?.name==="turn.failed"}function Ql(e){const t=U_(e.status),n=q_(e.timeUsedSeconds),a=`Goal ${n}`,o=e.tokensUsed===null?null:e.tokenBudget===null?`${ef(e.tokensUsed)} tokens`:`${ef(e.tokensUsed)} / ${ef(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: ${B_(e.timeUsedSeconds)}. ${i}. ${e.objective}`,tone:t.tone,observedAt:e.observedAt}}function TK(e,t){if(!e||e.tone!=="active"||!e.observedAt)return e;const n=D_(e.observedAt,t);if(n<=0)return e;const a=e.timeUsedSeconds+n,o=q_(a);return{...e,timeUsedSeconds:a,timeLabel:o,label:`Goal ${o}`,tooltip:`Goal runtime: ${B_(a)}. ${e.detail}. ${e.objective}`,observedAt:t}}function Pv(e,t=null,n=null){if(!e)return null;const a=Wn(e.objective)??"Active goal",o=Wn(e.status)??"active";if((dh(t)??dh(Wn(e.provider)))!=="codex")return null;const s=n??Wn(e.updatedAt)??Wn(e.updated_at)??null,l=Di(e.timeUsedSeconds)??Di(e.time_used_seconds)??0,m=Wn(e.activeSinceAt)??Wn(e.active_since_at),d=U_(o).tone==="active"?D_(m??Wn(e.createdAt)??Wn(e.created_at),s):0,h=m?l+d:Math.max(l,d),v=Di(e.tokensUsed)??Di(e.tokens_used),y=Di(e.tokenBudget)??Di(e.token_budget);return{objective:a,status:o,statusLabel:z_(o),timeUsedSeconds:Math.max(0,Math.floor(h)),tokensUsed:v===null?null:Math.max(0,Math.floor(v)),tokenBudget:y===null?null:Math.max(0,Math.floor(y)),observedAt:s}}function N_(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 D_(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 L_(e,t=null,n=null){if(!e.trim()||dh(t)!=="codex")return null;const a=H_(e,"Status")??"active",o=ml(e,"Tokens used"),i=ml(e,"Token budget"),s=ml(e,"Time used seconds")??ml(e,"Time spent pursuing goal")??ml(e,"Elapsed seconds")??0;return{objective:k0(e,"objective")??k0(e,"untrusted_objective")??"Active goal",status:a,statusLabel:z_(a),timeUsedSeconds:Math.max(0,Math.floor(s)),tokensUsed:o,tokenBudget:i,observedAt:n}}function U_(e){switch(EK(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 EK(e){return e.trim().toLowerCase().replace(/[-\s]+/g,"_")}function H_(e,t){const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^\\s*-?\\s*${n}:\\s*(.+?)\\s*$`,"im").exec(e)?.[1]?.trim()||null}function ml(e,t){const n=H_(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 k0(e,t){return new RegExp(`<${t}>\\s*([\\s\\S]*?)\\s*<\\/${t}>`,"i").exec(e)?.[1]?.trim()||null}function z_(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function q_(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 B_(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 ef(e){if(e<1e3)return String(e);if(e>=1e6){const n=e/1e6;return n<10?`${w0(n,2)}M`:n<100?`${w0(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 w0(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 dh(e){return e?.trim().toLowerCase()||null}function Di(e){return typeof e=="number"&&Number.isFinite(e)?e:null}const MK=new Set(["planning","applying_source","running_checks","evaluating","pushing_hosted","running_hosted_checks"]),jK=new Set(["awaiting_questions","awaiting_plan_approval","paused"]);function uh(e){const t=F_(e);return t?DK(t):null}function F_(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="create_improve.updated")continue;const a=NK(qK(n.data));if(a)return a}return null}function OK(e){if(e.events)return F_(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 $K(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 NK(e){const t=ic.safeParse(e?.createImproveRun);return t.success?t.data:null}function DK(e){const t=LK(e);if(!t)return null;const n=UK(e.createdAt,e.updatedAt),a=e.blockedReason??HK(e.state);return{objective:e.objective,status:e.state,timeUsedSeconds:n,tokensUsed:null,tokenBudget:null,actionLabel:t.actionLabel,timeLabel:zK(n),label:t.actionLabel,detail:a,tooltip:`${t.actionLabel}: ${a}. ${e.objective}`,tone:t.tone}}function LK(e){const t=e.state,n=e.target.kind==="agent"?"Agent":"Work";return MK.has(t)?{tone:"active",actionLabel:`${n} running`}:jK.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 UK(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 HK(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function zK(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 qK(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function V_(e,t){if(!t)return null;const n=new Map,a=[];for(const j of e){if(!j.name.startsWith("subagent."))continue;const k=VK(j);k&&a.push(k);const P=FK(j);P?.parentSessionId===t&&n.set(P.id,P)}if(n.size===0)return null;const o=[...n.values()].sort((j,k)=>Ui(k).localeCompare(Ui(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,k)=>Ui(k).localeCompare(Ui(j))),v=o.reduce((j,k)=>{const P=ys(k.metadata?.usage);return j.totalTokens+=nd(P?.totalTokens),j.promptTokens+=nd(P?.promptTokens),j.completionTokens+=nd(P?.completionTokens),j.requestCount+=nd(P?.requestCount),j},{totalTokens:0,promptTokens:0,completionTokens:0,requestCount:0}),y=o.flatMap(j=>K_([...j.report?.blockers??[],j.error,j.progress.currentBlocker]).map(k=>({runId:j.id,roleId:j.roleId,status:j.status,message:k}))),w=o.flatMap(j=>W_([...j.report?.artifacts??[],j.report?.patchRef,j.report?.diffRef,...j.progress.patchRefs]).map(k=>({...k,runId:j.id,roleId:j.roleId}))),_=h.map(j=>BK(j,a)),R=o[0]??null,M=R?{runId:R.id,roleId:R.roleId,status:R.status,message:R.progress.latestMeaningfulActivity||R.report?.summary||R.objective,updatedAt:Ui(R)}: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?`${GK(M.roleId)}: ${M.message}`:"";return{sessionId:t,runs:o,activeRuns:i,completedRuns:s,failedRuns:l,cancelledRuns:m,needsResumeRuns:d,terminalRuns:h,latestRun:R,latestMeaningfulUpdate:M,activeCount:i.length,completedCount:s.length,failedCount:l.length,cancelledCount:m.length,needsResumeCount:d.length,terminalCount:h.length,usage:v,blockers:y,evidenceRefs:w,finalResults:_,testsRunCount:o.reduce((j,k)=>j+k.progress.validationAttempts.length,0),label:C,tooltip:[N,$].filter(Boolean).join(". ")}}function BK(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:W_([...e.report?.artifacts??[],e.report?.patchRef,e.report?.diffRef]),testsRun:e.report?.testsRun??[],validationAttempts:e.progress.validationAttempts.map(n=>n.command),blockers:K_([...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:KK(e),updatedAt:Ui(e)}}function FK(e){const t=ys(e.data),n=[t?.run,ys(t?.message)?.run];for(const a of n){const o=Dx.safeParse(a);if(o.success)return o.data}return null}function VK(e){const t=pj.safeParse(ys(e.data)?.message);return t.success?t.data:null}function KK(e){const t=ys(ys(e.metadata?.workspaceHandoff)?.workspaceRetention);return t?.status!=="retained"?null:{status:"retained",reason:td(t.reason),retainedAt:td(t.retainedAt),expiresAt:td(t.expiresAt),retentionDays:WK(t.retentionDays),trigger:td(t.trigger),cleanupAfterExpiry:t.cleanupAfterExpiry===!0}}function Ui(e){return e.updatedAt??e.completedAt??e.startedAt??e.createdAt}function K_(e){return[...new Set(e.map(t=>t?.trim()).filter(t=>!!t))]}function W_(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 td(e){return typeof e=="string"&&e.trim()?e.trim():null}function nd(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function WK(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function GK(e){return e.slice(0,1).toUpperCase()+e.slice(1).replace(/[-_]+/g," ")}const mh=[];function ph(e,t){return G_(e,t,null)}function G_(e,t,n){const a=n&&XK(n.events,e)?JK(n.indexes,n.events.length,e):ZK(e),o=QK(t);return{...a,...o}}function ZK(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 YK(t)}function JK(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 v=n[h];if(!v.sessionId)continue;if(d.has(v.sessionId)){a.get(v.sessionId).push(v);continue}const y=a.get(v.sessionId);a.set(v.sessionId,y?[...y,v]:[v]),d.add(v.sessionId)}for(const h of d){const v=a.get(h)??mh,y=O_(v);y?o.set(h,y):o.delete(h);const w=J_(v);w?(i.set(h,w),w.tone==="active"?l.add(h):l.delete(h)):(i.delete(h),l.delete(h));const _=V_(v,h);_?(s.set(h,_),Z_({sessionEvents:v,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 YK(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=O_(l);m&&t.set(s,m);const d=J_(l);d&&(n.set(s,d),d.tone==="active"&&o.add(s))}for(const[s,l]of e){const m=V_(l,s);m&&(a.set(s,m),Z_({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 Z_(e){if(e.latestGoalRuntimeBySessionId.has(e.sessionId))return;const t=Xd(e.sessionEvents);t&&(e.latestGoalRuntimeBySessionId.set(e.sessionId,t),t.tone==="active"&&e.activeGoalSessionIds.add(e.sessionId))}function J_(e){return uh(e)??Rv(e)??Xd(e)}function QK(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||I0(i.createdAt)>I0(m.createdAt))&&o.set(i.sessionId,i)}return{approvalsById:t,approvalsByStatus:n,pendingApprovalsBySessionId:a,latestPendingApprovalBySessionId:o}}function XK(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 Ic(e,t){return t?e.eventsBySessionId.get(t)??mh:mh}function Y_(e,t){return t?e.latestContextUsageBySessionId.get(t)??null:null}function Q_(e,t){return t?e.latestGoalRuntimeBySessionId.get(t)??null:null}function e9(e,t){return t?e.latestSubagentRuntimeBySessionId.get(t)??null:null}function t9(e,t){return t?e.latestPendingApprovalBySessionId.get(t)??null:null}function I0(e){const t=Date.parse(e);return Number.isFinite(t)?t:Number.NEGATIVE_INFINITY}function n9(e,t){return e?.conversationId===t}function a9(e,t){return e?.id===t?null:e}function o9(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 r9(e){return JSON.stringify([e.source,e.repositoryId,e.profileId])}function HQ(e,t){return e.profiles.find(n=>r9(n.ref)===t)?.ref??null}function i9(e,t){return!!(e&&t&&e.source===t.source&&e.repositoryId===t.repositoryId&&e.profileId===t.profileId)}function zQ(e,t){return e.profiles.find(n=>i9(n.ref,t))?.state??null}function s9(e,t){const n=new Map(LN.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 l9(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 X_="openpond:last-chat-task-mode";function c9(e,t){return e==="labs"?"models":"chat"}function d9(e){try{return e.getItem(X_)==="work"?"work":"chat"}catch{return"chat"}}function Av(){if(typeof window>"u")return"chat";try{return d9(kc)}catch{return"chat"}}function u9(e,t){try{e.setItem(X_,t==="chat"?"chat":"work")}catch{}}function m9(e){if(!(typeof window>"u"))try{u9(kc,e)}catch{}}const p9="uploaded to a different account";function eC(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 ka(e,t){const n=eC(e,t);return n.state==="confirmed"?n.cloudProject:null}function f9(e,t){return eC(e,t).state==="different_account"?p9:null}function go(e){return e==="sandbox"||e==="sandbox_template"||e==="sandbox_app"}function tC(e={}){return{...e,workspaceTarget:"hybrid"}}function h9(e={}){return{...e,workspaceTarget:"local"}}function vo(e){return e?.metadata?.workspaceTarget==="hybrid"}function g9(e){return!!(e&&e.provider==="openpond"&&e.workspaceKind==="local_project"&&e.cloudProjectId&&e.title.trim().endsWith(" Cloud"))}function nC({cloudProjects:e,selectedCloudProject:t,selectedProject:n}){const a=n?.linkedSandboxProject??null,o=e?ka(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 aC({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:tC(),cwd:n.cwd,title:a}}function v9(e){return g.useEffect(()=>{const t=f_(e.selectedSession);!t||e.composerDraftStore.getSnapshot()||e.composerDraftStore.set(t)},[e.composerDraftStore,e.selectedSession?.id]),g.useCallback(async t=>{const n=t.trim();if(!e.connection||!n||e.activeExperience==="chat")return!1;const a=d6(n);try{let o;const i=e.selectedSession;if(i&&Jl(i))o=await Y.patchSession(e.connection,i.id,{title:a,metadata:Gp(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:ds}:{providerId:l,modelId:e.activeModel}),d=s?{workspaceTarget:s}:!i&&e.workspaceTarget==="local"?{workspaceTarget:"local"}:{};let h;if(!i&&e.workspaceTarget==="hybrid"){const v=nC({cloudProjects:e.cloudProjects,selectedCloudProject:e.selectedCloudProject,selectedProject:e.selectedProject});if(v.kind!=="ready")throw new Error(v.message);const y=aC({modelRef:m,provider:l,target:v,title:a});h={...y,experience:"work",metadata:Gp(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:Gp(d,n),title:a};o=await Y.createSession(e.connection,h),e.setSessions(v=>[o,...v])}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 b9=[];function y9({primary:e,secondary:t}){const[n,a]=g.useState(null),o=g.useRef(new Set),[i,s]=g.useState(!1),l=B3(),{composerDraftStore:m,appDispatch:d,pendingTerminalCommand:h,setPendingTerminalCommand:v,terminalTabs:y,setTerminalTabs:w,trainingDetailTasksetId:_,setTrainingDetailTasksetId:R,mentionedAppId:M,setMentionedAppId:C,cloudSetupDialog:N,setCloudSetupDialog:$,rightPanelTabRequest:j,workspaceDiffPanelViewState:k,mainComposerFocusRequestId:P,requestMainComposerFocus:T,projectConfirmDialog:U,resolveProjectConfirmDialog:B,query:D,searchOpen:W,archivedChatsOpen:se,sectionMenuOpen:me,cloudProjectsExpanded:Te,sidebarOpen:ke,view:V,selectedAppId:Re,selectedProjectId:be,selectedSessionId:ce,codexPermissionMode:ye,codexReasoningEffort:ne,busy:ge,diffPanelOpen:xe,diffPanelExpanded:De,rightPanelMode:we,activeExperience:ae,changeNewExperience:Se,terminalOpen:ze,settingsSection:Qe,newProjectDialogOpen:We,newProjectMode:nt,newProjectName:qe,newProjectPath:Ze,newProjectBusy:He,commitDialogOpen:L,commitMessage:O,commitIncludeUnstaged:z,commitNextStep:X,commitDraft:fe,branchDialogOpen:Me,branchDialogName:Le,toast:et,labDetailNavigation:Xe,setQuery:st,setSearchOpen:mt,setArchivedChatsOpen:Oe,setSectionMenuOpen:Ge,setCloudProjectsExpanded:f,setChatRowsVisibleCount:H,setSidebarOpen:Z,setView:le,setSelectedAppId:ee,setSelectedProjectId:F,setSelectedSessionId:I,setPrompt:G,setDraftProvider:ie,setDraftModel:te,setDraftExperience:oe,setDiffPanelOpen:ue,setDiffPanelExpanded:pe,setRightPanelMode:Ie,setTerminalOpen:je,setSettingsSection:Ne,setNewProjectDialogOpen:$e,setNewProjectName:at,setNewProjectPath:pt,setCommitDialogOpen:sn,setCommitMessage:At,setCommitIncludeUnstaged:nn,setCommitNextStep:un,setCommitDraft:mn,setBranchDialogOpen:qt,setBranchDialogName:_a,setError:Cn,showToast:Tt,applyBootstrapPayload:Wt,bootstrap:ut,connection:lt,startup:Fn,training:Gt,pinnedCollapsed:Ca,cloudProjectsCollapsed:Ra,chatsCollapsed:Qt,savedForLaterCollapsed:pn,sidebarWidth:rt,sidebarResizing:xn,diffPanelWidth:Pa,diffPanelResizing:Aa,togglePinnedCollapsed:ea,toggleCloudProjectsCollapsed:Ta,toggleChatsCollapsed:Nn,toggleSavedForLaterCollapsed:yo,startSidebarResize:Ea,startDiffPanelResize:K,selectedApp:Ue,selectedCloudProject:_e,selectedProject:Be,selectedProjectLinkedApp:vt,selectedSession:kn,sidebarSessions:Xt,runtimeIndexes:Ke,runtimeEventStore:Dn,chatMentionApps:St,connectedAppMentions:Rn,pendingApproval:Ma,pendingChatUserMessages:Yo,account:wn,activeModel:Vn,activeProvider:ta,appDefaults:Ga,startMessage:Za,organizations:ii,teamChatOrganization:na,teamChatTeamId:ja,teamChat:bt,publishTeamProfileAgent:si,communitySidebar:kr,communityView:Ts,teamAiThreadId:li,toggleTeamAiSidebar:Es,activeOpenPondCommandAccessMode:So,viewWorkspaceAppId:Ms,viewWorkspaceId:ci,viewWorkspaceKind:di,viewWorkspaceName:ui,selectedActionCatalog:js,expandedProjectIds:Os,expandProject:Ja,toggleProjectExpanded:$s,changeCodexPermissionMode:mi,changeCodexReasoningEffort:pi,changeOpenPondCommandAccessMode:fi,resolveApproval:Ns,beginNewChat:aa,beginNewChatWithTrainingModel:wr,dismissTrainingChatHandoff:hi,trainingChatHandoff:Ds,selectTrainingChatTaskForComposer:Ls,chatHistoryLoadStates:Ir,loadMoreSelectedChatHistory:xo,selectedPagedSessionEvents:Kn,activeSessions:Qo,archivedSessions:Us,pinnedSessions:gn,savedForLaterSessions:Hs,savedForLaterFiles:ca,sidebarFileBookmarks:Oa,setSidebarFileStatus:Xo,setSessions:Ya,projectRows:_r,localProjectRows:Cr,cloudProjectRows:zs,projectSessionRowsByProjectId:Rr,childSessionRowsByParentId:gi,sidebarProjectIdBySessionId:da,chatRows:vi,visibleChatRows:bi,chatRowsVisibleCount:er,sessionEvents:ua,goalRuntime:yi,subagentRuntime:Pr,visibleChatMessages:Qa,activeTerminalScope:Ar,terminalSummaries:ko,runningSessionIds:Si,selectedSessionRunning:xi,sidebarGoalRuntimeBySessionId:ki,sidebarSubagentRuntimeBySessionId:qs,taskDragSessionId:wi,taskPreviewSessionIds:Ii,startTaskDrag:Bs,clearTaskDrag:tr,previewTaskDrop:_i,commitTaskDrop:Tr,commitTaskPreviewDrop:Xa,dragItem:Fs,startPinnedDrag:Vs,clearSidebarDrag:Ks,previewPinnedDrop:Ws,commitPinnedDrop:eo,commitPinnedPreviewDrop:Ci,commandProjectRows:Gs,contextWindowStatus:Ri,pinnedRows:Zs,workspaceBusy:Ln,diffBusy:Js,visibleWorkspaceState:wo,visibleWorkspaceDiff:ct,refreshVisibleWorkspaceDiff:Zt,managedWorkspace:to,canSyncActiveWorkspace:vn,canPublishOpenPondProject:Pn,projectTarget:oa,workspaceTarget:Cc}=e,{title:Xu,browserConversationId:Ys,handleWorkspaceDiffPanelViewStateChange:em,openSessionInChat:Pi,changeProjectTarget:Qs,submitNewProjectDialog:Rc,changeWorkspaceBranch:tm,openCommitDialog:nm,openCreateWorkspaceBranchDialog:am,openDefaultsSettingsFromBranchDialog:om,runWorkspaceTool:rm,submitCommitDialog:im,submitCreateWorkspaceBranch:sm,syncWorkspaceLocally:lm,answerCreateImproveQuestion:cm,applyCreateImproveCandidate:dm,approveCreateImproveRun:um,cancelCreateImproveRun:Pc,changeDraftProvider:Ac,openCreateImprovePullRequest:mm,reconcileCreateImprovePullRequest:pm,rejectCreateImproveCandidate:Tc,pauseCreateImproveRun:Ec,resumeCreateImproveRun:fm,reviseCreateImproveRun:hm,stopTurn:Xs,archiveSession:Mc,restoreSession:gm,renameSession:el,toggleSessionPinned:vm,toggleProjectPinned:tl,toggleSessionSavedForLater:bm,moveProjectToCloud:nl,startCloudSetupUpload:ym,changeWorkspaceTarget:jc,sendPromptFromMainComposer:Sm,openSandboxWorkspace:Oc,openCloudProjectDialog:xm,openExistingProjectPathDialog:$c,openUrlInBrowserPanel:Nc,showBrowserPanel:km,showChangesPanel:wm,showGoalSidebarTab:Im,rightChatTrainingLaunchRequest:_m,setRightChatTrainingLaunchRequest:Cm,closeRightChatPanel:nr,openRightChatPanel:Ai,rightChatPanelViews:Rm,showRightChatPanel:Pm,showRightPanelDiffTab:Am,submitRightChatPrompt:Tm,activateRightChatPanel:Em,updateRightChatModel:Mm,updateRightChatPrompt:jm,updateRightChatProvider:Om,updateRightChatScrollState:$m,openProfileSettings:Nm,diagnosticEvents:Dm,toggleRightSidebar:Dc,removeProject:Lm}=t,$a=ut?.account.activeProfile&&ut?.preferences.defaultTeamId?`${ut.account.activeProfile.handle}:${ut.preferences.defaultTeamId}`:null;g.useEffect(()=>{if(!(!$a||V!=="chat"||l?.kind!=="chat"||l.sessionId||ce||o.current.has($a))){o.current.add($a);try{const Pe=localStorage.getItem(`openpond:ponder-mode:v1:${$a}`);(Pe==="clean"||Pe==="activity")&&a(Pe)}catch{}}},[$a,l,V,ce]),g.useEffect(()=>{if(!(!$a||!o.current.has($a)))try{localStorage.setItem(`openpond:ponder-mode:v1:${$a}`,n??"off")}catch{}},[$a,n]);const Ti=g.useCallback(Pe=>{ee(null),F(Pe),I(null),le("chat"),Ja(Pe),T()},[Ja,T,ee,F,I,le]),Um=g.useCallback((Pe=null)=>{a(null);const it=ce?da[ce]??null:null;if(!Pe&&it){Ti(it);return}aa(Pe)},[aa,Ti,ce,da]),Hm=g.useCallback(async Pe=>{if(!(!lt||!ut))try{const it=await Y.savePreferences(lt,{defaultTeamId:Pe});Wt({...ut,preferences:it.preferences})}catch(it){const jt=it instanceof Error?it.message:String(it);throw Cn(jt),Tt("Could not switch teams","error"),it}},[Wt,ut,lt,Cn,Tt]),zm=g.useCallback(async()=>{if(lt)try{const Pe=await Y.signOutOpenPondAccount(lt);Wt(Pe);const it=await Y.savePreferences(lt,{defaultTeamId:null});Wt({...Pe,preferences:it.preferences}),Tt("Logged out","success")}catch(Pe){const it=Pe instanceof Error?Pe.message:String(Pe);throw Cn(it),Tt("Could not log out","error"),Pe}},[Wt,lt,Cn,Tt]),al=ja??Ga.defaultTeamId??null,qm=g.useMemo(()=>_r.filter(Pe=>Pe.kind==="local"||al!==null&&Pe.project.teamId===al),[_r,al]),Bm=g.useMemo(()=>{const Pe={};for(const it of Qo){const jt=da[it.id];jt&&(Pe[jt]=(Pe[jt]??0)+1)}for(const it of Cr){if(it.kind!=="local")continue;const jt=it.project.linkedSandboxProject?.projectId;if(!jt||!it.cloudLinkTrusted)continue;const ma=yt("cloud",jt);Pe[it.id]=(Pe[it.id]??0)+(Pe[ma]??0)}return Pe},[Qo,Cr,da]),[ol,rl]=g.useState(null),[il,Lc]=g.useState(null),Er=s9(ut?.profile,ut?.extensionCatalog),[Ei,Mi]=g.useState(null),[sl,Mr]=g.useState(null),[ji,ll]=g.useState(null),Fm=g.useCallback(()=>{ee(null),F(null),I(null),Ge(null),le("team")},[Ge,ee,F,I,le]),jr=g.useCallback(()=>{ee(null),F(null),I(null),Ge(null),kr.discoverCommunities()},[kr.discoverCommunities,Ge,ee,F,I]),Vm=v9({activeExperience:ae,activeModel:Vn,activeOpenPondCommandAccessMode:So,activeProvider:ta,cloudProjects:ut?.cloudProjects??b9,composerDraftStore:m,connection:lt,requestComposerFocus:T,selectedCloudProject:_e,selectedProject:Be,selectedSession:kn,setMentionedAppId:C,setSelectedSessionId:I,setSessions:Ya,setView:le,showToast:Tt,workspaceTarget:Cc.value}),Km=g.useCallback(async Pe=>{if(!lt)throw new Error("OpenPond is not connected.");let it=ta,jt=Vn;it==="codex"&&(it=lh(ut?.providers,{enabledOnly:!0}).find(bn=>bn.value!=="codex")?.value??Gr,jt=Zd(it,ut?.providers)??Nl);const ma=Xt.find(bn=>bn.id===Pe.sourceSessionId),Io=await Y.createSession(lt,{experience:Pe.target,provider:it,modelRef:{providerId:it,modelId:jt},openPondCommandAccessMode:So,appId:null,appName:null,workspaceId:null,workspaceName:null,localProjectId:null,cloudProjectId:null,cloudTeamId:null,cwd:null,title:`Continue ${ma?.title??"task"}`.slice(0,120),metadata:{experienceHandoff:l9({sourceTaskId:Pe.sourceSessionId,sourceExperience:ma?.experience??null,targetExperience:Pe.target,sourceMessageIds:Pe.sourceMessageIds??[],sourceContext:Pe.sourceContext,output:Pe.output})}});return Ya(bn=>[Io,...bn]),oe(Pe.target),ie(it),te(jt),m.set(Pe.prompt),en({kind:"chat",sessionId:Io.id}),d({type:"selectSession",sessionId:Io.id,appId:null,projectId:null}),ee(null),F(null),je(!1),le("chat"),Ie("home"),ue(Pe.target==="work"),pe(!1),Io},[Vn,So,ta,d,ut?.providers,m,lt,pe,ue,oe,te,ie,Ie,ee,F,Ya,je,le,Xt]),Wm=g.useCallback(Pe=>{Mi(Pe),Mr(null),aa(null),Z(!0)},[aa,Z]),Gm=g.useCallback(Pe=>{aa(null),oe("work"),m.set(`$openpond-refiner-authoring ${Pe}`),le("chat"),Z(!0)},[aa,m,oe,Z,le]),Zm=g.useCallback(Pe=>{Mr(o9(Pe)),Mi(null),aa(null),Z(!0)},[aa,Z]);g.useEffect(()=>{!Ei&&!sl||V!=="chat"||ce||be||Re||(rl(Ei),Lc(sl),Mi(null),Mr(null),Ie("home"),pe(!1),ue(!0))},[Ei,sl,Re,be,ce,pe,ue,Ie,V]),g.useEffect(()=>{!ol&&!il||V==="chat"&&xe&&we==="home"||(rl(null),Lc(null))},[xe,il,ol,we,V]);const Jm=g.useCallback(()=>{rl(null),Lc(null),pe(!1),ue(!1)},[pe,ue]),Ym=g.useCallback(Pe=>{let it;if(Pe.workspaceKind==="local"){const jt=yt("local",Pe.workspaceId);it=`draft:${jt}`,ee(null),F(jt),I(null),Ja(jt),le("chat")}else{const jt=Xt.find(ma=>ma.id===Pe.sourceSessionId||ma.workspaceId===Pe.workspaceId);if(!jt){Tt("This saved file's cloud chat is no longer available.","error");return}it=jt.id,Pi(jt.id)}Ie("changes"),ue(!0),ll({id:Date.now(),conversationId:it,file:Pe}),Pe.available||Tt(`File unavailable: ${Pe.path}`,"error")},[Ja,Pi,ue,Ie,ee,F,I,le,Tt,Xt]);g.useEffect(()=>{if(!n9(ji,Ys))return;const Pe=window.setTimeout(()=>{Ie("changes"),ue(!0),ll(it=>a9(it,ji.id))},0);return()=>window.clearTimeout(Pe)},[Ys,ue,Ie,ji]);const Uc=c9(V);g.useEffect(()=>{if(l){if(l.kind==="models"||l.kind==="models_unavailable"){V!=="labs"&&le("labs");return}if(l.kind==="settings"){ee(null),F(null),I(null),Ne(l.section),V!=="settings"&&le("settings");return}if(l.kind==="view"){ee(null),F(null),I(null),V!==l.view&&le(l.view);return}l.sessionId!==null&&(a(null),ee(null),F(null)),I(l.sessionId),V!=="chat"&&le("chat")}},[l,ee,F,I,Ne,le,V]);const Hc=g.useCallback(Pe=>{if(Pe==="console"){_K(wn?.baseUrl??wn?.activeProfile?.baseUrl);return}if(Ge(null),ee(null),F(null),I(null),Pe==="models"){os(po()),le("labs");return}Pe==="chat"&&en({kind:"chat",sessionId:null}),Se(Av())},[wn?.baseUrl,wn?.activeProfile?.baseUrl,Se,en,Ge,ee,F,I,le]),Qm=g.useCallback(async(Pe,it)=>{const jt=await Gt.actions.acceptHarnessReview(Pe,it,{providerId:ta,modelId:Vn},ne);return jt?(R(jt.materializedTasksetId??null),os(po()),le("labs"),!0):(Tt("Taskset review could not be opened.","error"),!1)},[Vn,ta,ne,os,po,R,le,Tt,Gt.actions]);if(!Fn.ready)return x.jsx(yK,{startup:Fn});if(V==="settings")return x.jsx(g0,{showToast:Tt,children:x.jsx(hK,{settings:{payload:ut,connection:lt,diagnostics:Dm,initialSection:Qe,onPayload:Wt,onError:Cn,onToast:Tt,onOpenSourceSession:Pi,onStartRefinerAuthoring:Gm,onAcceptEvaluationReview:Qm,onOpenSkill:Wm,onOpenExtension:Zm,teamChatCurrentUserId:bt.currentUserId,teamChatEnabled:ja!==null,teamChatNotificationMode:bt.notificationMode,teamChatThreads:bt.threads,onTeamChatNotificationModeChange:bt.setNotificationMode,onTeamChatThreadMuteChange:bt.setThreadMuted,diffPanelWidth:Pa,diffPanelResizing:Aa,diffPanelExpanded:De,onDiffPanelResizeStart:K,onDiffPanelExpandedChange:pe,onBack:()=>{const Pe=H3(l);en(Pe),le(Pe.kind==="models"?"labs":"chat"),Z(!0)}},toast:{toast:et,onDismiss:()=>d({type:"field",key:"toast",value:null})}})});const Xm=Bu(),cl=lt?.platform??navigator.platform,ep=Xm&&cv(cl),ot=Ar,Jt=wo?.initialized?wo.repoPath:kn?.cwd??null,Ut={"--sidebar-width":`${rt}px`,"--diff-panel-width":`${Pa}px`},Bt=V==="chat"&&ae!=="chat"||V==="labs"||V==="scheduled"&&i||V==="team"&&!!li,Na=["app-shell",ep?"platform-macos":"",ke?"sidebar-open":"sidebar-closed",xn?"sidebar-resizing":"",Aa?"diff-panel-resizing":""].filter(Boolean).join(" "),dl=ce?Ir[ce]:null,sR=ce?dl?.cursorSequence??kK(To(Kn,Ic(Ke,ce))):null,lR=!!ce&&!!lt&&(Lt(ce)?!0:!!ut?.eventWindow?.hasMoreBefore&&!!sR)&&(dl?.hasMore??!0),cR=!!dl?.loading,dR=(()=>{const Pe=Gt.payload;if(!Pe)return{};const it=new Map(Pe.plans.map(bn=>[bn.id,bn])),jt=new Set(["queued","starting","running","cancelling","reconciling"]),ma={queued:"Queued",starting:"Starting",running:"Running",cancelling:"Cancelling",reconciling:"Reconciling"},Io={};for(const bn of[...Pe.modelRuns].sort((Da,Oi)=>Oi.updatedAt.localeCompare(Da.updatedAt))){if(bn.kind==="evaluation"||!["prepared","running"].includes(bn.status))continue;const Da=Pe.jobs.filter(tp=>tp.metadata.modelRunId===bn.id).sort((tp,uR)=>uR.updatedAt.localeCompare(tp.updatedAt))[0];if(Da&&!jt.has(Da.status))continue;const Oi=Da?.status??(bn.status==="prepared"?"starting":"running");Io[bn.modelId]={label:ma[Oi]??"Running",status:Oi}}for(const bn of[...Pe.jobs].sort((Da,Oi)=>Oi.updatedAt.localeCompare(Da.updatedAt))){if(!jt.has(bn.status))continue;const Da=it.get(bn.planId)?.modelId;!Da||Io[Da]||(Io[Da]={label:ma[bn.status]??"Active",status:bn.status})}return Io})();return x.jsx(g0,{showToast:Tt,children:x.jsx(fK,{className:Na,style:Ut,sidebar:{onOpenPonder:()=>{en({kind:"chat",sessionId:null}),I(null),le("chat"),a("activity")},productArea:Uc,modelProjects:(Gt.payload?.modelProjects??[]).filter(Pe=>Pe.hosted===null||Pe.hosted.teamId===(Ga.defaultTeamId?.trim()??null)),modelTrainingActivityByProjectId:dR,onProductAreaChange:Hc,experience:ae,view:V,selectedAppId:Re,selectedProjectId:be,selectedSessionId:ce,selectedTeamThreadId:bt.selectedThreadId,teamChatEnabled:ja!==null,organizations:ii,teamChatOrganization:na,teamChatLoading:bt.loading,currentUserId:bt.currentUserId,teamMembers:bt.members,teamThreads:bt.threads,...kr,account:wn,connection:lt,profile:ut?.profile,pinnedCollapsed:Ca,cloudProjectsCollapsed:Ra,chatsCollapsed:Qt,savedForLaterCollapsed:pn,archivedChatsOpen:se,cloudProjectsExpanded:Te,sectionMenuOpen:me,dragItem:Fs,taskDragSessionId:wi,taskPreviewSessionIds:Ii,activeSessions:Qo,archivedSessions:Us,pinnedRows:Zs,pinnedSessions:gn,savedForLaterSessions:Hs,savedForLaterFiles:ca,projectRows:_r,localProjectRows:Cr,cloudProjectRows:zs,projectSessionRowsByProjectId:Rr,childSessionRowsByParentId:gi,sidebarProjectIdBySessionId:da,terminalSummaries:ko,runningSessionIds:Si,goalRuntimeBySessionId:ki,subagentRuntimeBySessionId:qs,visibleChatRows:bi,chatRows:vi,chatRowsVisibleCount:er,expandedProjectIds:Os,currentVersion:ut?.server.version??null,platform:cl,arch:lt?.arch??null,onSidebarResizeStart:Ea,setSidebarOpen:Z,setView:le,setSelectedAppId:ee,setSelectedProjectId:F,setSelectedSessionId:I,setSearchOpen:mt,setSectionMenuOpen:Ge,setSettingsSection:Ne,onSelectTeam:Hm,onLogOut:zm,onTogglePinnedCollapsed:ea,onToggleCloudProjectsCollapsed:Ta,onToggleChatsCollapsed:Nn,onToggleSavedForLaterCollapsed:yo,setArchivedChatsOpen:Oe,setCloudProjectsExpanded:f,setChatRowsVisibleCount:H,beginNewChat:Um,beginProjectChat:Ti,onAddProject:$c,dockSessionRight:Ai,selectTeamThread:Pe=>{le("team"),bt.selectThread(Pe)},openTeamDm:Pe=>{le("team"),bt.openDm(Pe)},toggleSessionPinned:vm,toggleProjectPinned:tl,toggleSessionSavedForLater:bm,openSidebarFile:Ym,setSidebarFileStatus:(Pe,it)=>{Xo(Pe,it)},archiveSession:Mc,restoreSession:gm,renameSession:el,removeProject:Lm,expandProject:Ja,toggleProjectExpanded:$s,startPinnedDrag:Vs,clearSidebarDrag:Ks,previewPinnedDrop:Ws,commitPinnedDrop:eo,commitPinnedPreviewDrop:Ci,startTaskDrag:Bs,clearTaskDrag:tr,previewTaskDrop:_i,commitTaskDrop:Tr,commitTaskPreviewDrop:Xa},topBar:{sidebarOpen:ke,title:V==="chat"&&n?"Ponder Pal":Xu,backAction:Xe.backAction,breadcrumbs:Xe.breadcrumbs,conversationId:V==="chat"?ce:null,workspaceName:ui,workspaceId:ci,busy:ge,workspaceState:wo,workspaceKind:di,selectedApp:vt??Ue,selectedProject:Be,workspaceDiff:ct,managedWorkspace:to,workspaceBusy:Ln,defaultTeamId:Ga.defaultTeamId,showDiffControls:V==="chat"&&ae==="development",diffPanelOpen:xe,terminalOpen:ze,rightSidebarAvailable:Bt,rightSidebarOpen:V==="scheduled"?i:xe,onToggleDiffPanel:Dc,onToggleRightSidebar:V==="scheduled"?()=>s(Pe=>!Pe):V==="team"&&li?Es:Dc,onOpenSearch:()=>{Ge(null),mt(!0)},onToggleTerminal:()=>je(Pe=>!Pe),onRunTerminalCommand:Pe=>{v({id:Date.now(),scope:ot,command:Pe}),je(!0)},onWorkspaceToolAction:rm,onOpenCommitDialog:nm,onWorkspaceBranchChange:tm,onWorkspaceBranchCreate:am,connection:lt,onBootstrap:Wt,onOpenSandboxWorkspace:Oc,onShowSidebar:()=>Z(!0),onOpenTeamChat:Fm,onDiscoverCommunities:jr,collaborationView:V==="team"||V==="community"?V:null,platform:cl,showWorkspaceControls:V!=="team"&&V!=="community"&&V!=="labs"&&V!=="scheduled"&&V!=="outputs"&&V!=="projects"&&(ae==="development"||ae==="work"&&!!(Be||kn?.localProjectId||kn?.cloudProjectId||kn?.workspaceKind==="local_project"))},mainPane:{ponderMode:n,onPonderModeChange:a,experience:ae,onNewExperienceChange:Se,view:V,teamChat:{currentUserId:bt.currentUserId,members:bt.members,agents:bt.agents,profile:ut?.profile??null,teamId:ja,teamName:na?.displayName??null,detail:bt.detail,aiThread:bt.aiThread,agentConversation:bt.agentConversation,loading:bt.loading,busy:bt.busy,error:bt.error,connection:lt,providerSettings:ut?.providers??null,provider:ta,model:Vn,codexPermissionMode:ye,codexReasoningEffort:ne,openPondCommandAccessMode:So,contextWindowStatus:Ri,showToast:Tt,onProviderChange:Ac,onModelChange:te,onCodexPermissionModeChange:mi,onCodexReasoningEffortChange:pi,onOpenPondCommandAccessModeChange:fi,onOpenProviderSettings:()=>{Ne("providers"),le("settings"),en({kind:"settings",section:"providers"})},onSendMessage:bt.sendMessage,onPublishProfileAgent:si,onOpenAiThread:async Pe=>{await bt.openAiThread(Pe),Ie("chat"),ue(!0)},onOpenAgentConversation:async Pe=>{await bt.openAgentConversation(Pe),Ie("chat"),ue(!0)},onCloseAiThread:()=>ue(!1),onCloseAgentConversation:()=>{bt.closeAgentConversation(),ue(!1)},onSendAgentTurn:bt.sendAgentTurn,onSendAiTurn:bt.sendAiTurn,onStopAiTurn:bt.stopAiTurn,onEditMessage:bt.editMessage,onDeleteMessage:bt.deleteMessage,onRetryMessage:bt.retryMessage,onDismissFailedMessage:bt.dismissFailedMessage,onLoadMoreMessages:bt.loadMoreMessages,onRetryLoad:bt.refresh},community:Ts,bootstrap:ut,runtimeEvents:ua,chatMessages:Qa,pendingUserMessage:ce?Yo[ce]??null:null,contextWindowStatus:Ri,goalRuntime:yi,subagentRuntime:Pr,selectedSessionId:ce,composerDraftStore:m,mainComposerFocusRequestId:P,labCloseDetailRequestId:Xe.closeDetailRequestId,labCloseDetailKind:Xe.closeDetailKind,sideChatTrainingLaunchRequest:_m,onSideChatTrainingLaunchHandled:Pe=>Cm(it=>it?.id===Pe?null:it),mentionApps:St,connectedAppMentions:Rn,profileSkills:Er,selectedMentionAppId:M,busy:ge,turnRunning:xi,activeProvider:ta,activeModel:Vn,codexPermissionMode:ye,codexReasoningEffort:ne,openPondCommandAccessMode:So,pendingApproval:Ma,activeWorkspaceAppId:Ms,activeWorkspaceId:ci,activeWorkspaceKind:di,projectTarget:oa,actionCatalog:js,workspaceTarget:Cc,connection:lt,workspaceName:ui,workspaceState:wo,workspaceDiff:ct,workspaceBusy:Ln,diffBusy:Js,forceChatThread:!!ce,diffPanelOpen:xe,diffPanelExpanded:De,rightPanelMode:we,rightPanelTabRequest:j,rightChatPanels:Rm,runtimeEventStore:Dn,nativeSkillSidebar:ol,extensionSkillSidebar:il,workspaceDiffPanelViewState:k,sidebarFileOpenRequest:ji,sidebarFileBookmarks:Oa,onSetSidebarFileStatus:(Pe,it)=>{Xo(Pe,it)},browserConversationId:Ys,terminalScope:ot,terminalTabs:y,terminalCwd:Jt,pendingTerminalCommand:h,terminalOpen:ze,onToggleTerminal:()=>je(Pe=>!Pe),onWorkspaceDiffPanelViewStateChange:em,training:Gt,trainingSessions:Xt,trainingChatHandoff:Ds,trainingDetailTasksetId:_,onTrainingDetailTasksetIdChange:R,onTrainingChatTaskSelect:Ls,onTrainingChatHandoffDismiss:hi,onOpenSession:Pi,onExperienceHandoff:Km,cloudProjects:ut?.cloudProjects??[],projects:qm,projectsAccountBaseUrl:wn?.baseUrl??wn?.activeProfile?.baseUrl??null,projectsTeamName:na?.displayName??null,projectTaskCounts:Bm,onNewCloudProject:xm,onNewLocalProject:$c,onNewProjectTask:Pe=>Ti(Pe.id),onToggleProjectPinned:tl,onUploadLocalProject:nl,chatHistoryHasMore:lR,chatHistoryLoading:cR,onDiffPanelResizeStart:K,onToggleDiffPanelExpanded:()=>pe(Pe=>!Pe),onShowDiffPanel:wm,onShowBrowserPanel:km,onShowFilesPanel:()=>Am("files"),onShowGoalSidebarTab:Im,onShowTrainingDraftPanel:()=>{Ie("training"),ue(!0)},onShowRightChatPanel:Pm,onAddRightChat:()=>Ai(null),onOpenRightChatForSession:(Pe,it)=>{const jt=it??Xt.find(ma=>ma.id===Pe)??null;jt&&Ai(jt,{preserveView:!0})},onLabDetailOpenChange:Xe.onDetailOpenChange,scheduledDetailOpen:i,onScheduledDetailOpenChange:s,onTerminalTabsChange:w,onCloseRightChatPanel:nr,onCloseNativeSkillSidebar:Jm,onActivateRightChatPanel:Em,onRightChatModelChange:Mm,onRightChatPromptChange:jm,onRightChatScrollStateChange:$m,onRightChatProviderChange:Om,onSubmitRightChat:Tm,onStopRightChat:Pe=>Xs(Pe),onCloseTerminal:()=>je(!1),onLoadMoreChatHistory:xo,canSyncWorkspace:vn,startMessage:Za,onPayload:Wt,onError:Cn,setView:le,onOpenProfileSettings:Nm,onOpenProviderSettings:()=>{en({kind:"settings",section:"providers"})},onOpenTrainingSettings:()=>{en({kind:"settings",section:"training"})},onOpenDatasetStorageSettings:()=>{en({kind:"settings",section:"dataset-storage"})},changeDraftProvider:Ac,changeProjectTarget:Qs,changeWorkspaceTarget:jc,setDraftProvider:ie,setDraftModel:te,onBeginNewChatWithModel:wr,changeCodexPermissionMode:mi,changeCodexReasoningEffort:pi,changeOpenPondCommandAccessMode:fi,resolveApproval:Ns,answerCreateImproveQuestion:cm,applyCreateImproveCandidate:dm,approveCreateImproveRun:um,cancelCreateImproveRun:Pc,openCreateImprovePullRequest:mm,reconcileCreateImprovePullRequest:pm,rejectCreateImproveCandidate:Tc,pauseCreateImproveRun:Ec,resumeCreateImproveRun:fm,reviseCreateImproveRun:hm,setMentionedAppId:C,showToast:Tt,onSaveTaskDraft:Vm,sendPrompt:Sm,stopTurn:Pe=>Xs(void 0,Pe),syncWorkspaceLocally:lm,refreshWorkspaceDiff:Zt},cloudSetup:{state:N,onClose:()=>$(null),onOpenBrowserUrl:Nc,onStart:()=>{ym()}},projectConfirm:{state:U,onResolve:B},lazyPanels:{activeSessions:Qo,branchDialogName:Le,branchDialogOpen:Me,commitDialogOpen:L,commitDraft:fe,commitIncludeUnstaged:z,commitMessage:O,commitNextStep:X,canPublishOpenPondProject:Pn,connection:lt,expandProject:Ja,newProjectBusy:He,newProjectDialogOpen:We,newProjectDirectory:Ga.defaultNewProjectDirectory,newProjectMode:nt,newProjectName:qe,newProjectPath:Ze,projectRows:Gs,query:D,searchOpen:W,visibleWorkspaceDiff:ct,visibleWorkspaceState:wo,workspaceBusy:Ln,appDispatch:d,beginNewChat:()=>aa(null),openDefaultsSettingsFromBranchDialog:om,setBranchDialogName:_a,setBranchDialogOpen:qt,setCommitDialogOpen:sn,setCommitDraft:mn,setCommitIncludeUnstaged:nn,setCommitMessage:At,setCommitNextStep:un,setNewProjectDialogOpen:$e,setNewProjectName:at,setNewProjectPath:pt,setPrompt:G,setQuery:st,setSearchOpen:mt,submitCommitDialog:im,submitCreateWorkspaceBranch:sm,submitNewProjectDialog:Rc},toast:{toast:et,onDismiss:()=>d({type:"field",key:"toast",value:null})}})})}const Ji=new Map,_d=new Map;function fh(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 S9(e){const t=e?.trim();if(!t)return null;const n=Ji.get(t);return n?.updatedAt?n.organizations:null}function x9(e,t){const n=e?.trim();if(n){Ji.set(n,{organizations:t,promise:null,updatedAt:Date.now()});for(const a of _d.get(n)??[])a()}}function k9(e,t){const n=e?.trim();if(!n)return()=>{};const a=_d.get(n)??new Set;return a.add(t),_d.set(n,a),()=>{a.delete(t),a.size===0&&_d.delete(n)}}function _0(e){const t=e.accountKey?.trim();if(!t)return Promise.resolve([]);const n=Ji.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=>(x9(t,o),o)).catch(o=>{const i=Ji.get(t);throw i?.promise===a&&Ji.set(t,{organizations:i.organizations,promise:null,updatedAt:i.updatedAt}),o});return Ji.set(t,{organizations:n?.organizations??[],promise:a,updatedAt:n?.updatedAt??0}),a}const BQ="openpond.config.json";function FQ(e,t,n){return t<=0?-1:n==="Home"?0:n==="End"?t-1:n==="ArrowRight"?(e+1)%t:(e-1+t)%t}function oC(){return{activeTab:"files",openFilePaths:[],selectedPath:null}}function tf(e){return{activeTab:e.activeTab,openFilePaths:[...e.openFilePaths],selectedPath:e.selectedPath}}function VQ(e,t=null){const n=I9(e.openFilePaths.map(o=>R0(o,t)).filter(Boolean)),a=e.selectedPath&&R0(e.selectedPath,t)||null;return{activeTab:e.activeTab==="file"&&!a?"files":e.activeTab,openFilePaths:n,selectedPath:a}}function C0(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 R0(e,t=null){let n=w9(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 KQ(e){return e.startsWith("/")||/^[A-Za-z]:\//.test(e)}function WQ(e){return{path:e,status:"unchanged",additions:0,deletions:0,patch:"",content:null}}function GQ(e,t){const n=P0(e.path);return!n||e.path.endsWith("/")||e.content==null&&/Could not access .+\/null['"]?/.test(e.patch)?!0:t.some(a=>{const o=P0(a);return!!(o&&o.startsWith(`${n}/`))})}function ZQ(e){return/\.(?:md|markdown|mdx)$/i.test(e)||/(?:^|\/)readme$/i.test(e)}function JQ(e){return/\.(?:doc|docx|pdf)$/i.test(e)}function w9(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 I9(e){return Array.from(new Set(e))}function P0(e){const n=e.replace(/\\/g,"/").replace(/^\.\/+/,"").split("/").filter(Boolean);return n.length===0?null:n.join("/")}function _9(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 rC(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"cloud-project"}function C9(e){const t=new TextEncoder().encode(e);let n="";for(const a of t)n+=String.fromCharCode(a);return btoa(n)}function Ku(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||rC(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 R9(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 P9(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 A9(...e){for(const t of e){const n=t?.trim();if(n)return n}return""}function T9({draftProvider:e,hasSelectedCloudProject:t,selectedSessionHybridWorkspace:n}){return t&&!n?"openpond":e}const E9=[{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 M9(...e){return A9(...e.map(t=>{const n=t?.trim();return n&&!n.includes("@")?n:null}))}function j9(e){if(e?.state!=="signed_in")return"";const t=e.accounts.find(n=>n.isActive)??null;return M9(e.profile?.name,e.label,t?.displayLabel,e.profile?.handle,t?.handle,e.activeProfile?.handle)}function O9({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,v=Lt(m)&&!l,y=l?go(l.workspaceKind):!1,w=vo(l),_=l?g9(l):!1,R=l?.cwd&&(!y||w)?dk(l.cwd):null,M=e?.providers??null,C=ka(s,e?.cloudProjects??[]),N=T9({draftProvider:n,hasSelectedCloudProject:!!i,selectedSessionHybridWorkspace:w}),$=Sr(N,t,M),j=fa(e?.preferences),k=v?null:l?y?l.workspaceKind??"sandbox":_?"sandbox":h?"local_project":l.workspaceKind??(l.appId?"sandbox_app":R?"local_project":null):i?"sandbox":s?"local_project":o?"sandbox_app":null,P=v?null:l?y&&!w||_?null:h||(l.workspaceId??l.appId??R):i?null:s?.id??o,T=v?null:l?y?l.workspaceId??null:_?null:h??l.workspaceId??l.appId??R: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=j9(U),me=se?`Welcome, ${se}`:"Welcome",Te=l?.workspaceName??l?.appName??i?.name??s?.name??a?.name??null,ke=go(k)?"cloud":"local",V=s?.name??d?.name??(l?.workspaceKind==="local_project"?l.workspaceName:null)??"Local workspace",Re=(ke==="cloud"?Te:null)??i?.name??C?.name??s?.name??"Cloud workspace",be=!!(i?.id||C?.id||l?.cloudProjectId||ke==="cloud");return{account:U,accountLabel:W,accountPending:B,accountSignedOut:D,activeModel:$,activeProvider:N,activeWorkspaceAppId:P,activeWorkspaceId:T,activeWorkspaceKind:k,activeWorkspaceLocation:ke,appDefaults:j,cloudLinked:be,cloudTargetName:Re,localTargetName:V,selectedCodexHistoryPending:v,selectedSessionCloudWorkspace:y,selectedSessionLocalPathWorkspaceId:R,selectedSessionPendingCloudStart:_,selectedSessionProjectId:h,startMessage:me,workspaceName:Te}}function $9({accountPending:e,accountSignedOut:t,activeWorkspaceLocation:n,bootstrap:a,busy:o,cloudLinked:i,selectedCloudProject:s,selectedProject:l,selectedSession:m,pendingWorkspaceTarget:d,workspaceStates:h,workspaceBusy:v}){const y=ka(l,a?.cloudProjects??[]),_=!!!l?.linkedSandboxProject?.projectId||!!y,R=g.useMemo(()=>{const T=(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=[...T,...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:v||o,options:[...T,...U,...E9,{value:"none",label:"Don't work in a project",detail:"General chat without project files",kind:"none"}]}},[a?.cloudProjects,a?.localProjects,o,s,l,v]),M=!!(i||l),C=!!(s?.id||y?.id||m?.cloudProjectId||vo(m)),N=l?h[l.id]??null:null,$=x_(N,{branch:l?.linkedSandboxProject?.defaultBranch??null,path:l?.workspacePath??m?.cwd??null,linkedCloudSourceKnown:l?.linkedSandboxProject?.projectId&&_?!!l.linkedSandboxProject.lastUploadedCommit||!N?.headCommit:!0}),j=k_(l,s??y,N,{cloudLinkTrusted:_}),k=_6(l,N,{cloudLinkTrusted:_}),P=g.useMemo(()=>{const T={value:"local",label:l?"Local checkout":"Local",detail:l?"Use the selected checkout on this machine.":"Use an app-managed task workspace on this machine.",stateNote:l?$:"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:k,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"?T:B;let me=n==="cloud"?B:T;return d==="cloud"?me=B:d==="local"?me=T:(vo(m)||d==="hybrid")&&(me=U),{value:me.value,label:me.label,detail:me.stateNote||me.detail,busy:v,action:{...se,label:W==="cloud"?"Hosted":l?"Local checkout":"Check out locally"},uploadAction:l?D:null,options:[T,U,B]}},[n,e,t,i,M,j,C,$,d,l,m,k,v]);return{projectTarget:R,workspaceTarget:P}}function $n(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")}function iC(e){return $n(e.name||e.gitRepo||e.id)}function YQ(e){return`@${iC(e)}`}function sC(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>$n(t[1]??"")).filter(Boolean)}function N9(e,t){const n=sC(e);if(n.length===0)return!1;const a=new Set([$n(t.id),iC(t),t.gitRepo?$n(t.gitRepo):""].filter(Boolean));return n.some(o=>a.has(o))}function lC(e){return e.filter(t=>t.sandbox)}function D9(e,t){const n=sC(e);if(n.length===0)return null;const a=new Map;for(const o of n){const i=t.find(s=>{const l=$n(s.id),m=$n(s.name),d=s.gitRepo?$n(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 QQ(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:$n(a[1]??""),start:a.index+o}}function L9(e){return new Set(e.map(t=>t.id))}function A0(e,t){const n=e?.linkedOpenPondApp??null;return n?.appId&&t.has(n.appId)?n:null}function U9({bootstrap:e,codexHistorySessions:t,selectedProjectId:n,selectedSessionId:a,selectedAppId:o,sessions:i}){const s=g.useMemo(()=>e?.apps.find(D=>D.id===o)??null,[e?.apps,o]),l=g.useMemo(()=>new Map((e?.localProjects??[]).map(D=>[D.id,D])),[e?.localProjects]),m=g.useMemo(()=>new Map((e?.cloudProjects??[]).map(D=>[D.id,D])),[e?.cloudProjects]),d=g.useMemo(()=>c_(n),[n]),h=g.useMemo(()=>d?.kind==="local"?l.get(d.id)??null:null,[l,d]),v=g.useMemo(()=>d?.kind==="cloud"?m.get(d.id)??null:null,[m,d]),y=g.useMemo(()=>L9(e?.apps??[]),[e?.apps]),w=g.useMemo(()=>lC(e?.apps??[]),[e?.apps]),_=g.useMemo(()=>{const D=[];for(const W of e?.localProjects??[]){const se=A0(W,y);se&&D.push([se.appId,W.id])}return new Map(D)},[e?.localProjects,y]),R=g.useMemo(()=>new Set((e?.localProjects??[]).map(D=>D.id)),[e?.localProjects]),M=g.useMemo(()=>h_(e?.localProjects??[]),[e?.localProjects]),C=g.useRef([]),N=g.useMemo(()=>H9(i,t,C.current),[t,i]),$=g.useMemo(()=>N.find(D=>D.id===a)??null,[N,a]),j=g.useMemo(()=>{if(!$)return null;if($.localProjectId)return l.get($.localProjectId)??null;if($.workspaceKind==="local_project")return $.workspaceId?l.get($.workspaceId)??null:null;const D=f6($,R,M);if(D)return l.get(D)??null;if(!$.appId)return null;const W=_.get($.appId);return W?l.get(W)??null:null},[_,l,R,M,$]),k=g.useMemo(()=>$?.cloudProjectId?m.get($.cloudProjectId)??null:null,[m,$]),P=h??j,T=v??k,U=g.useMemo(()=>A0(P,y),[y,P]),B=g.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:T,selectedProject:P,selectedProjectLinkedApp:B,selectedProjectLinkedOpenPondApp:U,selectedSession:$,selectedSessionLinkedProject:j,sidebarSessions:N}}function H9(e,t,n){const a=new Map;for(const d of e){const h=T0(d);a.set(h,d)}for(const d of t){const h=T0(d),v=a.get(h);a.set(h,v?z9(v,d):d)}const o=Array.from(a.entries());if(!n)return o.sort((d,h)=>E0(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)=>E0(d[1],h[1])),...i];return n.splice(0,n.length,...m.map(([d])=>d)),m.map(d=>d[1])}function z9(e,t){return{...e,metadata:q9(e.metadata,t.metadata),status:e.status==="active"||t.status==="active"?"active":e.status,updatedAt:B9(e.updatedAt,t.updatedAt)}}function T0(e){return e.codexThreadId?`codex:${e.codexThreadId}`:`session:${e.id}`}function E0(e,t){const n=M0(t)-M0(e);return n!==0?n:e.title.localeCompare(t.title)}function q9(e,t){const n={...e??{},...t??{}};return Object.keys(n).length>0?n:void 0}function B9(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 M0(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 F9(e){return!!(e&&go(e.workspaceKind)&&!vo(e)&&e.provider!=="openpond")}function V9(e,t){const n=m_(e,t);return`${e.id}\0${n.provider}\0${n.model}`}function K9({activeWorkspaceId:e,activeWorkspaceKind:t,appDispatch:n,connection:a,expandProject:o,linkedProjectByAppId:i,providerSettings:s,selectedAppId:l,selectedSession:m,selectedSessionId:d,selectedSessionProjectId:h,setDiffPanelExpanded:v,setDraftModel:y,setDraftProvider:w,setError:_,setSelectedAppId:R,setSelectedProjectId:M,setSessions:C,setTerminalOpen:N,toast:$}){const j=g.useRef(null);g.useEffect(()=>{if(!l)return;const k=h??(d?null:i.get(l)??null);if(!k)return;const P=yt("local",k);R(null),M(P),o(P)},[o,i,l,d,h,R,M]),g.useEffect(()=>{if(!$||$.persistent)return;const k=window.setTimeout(()=>{n({type:"clearToast",toastId:$.id})},$.durationMs??($.tone==="error"?7e3:3500));return()=>window.clearTimeout(k)},[n,$]),g.useEffect(()=>{function k(P){(P.metaKey||P.ctrlKey)&&P.key==="`"&&(P.preventDefault(),N(T=>!T))}return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[N]),g.useEffect(()=>{v(!1)},[e,t,v]),g.useEffect(()=>{if(!d){j.current=null;return}if(!m||m.id!==d)return;const k=V9(m,s);if(j.current===k)return;j.current=k;const P=m_(m,s);w(P.provider),y(P.model)},[s,m,d,y,w]),g.useEffect(()=>{!a||!m||!F9(m)||Y.patchSession(a,m.id,{provider:"openpond"}).then(k=>{C(P=>P.map(T=>T.id===k.id?k:T)),w("openpond"),y(P=>Sr("openpond",P))}).catch(k=>{_(k instanceof Error?k.message:String(k))})},[a,m,y,w,_,C])}function W9({connection:e,setError:t}){return g.useCallback(async(n,a)=>{if(!e){const o=new Error("OpenPond App server is not connected.");throw t(o.message),o}t(null);try{await Y.resolveApproval(e,n,{decision:a})}catch(o){const i=o instanceof Error?o.message:String(o);throw t(i),o}},[e,t])}function G9({activeProvider:e,contextCompaction:t,contextUsage:n,pinnedItems:a,pinnedPreviewKeys:o,pinnedProjects:i,projectRows:s,visibleProjectRows:l}){const m=g.useMemo(()=>t6(a,o),[a,o]),d=g.useMemo(()=>$_({provider:e,snapshot:n,preferences:t}),[e,t,n]),h=g.useMemo(()=>Array.from(new Set([...i,...l].filter(yv).map(y=>y.project.id))),[i,l]);return{commandProjectRows:g.useMemo(()=>s,[s]),contextWindowStatus:d,pinnedRows:m,sidebarWorkspaceAppIds:h}}function Z9({appDispatch:e,expandProject:t,linkedProjectByAppId:n,requestComposerFocus:a,onBeginNewChat:o,setMentionedAppId:i}){return g.useCallback((s=null)=>{o?.();const l=s?.id?n.get(s.id)??null:null;if(l){const 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 cC={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 XQ(e){return`@${e.token}`}function J9(e){return`@${tW(e)}`}function Y9(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=Hi(a.flatMap(v=>v.capabilities.map(y=>y.id))),s=Hi(a.flatMap(v=>v.capabilityLabels)),l=Hi(a.flatMap(v=>v.connections.map(y=>y.id).filter(aW))),m=Hi(a.map(v=>v.id)),d=Hi(a.map(v=>v.setupSurface)),h=eW(n);return{provider:n,label:o.providerLabel,detail:s.length>0?s.slice(0,4).join(", "):o.description,token:h,tokens:X9(a),ref:{kind:"integration",provider:n,appIds:m,setupSurfaces:d,...l.length>0?{connectionIds:l}:{},...i.length>0?{capabilities:i}:{}}}})}function eX(e,t){const n=$n(t);return e.filter(a=>n?a.tokens.some(o=>o.includes(n)):!0).slice(0,8)}function Q9(e,t){const n=nW(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 tX(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=$n(o);if(!i)continue;const s=t.find(v=>v.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:J9(s),end:d+h.length,label:s.label,provider:s.provider,start:d,text:h})}return n}function X9(e){return Hi(e.flatMap(t=>[...cC[t.providerFamily],t.providerFamily,t.id,t.label,t.shortLabel]).map($n).filter(Boolean))}function eW(e){return $n(cC[e][0]??e)}function tW(e){return e.provider==="github"?"GitHub":e.provider==="x"?"X":e.provider==="mcp"?"MCP":e.label}function nW(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>$n(t[1]??"")).filter(Boolean)}function Hi(e){return Array.from(new Set(e))}function aW(e){return typeof e=="string"&&e.length>0}function oW({bootstrap:e,connectedAppRows:t,mentionableSandboxApps:n,runtimeIndexes:a,selectedApp:o,selectedCloudProject:i,selectedProject:s,selectedSession:l,selectedSessionId:m}){const d=g.useMemo(()=>{const _=new Map;for(const R of e?.cloudProjects??[]){const M=_.get(R.teamId)??[];M.push(R.id),_.set(R.teamId,M)}return _},[e?.cloudProjects]),v=!!(l||o||s||i)?[]:n,y=g.useMemo(()=>Y9(t),[t]),w=g.useMemo(()=>t9(a,m),[a,m]);return{chatMentionApps:v,cloudProjectIdsByTeam:d,connectedAppMentions:y,pendingApproval:w}}function rW({connection:e,setBootstrap:t,setCodexPermissionMode:n,setCodexReasoningEffort:a,setError:o}){const i=g.useCallback(l=>{if(!e){o("Connect to OpenPond before saving preferences.");return}Y.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=g.useCallback(l=>{if(!e){o("Connect to OpenPond before saving preferences.");return}Y.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 iW=6e4;function Tv(e,t){if(!e)return t;const n=lW(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 uC(e,n)?e:n}function sW(e,t){const n=Tv(e,t),a=e?{...n,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order,updatedAt:e.updatedAt}:n;return e&&uC(e,a)?e:a}function kl(e,t){let n=!1,a=!1;const o=e.map(i=>{if(i.id!==t.id)return i;n=!0;const s=Tv(i,t);return s!==i&&(a=!0),s});return n?a?o:e:[t,...e]}function Wu(e,t){let n=!1,a=!1;const o=e.map(i=>{if(i.id!==t.id)return i;n=!0;const s=sW(i,t);return s!==i&&(a=!0),s});return n?a?o:e:[t,...e]}function hh(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=dW(s,i,n,a);if(l)return l}return Tv(s,i)})}function j0(e,t,n,a=Date.now()){const o=new Map(e.map(d=>[d.id,d])),i=new Map(hh(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||(dC(d,t)?d:null)}).filter(d=>!!d);return[...l,...m]}function dC(e,t){const n=Date.parse(e.updatedAt);if(!Number.isFinite(n))return!1;const a=cW(t);return a===null||n>=a}function O0(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&&(mC(s,i)||(e[i.id]=a))}}function lW(e,t){const n=Date.parse(e),a=Date.parse(t);return Number.isFinite(n)&&Number.isFinite(a)&&n>a}function uC(e,t){return JSON.stringify(e)===JSON.stringify(t)}function cW(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 dW(e,t,n,a){const o=n[t.id];return o===void 0?null:a-o>iW||mC(e,t)?(delete n[t.id],null):{...t,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order}}function mC(e,t){return e.pinned===t.pinned&&e.savedForLater===t.savedForLater&&e.archived===t.archived&&e.order===t.order}const pC=800,uW=5e3,$0=5e4,mW=16,pW=3e4,Zn=new Map;function fW(e,t){return Zn.get(hC(e,t))?.payload??null}async function fC(e,t,n={}){const a=hC(e,t),o=Zn.get(a),i=n.limit??pC,s=n.tail??!0;if(o?.promise)return o.promise;if(!n.force&&s&&o?.payload&&Date.now()-o.fetchedAt<=pW)return N0(a,o),o.payload;const l=!!(n.force&&s&&o?.payload),m=l?o?.payload?.events.at(-1)?.id:void 0,d=Y.codexHistoryThreadIncremental(e,t,{afterEventId:m,limit:i,revision:l?o?.revision:void 0,tail:s}).then(h=>{const v=Zn.get(a)?.payload??o?.payload;if(h.unchanged){if(!v)throw new Error("Codex history revision matched without a cached thread.");return Zn.set(a,{fetchedAt:Date.now(),payload:v,revision:h.revision}),N0(a,Zn.get(a)),v}const y={session:h.session,events:h.events},w=s&&v&&!h.reset?{...y,events:hW(v.events,y.events)}:y;return Zn.set(a,{fetchedAt:Date.now(),payload:w,revision:h.revision}),D0(),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}),D0(),d}function hC(e,t){return`${e.serverUrl}
|
|
185
|
+
${e.token}
|
|
186
|
+
${t}`}function N0(e,t){Zn.delete(e),Zn.set(e,t)}function D0(){for(;Zn.size>mW;){const e=Zn.keys().next().value;if(!e)return;Zn.delete(e)}}function hW(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 gW=500,vW=2500,bW=15e3;function yW(e){return e.active?gW:e.surface==="thread"?vW:bW}function Ev(e,t){return!t||e.session.status==="active"?e:{...e,session:{...e.session,status:"active"}}}function SW(e={}){const t={cachedPayload:e.cachedPayload??fW,clearTimer:e.clearTimer??(d=>globalThis.clearTimeout(d)),loadPayload:e.loadPayload??fC,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=kW(d.connection,d.sessionId);let v=n.get(h);v||(v={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,v));const y=a++;return v.subscribers.set(y,d),v.latestPayload&&d.onPayload(v.latestPayload),i(v,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 v=t.now()+Math.max(0,h);d.timer&&d.nextRefreshAt!==null&&d.nextRefreshAt<=v||(m(d),d.nextRefreshAt=v,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 v=await h;if(d.disposed||v===d.latestPayload)return;d.latestPayload=v;for(const y of d.subscribers.values())y.onPayload(v)}catch(v){if(d.disposed)return;for(const y of d.subscribers.values())y.onError?.(v)}finally{d.inFlight===h&&(d.inFlight=null),d.disposed||i(d,l(d))}}function l(d){const h=[...d.subscribers.values()],v=h.some(w=>w.locallyActive||w.reportedActive)||d.latestPayload?.session.status==="active"||Rv(d.latestPayload?.events??[])?.tone==="active",y=h.some(w=>w.surface==="thread")?"thread":"sidebar";return yW({active:v,surface:y})}function m(d){d.timer&&t.clearTimer(d.timer),d.timer=null,d.nextRefreshAt=null}return{subscribe:o}}const xW=SW();function Mv(e){return xW.subscribe(e)}function kW(e,t){return`${e.serverUrl}
|
|
187
|
+
${e.token}
|
|
188
|
+
${t}`}function wW({connection:e,selectedSessionId:t,selectedSessionLocallyActive:n,selectedSessionStatus:a,setCodexHistorySessions:o,setError:i}){const[s,l]=g.useState({events:[],sessionId:null}),m=Lt(t)?t:null,d=m&&s.sessionId===m?s.events:[],h=g.useCallback(v=>{l(y=>{if(!m)return{events:[],sessionId:null};const w=y.sessionId===m?y.events:[];return{events:typeof v=="function"?v(w):v,sessionId:m}})},[m]);return g.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 v=n;return Mv({connection:e,locallyActive:v,onError:w=>i(w instanceof Error?w.message:String(w)),onPayload:w=>{const _=Ev(w,v);l(R=>R.sessionId!==m?{events:_.events,sessionId:m}:{events:To(R.events,_.events),sessionId:m}),i(R=>R==="Session not found"?null:R),o(R=>Wu(R,_.session))},reportedActive:a==="active",sessionId:m,surface:"thread"})},[e,m,n,a,o,i]),{codexHistoryEvents:d,setCodexHistoryEvents:h}}function gC(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 IW({connection:e,appPreferences:t,sessions:n,pinnedItems:a,setAppPreferences:o,setCodexHistorySessions:i,setSessions:s,sidebarFileBookmarks:l,setSidebarFileBookmarks:m,setError:d}){const[h,v]=g.useState(null),[y,w]=g.useState(null),_=g.useRef(null),R=g.useRef(null);function M(P,T){P.dataTransfer.effectAllowed="move",P.dataTransfer.setData("text/plain",`${T.type}:${T.id}`),gC(P);const U=a.map(B=>B.key);_.current=T,R.current=U,v(T),w(U)}function C(){_.current=null,R.current=null,v(null),w(null)}function N(P,T){const U=_.current;if(!U)return;const B=Wd(P),D=R.current??a.map(se=>se.key),W=Gd(D,Br(U),Br(T),B);e0(D,W)||(R.current=W,w(W))}function $(P){if(!e)return;const T=a.map(ke=>ke.key),U=new Set(T),B=[...P.filter(ke=>U.has(ke)),...T.filter(ke=>!P.includes(ke))];if(e0(T,B))return;const D=t,W=new Map(n.map(ke=>[ke.id,ke])),se=l,me=new Map(a.map(ke=>[ke.key,ke]));o(ke=>{const V={...ke};return B.forEach((Re,be)=>{const ce=me.get(Re);ce?.type==="project"&&(V[ce.id]={...V[ce.id]??{},pinned:!0,archived:!1,order:be})}),V});const Te=ke=>{const V=new Map(ke.map(ce=>[ce.id,ce])),Re=B.map((ce,ye)=>{const ne=me.get(ce),ge=ne?.type==="session"?V.get(ne.id):null;return ge?{...ge,order:ye}:null}).filter(ce=>!!ce),be=new Map(Re.map(ce=>[ce.id,ce]));return ke.map(ce=>be.get(ce.id)??ce)};s(Te),i(Te),m(ke=>{const V=new Map;return B.forEach((Re,be)=>{const ce=me.get(Re);ce?.type==="file"&&V.set(ce.id,be)}),ke.map(Re=>{const be=V.get(Re.id);return be===void 0?Re:{...Re,order:be}})}),Promise.all(B.map((ke,V)=>{const Re=me.get(ke);return Re?Re.type==="project"?Y.patchSidebarAppPreference(e,Re.id,{pinned:!0,archived:!1,order:V}):Re.type==="session"?Y.patchSession(e,Re.id,{order:V}):Y.patchSidebarFile(e,{workspaceKind:Re.file.workspaceKind,workspaceId:Re.file.workspaceId,workspaceName:Re.file.workspaceName,path:Re.file.path,status:"pinned",order:V,sourceSessionId:Re.file.sourceSessionId}):Promise.resolve(null)})).catch(ke=>{d(ke instanceof Error?ke.message:String(ke)),o(D);const V=Re=>Re.map(be=>W.get(be.id)??be);s(V),i(V),m(se)})}function j(P,T){const U=_.current;if(U){const B=R.current??a.map(W=>W.key),D=Gd(B,Br(U),Br(T),Wd(P));$(D)}C()}function k(){_.current&&$(R.current??a.map(T=>T.key)),C()}return{dragItem:h,pinnedPreviewKeys:y,startPinnedDrag:M,clearSidebarDrag:C,previewPinnedDrop:N,commitPinnedDrop:j,commitPinnedPreviewDrop:k}}function _W({connection:e,sessions:t,setCodexHistorySessions:n,setError:a,setSessions:o}){const[i,s]=g.useState(null),[l,m]=g.useState(null),d=g.useRef(null),h=g.useRef(null);function v(C,N){C.dataTransfer.effectAllowed="move",C.dataTransfer.setData("text/plain",`session:${N.sessionId}`),gC(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,k=Gd(j,$.sessionId,N,Wd(C));CW(j,k)||(h.current=k,m(k))}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,k=Gd(j,$.sessionId,N,Wd(C));M(s0($.allSessionIds,$.visibleSessionIds,k)),w()}function R(){const C=d.current;C&&M(s0(C.allSessionIds,C.visibleSessionIds,h.current??C.visibleSessionIds)),w()}function M(C){const N=new Map(C.map((P,T)=>[P,T])),$=new Map(t.map(P=>[P.id,P.order])),j=C.filter((P,T)=>$.get(P)!==T);if(j.length===0)return;const k=P=>P.map(T=>{const U=N.get(T.id);return U===void 0||U===T.order?T:{...T,order:U}});o(k),n(k),e&&Promise.all(j.map(P=>Y.patchSession(e,P,{order:N.get(P)}))).catch(P=>{const T=U=>U.map(B=>{const D=$.get(B.id);return D===void 0||D===B.order?B:{...B,order:D}});o(T),n(T),a(P instanceof Error?P.message:String(P))})}return{clearTaskDrag:w,commitTaskDrop:_,commitTaskPreviewDrop:R,previewTaskDrop:y,startTaskDrag:v,taskDragSessionId:i,taskPreviewSessionIds:l}}function CW(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function L0({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=RW(t);return{id:i,role:"user",content:n,sessionId:a,afterMessageId:e,timestamp:o,turnId:i,...s.length>0?{attachments:s}:{}}}function vC(e,t){return!t||bC(e,t)?e:[...e,t]}function bC(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 RW(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 xr(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 Fo(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];if(t(a))return a}return null}function PW(e,t,n){if(t.name==="workspace_action_result"){const a=Fo(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:gh([...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 AW(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"])??nf(t)??nf(Ce(t?.run))??nf(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),v=Ce(t?.traceSummary)??Ce(i?.traceSummary)??Ce(s?.traceSummary),y=Ce(t?.evalSummary)??Ce(i?.evalSummary)??Ce(s?.evalSummary),w=gh([...Ro("artifact",t?.artifactRefs,"Artifact"),...Ro("artifact",m?.artifactRefs,"Artifact"),...Ro("artifact",l?.artifactRefs,"Artifact"),...Ro("artifact",d?.artifactRefs,"Artifact"),...Ro("trace",t?.traceArtifactRefs,"Trace"),...Ro("trace",v?.artifactRefs,"Trace"),...Ro("eval",t?.evalResultArtifactRefs,"Eval"),...Ro("eval",y?.artifactRefs,"Eval"),...Ro("output",t?.outputRefs,"Output")]),_=ve(h,["sourceRef","ref"]);return _&&w.push({id:vh("source",_),kind:"source",label:"Source",target:_}),{actionName:a,title:ve(m,["label","title","name"])??ve(s,["selectedActionLabel"])??$W(a),status:TW(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:gh(w),childCalls:MW(t,i,s)}}function nf(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 TW(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 Ro(e,t,n){return(Array.isArray(t)?t:t?[t]:[]).flatMap(o=>{const i=EW(e,o,n);return i?[i]:[]})}function EW(e,t,n){if(typeof t=="string"&&t.trim()){const s=t.trim();return{id:vh(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:vh(e,o),kind:e,label:i,target:o}}function gh(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 vh(e,t){return`${e}:${t}`}function MW(e,t,n){return[e?.childCalls,e?.childRuns,e?.implementationCalls,t?.childCalls,t?.childRuns,n?.childCalls,n?.childRuns].flatMap(o=>jW(o)).slice(0,6)}function jW(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:OW(o),detail:l}]})}function OW(e){const t=ve(e,["status","state"]);return t==="running"||t==="completed"||t==="failed"||t==="pending"?t:t==="succeeded"?"completed":"unknown"}function $W(e){const t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e}const NW=new Set([".avif",".gif",".jpeg",".jpg",".png",".webp"]);function yC(e){if(!e)return!1;const t=e.split("?")[0]?.split("#")[0]??e,n=t.lastIndexOf(".");return n<0?!1:NW.has(t.slice(n).toLowerCase())}function SC(e){return e.split("/").filter(Boolean).pop()??e}function DW(e){if(!yh(e))return;const t=Ce(e.data),a=(typeof t?.openpondImagePreviewPath=="string"?t.openpondImagePreviewPath:null)??Fr(e.data)??Fr(e.args)??Fr(e.output);if(!(!a||!yC(a)))return{path:a,appId:e.appId??null,title:SC(a)}}function LW(e){if(e.name!=="tool.completed"&&e.name!=="workspace_action_result")return[];const t=[],n=new Set;return bh(e.data,t,n),t.slice(0,12)}function bh(e,t,n,a=0){if(a>7||e==null)return;if(Array.isArray(e)){for(const l of e)bh(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"])??SC(i),contentType:s,sizeBytes:typeof o.sizeBytes=="number"?o.sizeBytes:null}));for(const l of Object.values(o))bh(l,t,n,a+1)}function yh(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 Fr(e,t=0,n=""){if(t>5||e==null)return null;if(typeof e=="string"){if(af(n)&&yC(e.trim()))return e.trim();const o=xr(e);if(o!==null){const i=Fr(o,t+1,n);if(i)return i}return UW(e)}if(Array.isArray(e)){for(const o of e){const i=Fr(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(!af(o))continue;const s=Fr(i,t+1,o);if(s)return s}for(const[o,i]of Object.entries(a)){if(af(o))continue;const s=Fr(i,t+1,o);if(s)return s}return null}function af(e){return/^(path|filePath|filepath|imagePath|image|localPath|uri|url)$/i.test(e)}function UW(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 HW(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=qW(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 zW(e){if(e.action!=="connected_app_search"&&e.action!=="connected_app_read"&&e.action!=="connected_app_write")return null;const t=xC(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 qW(e){return xC(e).providerLabel}function xC(e){const t=Ce(e.args),n=Ce(e.data),a=Ce(n?.result),o=uu(ve(t,["provider"])??ve(a,["provider"])??ve(n,["provider"])??void 0),i=ve(a,["providerLabel"])??ve(n,["providerLabel"])??(o?Qh(o)?.label:null)??"connected app",s=ve(t,["operation"]),l=ve(a,["operation"])??ve(n,["operation"]),m=of(t?.capabilityIds)||of(a?.capabilityIds)||of(n?.capabilityIds);return{providerLabel:i,providerOperation:s,operation:l,capabilityCount:m}}function of(e){return Array.isArray(e)?e.length:0}function kC(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()||rf(a)}}return t==="<turn_aborted>"?{kind:"turn_aborted",text:rf("turn_aborted")}:t==="<goal_context>"?{kind:"goal_context",text:rf("goal_context")}:null}function rf(e){return e==="turn_aborted"?"The previous turn was interrupted.":"Goal context updated."}function Gu(e){return e.name==="diagnostic"&&Ce(e.data)?.kind==="goal_context"}const BW="Steered by user";function FW(e){return e?.trim().toLowerCase()===BW.toLowerCase()}function VW(e,t){if(!t.turnId)return;JW(e,t.turnId);const n=KW(t);if(!n)return;const a=ZW(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 KW(e){const t=Ce(e.data),n=Ce(t?.activity);return n?WW(n,e):GW(e,t)}function nX(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 · ${e8(e.route??"external")} issue routed`;const t=e.result==="applied"?"Applied":"Needs review";return`Refiner · ${e.summary} — ${t}`}function WW(e,t){const n=so(e.state,["running","completed","failed"]);if(!n)return null;const a=n==="failed"?"failed":so(e.result,["no_action","routed","applied","retained"]),o=zn(e.reason)??t.output??t.error??null;return{state:n,visibility:so(e.visibility,["always","material_only"])??"material_only",result:n==="running"?null:a,workspaceId:zn(e.workspaceId),decision:so(e.decision,["no_action","route","propose"]),route:zn(e.route),operation:so(e.operation,["create","update","delete"]),target:zn(e.target),summary:zn(e.summary)??wC(n,a),expectedOutcome:zn(e.expectedOutcome),reason:o,evidenceBasis:YW(e.evidenceBasis),critiqueStatus:so(e.critiqueStatus,["not_applicable","pending","passed","rejected","failed"])??(n==="running"?"pending":"not_applicable"),validationStatus:so(e.validationStatus,["not_applicable","pending","passed","failed"])??(n==="running"?"pending":"not_applicable"),validations:QW(e.validationReceipts),edits:XW(e.edits),refs:{trigger:io(e.trigger),outcome:io(e.outcome),proposal:io(e.proposal),applyReceipt:io(e.applyReceipt),advanceReceipt:io(e.advanceReceipt),inputHarness:io(e.inputHarness),outputHarness:io(e.outputHarness)}}}function GW(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=zn(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:zn(o?.route),operation:null,target:null,summary:wC(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:io(t?.trigger),outcome:io(o),proposal:io(i),applyReceipt:null,advanceReceipt:null,inputHarness:null,outputHarness:null}}}function ZW(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 JW(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 YW(e){const t=Ce(e),n=so(t?.kind,["single_deterministic","recurrent_independent"]);return!t||!n?null:{kind:n,supportingEvidenceIds:U0(t.supportingEvidenceIds),counterevidence:U0(t.counterevidence)}}function QW(e){return Array.isArray(e)?e.flatMap(t=>{const n=Ce(t),a=zn(n?.id),o=so(n?.status,["passed","failed","blocked","skipped"]),i=zn(n?.summary);return a&&o&&i?[{id:a,status:o,summary:i}]:[]}):[]}function XW(e){return Array.isArray(e)?e.flatMap(t=>{const n=Ce(t),a=zn(n?.id),o=so(n?.operation,["create","update","delete"]),i=zn(n?.target),s=zn(n?.summary);return!a||!o||!i||!s?[]:[{id:a,operation:o,target:i,summary:s,content:typeof n?.content=="string"?n.content:null}]}):[]}function io(e){const t=Ce(e),n=zn(t?.id),a=zn(t?.contentHash);return n&&a?`${n} · ${a.slice(0,12)}`:null}function U0(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()):[]}function zn(e){return typeof e=="string"&&e.trim()?e.trim():null}function so(e,t){return typeof e=="string"&&t.includes(e)?e:null}function wC(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 e8(e){return e.length>0?`${e[0].toUpperCase()}${e.slice(1)}`:e}const H0=64*1024,z0=8*1024;function q0(e,t){const n=IC(t);if(n.subagentMessage){e.push({id:t.id,role:"activity_group",activities:[n],timestamp:t.timestamp,turnId:t.turnId});return}const a=t8(e,t.turnId);if(a){a.activities=o8(a.activities??[],t,n),a.timestamp=t.timestamp;return}Cd(e,t),e.push({id:t.id,role:"activity_group",activities:[n],timestamp:t.timestamp,turnId:t.turnId,traceState:"running",traceStartedAt:t.timestamp})}function Cd(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 t8(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 Sh(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 n8(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)}Sh(e,t,"interrupted"),!FW(t.output)&&e.push({id:t.id,role:"status_divider",content:a8(t),timestamp:t.timestamp,turnId:t.turnId,statusKind:"interruption",statusState:"failed",statusTone:"danger"})}function a8(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 o8(e,t,n=IC(t)){const a=[...e];return f8(a,t,n)||u8(a,t,n)||m8(a,t,n)||p8(a,t,n)?a:[...a,n]}function r8(e){return e.name==="session.compaction.started"||e.name==="session.compaction.completed"||e.name==="session.compaction.failed"}function i8(e,t){const n={id:t.id,role:"status_divider",content:s8(t),timestamp:t.timestamp,turnId:t.turnId,statusKind:"compaction",statusState:l8(t),statusTone:c8(t)};if(t.name!=="session.compaction.started"){const a=Fo(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 s8(e){const t=d8(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 l8(e){return e.name==="session.compaction.started"?"running":e.name==="session.compaction.completed"?"completed":"failed"}function c8(e){return e.name==="session.compaction.failed"?"danger":e.name==="session.compaction.completed"?"success":"info"}function d8(e){return Ce(e.data)?.reason==="auto"?"auto":"manual"}function IC(e){const t=DW(e),n=e.name==="assistant.reasoning.delta"?"reasoning":I8(e),a=_8(e),o=P8(e),i=R8(e),s=A8(e),l=T8(e),m=LW(e);return{id:e.id,label:l?l.direction==="received"?"Child message received":"Child message sent":v8(e),content:l?.summary??y8(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:jv(e)??void 0}:{},...n&&e.name==="command.output"?{detail:xh(e)}:{},...n==="command"?{terminal:N8(e)}:{},...i?{meta:i}:{},...o?{receipt:o}:{},...s?{openSession:s}:{},...l?{subagentMessage:l}:{},state:g8(e),...t?{imagePreview:t}:{},...m.length>0?{artifacts:m}:{}}}function u8(e,t,n){if(t.name==="tool.completed"){const a=B0(e,t);if(!a)return!1;const o=D8(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=xh(t);return i&&i!==a.content&&(a.detail=eu(a.detail,i)),!0}if(t.name==="command.output"){const a=B0(e,t);if(!a)return!1;const o=xh(t);return o&&(a.detail=eu(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 m8(e,t,n){if(t.name!=="tool.completed"||n.kind==="command")return!1;const a=jv(t),o=Fo(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=eu(o.detail,i)),n.detail&&(o.detail=eu(o.detail,n.detail)),o.meta=n.meta,o.receipt=n.receipt,o.imagePreview=n.imagePreview??o.imagePreview,o.artifacts=n.artifacts,!0}function p8(e,t,n){if(t.name!=="workspace_action_result")return!1;const a=h8(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 f8(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 B0(e,t){const n=jv(t);if(n){const a=Fo(e,o=>o.kind==="command"&&o.callId===n);if(a)return a}return Fo(e,a=>a.kind==="command")}function h8(e,t){const n=t.action??"",a=_C[n]??{started:"Running workspace action"};return Fo(e,o=>o.state==="running"&&o.label===a.started&&o.kind!=="command"&&!o.controlKind)}function g8(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 v8(e){if(e.name==="assistant.reasoning.delta")return ve(Ce(e.data),["kind"])==="commentary"?"Update":"Reasoning";if(Gu(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(yh(e)&&e.name==="tool.started")return"Reading image";if(yh(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=HW(e);if(t)return t;const n=x8(e);if(n)return n;const a=S8(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"?b8(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 _C={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 b8(e){const t=e.action??"",n=_C[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 y8(e,t){if(e.name==="assistant.reasoning.delta")return e.output??"";if(t)return t.path;const n=kC(e.output??"");if(n)return n.text;if(Gu(e)||e.name==="turn.interrupted")return e.output??e.error??"";const a=k8(e);if(a)return a;const o=w8(e);if(o)return o;const i=zW(e);if(i)return i;const s=CC(e);if(s)return s;if(e.name==="command.output")return PC(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 S8(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 x8(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 k8(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(xr(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 w8(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(xr(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 I8(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"||CC(e)||a&&/(^|[._-])exec_command$/i.test(a))return"command"}function _8(e){if(e.name==="turn.interrupted")return"turn_aborted";if(Gu(e))return"goal_context"}function CC(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(xr(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"])??C8(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 C8(e){if(!e)return null;const t=xr(e),n=Ce(t);return ve(n,["command","cmd"])}function jv(e){const t=Ce(e.data);return ve(t,["callId","call_id","toolCallId","tool_call_id","id","itemId","item_id"])}function R8(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(j8(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?` ${F0(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 ${$8(d)}`:"checkpoint saved")}else n.push("checkpoint clean");const m=RC(t);return m&&(n.push(`receipt ${F0(m.id)}`),n.push(`${O8(m.totalUsd)} ${m.status}`)),n.length>0?n.join(" · "):null}function P8(e){const t=RC(Ce(e.data));return t?{id:t.id,status:t.status,totalUsd:t.totalUsd}:void 0}function A8(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 T8(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 R=Ce(_),M=ve(R,["kind"]),C=ve(R,["id"]),N=ve(R,["label"]);return M&&C&&N?[{kind:M,id:C,label:N}]:[]}):[];return{direction:y,summary:E8(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 E8(e){const t=e.replace(/\s+/g," ").trim();if(!t)return"No message body";const n=/^(.*?[.!?])(?:\s|$)/.exec(t)?.[1]??t;return M8(n,96)}function M8(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 RC(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 j8(e){return e<1e3?`${Math.max(0,Math.round(e))} ms`:e<1e4?`${(e/1e3).toFixed(1)} s`:`${Math.round(e/1e3)} s`}function O8(e){const t=e.trim();return t.startsWith("$")?t:`$${t}`}function $8(e){return e.length>12?e.slice(0,12):e}function F0(e){const t=e.trim();return t.length<=14?t:`${t.slice(0,6)}...${t.slice(-4)}`}function PC(e){let t=e.replace(/\r\n/g,`
|
|
189
|
+
`).trim();if(!t)return"";const n=L8(t);if(n!==null)return is(n);const a=`
|
|
190
|
+
Output:
|
|
191
|
+
`,o=t.indexOf(a);return o>=0&&U8(t.slice(0,o))&&(t=t.slice(o+a.length).trim()),t=t.replace(/^Total output lines: \d+\n\n/,""),is(t.trim())}function xh(e){const t=PC(e.output??"");if(t)return t;const n=Ce(Ce(e.data)?.result);return n?is(AC(n)):""}function N8(e){const t=Ce(e.data),n=Ce(t?.result),a=Ce(xr(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 D8(e,t){const n=Date.parse(t)-Date.parse(e);return Number.isFinite(n)&&n>0?n:null}function L8(e){const t=Ce(xr(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?AC(a,ve(t,["output"])):typeof t.output=="string"?t.output.trim():""}function AC(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 U8(e){return/^(Chunk ID|Exit code):/m.test(e)&&/Wall time:/m.test(e)}function eu(e,t){const n=e??"";if(!n)return is(t);if(n===t||n.includes(t))return n;if(t.includes(n))return is(t);const a=n.endsWith(`
|
|
196
|
+
`)||t.startsWith(`
|
|
197
|
+
`)?"":`
|
|
198
|
+
`;return is(`${n}${a}${t}`)}function is(e){if(e.length<=H0)return e;const t=`
|
|
199
|
+
|
|
200
|
+
… output omitted from live view; full output remains in task history …
|
|
201
|
+
|
|
202
|
+
`,n=Math.max(0,H0-z0-t.length);return`${e.slice(0,z0)}${t}${e.slice(-n)}`}const H8=/\bopenpond\s+opchat\b/i,z8=/\b(?:50[0-9]|52[0-9]|53[0-9])\b|bad\s+gateway|gateway\s+timeout|service\s+unavailable/i;function TC(e){const t=e?.trim()||"Turn failed";return H8.test(t)&&z8.test(t)?"Server connection lost. Retry your message.":t}function q8(e,t){if((ad(t,"code")??ad(t,"errorCode"))==="opchat_quota_exceeded")return"opchat_quota_exceeded";const a=t&&typeof t=="object"?t.error:null;if(a&&typeof a=="object"&&(ad(a,"code")??ad(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 ad(e,t){if(!e||typeof e!="object")return null;const a=e[t];return typeof a=="string"&&a.trim()?a.trim():null}function B8(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=F8(a.activities??[]);if(o.length===0){a.deliverables=void 0;continue}const i=t.get(a.turnId)??"",s=i?V8(o,i):[];if(s.length>0){a.deliverables=s;continue}a.deliverables=n.has(a.turnId)?[o[o.length-1]]:void 0}}function F8(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 V8(e,t){const n=EC(t);return e.filter(a=>K8(a).some(o=>t.includes(o)||n.includes(o)))}function K8(e){const t=new Set;for(const n of[e.path,e.title,W8(e.path)]){const a=n.trim();a&&(t.add(a),t.add(EC(a)))}return[...t]}function W8(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).at(-1)??e}function EC(e){try{return decodeURIComponent(e)}catch{return e}}const MC=8;function G8(e){if(e.name!=="tool.completed"||e.status==="failed")return[];if(e.action!=="web_search"&&e.action!=="web_fetch")return[];const t=wh(e.data),n=e.output?wh(xr(e.output)):null;return Z8(t??n)}function kh(e,t){if(t.length===0)return e;const n=[],a=new Set;for(const o of[...e??[],...t]){const i=jC(o.url);if(!(!i||a.has(i))&&(a.add(i),n.push(o),n.length>=MC))break}return n.length>0?n:void 0}function wh(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=wh(n[o],t+1);if(i)return i}return null}function Z8(e){if(!e)return[];const t=[],n=new Set;for(let a=0;a<e.results.length;a+=1){const o=J8(e.results[a],a,e.provider);if(!o)continue;const i=jC(o.url);if(!(!i||n.has(i))&&(n.add(i),t.push(o),t.length>=MC))break}return t}function J8(e,t,n){const a=Ce(e);if(!a)return null;const o=ve(a,["url","href"]);if(!o||!Y8(o))return null;const i=ve(a,["title"])??V0(o)??`Source ${t+1}`;return{id:ve(a,["id"])??`source_${t+1}`,title:i,url:o,sourceName:ve(a,["sourceName","source_name","source"])??V0(o),snippet:ve(a,["snippet","description"]),provider:n,faviconUrl:Q8(ve(a,["faviconUrl","favicon_url","iconUrl","icon_url"]))??X8(o),publishedAt:ve(a,["publishedAt","published_at"]),updatedAt:ve(a,["updatedAt","updated_at"])}}function Y8(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function jC(e){try{const t=new URL(e);return t.hash="",t.toString()}catch{return null}}function Q8(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 X8(e){try{return new URL("/favicon.ico",e).toString()}catch{return null}}function V0(e){try{return new URL(e).hostname.replace(/^www\./i,"")}catch{return null}}const K0=new WeakMap;function Zu(e){const t=K0.get(e);if(t)return t;const n=eG(e);return K0.set(e,n),n}function eG(e){const t=[],n=new Set,a=new Map;for(const o of e){if(o.name==="task.input"){const i=HI.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"){Cd(t,o),tG(t,o);const i=rG(o.args);if(i){const s=kC(i);if(s){q0(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:iG(o.args),timestamp:o.timestamp,turnId:o.turnId});const l=G0(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=G0(o.data);if(!i)continue;const s=Fo(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;Cd(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=kh(s.sources,W0(a,o.turnId)??[]);else{const l=W0(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;Cd(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=bj.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=yj.safeParse(i?.resolution);if(!s.success)continue;const l=Fo(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"){Sh(t,o,"completed");continue}if(o.name==="turn.failed"){Sh(t,o,"failed");const i=o.error??"Turn failed",s=q8(i,o.data);t.push({id:o.id,role:"error",content:TC(i),...s?{errorKind:s}:{},timestamp:o.timestamp,turnId:o.turnId});continue}if(o.name==="turn.interrupted"){n8(t,o);continue}if(r8(o)){i8(t,o);continue}if(o.name.startsWith("harness.refiner.")){VW(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.")||Gu(o)){if(aG(o))continue;const i=AW(o);if(i){PW(t,o,i);continue}const s=G8(o);s.length>0&&nG(t,a,o.turnId,s),q0(t,o)}if(o.name==="workspace.diff"){const i=oG(o.data);if(!i||i.filesChanged===0)continue;const s=Fo(t,l=>l.role==="assistant"&&l.turnId===o.turnId);s&&(s.changeSummary=i,s.timestamp=o.timestamp)}}return B8(t),t}function tG(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 nG(e,t,n,a){if(!n)return;const o=e[e.length-1];if(o?.role!=="assistant"||o.turnId!==n){t.set(n,kh(t.get(n),a));return}o.sources=kh(o.sources,a)}function W0(e,t){if(!t)return;const n=e.get(t);return n&&e.delete(t),n}function aG(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 oG(e){const t=MO.safeParse(e);return t.success?t.data:null}function rG(e){if(!e||typeof e!="object"||!("prompt"in e))return"";const t=e.prompt;return typeof t=="string"?t:""}function iG(e){if(!e||typeof e!="object"||!("attachments"in e))return;const t=pD.array().safeParse(e.attachments);return t.success&&t.data.length>0?t.data:void 0}function G0(e){const t=Ce(e);if(!t)return null;const n=ic.safeParse(t.createImproveRun);return n.success?n.data:null}function aX(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 oX(e){const t=OC(e);return t?t.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):""}function rX(e){const t=OC(e);return t?t.toLocaleString():""}function OC(e){if(!e)return null;const t=new Date(e);return Number.isNaN(t.getTime())?null:t}function sG(e){const{chatMessages:t,runtimeIndexes:n,selectedSessionId:a}=e,[o,i]=g.useState({}),s=g.useCallback(m=>{i(d=>({...d,[m.sessionId]:m}))},[]);g.useEffect(()=>{i(m=>{let d=m;for(const[h,v]of Object.entries(m)){const y=Zu(Ic(n,h));bC(y,v)&&(d===m&&(d={...m}),delete d[h])}return d})},[n]);const l=g.useMemo(()=>vC(t,a?o[a]:null),[t,o,a]);return{pendingChatUserMessages:o,recordPendingChatUserMessage:s,visibleChatMessages:l}}function lG({connection:e,selectedSession:t,setBootstrap:n,setError:a,setOpenPondCommandAccessMode:o,setSessions:i}){return{changeOpenPondCommandAccessMode:g.useCallback((l,m=t)=>{if(!e){a("Connect to OpenPond before saving preferences.");return}const d=m?.provider==="codex"?null:m;Y.savePreferences(e,{openPondCommandAccessMode:l}).then(h=>{o(h.preferences.openPondCommandAccessMode),n(v=>v&&{...v,preferences:h.preferences})}).catch(h=>{a(h instanceof Error?h.message:String(h))}),d&&Y.patchSession(e,d.id,{openPondCommandAccessMode:l}).then(h=>{i(v=>v.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 cG({localProjects:e,cloudProjects:t,sessions:n,runtimeIndexes:a,appPreferences:o,selectedSessionId:i,selectedProjectId:s,archivedChatsOpen:l,projectsExpanded:m,chatRowsVisibleCount:d,sidebarFileBookmarks:h=[]}){const v=g.useMemo(()=>e.filter(ae=>!ae.hiddenFromDefaultSidebar),[e]),y=g.useMemo(()=>n.filter(ae=>!ae.archived&&Z0(ae)),[n]),w=g.useMemo(()=>y.filter(ae=>ae.pinned),[y]),_=g.useMemo(()=>y.filter(ae=>!!ae.savedForLater),[y]),R=g.useMemo(()=>n.filter(ae=>ae.archived&&Z0(ae)),[n]),M=g.useMemo(()=>new Set(e.map(ae=>ae.id)),[e]),C=g.useMemo(()=>new Set(t.map(ae=>ae.id)),[t]),N=g.useMemo(()=>h_(e),[e]),$=g.useMemo(()=>{const ae={};for(const Se of[...y,...R]){const ze=n0(Se,M,N,C);ze&&(ae[Se.id]=ze)}return ae},[y,R,C,M,N]),j=g.useMemo(()=>y.filter(ae=>!ae.pinned&&!ae.savedForLater&&!ae.appId&&!$[ae.id]),[y,$]),k=g.useMemo(()=>R.filter(ae=>!ae.appId&&!n0(ae,M,N,C)),[R,C,M,N]),P=g.useMemo(()=>{const ae={};for(const Se of y){if(Se.pinned||Se.savedForLater)continue;const ze=$[Se.id];if(!ze)continue;const Qe=ae[ze];Qe?Qe.push(Se):ae[ze]=[Se]}return ae},[y,$]),T=g.useMemo(()=>{const ae={};for(const Se of n){if(Se.archived||!$C(Se))continue;const ze=ae[Se.parentSessionId];ze?ze.push(Se):ae[Se.parentSessionId]=[Se]}for(const Se of Object.values(ae))Se.sort((ze,Qe)=>Date.parse(Qe.updatedAt)-Date.parse(ze.updatedAt));return ae},[n]),U=g.useMemo(()=>v.map((ae,Se)=>{const ze=yt("local",ae.id),Qe=f9(ae,t);return{id:ze,kind:"local",project:ae,pinned:!!o[ze]?.pinned,order:o[ze]?.order??Se,cloudLinkTrusted:!Qe,cloudLinkWarning:Qe}}).sort(sf),[o,t,v]),B=g.useMemo(()=>t.map((ae,Se)=>{const ze=yt("cloud",ae.id);return{id:ze,kind:"cloud",project:ae,pinned:!!o[ze]?.pinned,order:o[ze]?.order??Se,cloudLinkTrusted:!0,cloudLinkWarning:null}}).sort(sf),[o,t]),D=g.useMemo(()=>new Set(v.map(ae=>ka(ae,t)?.id??null).filter(ae=>!!ae)),[t,v]),W=g.useMemo(()=>B.filter(ae=>!D.has(ae.project.id)),[B,D]),se=g.useMemo(()=>[...U,...W].sort(sf),[W,U]),me=g.useMemo(()=>se.filter(ae=>ae.pinned),[se]),Te=g.useMemo(()=>h.filter(ae=>ae.status==="pinned"),[h]),ke=g.useMemo(()=>h.filter(ae=>ae.status==="saved_for_later"),[h]),V=se,Re=g.useMemo(()=>dG(V,m,s),[V,m,s]),be=g.useMemo(()=>[...me.map(ae=>({type:"project",key:Br({type:"project",id:ae.id}),id:ae.id,item:ae,order:ae.order})),...w.map(ae=>({type:"session",key:Br({type:"session",id:ae.id}),id:ae.id,session:ae,order:ae.order})),...Te.map((ae,Se)=>({type:"file",key:Br({type:"file",id:ae.id}),id:ae.id,file:ae,order:ae.order??me.length+w.length+Se}))].sort((ae,Se)=>{if(ae.order!==Se.order)return ae.order-Se.order;if(ae.type!==Se.type){const We={project:0,session:1,file:2};return We[ae.type]-We[Se.type]}const ze=ae.type==="project"?ae.item.project.name:ae.type==="session"?ae.session.title:ae.file.path,Qe=Se.type==="project"?Se.item.project.name:Se.type==="session"?Se.session.title:Se.file.path;return ze.localeCompare(Qe)}),[Te,me,w]),ce=g.useMemo(()=>l?[...j,...k]:j,[l,k,j]),ye=g.useMemo(()=>ce.slice(0,Math.max(An,d)),[ce,d]),ne=g.useMemo(()=>Ic(a,i),[a,i]),ge=g.useMemo(()=>Zu(ne),[ne]),xe=Y_(a,i),De=Q_(a,i),we=e9(a,i);return{activeSessions:y,pinnedSessions:w,savedForLaterSessions:_,pinnedFiles:Te,savedForLaterFiles:ke,chatSessions:j,archivedSessions:R,pinnedProjects:me,pinnedItems:be,projectRows:V,localProjectRows:U,visibleProjectRows:Re,cloudProjectRows:W,projectSessionRowsByProjectId:P,childSessionRowsByParentId:T,sidebarProjectIdBySessionId:$,chatRows:ce,visibleChatRows:ye,sessionEvents:ne,chatMessages:ge,contextUsage:xe,goalRuntime:De,subagentRuntime:we}}function Z0(e){return $C(e)?!1:e.hiddenFromDefaultSidebar?e.metadata?.benchmarkRuntime==="desktop_local_work":!0}function $C(e){return!!(e.parentSessionId&&e.subagentRunId)}function sf(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 dG(e,t,n){if(t||e.length<=xd)return e;const a=e.slice(0,xd);if(!n||a.some(i=>i.id===n))return a;const o=e.find(i=>i.id===n);return o?[...a.slice(0,xd-1),o]:a}function uG(e){return e.name==="turn.completed"||e.name==="turn.failed"||e.name==="turn.interrupted"}function NC(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||!uG(o))&&!(n&&o.turnId&&o.turnId!==n))return o.name==="turn.completed"?"completed":"blocked"}return"pending"}function J0(e,t){if(e.systemKind)return!1;const n=Ic(t,e.id);if(n.length===0)return!1;const a=NC(n);return a==="pending"||a==="none"&&DC(n)==="pending"}function Y0(e,t){if(e.systemKind||e.status!=="active")return!1;const n=Ic(t,e.id);if(n.length===0)return!0;const a=NC(n);return a==="pending"||a==="none"&&DC(n)!=="terminal"}function DC(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 mG({goalRuntime:e,goalRuntimeBySessionId:t,runtimeIndexes:n,selectedSession:a,selectedSessionId:o,sidebarSessions:i,subagentRuntimeBySessionId:s}){const l=g.useMemo(()=>new Map(i.map(y=>[y.id,y])),[i]),m=g.useMemo(()=>{const y=new Set;for(const[w,_]of t??[]){const R=l.get(w);_.tone==="active"&&!R?.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=g.useMemo(()=>{const y=new Set(m);for(const[w,_]of s??[]){const R=l.get(w);_.activeCount>0&&!R?.systemKind&&y.add(w)}for(const w of n.activeSubagentSessionIds)l.get(w)?.systemKind||y.add(w);for(const w of i)w.systemKind||J0(w,n)&&y.add(w.id);return a&&J0(a,n)&&y.add(a.id),y},[m,n,a,i,l,s]),h=g.useMemo(()=>{const y=new Set(d);for(const w of i)Y0(w,n)&&y.add(w.id);return a&&Y0(a,n)&&y.add(a.id),y},[d,n,a,i]),v=!!(a&&!a.systemKind&&d.has(a.id));return{runningSessionIds:h,selectedSessionRunning:v}}const pG=1e3;function fG(e){const[t,n]=g.useState(()=>new Date().toISOString());return g.useEffect(()=>{if(!e)return;const a=()=>n(new Date().toISOString());a();const o=window.setInterval(a,pG);return()=>window.clearInterval(o)},[e]),t}function hG(e){const{codexHistoryEvents:t,codexHistorySessions:n,connection:a,expandedProjectIds:o,goalRuntime:i,locallyActiveCodexHistorySessionIds:s,pinnedSessions:l,savedForLaterSessions:m,projectSessionRowsByProjectId:d,rightChatHistoryEvents:h,runtimeIndexes:v,selectedSession:y,selectedSessionId:w,serverId:_,setCodexHistorySessions:R,sidebarSessions:M,subagentRuntime:C,visibleChatRows:N,visibleProjectRows:$}=e,[j,k]=g.useState({});g.useEffect(()=>{k({})},[_]);const P=g.useMemo(()=>{const ce=[],ye=new Set,ne=xe=>{!xe||xe.id===w||!Lt(xe.id)||ye.has(xe.id)||(ye.add(xe.id),ce.push(xe.id))};for(const xe of n)(xe.status==="active"||s.has(xe.id))&&ne(xe);const ge=ce.length;for(const xe of $)for(const De of(d[xe.id]??[]).slice(0,2))ne(De);for(const xe of o)for(const De of(d[xe]??[]).slice(0,xd))ne(De);for(const xe of l)ne(xe);for(const xe of m)ne(xe);for(const xe of N)ne(xe);return[...ce.slice(0,ge),...ce.slice(ge,ge+8)].join(`
|
|
203
|
+
`)},[n,o,s,l,m,d,w,N,$]),T=g.useCallback(ce=>{k(ye=>ye[ce.session.id]===ce.events?ye:{...ye,[ce.session.id]:ce.events}),R(ye=>Wu(ye,ce.session))},[R]),U=g.useMemo(()=>{if(!P)return"";const ce=new Set(P.split(`
|
|
204
|
+
`).filter(Boolean));return M.filter(ye=>ce.has(ye.id)&&ye.status==="active").map(ye=>ye.id).join(`
|
|
205
|
+
`)},[P,M]),B=g.useMemo(()=>P?P.split(`
|
|
206
|
+
`).filter(ce=>s.has(ce)).join(`
|
|
207
|
+
`):"",[P,s]);g.useEffect(()=>{!y||!w||!Lt(w)||t.length===0||T({session:y,events:t})},[T,t,y,w]),g.useEffect(()=>{if(!a||!P)return;const ce=a,ye=P.split(`
|
|
208
|
+
`).filter(Boolean),ne=new Set(U.split(`
|
|
209
|
+
`).filter(Boolean)),ge=new Set(B.split(`
|
|
210
|
+
`).filter(Boolean)),xe=ye.map(De=>Mv({connection:ce,locallyActive:ge.has(De),onPayload:we=>T(Ev(we,ge.has(De))),reportedActive:ne.has(De),sessionId:De,surface:"sidebar"}));return()=>xe.forEach(De=>De())},[T,U,B,P,a]);const D=g.useMemo(()=>new Map(M.map(ce=>[ce.id,ce])),[M]),W=g.useMemo(()=>{const ce=new Map(v.latestGoalRuntimeBySessionId);for(const ye of M){const ne=ye.status==="active"?Xp(ye.metadata):null;ne&&ce.set(ye.id,ne)}for(const ye of[j,h])for(const[ne,ge]of Object.entries(ye)){const xe=D.get(ne),De=xe?.status==="active"?Xp(xe.metadata):null,we=uh(ge)??Rv(ge)??(xe?.status==="active"?Xd(ge)??De:null);we?ce.set(ne,we):ce.delete(ne)}if(w)if(i)ce.set(w,i);else if(y?.status==="active"&&t.length>0){const ye=uh(t)??Xd(t)??Xp(y.metadata);ye?ce.set(w,ye):ce.delete(w)}else(!Lt(w)||t.length>0)&&ce.delete(w);return ce},[t.length,j,i,h,v.latestGoalRuntimeBySessionId,y?.status,y?.metadata,w,D,M]),se=g.useMemo(()=>[...W.values()].some(ce=>ce.tone==="active"&&!!ce.observedAt),[W]),me=fG(se),Te=g.useMemo(()=>se?new Map([...W].map(([ce,ye])=>[ce,TK(ye,me)??ye])):W,[W,me,se]),ke=w?Te.get(w)??i:i,V=g.useMemo(()=>{const ce=new Map(v.latestSubagentRuntimeBySessionId);return w&&(C?ce.set(w,C):ce.delete(w)),ce},[v.latestSubagentRuntimeBySessionId,w,C]),{runningSessionIds:Re,selectedSessionRunning:be}=mG({goalRuntime:ke,goalRuntimeBySessionId:Te,runtimeIndexes:v,selectedSession:y,selectedSessionId:w,sidebarSessions:M,subagentRuntimeBySessionId:V});return{goalRuntime:ke,runningSessionIds:Re,selectedSessionRunning:be,sidebarGoalRuntimeBySessionId:Te,sidebarSubagentRuntimeBySessionId:V}}function gG({searchOpen:e,sectionMenuOpen:t,setSectionMenuOpen:n,setSearchOpen:a,setQuery:o}){g.useEffect(()=>{const i=s=>{if((s.metaKey||s.ctrlKey)&&s.key.toLowerCase()==="k"){s.preventDefault(),n(null),a(l=>!l);return}if(s.key==="Escape"&&e){s.preventDefault(),a(!1),o(""),n(null);return}s.key==="Escape"&&t&&(s.preventDefault(),n(null))};return document.addEventListener("keydown",i),()=>document.removeEventListener("keydown",i)},[e,t,o,a,n])}function vG({afterSequence:e,appendEvents:t,connection:n,setApprovals:a,setSessions:o,setError:i,onDisconnected:s}){g.useEffect(()=>{if(!n?.token||e===null)return;const l=n;let m=null,d=[],h=null,v=null,y=!1;const w=new Map;let _=0;const R=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=bG(D);W.length>0&&o(se=>W.reduce(kl,se)),a(se=>{let me=se;for(const Te of D)if(Te.name==="approval.requested"&&Te.data&&(me=[Te.data,...me]),Te.name==="approval.resolved"&&Te.data&&typeof Te.data=="object"){const ke=Te.data;ke.approvalId&&(me=me.filter(V=>V.id!==ke.approvalId))}return me})}function $(){const D=Date.now()-_;if(D>=R){h!==null&&(window.clearTimeout(h),h=null),N();return}h===null&&(h=window.setTimeout(N,R-D))}function j(D){k(D),d.push(D),$()}function k(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),P())}}function P(){v!==null||w.size===0||(v=window.setTimeout(()=>{v=null,T()},1e3))}async function T(){if(!(y||w.size===0)){y=!0;try{await Promise.all([...w].map(async([D,W])=>{const se=await Y.runtimeEventsPage(l,{sessionId:D,afterSequence:W,limit:100});for(const me of se.events){const Te=me.event;w.set(D,Math.max(w.get(D)??0,me.sequence)),j(Te)}}))}catch{}finally{y=!1,P()}}}function U(){h!==null&&(window.clearTimeout(h),h=null),N()}document.addEventListener("visibilitychange",U);const B=W4(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),v!==null&&window.clearTimeout(v),h=null,v=null,d=[],document.removeEventListener("visibilitychange",U),B.close()}},[e,t,n,s,a,i,o])}function bG(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=Ul.safeParse(a[o]);i.success&&t.set(i.data.id,i.data)}return[...t.values()]}function lf(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function yG(e){return typeof e=="string"&&e.trim()?e.trim():null}function SG(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n.name!=="create_improve.updated")continue;const a=lf(n.data),o=lf(a?.createImproveRun);if(o?.state!=="ready_local"&&o?.state!=="released"||lf(o.adapter)?.kind!=="local")continue;const s=yG(o.id)??n.id;return[n.sessionId??"global",n.turnId??"turn",s].join(":")}return null}const xG=332,Q0=244,X0=560,kG=560,eS=320,tS=2400,wG=440;function cf(e){const t=typeof window>"u"?X0:Math.min(X0,Math.max(Q0,window.innerWidth-420));return Math.min(t,Math.max(Q0,Math.round(e)))}function df(e){const t=typeof window>"u"?tS:Math.min(tS,Math.max(eS,window.innerWidth-wG));return Math.min(t,Math.max(eS,Math.round(e)))}function IG(e,t){return!!(e&&e.serverUrl===t.serverUrl&&e.token===t.token&&e.platform===t.platform)}const Yi=new Map;function Ov(e,t){const n=e?.trim();return n?`${t?.trim()||"global"}|${n}`:null}function LC(e,t){const n=Ov(e,t);if(!n)return null;const a=Yi.get(n);return a?.updatedAt?a.agents:null}function _G(e,t,n){const a=Ov(e,n);a&&Yi.set(a,{agents:t,promise:null,updatedAt:Date.now()})}function $v(e){const t=e.teamId?.trim();if(!t)return Promise.resolve([]);const n=Ov(t,e.accountKey);if(!n)return Promise.resolve([]);const a=Yi.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=>(_G(t,i,e.accountKey),i)).catch(i=>{const s=Yi.get(n);throw s?.promise===o&&Yi.set(n,{agents:s.agents,promise:null,updatedAt:s.updatedAt}),i});return Yi.set(n,{agents:a?.agents??[],promise:o,updatedAt:a?.updatedAt??0}),o}const CG=6e4,RG=6e4,PG=6e4,Nv=["pinned","projects","cloudProjects","chats","savedForLater"];function AG(e,t,n,a=Date.now()){for(const o of jG(t,n))UC(t[o],n[o])||(e[o]=a)}function TG(e,t,n,a=Date.now()){const o={...t};for(const[i,s]of Object.entries(n)){if(a-s>CG){delete n[i];continue}const l=$G(e,i),m=e[i];!l||UC(m,t[i])||(o[i]=m)}return o}function EG(e,t,n,a=Date.now()){for(const o of Nv)t[o]!==n[o]&&(e[o]=a)}function MG(e,t,n,a=Date.now()){const o={...t};for(const i of Nv){const s=n[i];if(s!==void 0){if(a-s>RG){delete n[i];continue}if(e[i]===t[i]){delete n[i];continue}o[i]=e[i]}}return OG(e,o)?e:o}function nS(e,t,n=Date.now()){return e===t?null:{value:t,changedAt:n}}function aS(e,t,n=Date.now()){return t?n-t.changedAt>PG?{value:e,localChange:null}:e===t.value?{value:e,localChange:t}:{value:t.value,localChange:t}:{value:e,localChange:null}}function jG(e,t){return new Set([...Object.keys(e),...Object.keys(t)])}function UC(e,t){return e?.pinned===t?.pinned&&e?.archived===t?.archived&&e?.order===t?.order}function OG(e,t){return Nv.every(n=>e[n]===t[n])}function $G(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const NG=5e4,dr="\0openpond-unscoped-runtime-events",ro=[];class DG{perSessionLimit;totalLimit;entries=new Map;eventKeyById=new Map;listenersByKey=new Map;allListeners=new Set;summaryListeners=new Set;retainedKeys=new Set;allEventsSnapshot=ro;summaryEventsSnapshot=ro;clock=0;eventCount=0;constructor(t={}){if(this.perSessionLimit=iS(t.perSessionLimit??Cv,"perSessionLimit"),this.totalLimit=iS(t.totalLimit??NG,"totalLimit"),this.totalLimit<this.perSessionLimit)throw new Error("totalLimit must be greater than or equal to perSessionLimit")}append(t){if(t.length===0)return rS();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||dr,v=n.get(h);v?v.push(d):n.set(h,[d]),this.eventKeyById.set(d.id,h)}if(n.size===0)return{...rS(),duplicateEventCount:a};const o=new Set;let i=0,s=0,l=!1;for(const[d,h]of n){h.some(sS)&&(l=!0);const v=this.entries.get(d),y=v?.snapshot.events??ro,w=Math.max(0,Math.min(y.length,this.perSessionLimit-h.length)),_=h.length>this.perSessionLimit?h.slice(h.length-this.perSessionLimit):h,R=w===y.length?y:y.slice(y.length-w),M=R.length===0?_:[...R,..._],C=y.slice(0,y.length-R.length);C.some(sS)&&(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:v?.retained??this.retainedKeys.has(d),snapshot:{events:M,latestSequence:Qd(M),revision:(v?.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),UG({acceptedEventCount:i,duplicateEventCount:a,evictedEventCount:s,changedKeys:o})}mergeBootstrap(t){const n=LG(t),a=new Set([...this.entries.keys(),...n.keys()]),o=[];for(const i of a){const s=n.get(i)??ro,l=this.entries.get(i)?.snapshot.events??ro;o.push(...xK(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=ro,this.summaryEventsSnapshot=ro;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!==dr)]),unscopedEventsChanged:o.unscopedEventsChanged||l.has(dr)}}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=ro,this.summaryEventsSnapshot=ro,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??oS:oS;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(HG),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!==dr&&a.retained&&(t+=1);return{eventCount:this.eventCount,retainedSessionCount:t,sessionCount:this.entries.size-(this.entries.has(dr)?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:Qd(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 oS=Object.freeze({events:ro,latestSequence:null,revision:0});function LG(e){const t=new Map;for(const n of e){const a=n.sessionId||dr,o=t.get(a);o?o.push(n):t.set(a,[n])}return t}function UG(e){return{acceptedEventCount:e.acceptedEventCount,duplicateEventCount:e.duplicateEventCount,evictedEventCount:e.evictedEventCount,changedSessionIds:new Set([...e.changedKeys].filter(t=>t!==dr)),unscopedEventsChanged:e.changedKeys.has(dr)}}function rS(){return{acceptedEventCount:0,duplicateEventCount:0,evictedEventCount:0,changedSessionIds:new Set,unscopedEventsChanged:!1}}function HG(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 iS(e,t){if(!Number.isInteger(e)||e<=0)throw new Error(`${t} must be a positive integer`);return e}function sS(e){return e.name!=="assistant.delta"&&e.name!=="assistant.reasoning.delta"&&e.name!=="command.output"}const zG=256,qG=15e3,BG=5e3,FG=3e4;class VG{constructor(t={}){this.options=t}options;entries=new Map;connection=null;accountScope=null;generation=0;activateConnection(t){KG(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,WG(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??BG),lastAccessedAt:m}),this.prune(),null});return this.entries.set(t,{state:"loading",promise:l,expiresAt:o+(this.options.loadingTtlMs??FG),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??zG;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??qG:0;return t.expiresAt<=n+a}now(){return(this.options.now??Date.now)()}}const lS=new VG;function iX(e,t,...n){return[t,e.serverUrl,...n].join("\0")}function KG(e,t){return e?.serverUrl===t?.serverUrl&&e?.token===t?.token&&e?.platform===t?.platform}function WG(e,t,n){e.delete(t),e.set(t,n)}const GG={connecting:"Connecting to OpenPond",account:"Loading account",team:"Loading default team",ready:"Ready"};function ZG(e){return{label:GG[e],ready:e==="ready",stage:e}}const JG=650,YG=1200,QG=6e4;function XG(e){const{setDraftModel:t,setDraftProvider:n,setCodexPermissionMode:a,setCodexReasoningEffort:o,setOpenPondCommandAccessMode:i,setError:s,setSelectedAppId:l,setSelectedProjectId:m,setSelectedSessionId:d}=e,[h,v]=g.useState(null),[y,w]=g.useState(null),[_]=g.useState(()=>new DG),R=g.useSyncExternalStore(_.subscribeSummary,_.getSummaryEvents,_.getSummaryEvents),M=g.useCallback(O=>{const z=_.getAllEvents(),X=typeof O=="function"?O(z):O;X!==z&&_.replace(X)},[_]),C=g.useCallback(O=>{_.append(O)},[_]),[N,$]=g.useState(null),[j,k]=g.useState([]),[P,T]=g.useState([]),[U,B]=g.useState([]),[D,W]=g.useState({}),[se,me]=g.useState("connecting"),Te=fh(y?.account),ke=g.useRef({}),V=g.useRef({}),Re=g.useRef({}),be=g.useRef([]),ce=g.useRef([]),ye=g.useRef(null),ne=g.useRef(null),ge=g.useRef(!1),xe=g.useRef(Date.now()),De=g.useRef(null),we=g.useRef(null);g.useEffect(()=>{lS.activateConnection(h),lS.activateAccountScope(Te)},[h,Te]);const ae=g.useCallback(O=>{ge.current||me(O)},[]),Se=g.useCallback(O=>{W(z=>{const X=typeof O=="function"?O(z):O;return AG(ke.current,z,X),X})},[]),ze=g.useCallback(O=>{k(z=>{const X=typeof O=="function"?O(z):O;return O0(V.current,z,X),be.current=X,X})},[]),Qe=g.useCallback(O=>{T(z=>{const X=typeof O=="function"?O(z):O;return O0(Re.current,z,X),ce.current=X,X})},[]),We=g.useCallback(()=>{if(ge.current||De.current!==null)return;const O=()=>{De.current=null,!ge.current&&(ge.current=!0,me("ready"))},z=Date.now()-xe.current,X=e7(z);if(X===0){O();return}De.current=window.setTimeout(O,X)},[]);g.useEffect(()=>()=>{De.current!==null&&window.clearTimeout(De.current)},[]);const nt=g.useCallback(O=>{const z=ye.current,X=!z||z===O.server.id;ye.current=O.server.id,$(fe=>fe?.serverId===O.server.id?fe:{afterSequence:O.eventWindow?.latestSequence??Qd(O.events)??0,serverId:O.server.id}),w(O),X?_.mergeBootstrap(O.events):_.replace(O.events),k(fe=>{const Me=X?j0(fe,O.sessions,V.current):hh(fe,O.sessions,V.current);return be.current=Me,Me}),T(fe=>{const Me=X?j0(fe,O.codexHistorySessions??[],Re.current):hh(fe,O.codexHistorySessions??[],Re.current);return ce.current=Me,Me}),B(O.approvals),W(fe=>TG(fe,O.sidebarAppPreferences,ke.current)),l(fe=>fe&&O.apps.some(Me=>Me.id===fe)?fe:null),m(fe=>{if(!fe)return null;const Me=c_(fe);return Me?.kind==="local"&&O.localProjects.some(Le=>Le.id===Me.id)?yt("local",Me.id):Me?.kind==="cloud"&&(O.cloudProjects??[]).some(Le=>Le.id===Me.id)?yt("cloud",Me.id):O.localProjects.some(Le=>Le.id===fe)?yt("local",fe):(O.cloudProjects??[]).some(Le=>Le.id===fe)?yt("cloud",fe):null}),d(fe=>{if(!fe)return null;const Me=[...O.sessions,...O.codexHistorySessions??[]];if(Me.some(et=>et.id===fe&&!et.archived))return fe;if(!X)return null;const Le=be.current.find(et=>et.id===fe)??ce.current.find(et=>et.id===fe)??null;return Le&&!Le.archived&&dC(Le,Me)?fe:null})},[_,l,m,d]),qe=g.useCallback(O=>{w(z=>z&&{...z,preferences:O.preferences})},[]);g.useEffect(()=>{const O=fa(y?.preferences);n(O.defaultChatProvider),t(O.defaultChatModel)},[y?.preferences.defaultChatProvider,y?.preferences.defaultChatModel,t,n]),g.useEffect(()=>{a(fa(y?.preferences).codexPermissionMode)},[y?.preferences.codexPermissionMode,a]),g.useEffect(()=>{o(fa(y?.preferences).codexReasoningEffort)},[y?.preferences.codexReasoningEffort,o]),g.useEffect(()=>{i(fa(y?.preferences).openPondCommandAccessMode)},[y?.preferences.openPondCommandAccessMode,i]),g.useEffect(()=>{if(!h||!y){ne.current=null;return}if(y.account.state!=="signed_in"){ne.current=null,We();return}const O=fh(y.account);if(!O){ne.current=null,We();return}We(),ae("team");const z=y.preferences.defaultTeamId?.trim()??"",X=t7(O,z,y.accountMeta.asOf??"initial");if(ne.current===X)return;ne.current=X;let fe=!1;const Me=Le=>$v({teamId:Le,accountKey:O,fetchAgents:async et=>(await Y.listSandboxAgents(h,{teamId:et})).agents}).catch(()=>{!fe&&ne.current===X&&(ne.current=null)});return _0({accountKey:O,force:!0,fetchOrganizations:()=>cS(h)}).then(async Le=>{if(fe)return;if(Le.length===0){We();return}if(!!z&&Le.some(st=>st.teamId===z)){await Me(z),We();return}const Xe=R9(Le)?.teamId;if(!Xe){We();return}if(z){s("The configured default team is unavailable for this account. Select an available team in account settings."),We();return}await Me(Xe),fe||We()}).catch(Le=>{fe||(ne.current=null,s(Le instanceof Error?Le.message:String(Le)),We())}),()=>{fe=!0}},[nt,qe,y?.account,y?.accountMeta.asOf,y?.preferences.defaultTeamId,We,h,ae,s]),g.useEffect(()=>{if(!h||!Te)return;let O=!1;const z=()=>{O||(O=!0,_0({accountKey:Te,force:!0,fetchOrganizations:()=>cS(h)}).catch(()=>{}).finally(()=>{O=!1}))},X=()=>{document.visibilityState==="visible"&&z()},fe=window.setInterval(z,QG);return window.addEventListener("focus",z),document.addEventListener("visibilitychange",X),()=>{window.clearInterval(fe),window.removeEventListener("focus",z),document.removeEventListener("visibilitychange",X)}},[h,Te]),xc(()=>{const O=G3();s(O||(z=>z?.startsWith("Preference changes have not been saved.")?null:z))}),g.useEffect(()=>{h&&Xy(h).catch(O=>s(String(O)))},[h,Te,s]);const Ze=g.useCallback(async()=>{ae("connecting"),$(null);const O=await h5();v(X=>IG(X,O)?X:O),ae("account");const z=await Y.bootstrap(O);await Xy(O),nt(z),We(),s(X=>X&&(E_(X)||X==="Event stream disconnected")?null:X)},[nt,We,ae,s]);g.useEffect(()=>{let O=!1,z=null;const X=async fe=>{try{await Ze()}catch(Me){if(O)return;s(Me instanceof Error?Me.message:String(Me));const Le=Math.min(5e3,750+fe*750);z=window.setTimeout(()=>{X(fe+1)},Le)}};return X(0),()=>{O=!0,z!==null&&window.clearTimeout(z)}},[Ze,s]);const He=g.useCallback(()=>{Ze().catch(()=>{})},[Ze]);vG({afterSequence:N?.afterSequence??null,appendEvents:C,connection:h,setApprovals:B,setSessions:ze,setError:s,onDisconnected:He}),g.useEffect(()=>{if(!h||!y){we.current=null;return}const O=SG(R);!O||we.current===O||(we.current=O,Y.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,R,s]);const L=g.useCallback(()=>{h&&Y.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:nt,approvals:U,bootstrap:y,codexHistorySessions:P,connection:h,events:R,runtimeEventStore:_,refreshOpenPondAccount:L,sessions:j,startup:ZG(se),setAppPreferences:Se,setBootstrap:w,setCodexHistorySessions:Qe,setEvents:M,setSessions:ze}}async function cS(e){return(await Y.organizations(e)).organizations.map(Ku).filter(n=>!!n).filter(n=>n.status==="active")}function e7(e){return e>=YG?0:Math.max(0,JG-e)}function t7(e,t,n){return`${e}::${t||"none"}::${n}`}function n7({appDispatch:e,error:t,setErrorState:n}){const a=g.useRef(null),o=g.useRef(null),i=g.useRef(null),s=g.useRef(0),l=g.useCallback((d,h="info",v={})=>{const y=Date.now()+ ++s.current;return e({type:"showToast",toast:{id:y,message:d,tone:h,...v}}),y},[e]),m=g.useCallback(d=>{const h=o.current,v=typeof d=="function"?d(h):d;if(Object.is(h,v))return;if(o.current=v,n(v),!v){i.current!==null&&(e({type:"clearToast",toastId:i.current}),i.current=null);return}i.current=l(a7(v),"error");const y=a.current;y&&Y.recordClientDiagnostic(y,{message:v,surface:"app",context:{href:window.location.href}}).catch(w=>{console.warn("Unable to record client diagnostic.",w)})},[e,n,l]);return g.useEffect(()=>{o.current=t,!(t||i.current===null)&&(e({type:"clearToast",toastId:i.current}),i.current=null)},[e,t]),{connectionRef:a,setError:m,showToast:l}}function a7(e){return T_(e)}const o7={query:"",searchOpen:!1,archivedChatsOpen:!1,sectionMenuOpen:null,projectsExpanded:!1,cloudProjectsExpanded:!1,chatRowsVisibleCount:An,sidebarOpen:!0,view:"chat",selectedAppId:null,selectedProjectId:null,selectedSessionId:null,prompt:"",promptDrafts:{},draftProvider:Gr,draftModel:Nl,draftExperience:"chat",codexPermissionMode:eg,codexReasoningEffort:tg,openPondCommandAccessMode:mu,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 Dv(e){return e.selectedSessionId?`session:${e.selectedSessionId}`:e.selectedProjectId?`project:${e.selectedProjectId}`:e.selectedAppId?`app:${e.selectedAppId}`:`new-${e.draftExperience}`}function tu(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 r7(e){return tu(e.promptDrafts,Dv(e),e.prompt)}function pl(e,t,n={}){const a={...e,...t},o=Dv(a),i=r7(e),s=n.clearSelectedDraft?tu(i,o,""):n.preserveCurrentPrompt?tu(i,o,e.prompt):i;return{...e,...t,promptDrafts:s,prompt:n.clearSelectedDraft?"":n.preserveCurrentPrompt?e.prompt:s[o]??""}}function i7(e){return e==="draftExperience"||e==="selectedAppId"||e==="selectedProjectId"||e==="selectedSessionId"}function s7(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:tu(e.promptDrafts,Dv(e),o)}}return i7(t.key)?pl(e,{[t.key]:a}):{...e,[t.key]:a}}case"patch":return{...e,...t.patch};case"selectApp":return pl(e,{selectedAppId:t.appId,selectedProjectId:null,selectedSessionId:null,view:"chat"});case"selectProject":return pl(e,{selectedAppId:null,selectedProjectId:t.projectId,selectedSessionId:null,view:"chat"},{preserveCurrentPrompt:!0});case"selectSession":{const n=t.projectId??null;return pl(e,{selectedSessionId:t.sessionId,selectedAppId:n?null:t.appId??null,selectedProjectId:n,view:"chat"})}case"beginNewChat":return pl(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 l7(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 fl(e){return e.selectedSessionId?`session:${e.selectedSessionId}`:e.selectedProjectId?`project:${e.selectedProjectId}`:e.selectedAppId?`app:${e.selectedAppId}`:"new-chat"}function c7(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=fl(t);n?a.set(d,n):a.delete(d)},l=(d,h={})=>{const v=n;s(),t={...t,...d};const y=fl(t);if(h.clear&&a.delete(y),h.preserveCurrentDraft){v?a.set(y,v):a.delete(y),i(v);return}i(h.clear?"":a.get(y)??"")},m={getScopeKey:()=>fl(t),getSnapshot:()=>n,subscribe(d){return o.add(d),()=>o.delete(d)},set:d=>m.setForScope(fl(t),d),setForScope(d,h){const v=fl(t),y=d===v?n:a.get(d)??"",w=typeof h=="function"?h(y):h;Object.is(y,w)||(w?a.set(d,w):a.delete(d),d===v&&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],v=typeof d.value=="function"?d.value(h):d.value;Object.is(h,v)||l({[d.key]:v})}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 sX(e){return g.useSyncExternalStore(e.subscribe,e.getSnapshot,e.getSnapshot)}function d7(e){return{...e,draftExperience:Av()}}function u7(){const[e,t]=g.useReducer(s7,o7,d7),[n]=g.useState(()=>c7()),a=g.useCallback(i=>{n.applyAppAction(i),t(i)},[n]),o=g.useMemo(()=>({...l7(a),setPrompt:n.set}),[n,a]);return xc(()=>o.setDraftExperience(Av())),{composerDraftStore:n,dispatch:a,setters:o,state:e}}function m7(e){return!!(e&&e.includes("Git is required for OpenPond app workspaces")&&e.includes("Command Line Tools"))}function p7(e){const{connection:t,events:n,showToast:a}=e,o=g.useRef(new Set),i=g.useCallback(async()=>{if(t)try{const l=await Y.installMacOSCommandLineTools(t);a(l.message,"info")}catch(l){a(l instanceof Error?l.message:String(l),"error")}},[t,a]),s=g.useCallback((l="OpenPond needs Git to create and sync local projects.")=>{a(l,"error",{actionLabel:"Install Tools",onAction:()=>{i()},persistent:!0})},[a,i]);g.useEffect(()=>{if(!t)return;let l=!1;return Y.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]),g.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"&&m7(m)&&(o.current.add(l.id),s("OpenPond needs Git before it can update this project."))}},[n,s])}function f7({connection:e,preferences:t,sidebarOpen:n,diffPanelExpanded:a,setBootstrap:o,setError:i}){const[s,l]=g.useState(()=>fa().sidebarSectionsCollapsed),m=g.useRef(s),d=g.useRef({}),h=g.useRef(null),v=g.useRef(null),[y,w]=g.useState(xG),[_,R]=g.useState(!1),[M,C]=g.useState(kG),[N,$]=g.useState(!1),{pinned:j,projects:k,cloudProjects:P,chats:T,savedForLater:U}=s;g.useEffect(()=>{if(_)return;const ne=cf(fa(t).sidebarWidth),ge=aS(ne,h.current);h.current=ge.localChange,w(ge.value)},[t,_]),g.useEffect(()=>{if(N)return;const ne=df(fa(t).diffPanelWidth),ge=aS(ne,v.current);v.current=ge.localChange,C(ge.value)},[N,t]),g.useEffect(()=>{const ne=fa(t).sidebarSectionsCollapsed;l(ge=>{const xe=MG(ge,ne,d.current);return m.current=xe,xe})},[t]);const B=g.useCallback(ne=>{o(ge=>ge&&{...ge,preferences:ne.preferences})},[o]),D=g.useCallback(async ne=>{if(e&&cf(fa(t).sidebarWidth)!==ne)try{B(await Y.savePreferences(e,{sidebarWidth:ne}))}catch(ge){i(ge instanceof Error?ge.message:String(ge))}},[e,t,i,B]),W=g.useCallback(async ne=>{if(e&&df(fa(t).diffPanelWidth)!==ne)try{B(await Y.savePreferences(e,{diffPanelWidth:ne}))}catch(ge){i(ge instanceof Error?ge.message:String(ge))}},[e,t,i,B]),se=g.useCallback(async ne=>{if(!e)return;const ge=fa(t).sidebarSectionsCollapsed;if(!h7(ge,ne))try{B(await Y.savePreferences(e,{sidebarSectionsCollapsed:ne}))}catch(xe){i(xe instanceof Error?xe.message:String(xe))}},[e,t,i,B]),me=g.useCallback(ne=>{const ge=m.current;EG(d.current,ge,ne),m.current=ne,l(ne),se(ne)},[se]),Te=g.useCallback(()=>{const ne=m.current;me({...ne,pinned:!ne.pinned})},[me]),ke=g.useCallback(()=>{const ne=m.current;me({...ne,projects:!ne.projects})},[me]),V=g.useCallback(()=>{const ne=m.current;me({...ne,cloudProjects:!ne.cloudProjects})},[me]),Re=g.useCallback(()=>{const ne=m.current;me({...ne,chats:!ne.chats})},[me]),be=g.useCallback(()=>{const ne=m.current;me({...ne,savedForLater:!ne.savedForLater})},[me]),ce=g.useCallback(ne=>{if(!n)return;ne.preventDefault();const ge=ne.clientX,xe=y;let De=xe;R(!0);function we(Se){De=cf(xe+Se.clientX-ge),w(De)}function ae(){window.removeEventListener("pointermove",we),window.removeEventListener("pointerup",ae);const Se=nS(xe,De);Se&&(h.current=Se),R(!1),D(De)}window.addEventListener("pointermove",we),window.addEventListener("pointerup",ae,{once:!0})},[D,n,y]),ye=g.useCallback(ne=>{if(a)return;ne.preventDefault();const ge=ne.clientX,xe=M;let De=xe;$(!0);function we(Se){De=df(xe-(Se.clientX-ge)),C(De)}function ae(){window.removeEventListener("pointermove",we),window.removeEventListener("pointerup",ae);const Se=nS(xe,De);Se&&(v.current=Se),$(!1),W(De)}window.addEventListener("pointermove",we),window.addEventListener("pointerup",ae,{once:!0})},[a,M,W]);return{pinnedCollapsed:j,projectsCollapsed:k,cloudProjectsCollapsed:P,chatsCollapsed:T,savedForLaterCollapsed:U,sidebarWidth:y,sidebarResizing:_,diffPanelWidth:M,diffPanelResizing:N,togglePinnedCollapsed:Te,toggleProjectsCollapsed:ke,toggleCloudProjectsCollapsed:V,toggleChatsCollapsed:Re,toggleSavedForLaterCollapsed:be,startSidebarResize:ce,startDiffPanelResize:ye}}function h7(e,t){return e.pinned===t.pinned&&e.projects===t.projects&&e.cloudProjects===t.cloudProjects&&e.chats===t.chats&&e.savedForLater===t.savedForLater}function g7(e){const[t,n]=g.useState({id:0,kind:null}),[a,o]=g.useState(null),i=g.useCallback((d=null)=>{n(h=>({id:h.id+1,kind:d}))},[]),s=g.useCallback(d=>{o(d)},[]),l=null,m=g.useMemo(()=>{if(e)return v7(a,i)},[e,a,i]);return{backAction:l,breadcrumbs:m,closeDetailKind:t.kind,closeDetailRequestId:t.id,onDetailOpenChange:s}}function v7(e,t){return e?[{label:"Models",onSelect:()=>t(null)},{label:e.kindLabel,onSelect:e.kindOnSelect??(()=>t(e.kind))},...e.workproductLabel?[{label:e.workproductLabel,onSelect:e.workproductOnSelect}]:[],...e.segments]:[{label:"Models"}]}const dS=new WeakMap,Ih=new WeakMap;function b7(e){if(!e)return"disconnected";let t=dS.get(e);return(!t||t.serverUrl!==e.serverUrl||t.token!==e.token)&&(t={serverUrl:e.serverUrl,token:e.token,id:crypto.randomUUID()},dS.set(e,t)),t.id}function lX(e,t){return Ih.set(e,t),e}function cX(e){if(!e)return["learning","disconnected"];let t=Ih.get(e);return t||(t=["learning",crypto.randomUUID()],Ih.set(e,t)),t}var nu=xt.shape.id,y7=c({schemaVersion:S("openpond.modelBatchReviewInspection.v1"),packageHash:r().regex(/^[a-f0-9]{64}$/),definition:_u,binding:Iu,evidence:p(Cu).min(1).max(1e4),decisions:p(Eg).min(1).max(1e4)}).strict(),dX=c({schemaVersion:S("openpond.modelBatchReviewRequest.v1"),operationId:nu,modelId:nu,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:Ht.optional(),outputSchema:Ht.optional(),requiredOutputs:_u.shape.requiredOutputs}).strict(),examples:p(c({evidence:xt,input:Ht.optional(),expected:Ht.nullable().optional(),evaluatorContext:Ht.nullable().optional(),proposedTarget:Ht.nullable().optional()}).strict()).max(1e4)}).strict(),S7=c({schemaVersion:S("openpond.modelBatchReviewReceipt.v1"),operationId:nu,modelId:nu,source:Tg,evidence:p(Cu).min(1).max(1e4),proposals:p(Fw).max(1e4)}).strict();function x7(e,t,n){return{inspectModelBatch:async a=>{if(!e)throw new Error("Connect to OpenPond to inspect this batch.");return y7.parse(await Y.trainingRequest(e,"/models/batch-review/inspect",{profileId:t,modelId:a},"POST"))},beginModelBatchReview:async a=>{const o=await n(a);return o?S7.parse(o):null}}}function k7(e,t,n,a){async function o(i,s){if(!e)throw new Error("Connect to OpenPond to load tasks.");const l=Gq.parse(s),m=new URLSearchParams({profileId:t});for(const[d,h]of Object.entries(l))h!==void 0&&m.set(d,String(h));return Y.trainingRequest(e,`${i}?${m}`,{},"GET")}return{taskInventory:async(i={})=>Jq.parse(await o("/tasks",i)),taskInventoryDetail:async i=>{const s=await o("/tasks/detail",i);return{item:cI.parse(s.item),task:Kg.parse(s.task)}},tasksetDraftFiles:async i=>{if(!e)return null;try{return await Y.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 Y.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 Y.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 HC(e,t){return wU({id:e.id,profileId:e.profileId,name:e.name,objective:e.objective,defaultBaseModel:e.defaultBaseModel,defaultDestinationId:e.defaultDestinationId,trainingSetup:e.trainingSetup},t)}async function w7(e,t,n){if(!e)throw new Error("Connect to the execution owner to check this configuration.");const a=await HC(t,n);return s1.parse(await Y.trainingRequest(e,"/models/check",a,"POST"))}function I7(e,t){return{listModelStarters:async(n,a=!1)=>{if(!e)throw new Error("Connect to OpenPond to browse model starters.");return Y.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 Y.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 s1.parse(await Y.trainingRequest(e,"/model-starters/check",n))},createModelFromStarter:n=>t("create-model-from-starter","/model-starters/create",n)}}const uS=1e4,mS=3e4;function _7(e){const{connection:t,profileId:n}=e,a=OS(),o=b7(t),i=g.useMemo(()=>["training",o,n],[o,n]),s=g.useCallback(async()=>b4.parse(await Y.trainingState(t,n)),[t,n]),l=YR({queryKey:i,queryFn:s,enabled:!!t}),m=l.data??null,d=!!t&&l.isPending,[h,v]=g.useState(null),[y,w]=g.useState(null),_=g.useRef(null);_.current=m?.activityRevision??null;const R=g.useCallback(async()=>{if(!t)return null;try{const k=await a.fetchQuery({queryKey:i,queryFn:s,staleTime:0});return w(null),k}catch(k){return w(Po(k)),null}},[t,a,i,s]),M=g.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]}),R()),[a,i,o,n,R]),C=g.useCallback(async(k,P,T,U="POST",B={})=>{if(!t)return null;B.silent||v(k);try{const D=await Y.trainingRequest(t,P,T,U);return await M(),B.silent||w(null),D}catch(D){return B.silent||w(Po(D)),null}finally{B.silent||v(null)}},[t,M]),N=m?[m.jobs.some(k=>["queued","starting","running","cancelling","reconciling"].includes(k.status)),m.creations.some(k=>["planning","materializing","validating"].includes(k.state)),m.minerRuns.some(k=>["queued","running","cancelling"].includes(k.status)),m.datasetImports.some(k=>["inspecting","materializing","validating","cancelling"].includes(k.status))].some(Boolean):!1;g.useEffect(()=>{if(!t)return;let k=!0,P=null;const T=N?uS:mS,U=async()=>{let B=T;try{const D=await Y.trainingActivity(t,n);B=D.active?uS:mS,(_.current===null||_.current!==D.revision)&&await R()}catch(D){w(Po(D))}k&&(P=window.setTimeout(()=>{U()},B))};return P=window.setTimeout(()=>{U()},T),()=>{k=!1,P!==null&&window.clearTimeout(P)}},[t,N,n,R]);const $=g.useMemo(()=>({...I7(t,C),saveComparisonSeries:k=>C("save-comparison-series","/comparison-series",{series:k}),saveContinualBenchIssueReview:k=>C("save-continual-support-issue-review","/continual-support/issue-reviews",{review:k},"PUT"),importContinualLearningDailyBatch:(k,P="json_upload")=>C("import-continual-learning-daily-batch","/continual-learning/daily-batches/import",{manifest:k,source:P}),saveContinualLearningDailyBatch:k=>C("save-continual-learning-daily-batch","/continual-learning/daily-batches",{batch:k},"PUT"),generateContinualLearningResponses:k=>C("generate-continual-learning-responses","/continual-learning/responses",k),sealComparisonSeries:(k,P)=>C("seal-comparison-series",`/comparison-series/${encodeURIComponent(k)}/seal`,{expectedRevision:P}),archiveComparisonSeries:(k,P)=>C("archive-comparison-series",`/comparison-series/${encodeURIComponent(k)}/archive`,{expectedRevision:P}),queueComparisonRelease:k=>C("queue-comparison-release",`/comparison-series/${encodeURIComponent(k.seriesId)}/releases`,k),startComparisonEvaluation:k=>C("start-comparison-evaluation",`/comparison-series-entries/${encodeURIComponent(k.entryId)}/evaluations`,k),loadComparisonAttemptEvidence:k=>t?Y.trainingRequest(t,`/model-runs/${encodeURIComponent(k.runId)}/attempts/${encodeURIComponent(k.attemptId)}/evidence?kind=${k.kind}`,{},"GET"):Promise.resolve(null),linkComparisonRun:k=>C("link-comparison-run",`/comparison-series-entries/${encodeURIComponent(k.entryId)}/run`,k,"PATCH"),decideComparisonEntry:k=>C("decide-comparison-entry",`/comparison-series-entries/${encodeURIComponent(k.entryId)}/decision`,k),recordComparisonPromotion:k=>C("record-comparison-promotion",`/comparison-series-entries/${encodeURIComponent(k.entryId)}/promotion`,k),checkModelProject:(k,P=k.revision)=>w7(t,k,P),...x7(t,n,k=>C("begin-model-batch-review","/models/batch-review",{profileId:n,request:k})),saveModelProject:async(k,P=k.revision)=>C("save-model-project","/models",await HC(k,P),"PUT"),listHostedModelProjects:async(k={})=>{if(!t)return null;k.silent||v("list-hosted-model-projects");try{const P=await Y.trainingRequest(t,`/hosted-model-projects?profileId=${encodeURIComponent(n)}&refresh=${k.refresh===!0}`,{},"GET");return k.silent||w(null),P}catch(P){return k.silent||w(Po(P)),null}finally{k.silent||v(P=>P==="list-hosted-model-projects"?null:P)}},openHostedModelProject:(k,P,T,U={})=>C(`open-hosted-model-project:${k}`,`/hosted-model-projects/${encodeURIComponent(k)}/open`,{profileId:n,teamId:P,apiOrigin:T},"POST",U),pullHostedModelProject:k=>C(`pull-hosted-model-project:${k}`,`/hosted-model-projects/${encodeURIComponent(k)}/pull`,{profileId:n}),syncModelProject:k=>C("sync-model-project",`/models/${encodeURIComponent(k)}/sync`,{}),publishModelProjectTaskset:(k,P)=>C("publish-model-project-taskset",`/models/${encodeURIComponent(k)}/tasksets/${encodeURIComponent(P)}/publish`,{}),createScorer:(k,P,T)=>C("create-scorer","/scorers",{grader:k,tasksetId:P,modelProjectId:T??null}),prepareLearningBatch:k=>C("prepare-learning-batch","/learning-batches/prepare",{profileId:n,batchId:k}),...k7(t,n,C,k=>w(Po(k))),tasksetGraderDetails:async k=>{if(!t)return null;try{return await Y.trainingRequest(t,`/tasksets/${encodeURIComponent(k)}/graders`,{},"GET")}catch(P){return w(Po(P)),null}},inspectHuggingFaceDataset:k=>C("inspect-huggingface-dataset","/dataset-imports/huggingface/inspect",{profileId:n,url:k}),materializeDatasetImport:(k,P)=>C("materialize-dataset-import",`/dataset-imports/${encodeURIComponent(k)}/materialize`,P),cancelDatasetImport:k=>C("cancel-dataset-import",`/dataset-imports/${encodeURIComponent(k)}/cancel`,{}),datasetRows:(k,P={})=>{if(!t)return Promise.resolve(null);const T=new URLSearchParams;P.split&&T.set("split",P.split),P.cursor&&T.set("cursor",P.cursor),T.set("limit",String(P.limit??25));for(const U of P.columns??[])T.append("column",U);return Y.trainingRequest(t,`/tasksets/${encodeURIComponent(k)}/rows?${T}`,{},"GET")},addSource:(k,P)=>C("add-source","/sources",{profileId:n,sessionId:k,turnIds:P}),addSources:k=>C("add-sources","/sources/batch",{profileId:n,sessionIds:k}),estimateSources:k=>t?Y.trainingRequest(t,"/sources/estimate",{sessionIds:k}):Promise.resolve([]),searchChats:(k,P,T=0,U=20)=>t?Y.trainingRequest(t,"/sources/search",{query:k,candidates:P,offset:T,limit:U}):Promise.resolve({schemaVersion:"openpond.trainingChatSearchResult.v1",query:k,offset:T,limit:U,total:0,hasMore:!1,indexedChats:0,totalChats:0,indexing:!1,entries:[]}),removeSource:k=>C("remove-source",`/sources/${encodeURIComponent(k)}`,{},"DELETE"),deleteTaskset:k=>C("delete-model",`/tasksets/${encodeURIComponent(k)}`,{},"DELETE"),runBenchmark:(k,P,T,U)=>C(`run-benchmark-${P}`,`/tasksets/${encodeURIComponent(k)}/benchmark-runs`,{phase:P,model:T,reasoningEffort:U,seeds:[17],repetitions:1}),startHarnessRefinerBenchmark:(k,P,T)=>C("run-harness-refiner-benchmark",`/models/${encodeURIComponent(k)}/harness-refiner-benchmark`,{profileId:n,model:P,reasoningEffort:T,maximumSpendUsd:10}),acceptHarnessReview:(k,P,T=null,U=null)=>C("accept-harness-review","/harness-reviews/accept",{profileId:n,workspaceId:k,reviewRef:P,analysisModel:T,analysisReasoningEffort:U}),startCreation:(k,P={})=>C("create-taskset","/task-creations",{profileId:n,sourceIds:k,surface:P.surface??"training_page",mode:P.mode??"defaults",entryMode:P.entryMode??"manual",resourceIntent:P.resourceIntent??"workproduct",buildIntent:P.buildIntent??"demonstrations",buildSpecification:P.buildSpecification??null,objective:P.objective??null,methodHint:P.methodHint??null,preferredBaseModelId:P.preferredBaseModel?.modelId??null,preferredBaseModel:P.preferredBaseModel??null,candidateId:P.candidateId??null,analysisModel:P.analysisModel??null,analysisReasoningEffort:P.analysisReasoningEffort??null,createImproveRunId:P.createImproveRunId??null,targetIntent:P.targetIntent??{kind:"model",id:null,displayName:null,operation:"create"}}),createModelFromTaskset:(k,P)=>C("create-model","/models/from-taskset",{profileId:n,tasksetId:k,preferredBaseModelId:P.modelId,preferredBaseModel:P}),scanBaseModels:async()=>{if(!t)return null;v("scan-base-models");try{const k=await R();return w(null),k}catch(k){return w(Po(k)),null}finally{v(null)}},approveDisclosure:(k,P)=>C("approve-disclosure",`/task-creations/${encodeURIComponent(k)}/disclosure`,{approved:P}),retryCreation:k=>C("retry-creation",`/task-creations/${encodeURIComponent(k)}/retry`,{}),answerQuestions:(k,P)=>C("answer-questions",`/task-creations/${encodeURIComponent(k)}/questions`,{answers:P}),materialize:(k,P)=>C("materialize",`/task-creations/${encodeURIComponent(k)}/materialize`,{approved:P}),chatCreation:(k,P)=>C("task-creator-chat",`/task-creations/${encodeURIComponent(k)}/chat`,{message:P}),renameCreation:(k,P)=>C("rename-creation",`/task-creations/${encodeURIComponent(k)}/name`,{name:P},"PATCH"),cancelCreation:k=>C("cancel-creation",`/task-creations/${encodeURIComponent(k)}/cancel`,{}),runMiner:(k=[],P=[],T)=>C("run-miner","/miner/run",{profileId:n,sourceIds:k,sessionIds:P,config:T}),cancelMinerRun:k=>C("cancel-miner-run",`/miner/runs/${encodeURIComponent(k)}/cancel`,{}),configureMiner:k=>C("configure-miner","/miner/config",{profileId:n,config:k},"PUT"),patchCandidate:(k,P)=>C("candidate",`/candidates/${encodeURIComponent(k)}`,P,"PATCH"),createCandidate:(k,P,T,U)=>C("create-candidate",`/candidates/${encodeURIComponent(k)}/create`,{mode:P,analysisModel:T??null,analysisReasoningEffort:U??null}),auditGraders:k=>C("audit-graders","/audit-graders",{tasksetId:k}),executeTasksetAttempt:(k,P,T)=>C("execute-taskset-attempt",`/tasksets/${encodeURIComponent(k)}/attempts`,{taskId:P,model:T,seed:17,attempt:0,sampling:{maxOutputTokens:4096,temperature:0,topP:1}}),materializeSyntheticPreferenceCollection:k=>C("materialize-synthetic-preference-collection",`/tasksets/${encodeURIComponent(k.tasksetId)}/synthetic-preference-collection`,k),tasksetOperationalState:k=>t?Y.trainingRequest(t,`/tasksets/${encodeURIComponent(k)}/operations`,{},"GET"):Promise.resolve(null),calibrateJudges:k=>C("calibrate-judges","/calibrate-judges",{tasksetId:k}),nextPreferenceComparison:(k,P)=>C("next-preference-comparison",`/tasksets/${encodeURIComponent(k)}/preference-comparisons/next`,{reviewerKey:P}),submitPreferenceComparison:k=>C("submit-preference-comparison",`/tasksets/${encodeURIComponent(k.tasksetId)}/preference-comparisons/${encodeURIComponent(k.assignmentId)}/submit`,k),submitSyntheticFixturePreference:k=>C("submit-synthetic-fixture-preference",`/tasksets/${encodeURIComponent(k.tasksetId)}/preference-comparisons/${encodeURIComponent(k.assignmentId)}/fixture-submit`,{...k,id:crypto.randomUUID()}),listPreferenceDatasets:k=>t?Y.trainingRequest(t,`/tasksets/${encodeURIComponent(k)}/preference-datasets`,{},"GET"):Promise.resolve(null),materializePreferenceDataset:k=>C("materialize-preference-dataset",`/tasksets/${encodeURIComponent(k.tasksetId)}/preference-datasets`,{...k,id:`preference-dataset-${crypto.randomUUID()}`,revision:1}),launchRewardModelRun:k=>C("launch-reward-model-run",`/tasksets/${encodeURIComponent(k.tasksetId)}/reward-model-runs`,{...k,id:`reward-model-run-${crypto.randomUUID()}`}),learnedPreferenceRewardBinding:k=>C("learned-preference-reward-binding",`/tasksets/${encodeURIComponent(k.tasksetId)}/learned-preference-reward-binding`,k),retryRewardModelQualification:k=>C("retry-reward-model-qualification",`/reward-model-runs/${encodeURIComponent(k.runId)}/retry-qualification`,k),cancelRewardModelRun:k=>C("cancel-reward-model-run",`/reward-model-runs/${encodeURIComponent(k)}/cancel`,{}),markPreferenceComparisonUnreviewable:k=>C("mark-preference-comparison-unreviewable",`/tasksets/${encodeURIComponent(k.tasksetId)}/preference-comparisons/${encodeURIComponent(k.assignmentId)}/unreviewable`,k),preferenceCalibrationStatus:(k,P,T)=>{if(!t)return Promise.resolve(null);const U=new URLSearchParams({reviewerKey:P});return T&&U.set("comparisonReleaseId",T),Y.trainingRequest(t,`/tasksets/${encodeURIComponent(k)}/preference-comparisons/calibration/status?${U}`,{},"GET")},startPreferenceCalibrationBatch:k=>C("start-preference-calibration-batch",`/tasksets/${encodeURIComponent(k.tasksetId)}/preference-comparisons/calibration/batches`,{...k,id:crypto.randomUUID()}),syncPreferenceCalibrationBatch:k=>C("sync-preference-calibration-batch",`/tasksets/${encodeURIComponent(k.tasksetId)}/preference-comparisons/calibration/batches/${encodeURIComponent(k.jobId)}/sync`,k),reviewPreferenceComparisonWithModel:k=>C("review-preference-comparison-with-model",`/tasksets/${encodeURIComponent(k.tasksetId)}/preference-comparisons/${encodeURIComponent(k.assignmentId)}/model-review`,{...k,id:crypto.randomUUID()}),runNextPreferenceCalibrationReview:k=>C("run-next-preference-calibration-review",`/tasksets/${encodeURIComponent(k.tasksetId)}/preference-comparisons/calibration/model-reviews/next`,{...k,id:crypto.randomUUID()}),savePreferenceCalibration:k=>C("save-preference-calibration",`/tasksets/${encodeURIComponent(k.tasksetId)}/preference-comparisons/calibration/report`,{...k,id:crypto.randomUUID()}),preferenceArtifactUrl:async k=>{if(!t)return null;const P=await fetch(`${t.serverUrl}/v1/training/artifacts/${encodeURIComponent(k)}/download`,{headers:{Authorization:`Bearer ${t.token}`}});if(!P.ok)throw new Error(await P.text());return URL.createObjectURL(await P.blob())},readiness:k=>C("readiness","/readiness",{tasksetId:k}),previewExpertBootstrap:k=>C("preview-expert-bootstrap",`/tasksets/${encodeURIComponent(k)}/expert-bootstrap/preview`,{}),approveExpertBootstrap:(k,P)=>C("approve-expert-bootstrap",`/tasksets/${encodeURIComponent(k)}/expert-bootstrap/approve`,{previewHash:P}),createPlan:k=>C("create-plan","/plans",{...k,tasksetId:k.tasksetId}),buildBundle:k=>C("build-bundle","/bundles",{planId:k}),approveTraining:(k,P)=>C("approve-training","/approvals",{planId:k,bundleId:P}),launch:(k,P)=>C("launch","/launch",{planId:k,approvalId:P}),prepareTraining:k=>C("prepare-training","/prepare",k),prepareModelRun:(k,P)=>C("prepare-model-run",`/model-projects/${encodeURIComponent(k)}/training/prepare`,P),startModelRun:(k,P)=>C("start-model-run",`/model-projects/${encodeURIComponent(k)}/training/start`,P),startPreparedTraining:k=>C("start-prepared-training","/start/prepared",k),startTraining:k=>C("start-training","/start",k),cancelJob:k=>C("cancel-job",`/jobs/${encodeURIComponent(k)}/cancel`,{}),retryModelRunCollection:k=>C("retry-model-run-collection",`/model-runs/${encodeURIComponent(k)}/retry-collection`,{}),cancelModelRun:k=>C("cancel-model-run",`/model-runs/${encodeURIComponent(k)}/cancel`,{}),rejectModel:(k,P)=>C("reject-model",`/models/${encodeURIComponent(k)}/reject`,{reason:P}),bindModel:(k,P,T)=>C("bind-model",`/models/${encodeURIComponent(k)}/bind`,{profileId:n,role:P,roleTargetId:T,promotedBy:n}),rollbackModelBinding:k=>C("rollback-model-binding",`/bindings/${encodeURIComponent(k)}/rollback`,{rolledBackBy:n}),updateModelConfiguration:(k,P)=>C("update-model-configuration",`/models/${encodeURIComponent(k)}/configuration`,P,"PATCH",{silent:!0}),setModelPinned:(k,P)=>C("pin-model-version",`/models/${encodeURIComponent(k)}/pin`,{pinned:P},"PATCH"),downloadArtifact:async k=>{if(!t)return!1;v("download-artifact");try{const P=await fetch(`${t.serverUrl}/v1/training/artifacts/${encodeURIComponent(k)}/download`,{headers:{Authorization:`Bearer ${t.token}`}});if(!P.ok)throw new Error(await P.text());const T=P.headers.get("content-disposition")??"",U=/filename="([^"]+)"/.exec(T)?.[1]??"openpond-model-artifact",B=URL.createObjectURL(await P.blob()),D=document.createElement("a");return D.href=B,D.download=U,D.click(),URL.revokeObjectURL(B),!0}catch(P){return w(Po(P)),!1}finally{v(null)}},downloadModelPackage:async k=>j(`/models/${encodeURIComponent(k)}/download`,`${k}.openpond-lora.tar`),downloadBundle:async k=>j(`/bundles/${encodeURIComponent(k)}/download`,"openpond-model-improvement-bundle.json")}),[t,C,n,R]);async function j(k,P){if(!t)return!1;v("download-bundle");try{const T=await fetch(`${t.serverUrl}/v1/training${k}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!T.ok)throw new Error(await T.text());const U=T.headers.get("content-disposition")??"",B=/filename="([^"]+)"/.exec(U)?.[1]??P,D=URL.createObjectURL(await T.blob()),W=document.createElement("a");return W.href=D,W.download=B,W.click(),URL.revokeObjectURL(D),!0}catch(T){return w(Po(T)),!1}finally{v(null)}}return{connection:t,payload:m,loading:d,busyAction:h,error:y??l.error?.message??null,refresh:R,actions:$}}function Po(e){return e instanceof Error?e.message:String(e)}function uX({modelId:e,taskset:t}){const n=t.metadata.toolContractHash===vc?"cross_system":t.environment.kind==="stateful_harness"&&t.environment.actionBindings?.length?"harness":null,a=n?A7(t,n):[];return{model:{providerId:"openpond",modelId:e},tasksetId:t.id,tasksetName:t.name,taskRuntime:n,sourceProjectId:T7(t),tasks:a,selectedTaskIndex:0,sessionId:null}}function mX(e){return{model:{providerId:"openpond",modelId:e.modelId},tasksetId:e.tasksetId,tasksetName:e.modelName,taskRuntime:null,sourceProjectId:null,tasks:[],selectedTaskIndex:0,sessionId:null}}function zi(e){return e?.tasks.length?e.tasks[BC(e,e.selectedTaskIndex)]??null:null}function zC(e,t){return{...e,selectedTaskIndex:BC(e,t)}}function C7(e){return zC(e,e.selectedTaskIndex+1)}function R7(e,t,n){if(!e||qC(e,n))return null;const a=zi(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 qC(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 P7({model:e,connection:t,loadBootstrap:n,applyBootstrap:a}){e.providerId!=="openpond"||!t||a(await n(t))}function A7(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 T7(e){const t=new Set(e.sourceRefs.filter(vq).flatMap(n=>{const a=n.workspaceId?.trim();return a?[a]:[]}));return t.size===1?t.values().next().value??null:null}function BC(e,t){return e.tasks.length?Math.max(0,Math.min(Math.trunc(t),e.tasks.length-1)):0}function E7({activeModel:e,activeProvider:t,applyBootstrapPayload:n,beginNewChat:a,composerDraftStore:o,connection:i,requestComposerFocus:s,selectedLocalProjectId:l,selectedSessionId:m,selectLocalProject:d,setDraftModel:h,setDraftProvider:v,setError:y,view:w}){const[_,R]=g.useState(null),M=g.useCallback(T=>{T.sourceProjectId?d(T.sourceProjectId):a(null)},[a,d]),C=g.useCallback(T=>{if(!_)return;const U={...zC(_,T),sessionId:_.sessionId?null:_.sessionId},B=zi(U);R(U),B&&(_.sessionId&&M(U),o.set(B.prompt),s())},[M,o,_,s]),N=g.useCallback(()=>{const T=zi(_);T&&o.getSnapshot().trim()===T.prompt.trim()&&o.set(""),R(null)},[o,_]),$=g.useCallback(T=>{const U=T.model;P7({model:U,connection:i,loadBootstrap:Y.bootstrap,applyBootstrap:n}).then(()=>{const B={...T,selectedTaskIndex:0,sessionId:null};v(U.providerId),h(U.modelId),R(B.tasks.length?B:null),M(B);const D=zi(B);D&&o.set(D.prompt)}).catch(y)},[n,M,o,i,h,v,y]),j=g.useCallback(T=>{const U=!!(_&&_.model.providerId===t&&_.model.modelId===e);return{active:U,error:U?qC(_,l):null,metadata:U?R7(_,T,l):null}},[e,t,_,l]),k=g.useCallback(T=>{R(U=>U&&{...U,sessionId:T})},[]),P=g.useCallback(()=>{if(!_)return;const T={...C7(_),sessionId:null},U=zi(T);R(T),U&&(M(T),o.set(U.prompt),s())},[M,o,_,s]);return g.useEffect(()=>{const T=zi(_);!T||w!=="chat"||m||o.set(U=>U.trim()?U:T.prompt)},[o,_,l,m,w]),g.useEffect(()=>{_&&m&&_.sessionId!==m&&R(null)},[_?.sessionId,m]),{advanceAfterTurn:P,begin:$,bindSession:k,dismiss:N,handoff:_,prepareTurn:j,selectTask:C}}const hl=[],uf=500;function M7(e){const{approvals:t,codexHistoryEvents:n,connection:a,latestServerSequence:o,runtimeIndexes:i,runtimeEventStore:s,selectedSessionId:l,serverId:m,setCodexHistoryEvents:d,setCodexHistorySessions:h,setError:v}=e,[y,w]=g.useState({}),[_,R]=g.useState({}),M=g.useRef(new Set);g.useEffect(()=>{w({}),R({}),M.current.clear()},[m]);const C=g.useCallback(async()=>{if(!a||!l||M.current.has(l))return!1;const P=_[l];if(P?.hasMore===!1)return!1;if(Lt(l)){const B=Math.max(P?.totalMatchingEvents??0,n.length,pC),D=Math.min($0,Math.max(uW,B*2));M.current.add(l),R(W=>({...W,[l]:{cursorSequence:null,hasMore:!0,loading:!0,totalMatchingEvents:W[l]?.totalMatchingEvents??n.length}}));try{const W=await fC(a,l,{force:!0,limit:D,tail:!1});return d(W.events),h(se=>Wu(se,W.session)),R(se=>({...se,[l]:{cursorSequence:null,hasMore:W.events.length>=D&&D<$0,loading:!1,totalMatchingEvents:D}})),W.events.length>n.length}catch(W){return v(W instanceof Error?W.message:String(W)),R(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 T=Mo(y[l]??hl,s.getSessionEvents(l)),U=P?.cursorSequence??j7(T);if(!U)return!1;M.current.add(l),R(B=>({...B,[l]:{cursorSequence:B[l]?.cursorSequence??U,hasMore:B[l]?.hasMore??!0,loading:!0,totalMatchingEvents:B[l]?.totalMatchingEvents??null}}));try{const B=await Y.runtimeEventsPage(a,{sessionId:l,beforeSequence:U,limit:uf}),D=B.events.map(W=>W.event);return w(W=>({...W,[l]:Mo(D,W[l]??hl)})),R(W=>({...W,[l]:{cursorSequence:B.previousSequence,hasMore:B.hasMore,loading:!1,totalMatchingEvents:B.totalMatchingEvents}})),D.length>0}catch(B){return v(B instanceof Error?B.message:String(B)),R(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,v]),N=l?y[l]??hl:hl,$=g.useMemo(()=>s.getSessionEvents(l).length,[s,l]),j=g.useRef(null);g.useEffect(()=>{if(!a||!l||Lt(l)||M.current.has(l)||N.length>0||$>0)return;const P=o;if(!P)return;const T=l,U=P+1;M.current.add(T),R(B=>({...B,[T]:{cursorSequence:B[T]?.cursorSequence??U,hasMore:B[T]?.hasMore??!0,loading:!0,totalMatchingEvents:B[T]?.totalMatchingEvents??null}})),Y.runtimeEventsPage(a,{sessionId:T,beforeSequence:U,limit:uf}).then(B=>{const D=B.events.map(W=>W.event);w(W=>({...W,[T]:Mo(D,W[T]??hl)})),R(W=>({...W,[T]:{cursorSequence:B.previousSequence,hasMore:B.hasMore,loading:!1,totalMatchingEvents:B.totalMatchingEvents}}))}).catch(B=>{v(B instanceof Error?B.message:String(B)),R(D=>({...D,[T]:{cursorSequence:D[T]?.cursorSequence??U,hasMore:D[T]?.hasMore??!0,loading:!1,totalMatchingEvents:D[T]?.totalMatchingEvents??null}}))}).finally(()=>{M.current.delete(T)})},[o,a,N.length,$,l,v]),g.useEffect(()=>{if(!a||!l||Lt(l)||M.current.has(l)||!o)return;const P=Mo(N,s.getSessionEvents(l)),T=Qd(P);if(!T||T>=o)return;const U=`${l}:${T}:${o}`;if(j.current===U)return;j.current=U;let B=!1;return Y.runtimeEventsPage(a,{sessionId:l,afterSequence:T,limit:uf}).then(D=>{if(B)return;const W=D.events.map(se=>se.event);W.length!==0&&w(se=>SK(se,l,W))}).catch(D=>{B||(j.current=null,v(D instanceof Error?D.message:String(D)))}),()=>{B=!0}},[o,a,s,N,l,v]);const k=g.useMemo(()=>Lt(l)?ph(n,[]):!l||N.length===0?i:ph(Mo(N,s.getSessionEvents(l)),t),[t,n,i,N,l]);return{chatHistoryLoadStates:_,loadMoreSelectedChatHistory:C,selectedPagedSessionEvents:N,selectedRuntimeIndexes:k}}function j7(e){let t=null;for(const n of e)n.sequence!==void 0&&(t===null||n.sequence<t)&&(t=n.sequence);return t}function O7(e,t){const n=g.useRef(null);return g.useMemo(()=>{const a=G_(e,t,n.current);return n.current={events:e,indexes:a},a},[t,e])}function Qi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function mf(e){return Array.isArray(e)?e.filter(t=>!!Qi(t)):[]}function Nr(e){return typeof e=="string"&&e.trim()?e.trim():null}function pS(e){return Nr(e)??Qi(e)}function $7(e){if(!e)return[];const t=Qi(e.sandboxActionRegistry),n=Qi(e.sandboxManifest),a=new Map;for(const o of[...mf(n?.actionCatalog),...mf(t?.actions),...mf(n?.actions)]){const i=Nr(o.id)??Nr(o.name);if(!i)continue;const s=a.get(i);a.set(i,{id:i,name:Nr(o.name)??s?.name??i,label:Nr(o.label)??s?.label??N7(i),description:Nr(o.description)??s?.description??null,visibility:Nr(o.visibility)??s?.visibility??"default",inputSchema:pS(o.inputSchema)??s?.inputSchema??null,outputSchema:pS(o.outputSchema)??s?.outputSchema??null,implementation:Qi(o.implementation)??s?.implementation??null,mcp:Qi(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 N7(e){const t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e}function FC(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?ka(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 VC="openpond-agent",KC="openpond-profile-action";function Ju(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function jo(e){return typeof e=="string"&&e.trim()?e.trim():null}function Lv(e){return e.displayPrompt&&/(?:^|\s)@[A-Za-z0-9_-]+/.test(e.displayPrompt)?"mention":"slash"}function D7(e){const t=Ju(e),n=jo(t?.scope);return n!=="entire_manifest"&&n!=="start"&&n!=="action"&&n!=="service"&&n!=="schedule"?null:{scope:n,name:jo(t?.name)}}function L7(e){const t=jo(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 U7(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:VC,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 H7(e){const t=Ju(e.implementation);if(t?.type!==VC)return null;const n=jo(t.agentId),a=jo(t.teamId),o=jo(t.projectId),i=D7(t.selectedEntrypoint),s=L7(t.workflowMode);return!n||!a||!o||!i||!s?null:{agentId:n,agentName:jo(t.agentName)??e.label??e.name??e.id,teamId:a,projectId:o,projectName:jo(t.projectName),selectedEntrypoint:i,workflowMode:s}}function z7(e,t={}){const n=t.agentName?.trim()||null;return{...e,implementation:{...Ju(e.implementation)??{},type:KC,actionId:e.id,...n?{agentName:n}:{}},invokesModel:e.invokesModel??!0}}function q7(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=>z7(n,{agentName:n.agentId?t.get(n.agentId):null}))}function pX(e){return!!(e&&Uv(e))}function fX(e){return!!(e&&Uv(e)&&e.sourceActionId==="chat")}function Uv(e){const t=Ju(e.implementation);if(t?.type!==KC)return null;const n=jo(t.actionId)??e.id;return n?{actionId:n,actionLabel:e.label??e.name??n}:null}function B7({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:Lv({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{},...o?{sessionId:o}:{}}}}function F7({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:Lv({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{}}}}function V7({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:Lv({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{}},workflowMode:e.workflowMode}}const Xi=new Map;function Hv(e,t){const n=e?.trim();return n?`${t?.trim()||"global"}|${n}`:null}function K7(e,t){const n=Hv(e,t);if(!n)return null;const a=Xi.get(n);return a?.updatedAt?a.projects:null}function W7(e,t,n){const a=Hv(e,n);a&&Xi.set(a,{projects:t,promise:null,updatedAt:Date.now()})}function G7(e){const t=e.teamId?.trim();if(!t)return Promise.resolve([]);const n=Hv(t,e.accountKey);if(!n)return Promise.resolve([]);const a=Xi.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=>(W7(t,i,e.accountKey),i)).catch(i=>{const s=Xi.get(n);throw s?.promise===o&&Xi.set(n,{projects:s.projects,promise:null,updatedAt:s.updatedAt}),i});return Xi.set(n,{projects:a?.projects??[],promise:o,updatedAt:a?.updatedAt??0}),o}function pf(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 Z7({cloudProjectById:e,cloudProjects:t,connection:n,defaultTeamId:a,accountScopeKey:o,localProjects:i,profile:s,selectedCloudProject:l,selectedProject:m,reportError:d}){const[h,v]=g.useState(null),[y,w]=g.useState([]),[_,R]=g.useState([]),M=g.useMemo(()=>{const T=new Set;a&&T.add(a);for(const U of t)T.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&&T.add(B.teamId)}return[...T].sort()},[t,a,i]),C=M.join("\0"),N=g.useMemo(()=>FC({cloudProjects:t,selectedCloudProject:l,selectedProject:m}),[t,l,m]);g.useEffect(()=>{if(!n||M.length===0){R([]);return}let T=!1;const U=M.flatMap(B=>LC(B,o)??[]);return R(pf(U)),Promise.all(M.map(B=>$v({teamId:B,accountKey:o,fetchAgents:async D=>(await Y.listSandboxAgents(n,{teamId:D})).agents}))).then(B=>{T||R(pf(B.flat()))}).catch(()=>{T||R(pf(U))}),()=>{T=!0}},[o,n,C]),g.useEffect(()=>{if(!n||!N){v(null);return}const T=K7(N.teamId,o);T&&v(T.find(B=>B.id===N.id)??null);let U=!1;return G7({teamId:N.teamId,accountKey:o,fetchProjects:async B=>(await Y.listSandboxProjects(n,{teamId:B})).projects}).then(B=>{U||v(B.find(D=>D.id===N.id)??null)}).catch(()=>{U||v(null)}),()=>{U=!0}},[o,n,N?.id,N?.teamId]),g.useEffect(()=>{if(!n||!m){w([]);return}let T=!1;return Y.localProjectActions(n,m.id).then(U=>{T||w(U.actions)}).catch(U=>{T||(w([]),d?.(`Could not load Project Actions for ${m.name}: ${U instanceof Error?U.message:String(U)}`))}),()=>{T=!0}},[n,d,m?.id,m?.name,m?.updatedAt]);const $=g.useMemo(()=>{const T=new Map;for(const U of $7(h))T.set(U.id,U);for(const U of y)T.set(U.id,U);return[...T.values()]},[y,h]),j=g.useMemo(()=>q7(s),[s]),k=g.useMemo(()=>[..._.map(T=>U7(T,e.get(T.projectId)?.name??null)),...j,...$],[e,j,$,_]);return{openPondActionCatalog:g.useMemo(()=>[...j,...$],[j,$]),selectedActionCatalog:k,selectedProjectActionCatalog:$}}function J7({selectedProjectId:e}){const[t,n]=g.useState(()=>new Set),a=g.useCallback(i=>{n(s=>{if(s.has(i))return s;const l=new Set(s);return l.add(i),l})},[]),o=g.useCallback(i=>{n(s=>{const l=new Set(s);return l.has(i)?l.delete(i):l.add(i),l})},[]);return g.useEffect(()=>{e&&a(e)},[a,e]),{expandedProjectIds:t,expandProject:a,toggleProjectExpanded:o,setExpandedProjectIds:n}}function Y7(){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 ff(e,t,n){return`workspace-status:${e.serverUrl}:${t}:${n?"ensure":"read"}`}function Q7(e,t){return`workspace-diff:${e.serverUrl}:${t}`}function hf(e){return e instanceof Error&&e.name==="AbortError"}function X7({connection:e,activeWorkspaceAppId:t,view:n,shouldLoadWorkspaceDiff:a,sidebarWorkspaceAppIds:o,setError:i}){const[s,l]=g.useState(null),[m,d]=g.useState({}),[h,v]=g.useState(null),[y,w]=g.useState(!1),[_,R]=g.useState(!1),M=g.useRef(new Set),C=g.useRef(new Set),N=g.useRef(Y7()),$=t?m[t]??(s?.appId===t?s:null):null,j=h?.appId===t?h:null,k=n==="chat"||n==="labs",P=g.useCallback(B=>{M.current.add(B.appId),l(B),d(D=>({...D,[B.appId]:B}))},[]),T=g.useCallback(async(B,D=!1)=>{if(!e||!B)return l(null),null;w(!0);const W=N.current.request(ff(e,B,D),se=>Y.workspaceStatus(e,B,D,{signal:se}));try{const se=await W.promise;return P(se),D&&se.error?i(`Workspace sync failed: ${se.error}`):D&&i(null),se}catch(se){return hf(se)||(l(null),i(se instanceof Error?se.message:String(se))),null}finally{W.release(),w(!1)}},[e,P,i]),U=g.useCallback(async(B=t,D={})=>{if(!e||!B)return v(null),null;D.silent||R(!0);const W=N.current.request(Q7(e,B),se=>Y.workspaceDiff(e,B,{signal:se}));try{const se=await W.promise;return v(se),se}catch(se){return hf(se)||(v(null),i(se instanceof Error?se.message:String(se))),null}finally{W.release(),D.silent||R(!1)}},[t,e,i]);return g.useEffect(()=>{if(!e||!t||!k){l(null),v(null),w(!1);return}let B=!1;const D=N.current.request(ff(e,t,!1),W=>Y.workspaceStatus(e,t,!1,{signal:W}));return w(!0),D.promise.then(W=>{B||(P(W),W.initialized||v(se=>se?.appId===W.appId?null:se))}).catch(W=>{hf(W)||B||(l(null),i(W instanceof Error?W.message:String(W)))}).finally(()=>{D.release(),B||w(!1)}),()=>{B=!0,D.release()}},[t,e,P,i,k]),g.useEffect(()=>{if(!e||!t||!k){v(null);return}if(!$?.initialized){$&&!$.initialized&&v(B=>B?.appId===t?null:B);return}a&&U(t)},[t,e,U,a,k,$?.dirty,$?.initialized]),g.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(ff(e,se,!1),me=>Y.workspaceStatus(e,se,!1,{signal:me}))}));return Promise.all(W.map(({appId:se,request:me})=>me.promise.then(Te=>({appId:se,state:Te})).catch(()=>({appId:se,state:null})).finally(()=>{me.release(),C.current.delete(se)}))).then(se=>{if(!D)for(const me of se)me.state&&P(me.state)}),()=>{D=!0,W.forEach(({appId:se,request:me})=>{me.release(),C.current.delete(se)})}},[e,P,o]),g.useEffect(()=>()=>N.current.cancelAll(),[]),{workspaceState:s,workspaceStates:m,workspaceDiff:h,workspaceBusy:y,diffBusy:_,visibleWorkspaceState:$,visibleWorkspaceDiff:j,rememberWorkspaceState:P,refreshWorkspace:T,refreshWorkspaceDiff:U,setWorkspaceBusy:w}}const eZ=1,tZ=15e3,nZ=15e3,WC=5*6e4,aZ=5e3,oZ=1e4;function GC(e,t=(a,o)=>new WebSocket(a,o),n={}){const a=new rZ(e,t,n.reconnectDelayMs??iZ);return a.open(),{close:()=>a.close()}}class rZ{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=WC;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===eZ)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-${sZ(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."))},tZ))},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=cZ(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=dZ(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=lZ();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."))},nZ)}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."))},aZ)}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 iZ(e){const t=Math.min(oZ,500*2**Math.min(e,5));return Math.max(100,Math.floor(Math.random()*t))}function sZ(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 lZ(){return globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random().toString(36).slice(2)}`}function cZ(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:WC}function dZ(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 uZ(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 GC({realtimeUrl:e.session.realtimeUrl,httpUrl:e.session.httpUrl,authorizationToken:e.session.token,channels:a,onEvent:o=>{const i=xw.safeParse(o);i.success&&e.onEvent(i.data)},onReady:e.onReady,onError:e.onError},t,n)}function mZ(e){return e.refs.find(t=>t.refType==="message_reply")??null}function pZ(e){return{id:e.id,authorType:e.authorType,authorUserId:e.authorUserId,authorAgentId:e.authorAgentId,body:e.body,deleted:!!e.deletedAt}}function hX(e,t){const n=mZ(e);if(!n)return null;const a=t.get(n.refId);return a?pZ(a):hZ(n)}function fZ(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 gX(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 vX(e){return e.deleted?"Message deleted":e.body.replace(/\s+/g," ").trim()||"Attachment"}function hZ(e){const t=e.preview;return{id:e.refId,authorType:gZ(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 gZ(e){return e==="agent"||e==="system"?e:"user"}function fS(e,t,n){return n===t.conversationId?{...e,aiThread:t}:e}function vZ(e,t){return!e||e.thread.id!==t.thread.id?t:{...t,messages:_c([...e.messages,...t.messages]),hasMoreBefore:e.messages.length>t.messages.length?e.hasMoreBefore:t.hasMoreBefore}}function gf(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:_c([...e.messages,...n])}}function bZ(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 vf(e,t,n){for(const a of e)!a.clientRequestId||a.id.startsWith("pending:")||(t.delete(a.clientRequestId),n.delete(a.clientRequestId))}function bf(e,t,n){const a=e.get(t);a&&e.set(t,{...a,metadata:{...a.metadata,deliveryStatus:n}})}function hS(e,t,n){const a=e.get(t);a&&e.set(t,{...a,metadata:{...a.metadata,uploadProgress:n}})}function _c(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 ZC(e){return e.type!=="message.created"&&e.type!=="message.updated"&&e.type!=="message.deleted"?null:Ig.safeParse(e.payload.message).data??null}function JC(e,t,n){const a=ZC(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:_c([...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 yZ(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:fZ(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 SZ(e,t){const n=e.detail?.thread.id===t.threadId?{...e.detail,thread:Ss(e.detail.thread,t,"message.created",!0,t.authorUserId),messages:_c([...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 gS(e,t,n){return JC(e,{teamId:t.teamId,threadId:t.threadId,type:"message.created",payload:{message:t},createdAt:t.createdAt},n)}function xZ(e,t){return _h(e,t,"failed")}function _h(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 vS(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 kZ(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?bS(e.detail.thread,a):e.detail.thread,messages:n}:null;return{...e,detail:o,threads:e.threads.map(i=>i.lastMessageId===t?bS(i,a):i)}}function wZ(e){if(e.length>zr.maxAttachments)return null;const t=[];for(const n of e){if(n.kind!=="image"||!IZ(n.mediaType)||!n.contentsBase64||n.sizeBytes<=0||n.sizeBytes>zr.maxAttachmentBytes)return null;t.push({...n,kind:"image",mediaType:n.mediaType,contentsBase64:n.contentsBase64})}return t}function bS(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 IZ(e){return e==="image/png"||e==="image/jpeg"||e==="image/webp"||e==="image/gif"}const _Z={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 CZ(e){const t=e instanceof Error?e.message:String(e),n=t.trim().toLowerCase();for(const[a,o]of Object.entries(_Z))if(n.includes(a))return o;return n.includes("event stream ended")?"Team chat realtime disconnected. Messages will continue to refresh automatically.":TC(t)}const YC="openpond.team-chat.notification-mode";function QC(){try{return typeof window>"u"?null:kc}catch{return null}}function yS(e=QC()){const t=e?.getItem(YC);return t==="direct_mentions"||t==="none"?t:"all"}function RZ(e,t=QC()){try{t?.setItem(YC,e)}catch{}}function PZ(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 AZ(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 SS={members:[],agents:[],threads:[],selectedThreadId:null,detail:null,aiThread:null,agentConversation:null,loading:!1,busy:!1,error:null};function od(e,t){return e.map(n=>n.id===t&&n.unreadCount!==0?{...n,unreadCount:0}:n)}function rd(e){return!e||e.thread.unreadCount===0?e:{...e,thread:{...e.thread,unreadCount:0}}}function TZ(e){return{teamId:e.teamId,body:e.body.trim(),clientRequestId:e.clientRequestId,selectedAgentId:e.conversation.agent.id,conversationId:e.conversation.conversationId}}function EZ(e){return{teamId:e.teamId,body:e.body.trim(),clientRequestId:e.clientRequestId,selectedActionKey:e.selectedActionKey,approvalId:e.approvalId??null}}async function xS(e,t=Y.markTeamChatRead){return e.lastMessageSequence<=0?!1:t(e.connection,e.threadId,e.teamId,e.lastMessageSequence).then(()=>!0,()=>!1)}function MZ(e){const[t,n]=g.useState(SS),a=g.useRef(t);a.current=t;const[o,i]=g.useState(yS);xc(()=>i(yS()));const[s,l]=g.useState(null),m=g.useRef(null),d=g.useRef(null),h=g.useRef(0),v=g.useRef(new Map),y=g.useRef(new Map),w=g.useRef(0),_=g.useRef(null),R=g.useRef(0),M=g.useRef(new Set),C=g.useRef(0),N=g.useRef(!1),$=g.useRef(new Map),j=g.useRef(new Map),[k,P]=g.useState(null),[T,U]=g.useState(null),B=g.useCallback(L=>{i(L),RZ(L)},[]),D=g.useCallback(L=>{l(O=>O?.eventId===L?null:O)},[]),W=g.useCallback(async()=>{if(!e.connection||!e.teamId)return[];const L=await Y.teamChatThreads(e.connection,e.teamId),O=bZ(L.threads,$.current);return n(z=>({...z,threads:O})),O},[e.connection,e.teamId]),se=g.useCallback(async()=>{if(!e.connection||!e.teamId)return{members:[],agents:[]};const[L,O]=await Promise.all([Y.teamChatMembers(e.connection,e.teamId),Y.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]),me=g.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 Y.teamChatThread(e.connection,e.teamId,O);vf(X.messages,$.current,j.current);const fe=gf(X,$.current);return y.current.get(O)!==z||(n(Me=>Me.selectedThreadId===O?{...Me,threads:od(Me.threads,O),detail:rd(vZ(Me.detail,fe))}:Me),m.current===O&&fe.thread.lastMessageSequence>0&&await Y.markTeamChatRead(e.connection,O,e.teamId,fe.thread.lastMessageSequence).catch(()=>{})),fe},[e.connection,e.teamId]),Te=g.useCallback(async L=>{const O=L??d.current;if(!e.connection||!e.teamId||!O)return null;const z=(v.current.get(O)??0)+1;v.current.set(O,z);const X=await Y.teamChatAiThread(e.connection,e.teamId,O);return v.current.get(O)===z&&d.current===O&&n(fe=>fS(fe,X,d.current)),X},[e.connection,e.teamId]),ke=g.useCallback(async L=>{const O=L??_.current;if(!e.connection||!e.teamId||!O)return null;const z=await Y.teamChatAgentConversation(e.connection,e.teamId,O);return n(X=>X.agentConversation?.run.id===O?{...X,agentConversation:z}:X),z},[e.connection,e.teamId]);g.useEffect(()=>{m.current=t.selectedThreadId},[t.selectedThreadId]),g.useEffect(()=>{_.current=t.agentConversation?.run.id??null},[t.agentConversation?.run.id]),g.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:fn(z)}))})},2500);return()=>window.clearInterval(O)},[ke,t.agentConversation?.run.status]),g.useEffect(()=>{if(!e.connection||!e.teamId||!e.currentUserId){n(SS),P(null),U(null),j.current.clear(),$.current.clear(),y.current.clear(),v.current.clear(),w.current+=1,l(null),M.current.clear(),C.current=0,R.current=0;return}let L=!1;return d.current=null,h.current+=1,w.current+=1,P(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 Y.teamChatEvents(e.connection,e.teamId);if(L)return;R.current=O.cursor;const z=Y.teamChatMembers(e.connection,e.teamId),X=Y.teamChatAgents(e.connection,e.teamId),fe=await Y.teamChatGeneral(e.connection,e.teamId),[Me,Le,et]=await Promise.all([z,X,Y.teamChatThreads(e.connection,e.teamId)]);if(L)return;const Xe=m.current&&et.threads.some(Oe=>Oe.id===m.current)?m.current:fe.thread.id,st=Xe===fe.thread.id?fe:await Y.teamChatThread(e.connection,e.teamId,Xe);if(L)return;const mt=rd(st);n(Oe=>({...Oe,members:Me.members,agents:Le.agents,threads:od(et.threads,Xe),selectedThreadId:Xe,detail:mt,loading:!1,error:null})),xS({connection:e.connection,teamId:e.teamId,threadId:Xe,lastMessageSequence:mt?.thread.lastMessageSequence??0}),U(e.teamId)}catch(O){if(L)return;n(z=>({...z,loading:!1,error:fn(O)}))}})(),()=>{L=!0}},[e.connection,e.currentUserId,e.refreshToken,e.teamId]);const V=g.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=ZC(L);if(O&&L.type==="message.created"){const z=a.current,X=z.threads.find(Me=>Me.id===O.threadId)??(z.detail?.thread.id===O.threadId?z.detail.thread:null),fe=Me=>{L.id<=C.current||PZ({mode:o,currentUserId:e.currentUserId,message:O,thread:Me})&&(C.current=L.id,l(AZ({eventId:L.id,message:O,thread:Me,members:z.members})))};X?fe(X):W().then(Me=>{const Le=Me.find(et=>et.id===O.threadId);Le&&fe(Le)}).catch(()=>{})}O?.clientRequestId&&!O.id.startsWith("pending:")&&($.current.delete(O.clientRequestId),j.current.delete(O.clientRequestId)),n(z=>JC(z,L,e.currentUserId)),L.type==="thread.created"&&W().catch(z=>{n(X=>({...X,error:fn(z)}))}),(L.type==="ai_thread.created"||L.type==="ai_turn.updated")&&(me(L.threadId).catch(z=>{n(X=>({...X,error:fn(z)}))}),L.conversationId===d.current&&Te(L.conversationId).catch(z=>{n(X=>({...X,error:fn(z)}))})),O&&L.type==="message.created"&&m.current===O.threadId&&O.authorUserId!==e.currentUserId&&e.connection&&e.teamId&&Y.markTeamChatRead(e.connection,O.threadId,e.teamId,O.sequence).catch(()=>{})},[e.connection,e.currentUserId,e.teamId,o,Te,me,W]),Re=g.useCallback(async()=>{if(!(!e.connection||!e.teamId||N.current)){N.current=!0;try{let L=!0;for(;L;){const O=await Y.teamChatEvents(e.connection,e.teamId,{after:R.current,limit:250});for(const z of O.events)V(z);R.current=O.cursor,L=O.hasMore}}finally{N.current=!1}}},[V,e.connection,e.teamId]);g.useEffect(()=>{if(!e.connection||!e.teamId||T!==e.teamId)return;let L=!1,O=null;const z=async()=>{try{const X=await Y.teamChatRealtimeSession(e.connection,e.teamId);if(L||(await Re(),L))return;P(X);const fe=Math.max(3e4,new Date(X.expiresAt).getTime()-Date.now()-3e4);O=window.setTimeout(()=>{z()},fe)}catch{L||(Re().catch(()=>{}),O=window.setTimeout(()=>{z()},1e4))}};return z(),()=>{L=!0,O!==null&&window.clearTimeout(O),P(null)}},[Re,e.connection,e.teamId,T]);const be=t.threads.map(L=>L.id).sort().join(",");g.useEffect(()=>{if(!k)return;const L=uZ({session:k,threadIds:be?be.split(","):[],onEvent:V,onReady:()=>{Re().catch(O=>{n(z=>({...z,error:fn(O)}))})},onError:()=>{Re().catch(()=>{})}});return()=>{L.close()}},[V,Re,k,be]),g.useEffect(()=>{if(!e.connection||!e.teamId||T!==e.teamId)return;const L=window.setInterval(()=>{Re().catch(()=>{})},15e3);return()=>window.clearInterval(L)},[Re,e.connection,e.teamId,T]);const ce=g.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:od(X.threads,L),selectedThreadId:L,detail:X.detail?.thread.id===L?rd(X.detail):null,aiThread:z?null:X.aiThread,agentConversation:z?null:X.agentConversation,loading:!0,error:null}));try{const X=await Y.teamChatThread(e.connection,e.teamId,L);if(w.current!==O||m.current!==L)return;vf(X.messages,$.current,j.current);const fe=gf(X,$.current);n(Me=>({...Me,threads:od(Me.threads,L),detail:rd(fe),loading:!1})),await Y.markTeamChatRead(e.connection,L,e.teamId,fe.thread.lastMessageSequence).catch(()=>{})}catch(X){if(w.current!==O)return;n(fe=>({...fe,loading:!1,error:fn(X)}))}},[e.connection,e.teamId]),ye=g.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 Y.teamChatDm(e.connection,e.teamId,L);if(w.current!==O)return null;vf(z.messages,$.current,j.current);const X=gf(z,$.current),fe=m.current!==X.thread.id;return m.current=X.thread.id,fe&&(h.current+=1,d.current=null),n(Me=>({...Me,selectedThreadId:X.thread.id,detail:X,aiThread:fe?null:Me.aiThread,agentConversation:fe?null:Me.agentConversation,busy:!1})),await xS({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:fn(z)})),null}},[e.connection,e.teamId,W]),ne=g.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 Y.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 fe=[...z.messages,...X.detail.messages];return{...X,loading:!1,detail:{...X.detail,messages:_c(fe),hasMoreBefore:z.hasMoreBefore}}}),!0}catch(z){return n(X=>({...X,loading:!1,error:fn(z)})),!1}},[e.connection,e.teamId,t.detail]),ge=g.useCallback(async L=>{const O=m.current,z=wZ(L.attachments??[]);if(!z)return n(Me=>({...Me,error:"Team chat supports up to 10 PNG, JPEG, WebP, or GIF images per message."})),!1;if(!e.connection||!e.teamId||!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(Me=>({...Me,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 Me=h.current;n(Le=>({...Le,busy:!0,error:null}));try{const Le=await Y.createTeamChatAiThread(e.connection,O,{teamId:e.teamId,body:L.body.trim(),clientRequestId:crypto.randomUUID(),providerId:L.providerId,modelId:L.modelId}),et=h.current===Me&&m.current===O;return et&&(h.current+=1,d.current=Le.conversationId),n(Xe=>({...Xe,aiThread:et?Le:Xe.aiThread})),Le.activeTurn&&await Y.executeTeamChatAiTurn(e.connection,Le.activeTurn.id,e.teamId),await Promise.all([me(O),W()]),n(Xe=>({...Xe,busy:!1})),!0}catch(Le){return n(et=>({...et,busy:!1,error:fn(Le)})),!1}}const X=crypto.randomUUID();if(L.selectedActionKey){if(z.length>0)return n(Me=>({...Me,error:"Agent invocations do not support image attachments yet."})),!1;n(Me=>({...Me,busy:!0,error:null}));try{return await Y.createTeamChatAgentRun(e.connection,O,EZ({teamId:e.teamId,body:L.body,clientRequestId:X,selectedActionKey:L.selectedActionKey,approvalId:L.approvalId})),await Promise.all([me(O),W()]),n(Me=>({...Me,busy:!1})),!0}catch(Me){return n(Le=>({...Le,busy:!1,error:fn(Me)})),!1}}j.current.set(X,{inputs:z,uploaded:null});const fe=yZ({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,fe),n(Me=>SZ(Me,fe));try{const Me=[];for(const[Xe,st]of z.entries())Me.push(await Y.uploadTeamChatAttachment(e.connection,O,{teamId:e.teamId,attachment:st})),hS($.current,X,`${Xe+1} of ${z.length}`),n(mt=>vS(mt,X,`${Xe+1} of ${z.length}`));const Le=j.current.get(X);Le&&(Le.uploaded=Me);const et=await Y.sendTeamChatMessage(e.connection,O,{teamId:e.teamId,body:L.body.trim(),clientRequestId:X,mentionUserIds:L.mentionUserIds,attachmentIds:Me.map(Xe=>Xe.id),replyToMessageId:L.replyToMessage?.id??null});return j.current.delete(X),$.current.delete(X),n(Xe=>gS(Xe,et,e.currentUserId)),!0}catch(Me){return bf($.current,X,"failed"),n(Le=>({...xZ(Le,X),error:fn(Me)})),!1}},[e.connection,e.currentUserId,e.teamId,me,W,t.detail?.thread.lastMessageSequence]),xe=g.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 Y.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:fn(O)}))}}},[e.connection,e.teamId]),De=g.useCallback(async L=>{if(!(!e.connection||!e.teamId)){_.current=L,n(O=>({...O,busy:!0,error:null}));try{const O=await Y.teamChatAgentConversation(e.connection,e.teamId,L);n(z=>({...z,agentConversation:O,busy:!1}))}catch(O){n(z=>({...z,busy:!1,error:fn(O)}))}}},[e.connection,e.teamId]),we=g.useCallback(()=>{_.current=null,n(L=>({...L,agentConversation:null}))},[]),ae=g.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 Y.createTeamChatAgentRun(e.connection,O,TZ({teamId:e.teamId,body:L.body,clientRequestId:L.clientRequestId,conversation:z}));_.current=X.run.id;const[fe]=await Promise.all([Y.teamChatAgentConversation(e.connection,e.teamId,X.run.id),me(O),W()]);return n(Me=>({...Me,agentConversation:fe,busy:!1})),!0}catch(X){return n(fe=>({...fe,busy:!1,error:fn(X)})),!1}},[e.connection,e.teamId,me,W,t.agentConversation]),Se=g.useCallback(()=>{h.current+=1,d.current=null,n(L=>({...L,aiThread:null}))},[]),ze=g.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 Y.sendTeamChatAiTurn(e.connection,O,{teamId:e.teamId,body:L.body.trim(),clientRequestId:crypto.randomUUID(),providerId:L.providerId,modelId:L.modelId});return n(X=>({...fS(X,z,d.current),busy:!1})),z.activeTurn&&await Y.executeTeamChatAiTurn(e.connection,z.activeTurn.id,e.teamId),!0}catch(z){return n(X=>({...X,busy:!1,error:fn(z)})),!1}},[e.connection,e.teamId]),Qe=g.useCallback(async()=>{const L=t.aiThread?.activeTurn?.id;return!e.connection||!e.teamId||!L?!1:(await Y.cancelTeamChatAiTurnExecution(e.connection,L,e.teamId)).cancelled},[e.connection,e.teamId,t.aiThread?.activeTurn?.id]),We=g.useCallback(async(L,O)=>{if(!e.connection||!e.teamId)return!1;try{return await Y.editTeamChatMessage(e.connection,L.threadId,L.id,{teamId:e.teamId,body:O}),await me(L.threadId),!0}catch(z){return n(X=>({...X,error:fn(z)})),!1}},[e.connection,e.teamId,me]),nt=g.useCallback(async L=>{if(!e.connection||!e.teamId)return!1;try{return await Y.deleteTeamChatMessage(e.connection,L.threadId,L.id,e.teamId),await me(L.threadId),!0}catch(O){return n(z=>({...z,error:fn(O)})),!1}},[e.connection,e.teamId,me]),qe=g.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(fe=>typeof fe=="string"):[],z=j.current.get(L.clientRequestId),X=L.refs.find(fe=>fe.refType==="message_reply");bf($.current,L.clientRequestId,"sending"),n(fe=>_h(fe,L.clientRequestId,"sending"));try{let fe=z?.uploaded??[];if(z&&!z.uploaded){fe=[];for(const[Le,et]of z.inputs.entries())fe.push(await Y.uploadTeamChatAttachment(e.connection,L.threadId,{teamId:e.teamId,attachment:et})),hS($.current,L.clientRequestId,`${Le+1} of ${z.inputs.length}`),n(Xe=>vS(Xe,L.clientRequestId,`${Le+1} of ${z.inputs.length}`));z.uploaded=fe}const Me=await Y.sendTeamChatMessage(e.connection,L.threadId,{teamId:e.teamId,body:L.body,clientRequestId:L.clientRequestId,mentionUserIds:O,attachmentIds:fe.map(Le=>Le.id),replyToMessageId:X?.refId??null});return j.current.delete(L.clientRequestId),$.current.delete(L.clientRequestId),n(Le=>gS(Le,Me,e.currentUserId)),!0}catch(fe){return bf($.current,L.clientRequestId,"failed"),n(Me=>({..._h(Me,L.clientRequestId,"failed"),error:fn(fe)})),!1}},[e.connection,e.currentUserId,e.teamId]),Ze=g.useCallback(L=>{L.id.startsWith("pending:")&&(L.clientRequestId&&j.current.delete(L.clientRequestId),L.clientRequestId&&$.current.delete(L.clientRequestId),n(O=>kZ(O,L.id)))},[]),He=g.useCallback(async(L,O)=>{if(!e.connection||!e.teamId)return!1;try{const z=await Y.setTeamChatThreadMuted(e.connection,L,e.teamId,O),X=fe=>fe.id===z.threadId?{...fe,mutedAt:z.mutedAt}:fe;return n(fe=>({...fe,threads:fe.threads.map(X),detail:fe.detail?.thread.id===z.threadId?{...fe.detail,thread:X(fe.detail.thread)}:fe.detail,error:null})),!0}catch(z){return n(X=>({...X,error:fn(z)})),!1}},[e.connection,e.teamId]);return{...t,currentUserId:e.currentUserId,notificationMode:o,incomingNotification:s,setNotificationMode:B,dismissIncomingNotification:D,setThreadMuted:He,selectThread:ce,openDm:ye,loadMoreMessages:ne,sendMessage:ge,openAiThread:xe,openAgentConversation:De,closeAgentConversation:we,sendAgentTurn:ae,closeAiThread:Se,sendAiTurn:ze,stopAiTurn:Qe,editMessage:We,deleteMessage:nt,retryMessage:qe,dismissFailedMessage:Ze,refreshDirectory:se,refresh:async()=>{await Promise.all([se(),W(),me(),Te(),ke()])}}}function fn(e){return CZ(e)}const XC="local-profile-agent";function bX(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?[]:[Dr(l.agentName),Dr(s.name),Dr(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(Dr(s.name))||n.has(Dr(s.id))?[]:[$Z(t,s)]:[]);return[...e.hostedActions,...i]}function yX(e){return e?.implementation?.type===XC}function SX(e){const t=e.implementation?.profileAgentId;return typeof t=="string"&&t.trim()?t.trim():null}function jZ(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 OZ(e,t){const n=t.runtimeAgentId?.trim()??"",a=t.profileName?.trim()??"",o=Dr(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=>Dr(l)===o))})??null}function $Z(e,t){return{id:`local-profile:${e.activeProfile??"default"}:${t.id}:chat`,name:t.name,label:t.name,description:NZ(e),approvalPolicy:{required:!1,risk:"write"},setupRequirements:e.setupGate.blockingRequirements,invokesModel:!0,implementation:{type:XC,profileAgentId:t.id,profileName:e.activeProfile??"default"}}}function NZ(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 Dr(e){return typeof e=="string"?e.trim().toLowerCase().replace(/[^a-z0-9]+/g,""):""}const kS=5;function DZ(e){return g.useCallback(async t=>{if(!e.connection||!e.teamId)throw new Error("Connect OpenPond to a Team before publishing an agent.");const n=await Y.profileCheck(e.connection,{kind:"all"}),a=jZ(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 Y.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 Y.bootstrap(e.connection));let m=null;for(let d=0;d<kS;d+=1){const h=await e.refreshDirectory();if(m=OZ(h.agents,{runtimeAgentId:l,profileName:n.activeProfile,agentName:o.name}),m)break;d<kS-1&&await LZ(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 LZ(e){return new Promise(t=>{setTimeout(t,e)})}function UZ(e){g.useEffect(()=>{if(!e.notification)return;const{eventId:t,threadId:n,title:a,body:o}=e.notification;e.showToast(`${a}: ${o}`,"info",{actionLabel:"Open",onAction:()=>{e.setView("team"),e.selectThread(n)},durationMs:6500,placement:"top-right"}),e.dismiss(t)},[e.dismiss,e.notification,e.selectThread,e.setView,e.showToast])}function HZ(e){const{connection:t,refreshToken:n=null}=e,[a,o]=g.useState([]),[i,s]=g.useState(null),[l,m]=g.useState(null),[d,h]=g.useState(null),[v,y]=g.useState(!1),[w,_]=g.useState(!1),[R,M]=g.useState(!1),[C,N]=g.useState(null),[$,j]=g.useState(null),[k,P]=g.useState(null),[T,U]=g.useState(0),B=g.useRef(0),D=g.useMemo(()=>a.find(ne=>ne.id===l)??null,[a,l]),W=g.useCallback(async()=>{if(!t)return!1;y(!0),N(null);try{const ne=await Y.communities(t);return o(ne.items),s(ne.nextCursor),m(ge=>ge&&ne.items.some(xe=>xe.id===ge)?ge:null),!0}catch(ne){return N(Rd(ne)),!1}finally{y(!1)}},[t]),se=g.useCallback(async()=>{if(!t||!i||v)return!1;y(!0),N(null);try{const ne=await Y.communities(t,i);return o(ge=>zZ(ge,ne.items)),s(ne.nextCursor),!0}catch(ne){return N(Rd(ne)),!1}finally{y(!1)}},[t,v,i]),me=g.useCallback(async ne=>{if(!t)return null;const ge=++B.current;_(!0),j(null);try{const xe=await Y.communityPreview(t,ne.slug);return B.current===ge&&h(xe),xe}catch(xe){return B.current===ge&&j(Rd(xe)),null}finally{B.current===ge&&_(!1)}},[t]),Te=g.useCallback(ne=>{const ge=a.find(xe=>xe.id===ne);ge&&(m(ge.id),h(xe=>xe?.id===ge.id?xe:null),P(null),me(ge))},[a,me]),ke=g.useCallback(()=>{B.current+=1,m(null),h(null),j(null),P(null)},[]);g.useEffect(()=>{if(!t){o([]),h(null),m(null);return}W()},[t,W,n]),g.useEffect(()=>{!D||d?.id===D.id||w||me(D)},[me,d?.id,w,D]);const V=g.useCallback(async()=>{const ne=D;await W(),ne&&await me(ne)},[me,W,D]),Re=g.useCallback(async()=>{if(!t||!d?.currentRules||R)return!1;M(!0),P(null);try{return await Y.joinCommunity(t,d.id,d.currentRules.id),U(ne=>ne+1),await V(),!0}catch(ne){const ge=id(ne);return P(ge),ge.kind==="rules_stale"&&await V(),!1}finally{M(!1)}},[t,R,d,V]),be=g.useCallback(async()=>{if(!t||!d?.currentRules||R)return!1;M(!0),P(null);try{return await Y.acceptCommunityRules(t,d.id,d.currentRules.id),U(ne=>ne+1),await V(),!0}catch(ne){const ge=id(ne);return P(ge),ge.kind==="rules_stale"&&await V(),!1}finally{M(!1)}},[t,R,d,V]),ce=g.useCallback(async()=>{if(!t||!d||R)return!1;M(!0),P(null);try{return await Y.leaveCommunity(t,d.id),U(ne=>ne+1),await V(),!0}catch(ne){return P(id(ne)),!1}finally{M(!1)}},[t,R,d,V]),ye=g.useCallback(async ne=>{if(!t||!d||R)return!1;M(!0),P(null);try{return await Y.updateCommunityNotifications(t,d.id,ne),o(ge=>ge.map(xe=>xe.id===d.id&&xe.membership?{...xe,membership:{...xe.membership,notificationMode:ne}}:xe)),h(ge=>ge?.id===d.id&&ge.membership?{...ge,membership:{...ge.membership,notificationMode:ne}}:ge),!0}catch(ge){return P(id(ge)),!1}finally{M(!1)}},[t,R,d]);return{items:a,nextCursor:i,selectedCommunityId:l,selectedSummary:D,preview:d,discoveryLoading:v,previewLoading:w,membershipBusy:R,discoveryError:C,previewError:$,membershipError:k,membershipVersion:T,refresh:W,loadMore:se,showDiscovery:ke,selectCommunity:Te,join:Re,acceptRules:be,leave:ce,updateNotifications:ye,clearMembershipError:()=>P(null)}}function zZ(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 Rd(e){return e instanceof Error?e.message:String(e)}function id(e){const t=Rd(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 qZ(e,t,n){return GC({realtimeUrl:e.session.realtimeUrl,httpUrl:e.session.httpUrl,authorizationToken:e.session.token,channels:[e.session.channel],onEvent:a=>{const o=Tw.safeParse(a);o.success&&e.onEvent(o.data)},onReady:e.onReady,onError:e.onError},t,n)}function BZ(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]=g.useState([]),[h,v]=g.useState(null),[y,w]=g.useState({}),[_,R]=g.useState([]),[M,C]=g.useState(!1),[N,$]=g.useState(!1),[j,k]=g.useState(!1),[P,T]=g.useState(!1),[U,B]=g.useState(null),[D,W]=g.useState(null),[se,me]=g.useState(null),[Te,ke]=g.useState(null),[V,Re]=g.useState(!1),[be,ce]=g.useState(null),[ye,ne]=g.useState(null),ge=g.useRef(null),xe=g.useRef([]),De=g.useRef("mentions"),we=g.useRef(0),ae=g.useRef({}),Se=g.useRef(new Set),ze=g.useMemo(()=>m.find(Oe=>Oe.id===h)??null,[m,h]),Qe=h?y[h]??null:null;g.useEffect(()=>{ge.current=h},[h]),g.useEffect(()=>{xe.current=m},[m]),g.useEffect(()=>{De.current=n?.membership?.notificationMode??"mentions"},[n?.membership?.notificationMode]);const We=g.useCallback(async()=>{if(!t||!i)return!1;C(!0),B(null);try{const Oe=await Y.communityChannels(t,i);return d(Oe.channels),v(Ge=>Ge&&Oe.channels.some(f=>f.id===Ge)?Ge:Oe.channels.find(f=>f.isDefault)?.id??Oe.channels[0]?.id??null),Re(!1),!0}catch(Oe){const Ge=ra(Oe);return B(Ge),gl(Ge)&&Re(!0),!1}finally{C(!1)}},[i,t]),nt=g.useCallback(async Oe=>{if(!t||!i)return!1;const Ge=++we.current;$(!0),W(null);try{const f=await Y.communityMessages(t,i,Oe,{limit:50});return Ge!==we.current?!1:(w(H=>({...H,[Oe]:{items:f.messages,hasMoreBefore:f.hasMoreBefore,preview:f.preview}})),Re(!1),!0)}catch(f){if(Ge!==we.current)return!1;const H=ra(f);return W(H),gl(H)&&Re(!0),!1}finally{Ge===we.current&&$(!1)}},[i,t]);g.useEffect(()=>{d(n?.channels??[]),w({}),v(n?.channels.find(Oe=>Oe.isDefault)?.id??n?.channels[0]?.id??null),B(null),W(null),me(null),Re(!1),Se.current.clear(),i&&We()},[i,We,o]),g.useEffect(()=>{h&&nt(h)},[nt,h]);const qe=g.useCallback(async(Oe,Ge)=>{if(!t||!i||!s||!l||Ge<=0)return!1;if((ae.current[Oe]??0)>=Ge)return!0;ae.current[Oe]=Ge;try{const f=await Y.markCommunityRead(t,i,Oe,Ge);return d(H=>H.map(Z=>Z.id===Oe?{...Z,unreadCount:0,readState:Z.readState?{...Z.readState,lastReadSequence:f.sequence,lastReadAt:new Date().toISOString()}:{lastReadSequence:f.sequence,lastReadAt:new Date().toISOString(),mutedAt:null,pinnedAt:null}}:Z)),!0}catch(f){const H=ra(f);return gl(H)&&Re(!0),!1}},[i,t,s,l]);g.useEffect(()=>{const Oe=Qe?.items.at(-1)?.sequence??0;h&&Oe>0&&qe(h,Oe)},[qe,h,Qe?.items]);const Ze=g.useCallback(Oe=>{if(Oe.communityId!==i||Se.current.has(Oe.id))return;Se.current.add(Oe.id);const Ge=Aw.safeParse(Oe.payload.message);if(Ge.success&&Oe.type!=="read.updated"){const f=Ge.data;if(w(H=>{const Z=H[Oe.channelId];if(!Z)return H;const ee=Z.items.some(F=>F.id===f.id)?Z.items.map(F=>F.id===f.id?f:F):[...Z.items,f].sort((F,I)=>F.sequence-I.sequence);return{...H,[Oe.channelId]:{...Z,items:ee}}}),d(H=>H.map(Z=>Z.id===Oe.channelId?{...Z,lastMessageSequence:Math.max(Z.lastMessageSequence,f.sequence),unreadCount:ge.current===Oe.channelId||f.authorUserId===a?0:Math.max(Z.unreadCount+(Oe.type==="message.created"?1:0),0)}:Z)),Oe.type==="message.created"&&f.authorUserId!==a){const H=xe.current.find(ee=>ee.id===Oe.channelId),Z=FZ(f).includes(a??""),le=De.current;!H?.readState?.mutedAt&&(le==="all"||le==="mentions"&&Z)&&ne({communityId:Oe.communityId,channelId:Oe.channelId,message:f})}ge.current===Oe.channelId&&qe(Oe.channelId,f.sequence);return}Oe.type==="read.updated"&&Oe.payload.userId===a&&We()},[i,a,We,qe]);g.useEffect(()=>{if(!t||!i||!s||!l)return;let Oe=!1,Ge=null;return me(null),Promise.all([Y.communityRealtimeSession(t,i),Y.communityEvents(t,i)]).then(async([f,H])=>{if(Oe)return;const Z=async()=>{let ee=H.cursor;for(;;){const F=await Y.communityEvents(t,i,{after:ee,limit:200});if(Oe)return;for(const I of F.events)Ze(I);if(ee=F.cursor,!F.hasMore)return}},le=qZ({session:f,onEvent:Ze,onReady:()=>{me(null),Z().catch(ee=>me(ra(ee)))},onError:ee=>me(ra(ee))});Ge=()=>le.close(),await Z()}).catch(f=>{if(!Oe){const H=ra(f);me(H),gl(H)&&Re(!0)}}),()=>{Oe=!0,Ge?.()}},[Ze,i,t,s,o,l]);const He=g.useCallback(async()=>{if(!t||!i||!h||j)return!1;const Oe=y[h],Ge=Oe?.items[0]?.sequence;if(!Oe?.hasMoreBefore||Ge==null)return!1;k(!0),W(null);try{const f=await Y.communityMessages(t,i,h,{beforeSequence:Ge,limit:50});return w(H=>{const Z=H[h]??Oe,le=new Set(Z.items.map(ee=>ee.id));return{...H,[h]:{...Z,items:[...f.messages.filter(ee=>!le.has(ee.id)),...Z.items],hasMoreBefore:f.hasMoreBefore}}}),!0}catch(f){return W(ra(f)),!1}finally{k(!1)}},[i,t,y,j,h]),L=g.useCallback(async Oe=>{if(!t||!i||!h||P)return!1;T(!0),ke(null),ce(null);try{const Ge=await Promise.all(Oe.attachments.map(H=>Y.uploadCommunityAttachment(t,i,h,H))),f=await Y.sendCommunityMessage(t,i,h,{body:Oe.body,clientRequestId:Oe.clientRequestId,mentionUserIds:Oe.mentionUserIds,attachmentIds:Ge.map(H=>H.id),replyToMessageId:Oe.replyToMessageId});return w(H=>{const Z=H[h]??{items:[],hasMoreBefore:!1,preview:!1};return Z.items.some(le=>le.id===f.id)?H:{...H,[h]:{...Z,items:[...Z.items,f]}}}),await qe(h,f.sequence),!0}catch(Ge){const f=ra(Ge);return ke(f),ce({...Oe,message:f}),gl(f)&&Re(!0),!1}finally{T(!1)}},[i,t,qe,h,P]),O=g.useCallback(Oe=>L({body:Oe.body,clientRequestId:crypto.randomUUID(),mentionUserIds:Oe.mentionUserIds??[],attachments:Oe.attachments??[],replyToMessageId:Oe.replyToMessageId??null}),[L]),z=g.useCallback(async(Oe,Ge)=>{if(!t||!i||!h)return!1;ke(null);try{const f=await Y.editCommunityMessage(t,i,h,Oe,Ge);return wS(w,h,f),!0}catch(f){return ke(ra(f)),!1}},[i,t,h]),X=g.useCallback(async Oe=>{if(!t||!i||!h)return!1;ke(null);try{const Ge=await Y.deleteCommunityMessage(t,i,h,Oe);return wS(w,h,Ge),!0}catch(Ge){return ke(ra(Ge)),!1}},[i,t,h]),fe=g.useCallback(async(Oe,Ge)=>{if(!t||!i)return!1;ke(null);try{const f=await Y.setCommunityChannelMuted(t,i,Oe,Ge);return d(H=>H.map(Z=>Z.id===Oe&&Z.readState?{...Z,readState:{...Z.readState,mutedAt:f.mutedAt}}:Z)),!0}catch(f){return ke(ra(f)),!1}},[i,t]),Me=g.useCallback(async(Oe="")=>{if(!t||!i||!s)return[];try{const Ge=await Y.searchCommunityMembers(t,i,{query:Oe,limit:50});return R(f=>VZ(f,Ge.items)),Ge.items}catch(Ge){return ke(ra(Ge)),[]}},[i,t,s]);g.useEffect(()=>{s&&l?Me():R([])},[s,l,Me]);const Le=g.useCallback(async Oe=>{if(!t||!i||!h)return!1;try{const Ge=await Y.communityAttachmentDownload(t,i,h,Oe);return window.open(Ge.url,"_blank","noopener,noreferrer"),!0}catch(Ge){return ke(ra(Ge)),!1}},[i,t,h]),et=g.useCallback(()=>h?nt(h):Promise.resolve(!1),[nt,h]),Xe=g.useCallback(()=>be?L(be):Promise.resolve(!1),[be,L]),st=g.useCallback(()=>ce(null),[]),mt=g.useCallback(()=>ne(null),[]);return{channels:m,selectedChannelId:h,selectedChannel:ze,messages:Qe?.items??[],hasMoreBefore:Qe?.hasMoreBefore??!1,previewMode:Qe?.preview??!s,members:_,channelsLoading:M,messagesLoading:N,olderMessagesLoading:j,sending:P,channelsError:U,messagesError:D,realtimeError:se,actionError:Te,lostMembership:V,failedSend:be,incomingNotification:ye,selectChannel:v,loadChannels:We,loadMessages:et,loadOlder:He,sendMessage:O,retrySend:Xe,dismissFailedSend:st,editMessage:z,deleteMessage:X,setMuted:fe,searchMembers:Me,downloadAttachment:Le,dismissIncomingNotification:mt}}function wS(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 FZ(e){const t=e.metadata.mentionUserIds;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function VZ(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 gl(e){return e.includes("community_membership_required")||e.includes("community_rules")}function ra(e){return e instanceof Error?e.message:String(e)}function KZ(e){const t=HZ({connection:e.connection,refreshToken:e.refreshToken}),n=BZ({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,v=g.useCallback(()=>{t.showDiscovery(),d("community")},[t.showDiscovery,d]),y=g.useCallback(_=>{t.selectCommunity(_),d("community")},[t.selectCommunity,d]),w=g.useCallback(_=>{n.selectChannel(_),d("community")},[n.selectChannel,d]);return g.useEffect(()=>{if(!a)return;const _=o.find(M=>M.id===a.communityId),R=i.find(M=>M.id===a.channelId);h(`${_?.displayName??"Community"} · #${R?.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:v,selectCommunity:y,selectCommunityChannel:w},view:{communities:t,chat:n,currentUserId:e.currentUserId}}}const WZ=[];function GZ(e){const t=g.useCallback(a=>k9(e,a),[e]),n=g.useCallback(()=>S9(e)??WZ,[e]);return g.useSyncExternalStore(t,n,n)}function ZZ(e){const[t,n]=g.useState(()=>Op());return g.useEffect(()=>{let a=!0;return e?(Y.connectedAppStatus(e,{status:"all"}).then(o=>{a&&n(o.apps)}).catch(o=>{console.warn("Unable to load connected app mention status.",o),a&&n(Op())}),()=>{a=!1}):(n(Op()),()=>{a=!1})},[e]),t}function JZ(){const{composerDraftStore:e,dispatch:t,setters:n,state:a}=u7(),[o,i]=g.useState(null),[s,l]=g.useState([]),[m,d]=g.useState(null),[h,v]=g.useState(null),[y,w]=g.useState([]),[_,R]=g.useState(null),[M,C]=g.useState(null),[N,$]=g.useState(oC),[j,k]=g.useState({}),[P,T]=g.useState(()=>new Set),U=g.useCallback((ot,Jt)=>{T(Ut=>{if(Ut.has(ot)===Jt)return Ut;const Bt=new Set(Ut);return Jt?Bt.add(ot):Bt.delete(ot),Bt})},[]),[B,D]=g.useState(0),[W,se]=g.useState(null),me=g.useRef(null),{confirmProjectAction:Te,projectConfirmDialog:ke,resolveProjectConfirmDialog:V}=cK(),{query:Re,searchOpen:be,archivedChatsOpen:ce,sectionMenuOpen:ye,projectsExpanded:ne,cloudProjectsExpanded:ge,chatRowsVisibleCount:xe,sidebarOpen:De,view:we,selectedAppId:ae,selectedProjectId:Se,selectedSessionId:ze,draftProvider:Qe,draftModel:We,draftExperience:nt,codexPermissionMode:qe,codexReasoningEffort:Ze,openPondCommandAccessMode:He,busy:L,diffPanelOpen:O,diffPanelExpanded:z,rightPanelMode:X,rightChatPanels:fe,terminalOpen:Me,settingsSection:Le,newProjectDialogOpen:et,newProjectMode:Xe,newProjectName:st,newProjectPath:mt,newProjectBusy:Oe,commitDialogOpen:Ge,commitMessage:f,commitIncludeUnstaged:H,commitNextStep:Z,commitDraft:le,branchDialogOpen:ee,branchDialogName:F,toast:I,error:G}=a,ie=g7(we==="labs"),{setQuery:te,setSearchOpen:oe,setArchivedChatsOpen:ue,setSectionMenuOpen:pe,setProjectsExpanded:Ie,setCloudProjectsExpanded:je,setChatRowsVisibleCount:Ne,setSidebarOpen:$e,setView:at,setSelectedAppId:pt,setSelectedProjectId:sn,setSelectedSessionId:At,setPrompt:nn,setDraftProvider:un,setDraftModel:mn,setDraftExperience:qt,setCodexPermissionMode:_a,setCodexReasoningEffort:Cn,setOpenPondCommandAccessMode:Tt,setDiffPanelOpen:Wt,setDiffPanelExpanded:ut,setRightPanelMode:lt,setRightChatPanels:Fn,setTerminalOpen:Gt,setSyncingWorkspaceAppId:Ca,setSettingsSection:Ra,setNewProjectDialogOpen:Qt,setNewProjectMode:pn,setNewProjectName:rt,setNewProjectPath:xn,setNewProjectBusy:Pa,setCommitDialogOpen:Aa,setCommitMessage:ea,setCommitIncludeUnstaged:Ta,setCommitNextStep:Nn,setCommitDraft:yo,setBranchDialogOpen:Ea,setBranchDialogName:K,setError:Ue}=n,{connectionRef:_e,setError:Be,showToast:vt}=n7({appDispatch:t,error:G,setErrorState:Ue}),{appPreferences:kn,applyBootstrapPayload:Xt,bootstrap:Ke,codexHistorySessions:Dn,connection:St,events:Rn,runtimeEventStore:Ma,approvals:Yo,sessions:wn,startup:Vn,setAppPreferences:ta,setBootstrap:Ga,setCodexHistorySessions:Za,setEvents:ii,setSessions:na}=XG({setDraftModel:mn,setDraftProvider:un,setCodexPermissionMode:_a,setCodexReasoningEffort:Cn,setOpenPondCommandAccessMode:Tt,setError:Be,setSelectedAppId:pt,setSelectedProjectId:sn,setSelectedSessionId:At});_e.current=St,g.useEffect(()=>{Ke&&w(Ke.sidebarFileBookmarks??[])},[Ke?.sidebarFileBookmarks]);const ja=g.useMemo(()=>[...Rn].reverse().find(ot=>ot.name==="tool.completed"&&ot.action==="manage_sidebar_file")??null,[Rn]),bt=g.useRef(null);g.useEffect(()=>{!St||!ja||bt.current===ja.id||(bt.current=ja.id,Y.sidebarFiles(St).then(ot=>w(ot.items)).catch(ot=>Be(ot instanceof Error?ot.message:String(ot))))},[St,ja,Be]);const si=g.useCallback(async(ot,Jt)=>{if(!St)return;const Ut=y;w(Bt=>Jt==="none"?Bt.filter(Na=>Na.id!==ot.id):Bt.some(Na=>Na.id===ot.id)?Bt.map(Na=>Na.id===ot.id?{...Na,status:Jt}:Na):[...Bt,{...ot,status:Jt}]);try{const Bt=await Y.patchSidebarFile(St,{workspaceKind:ot.workspaceKind,workspaceId:ot.workspaceId,workspaceName:ot.workspaceName,path:ot.path,status:Jt,sourceSessionId:ot.sourceSessionId});w(Bt.items)}catch(Bt){w(Ut),Be(Bt instanceof Error?Bt.message:String(Bt))}},[St,Be,y]),kr=ZZ(St),Ts=_7({connection:St,profileId:Ke?.profile?.activeProfile??"default"}),{pinnedCollapsed:li,projectsCollapsed:Es,cloudProjectsCollapsed:So,chatsCollapsed:Ms,savedForLaterCollapsed:ci,sidebarWidth:di,sidebarResizing:ui,diffPanelWidth:js,diffPanelResizing:Os,togglePinnedCollapsed:Ja,toggleProjectsCollapsed:$s,toggleCloudProjectsCollapsed:mi,toggleChatsCollapsed:pi,toggleSavedForLaterCollapsed:fi,startSidebarResize:Ns,startDiffPanelResize:aa}=f7({connection:St,preferences:Ke?.preferences,sidebarOpen:De,diffPanelExpanded:z,setBootstrap:Ga,setError:Be}),{cloudProjectById:wr,linkedProjectByAppId:hi,localProjectById:Ds,mentionableSandboxApps:Ls,selectedApp:Ir,selectedCloudProject:xo,selectedProject:Kn,selectedProjectLinkedApp:Qo,selectedProjectLinkedOpenPondApp:Us,selectedSession:gn,selectedSessionLinkedProject:Hs,sidebarSessions:ca}=U9({bootstrap:Ke,codexHistorySessions:Dn,selectedAppId:ae,selectedProjectId:Se,selectedSessionId:ze,sessions:wn}),Oa=gn?.experience??nt;g.useEffect(()=>{m9(Oa)},[Oa]);const Xo=g.useMemo(()=>l6(ca,Oa),[Oa,ca]),Ya=O7(Rn,Yo),{chatMentionApps:_r,connectedAppMentions:Cr,pendingApproval:zs}=oW({bootstrap:Ke,connectedAppRows:kr,mentionableSandboxApps:Ls,runtimeIndexes:Ya,selectedApp:Ir,selectedCloudProject:xo,selectedProject:Kn,selectedSession:gn,selectedSessionId:ze}),{codexHistoryEvents:Rr,setCodexHistoryEvents:gi}=wW({connection:St,selectedSessionId:ze,selectedSessionLocallyActive:!!(ze&&P.has(ze)),selectedSessionStatus:gn?.status,setCodexHistorySessions:Za,setError:Be}),{account:da,accountPending:vi,accountSignedOut:bi,activeModel:er,activeProvider:ua,activeWorkspaceAppId:yi,activeWorkspaceId:Pr,activeWorkspaceKind:Qa,activeWorkspaceLocation:Ar,appDefaults:ko,cloudLinked:Si,selectedCodexHistoryPending:xi,selectedSessionProjectId:ki,startMessage:qs,workspaceName:wi}=O9({bootstrap:Ke,draftModel:We,draftProvider:Qe,selectedApp:Ir,selectedAppId:ae,selectedCloudProject:xo,selectedProject:Kn,selectedSession:gn,selectedSessionId:ze,selectedSessionLinkedProject:Hs}),Ii=g.useMemo(()=>_9(Ke?.account??null),[Ke?.account]),Bs=g.useMemo(()=>fh(Ke?.account??null),[Ke?.account]),tr=GZ(Bs),_i=g.useMemo(()=>P9(tr,ko.defaultTeamId),[ko.defaultTeamId,tr]),Tr=_i?.teamId??null,Xa=MZ({connection:St,teamId:Tr,currentUserId:da?.profile?.id??null,refreshToken:Ke?.accountMeta.asOf??null}),Fs=DZ({connection:St,teamId:Tr,applyBootstrapPayload:Xt,refreshDirectory:Xa.refreshDirectory});UZ({notification:Xa.incomingNotification,dismiss:Xa.dismissIncomingNotification,selectThread:Xa.selectThread,setView:at,showToast:vt});const{communities:Vs,sidebar:Ks,view:Ws}=KZ({connection:St,currentUserId:da?.profile?.id??null,refreshToken:Ke?.accountMeta.asOf??null,setView:at,showToast:vt}),eo=Xa.aiThread?.conversationId??null,Ci=we==="team"&&!!eo&&O&&X==="chat";g.useEffect(()=>{if(we==="team"){if(eo){lt("chat"),Wt(!0);return}X==="chat"&&Wt(!1)}},[X,Wt,lt,eo,we]);const Gs=g.useCallback(()=>{if(eo){if(Ci){Wt(!1);return}lt("chat"),Wt(!0)}},[Wt,lt,Ci,eo]),Ri=g.useMemo(()=>ka(Kn,Ke?.cloudProjects??[]),[Ke?.cloudProjects,Kn]),Zs=gn?.provider==="codex"?He:gn?.openPondCommandAccessMode??He,Ln=yi,Js=Pr,wo=Qa,ct=wi,{openPondActionCatalog:Zt,selectedActionCatalog:to}=Z7({cloudProjectById:wr,cloudProjects:Ke?.cloudProjects??[],connection:St,defaultTeamId:ko.defaultTeamId,accountScopeKey:Ii,localProjects:Ke?.localProjects??[],profile:Ke?.profile,selectedCloudProject:xo,selectedProject:Kn,reportError:Be}),{expandedProjectIds:vn,expandProject:Pn,toggleProjectExpanded:oa,setExpandedProjectIds:Cc}=J7({selectedProjectId:Se});K9({activeWorkspaceId:Pr,activeWorkspaceKind:Qa,appDispatch:t,connection:St,expandProject:Pn,linkedProjectByAppId:hi,providerSettings:Ke?.providers??null,selectedAppId:ae,selectedSession:gn,selectedSessionId:ze,selectedSessionProjectId:ki,setDiffPanelExpanded:ut,setDraftModel:mn,setDraftProvider:un,setError:Be,setSelectedAppId:pt,setSelectedProjectId:sn,setSessions:na,setTerminalOpen:Gt,toast:I});const{changeCodexPermissionMode:Xu,changeCodexReasoningEffort:Ys}=rW({connection:St,setBootstrap:Ga,setCodexPermissionMode:_a,setCodexReasoningEffort:Cn,setError:Be}),{changeOpenPondCommandAccessMode:em}=lG({connection:St,selectedSession:gn,setBootstrap:Ga,setError:Be,setOpenPondCommandAccessMode:Tt,setSessions:na}),Pi=W9({connection:St,setError:Be}),Qs=g.useCallback(()=>{D(ot=>ot+1)},[]),Rc=Z9({appDispatch:t,expandProject:Pn,linkedProjectByAppId:hi,requestComposerFocus:Qs,onBeginNewChat:()=>{en({kind:"chat",sessionId:null}),se(null),qt(ot=>ot==="development"?"work":ot)},setMentionedAppId:v}),tm=g.useCallback(ot=>{const Jt=yt("local",ot);t({type:"selectProject",projectId:Jt}),Pn(Jt)},[t,Pn]),{advanceAfterTurn:nm,begin:am,bindSession:om,dismiss:rm,handoff:im,prepareTurn:sm,selectTask:lm}=E7({activeModel:er,activeProvider:ua,applyBootstrapPayload:Xt,beginNewChat:Rc,composerDraftStore:e,connection:St,requestComposerFocus:Qs,selectedLocalProjectId:Kn?.id??null,selectedSessionId:ze,selectLocalProject:tm,setDraftModel:mn,setDraftProvider:un,setError:Be,view:we});p7({connection:St,events:Rn,showToast:vt}),gG({searchOpen:be,sectionMenuOpen:ye,setSectionMenuOpen:pe,setSearchOpen:oe,setQuery:te}),g.useEffect(()=>{k({})},[Ke?.server.id]);const{chatHistoryLoadStates:cm,loadMoreSelectedChatHistory:dm,selectedPagedSessionEvents:um,selectedRuntimeIndexes:Pc}=M7({approvals:Yo,codexHistoryEvents:Rr,connection:St,latestServerSequence:Ke?.eventWindow?.latestSequence,runtimeIndexes:Ya,runtimeEventStore:Ma,selectedSessionId:ze,serverId:Ke?.server.id,setCodexHistoryEvents:gi,setCodexHistorySessions:Za,setError:Be}),{activeSessions:Ac,archivedSessions:mm,pinnedProjects:pm,pinnedSessions:Tc,savedForLaterSessions:Ec,pinnedFiles:fm,savedForLaterFiles:hm,pinnedItems:Xs,projectRows:Mc,localProjectRows:gm,visibleProjectRows:el,cloudProjectRows:vm,projectSessionRowsByProjectId:tl,childSessionRowsByParentId:bm,sidebarProjectIdBySessionId:nl,chatRows:ym,visibleChatRows:jc,sessionEvents:Sm,chatMessages:Oc,contextUsage:xm,goalRuntime:$c,subagentRuntime:Nc}=cG({localProjects:Ke?.localProjects??[],cloudProjects:Ke?.cloudProjects??[],sessions:Xo,runtimeIndexes:Pc,appPreferences:kn,selectedSessionId:ze,selectedProjectId:Se,archivedChatsOpen:ce,projectsExpanded:ne,chatRowsVisibleCount:xe,sidebarFileBookmarks:y}),km=g.useCallback(ot=>{qt(ot);const Jt=[...Xo].filter(Ut=>ot==="work"?Ut.experience==="work"||Ut.experience==="development":Ut.experience===ot).sort((Ut,Bt)=>Bt.updatedAt.localeCompare(Ut.updatedAt))[0]??[...ca].filter(Ut=>Ut.experience===ot).sort((Ut,Bt)=>Bt.updatedAt.localeCompare(Ut.updatedAt))[0]??null;if(Jt)t({type:"selectSession",sessionId:Jt.id,appId:ot!=="chat"?Jt.appId:null,projectId:ot!=="chat"?nl[Jt.id]??null:null});else if(t({type:"beginNewChat",appId:null}),ot==="chat"&&ua==="codex"){const Ut=lh(Ke?.providers,{enabledOnly:!0}).find(Bt=>Bt.value!=="codex")?.value??Gr;un(Ut),mn(Zd(Ut,Ke?.providers)??Nl)}ot==="chat"&&(Gt(!1),ut(!1),lt("home")),at("chat")},[t,ua,Ke?.providers,Xo,ut,qt,mn,un,lt,Gt,at,nl,ca]),wm=g.useCallback(ot=>{const Jt=e.getSnapshot();if(qt(ot),(ze||ae||Se)&&(t({type:"beginNewChat",appId:null}),Jt&&e.set(Jt)),ot==="chat"&&ua==="codex"){const Ut=lh(Ke?.providers,{enabledOnly:!0}).find(Bt=>Bt.value!=="codex")?.value??Gr;un(Ut),mn(Zd(Ut,Ke?.providers)??Nl)}ot==="chat"&&(Gt(!1),ut(!1),lt("home")),at("chat")},[ua,t,Ke?.providers,e,ae,Se,ze,ut,qt,mn,un,lt,Gt,at]),{pendingChatUserMessages:Im,recordPendingChatUserMessage:_m,visibleChatMessages:Cm}=sG({chatMessages:Oc,runtimeIndexes:Pc,selectedSessionId:ze}),nr=g.useMemo(()=>S6({selectedAppId:ae,selectedProjectId:Se,selectedSessionId:ze}),[ae,Se,ze]),Ai=g.useRef(null);g.useEffect(()=>{const ot=Ai.current;Ai.current=nr,!(!ot||ot.kind!=="draft"||nr.kind!=="session")&&(Yl(ot,nr)||l(Jt=>{const Ut=x6({tabs:Jt,previousScope:ot,activeScope:nr});return Ut.some((Na,dl)=>Na!==Jt[dl])?Ut:Jt}))},[nr]);const Rm=g.useMemo(()=>k6(s),[s]),{goalRuntime:Pm,runningSessionIds:Am,selectedSessionRunning:Tm,sidebarGoalRuntimeBySessionId:Em,sidebarSubagentRuntimeBySessionId:Mm}=hG({codexHistoryEvents:Rr,codexHistorySessions:Dn,connection:St,expandedProjectIds:vn,goalRuntime:$c,locallyActiveCodexHistorySessionIds:P,pinnedSessions:Tc,savedForLaterSessions:Ec,projectSessionRowsByProjectId:tl,rightChatHistoryEvents:j,runtimeIndexes:Ya,selectedSession:gn,selectedSessionId:ze,serverId:Ke?.server.id,setCodexHistorySessions:Za,sidebarSessions:ca,subagentRuntime:Nc,visibleChatRows:jc,visibleProjectRows:el}),{dragItem:jm,pinnedPreviewKeys:Om,startPinnedDrag:$m,clearSidebarDrag:Nm,previewPinnedDrop:Dm,commitPinnedDrop:Dc,commitPinnedPreviewDrop:Lm}=IW({connection:St,appPreferences:kn,sessions:ca,pinnedItems:Xs,setAppPreferences:ta,setCodexHistorySessions:Za,setSessions:na,sidebarFileBookmarks:y,setSidebarFileBookmarks:w,setError:Be}),{clearTaskDrag:$a,commitTaskDrop:Ti,commitTaskPreviewDrop:Um,previewTaskDrop:Hm,startTaskDrag:zm,taskDragSessionId:al,taskPreviewSessionIds:qm}=_W({connection:St,sessions:ca,setCodexHistorySessions:Za,setError:Be,setSessions:na}),{commandProjectRows:Bm,contextWindowStatus:ol,pinnedRows:rl,sidebarWorkspaceAppIds:il}=G9({activeProvider:ua,contextCompaction:ko.contextCompaction,contextUsage:xm,pinnedItems:Xs,pinnedPreviewKeys:Om??[],pinnedProjects:pm,projectRows:Mc,visibleProjectRows:el}),Er=!!(Ln&&(we==="chat"||we==="labs")&&(Ge||O&&(X==="changes"||X==="goal"))),{workspaceStates:Ei,workspaceBusy:Mi,diffBusy:sl,visibleWorkspaceState:Mr,visibleWorkspaceDiff:ji,rememberWorkspaceState:ll,refreshWorkspace:Fm,refreshWorkspaceDiff:jr,setWorkspaceBusy:Vm}=X7({connection:St,activeWorkspaceAppId:Ln,view:we,shouldLoadWorkspaceDiff:Er,sidebarWorkspaceAppIds:il,setError:Be});me.current=ll;const Km=g.useCallback((ot=Ln)=>!ot||ot!==Ln||!Er?Promise.resolve(null):jr(ot),[jr,Er,Ln]),Wm=g.useCallback(async(ot={})=>{!Ln||!Er||await jr(Ln,ot)},[jr,Er,Ln]),Gm=!1,Zm=!!(gn?.provider==="codex"&&gn.cwd&&!go(gn.workspaceKind)),Jm=!!(Mr&&!Mr.initialized&&Qa!=="local_project"&&ua!=="codex"&&!Zm&&!xi),Ym=Qa==="local_project"&&!!Kn?.sandboxTemplate?.detected&&!Kn?.linkedOpenPondApp?.appId,[Uc,Hc]=g.useState(null),[Qm,Xm]=g.useState(null),{projectTarget:cl,workspaceTarget:ep}=$9({accountPending:vi,accountSignedOut:bi,activeWorkspaceLocation:Ar,bootstrap:Ke,busy:L,cloudLinked:Si,selectedCloudProject:xo,selectedProject:Kn,selectedSession:gn,pendingWorkspaceTarget:Uc,workspaceStates:Ei,workspaceBusy:Mi});return g.useEffect(()=>{Hc(null)},[gn?.id]),{composerDraftStore:e,appDispatch:t,pendingTerminalCommand:o,setPendingTerminalCommand:i,terminalTabs:s,setTerminalTabs:l,trainingDetailTasksetId:m,setTrainingDetailTasksetId:d,mentionedAppId:h,setMentionedAppId:v,cloudSetupDialog:_,setCloudSetupDialog:R,rightPanelTabRequest:M,setRightPanelTabRequest:C,workspaceDiffPanelViewState:N,setWorkspaceDiffPanelViewState:$,rightChatHistoryEvents:j,setRightChatHistoryEvents:k,locallyActiveCodexHistorySessionIds:P,setCodexHistoryTurnLocallyActive:U,mainComposerFocusRequestId:B,requestMainComposerFocus:Qs,draftSubagentDelegationMode:W,setDraftSubagentDelegationMode:se,confirmProjectAction:Te,projectConfirmDialog:ke,resolveProjectConfirmDialog:V,query:Re,searchOpen:be,archivedChatsOpen:ce,sectionMenuOpen:ye,projectsExpanded:ne,cloudProjectsExpanded:ge,sidebarOpen:De,view:we,selectedAppId:ae,selectedProjectId:Se,selectedSessionId:ze,draftProvider:Qe,draftModel:We,draftExperience:nt,activeExperience:Oa,changeExperience:km,changeNewExperience:wm,codexPermissionMode:qe,codexReasoningEffort:Ze,openPondCommandAccessMode:He,busy:L,diffPanelOpen:O,diffPanelExpanded:z,rightPanelMode:X,rightChatPanels:fe,terminalOpen:Me,settingsSection:Le,newProjectDialogOpen:et,newProjectMode:Xe,newProjectName:st,newProjectPath:mt,newProjectBusy:Oe,commitDialogOpen:Ge,commitMessage:f,commitIncludeUnstaged:H,commitNextStep:Z,commitDraft:le,branchDialogOpen:ee,branchDialogName:F,toast:I,error:G,labDetailNavigation:ie,setQuery:te,setSearchOpen:oe,setArchivedChatsOpen:ue,setSectionMenuOpen:pe,setProjectsExpanded:Ie,setCloudProjectsExpanded:je,setChatRowsVisibleCount:Ne,setSidebarOpen:$e,setView:at,setSelectedAppId:pt,setSelectedProjectId:sn,setSelectedSessionId:At,setPrompt:nn,setDraftProvider:un,setDraftModel:mn,setDraftExperience:qt,setDiffPanelOpen:Wt,setDiffPanelExpanded:ut,setRightPanelMode:lt,setRightChatPanels:Fn,setTerminalOpen:Gt,setSyncingWorkspaceAppId:Ca,setSettingsSection:Ra,setNewProjectDialogOpen:Qt,setNewProjectMode:pn,setNewProjectName:rt,setNewProjectPath:xn,setNewProjectBusy:Pa,setCommitDialogOpen:Aa,setCommitMessage:ea,setCommitIncludeUnstaged:Ta,setCommitNextStep:Nn,setCommitDraft:yo,setBranchDialogOpen:Ea,setBranchDialogName:K,setError:Be,showToast:vt,appPreferences:kn,applyBootstrapPayload:Xt,approvals:Yo,bootstrap:Ke,connection:St,events:Rn,runtimeEventStore:Ma,sessions:wn,startup:Vn,setAppPreferences:ta,setCodexHistorySessions:Za,setEvents:ii,setSessions:na,training:Ts,pinnedCollapsed:li,projectsCollapsed:Es,cloudProjectsCollapsed:So,chatsCollapsed:Ms,savedForLaterCollapsed:ci,sidebarWidth:di,sidebarResizing:ui,diffPanelWidth:js,diffPanelResizing:Os,togglePinnedCollapsed:Ja,toggleProjectsCollapsed:$s,toggleCloudProjectsCollapsed:mi,toggleChatsCollapsed:pi,toggleSavedForLaterCollapsed:fi,startSidebarResize:Ns,startDiffPanelResize:aa,cloudProjectById:wr,localProjectById:Ds,selectedApp:Ir,selectedCloudProject:xo,selectedProject:Kn,selectedProjectLinkedApp:Qo,selectedProjectLinkedOpenPondApp:Us,selectedSession:gn,sidebarSessions:ca,runtimeIndexes:Ya,chatMentionApps:_r,connectedAppMentions:Cr,pendingApproval:zs,codexHistoryEvents:Rr,setCodexHistoryEvents:gi,account:da,accountPending:vi,accountSignedOut:bi,activeModel:er,activeProvider:ua,activeWorkspaceAppId:yi,activeWorkspaceId:Pr,activeWorkspaceKind:Qa,activeWorkspaceLocation:Ar,appDefaults:ko,selectedSessionProjectId:ki,startMessage:qs,workspaceName:wi,accountScopeKey:Ii,organizations:tr,teamChatOrganization:_i,teamChatTeamId:Tr,teamChat:Xa,publishTeamProfileAgent:Fs,communities:Vs,communitySidebar:Ks,communityView:Ws,teamAiThreadId:eo,toggleTeamAiSidebar:Gs,selectedProjectConfirmedCloudProject:Ri,activeOpenPondCommandAccessMode:Zs,viewWorkspaceAppId:Ln,viewWorkspaceId:Js,viewWorkspaceKind:wo,viewWorkspaceName:ct,openPondActionCatalog:Zt,selectedActionCatalog:to,expandedProjectIds:vn,expandProject:Pn,toggleProjectExpanded:oa,setExpandedProjectIds:Cc,changeCodexPermissionMode:Xu,changeCodexReasoningEffort:Ys,changeOpenPondCommandAccessMode:em,resolveApproval:Pi,beginNewChat:Rc,advanceTrainingModelChatAfterTurn:nm,beginNewChatWithTrainingModel:am,bindTrainingModelChatSession:om,dismissTrainingChatHandoff:rm,trainingChatHandoff:im,prepareTrainingModelChatTurn:sm,selectTrainingChatTaskForComposer:lm,chatHistoryLoadStates:cm,loadMoreSelectedChatHistory:dm,selectedPagedSessionEvents:um,activeSessions:Ac,archivedSessions:mm,pinnedSessions:Tc,savedForLaterSessions:Ec,pinnedFiles:fm,savedForLaterFiles:hm,sidebarFileBookmarks:y,setSidebarFileStatus:si,projectRows:Mc,localProjectRows:gm,visibleProjectRows:el,cloudProjectRows:vm,projectSessionRowsByProjectId:tl,childSessionRowsByParentId:bm,sidebarProjectIdBySessionId:nl,chatRows:ym,visibleChatRows:jc,chatRowsVisibleCount:xe,sessionEvents:Sm,chatMessages:Oc,goalRuntime:Pm,subagentRuntime:Nc,pendingChatUserMessages:Im,recordPendingChatUserMessage:_m,visibleChatMessages:Cm,activeTerminalScope:nr,terminalSummaries:Rm,runningSessionIds:Am,selectedSessionRunning:Tm,sidebarGoalRuntimeBySessionId:Em,sidebarSubagentRuntimeBySessionId:Mm,taskDragSessionId:al,taskPreviewSessionIds:qm,startTaskDrag:zm,clearTaskDrag:$a,previewTaskDrop:Hm,commitTaskDrop:Ti,commitTaskPreviewDrop:Um,dragItem:jm,startPinnedDrag:$m,clearSidebarDrag:Nm,previewPinnedDrop:Dm,commitPinnedDrop:Dc,commitPinnedPreviewDrop:Lm,commandProjectRows:Bm,contextWindowStatus:ol,pinnedRows:rl,workspaceStates:Ei,workspaceBusy:Mi,diffBusy:sl,visibleWorkspaceState:Mr,visibleWorkspaceDiff:ji,rememberWorkspaceState:ll,refreshWorkspace:Fm,refreshWorkspaceDiff:jr,setWorkspaceBusy:Vm,refreshWorkspaceDiffWhenNeeded:Km,refreshVisibleWorkspaceDiff:Wm,managedWorkspace:Gm,canSyncActiveWorkspace:Jm,canPublishOpenPondProject:Ym,pendingWorkspaceTarget:Uc,setPendingWorkspaceTarget:Hc,pendingSidebarWorkspaceTarget:Qm,setPendingSidebarWorkspaceTarget:Xm,projectTarget:cl,workspaceTarget:ep}}const YZ=/^(localhost|\[::1\]|127(?:\.\d{1,3}){3})(?::\d+)?(?:[/?#].*)?$/i,QZ=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+(?:[:/?#].*)?$/i;function XZ(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)?sd(n,new Set(["http:","https:"])):/^file:\/\//i.test(n)?t.explicitFile?sd(n,new Set(["file:"])):null:YZ.test(n)?sd(`http://${n}`,new Set(["http:"])):QZ.test(n)?sd(`https://${n}`,new Set(["https:"])):null}function sd(e,t){try{const n=new URL(e);return t.has(n.protocol)?n.toString():null}catch{return null}}async function eJ(e){const t=XZ(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 tJ="openpond-coding-core-v1",nJ="feature";function Ch(e){const t=new URL("/sandboxes",zv(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",nJ),t.searchParams.set("runtimeProfileId",tJ),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 xX(e){const t=e.organizationSlug?.trim(),n=t?`/sandboxes/${encodeURIComponent(t)}/billing`:"/sandboxes/billing",a=new URL(n,zv(e.accountBaseUrl));return!t&&e.teamId?.trim()&&a.searchParams.set("teamId",e.teamId.trim()),a.toString()}function IS(e){const t=e.organizationSlug?.trim(),n=e.projectSlug?.trim();return!t||!n?null:new URL(`/${encodeURIComponent(t)}/${encodeURIComponent(n)}`,zv(e.accountBaseUrl)).toString()}function zv(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 aJ({account:e,browserConversationId:t,cloudProjectById:n,cloudProjects:a,diffPanelOpen:o,rightPanelMode:i,selectedProjectId:s,setDiffPanelOpen:l,setNewProjectDialogOpen:m,setNewProjectMode:d,setNewProjectName:h,setRightPanelMode:v}){const y=g.useCallback(()=>{v("changes"),l(!0)},[l,v]),w=g.useCallback(()=>{if(o&&i==="changes"){l(!1);return}y()},[o,i,l,y]),_=g.useCallback(()=>{v("browser"),l(!0)},[l,v]),R=g.useCallback(()=>{v("goal"),l(!0)},[l,v]),M=g.useCallback((j,k)=>{eJ({conversationId:t,href:j,explicitFile:k?.explicitFile,newTab:k?.newTab}).then(P=>{P&&_()})},[t,_]),C=g.useCallback(()=>{d("cloud"),h(""),m(!0)},[m,d,h]),N=g.useCallback(j=>{const k=n.get(j);k&&M(Ch({accountBaseUrl:e?.baseUrl??e?.activeProfile?.baseUrl??null,teamId:k.teamId,projectId:k.id,projectName:k.name,baseBranch:k.defaultBranch,source:"openpond-app"}),{newTab:!0})},[e,n,M]);return{createCloudEnvironmentFromSidebar:g.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:R,toggleChangesPanel:w}}function oJ(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 rJ({browserConversationId:e,sessionIds:t,onOpenSession:n,onShowBrowserPanel:a}){g.useEffect(()=>window.openpond?.browser?.onRevealRequest?.(i=>{const s=oJ({currentConversationId:e,requestConversationId:i.conversationId,sessionIds:t});s.reveal&&(s.sessionIdToOpen&&n(s.sessionIdToOpen),a())}),[e,n,a,t])}const iJ="chat",sJ=["help me","please","can you","could you","make","create","build"],lJ=new Set(["a","an","and","for","from","i","me","my","of","our","please","produce","summary","the","to","with"]);function _S(e){const t=yf(e.label);if(t&&!Rh(t))return CS(t);const n=yf(e.name);if(n&&!Rh(n))return CS(n);const a=yf(e.actionId)?.replace(/\.chat$/i,"")??"";return cJ(a||t||"Profile Agent")}function Rh(e){return e.trim().toLowerCase()===iJ}function cJ(e){const t=dJ(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&&!lJ.has(o)).slice(0,3);return eR(a.length?a.join(" "):t||e)}function CS(e){return eR(e).split(/\s+/).slice(0,4).join(" ")}function dJ(e){let t=e.trim();for(const n of sJ)if(t.toLowerCase().startsWith(`${n} `)){t=t.slice(n.length).trim();break}return t}function yf(e){return typeof e=="string"&&e.trim()?e.trim():null}function eR(e){return e.replace(/[._-]+/g," ").replace(/\s+/g," ").trim().replace(/\b[a-z0-9]/gi,t=>t.toUpperCase())}const uJ="openpond-profile-action";function mJ(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ld(e){return typeof e=="string"&&e.trim()?e.trim():null}function pJ(e){const t=mJ(e.implementation);if(t?.type!==uJ)return null;const n=ld(t.actionId)??e.id;if(e.sourceActionId!=="chat"&&n!=="chat"&&!n.endsWith(".chat"))return null;const a=ld(e.label);if(a&&!Rh(a))return _S({label:a,description:e.description});const o=ld(t.agentName)??ld(e.name);return _S({actionId:n,description:e.description,name:o})}function fJ(e){const t=pJ(e);return t||e.label?.trim()||e.name?.trim()||e.id}function tR(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 hJ=new Set(["action","agent","chat","customer","default","filter","items","open","openpond","profile","run","summarize","track","workflow"]);function nR(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function xs(e){return typeof e=="string"&&e.trim()?e.trim():null}function es(e,t,n={}){const a=xs(t)?$n(String(t)):"";a&&(!n.generic&&hJ.has(a)||e.add(a))}function cd(e,t){const n=xs(t);if(n)for(const a of n.split(/[.:/\\\s]+/g))es(e,a)}function gJ(e,t){const n=xs(t);if(n)for(const a of n.split(/[^A-Za-z0-9_-]+/g))a.length<4||es(e,a)}function aR(e){const t=new Set,n=nR(e.implementation),a=xs(n?.actionId);return es(t,e.id,{generic:!0}),cd(t,e.id),es(t,a,{generic:!0}),cd(t,a),es(t,e.name,{generic:!0}),cd(t,e.name),es(t,e.label,{generic:!0}),cd(t,e.label),gJ(t,e.description),t}function vJ(e){const t=nR(e.implementation);return[e.id,e.name??"",e.label??"",e.description??"",xs(t?.actionId)??"",xs(t?.agentName)??"",tR(e),...Array.from(aR(e))].join(" ").toLowerCase()}function kX(e,t,n=8){const a=$n(t);return e.length===0?[]:e.filter(o=>a?vJ(o).includes(a):!0).slice(0,n)}function bJ(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>$n(t[1]??"")).filter(Boolean)}function yJ(e,t){const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return e.replace(new RegExp(`(^|\\s)@${n}(?=\\s|$)`,"g"),"$1").replace(/\s+/g," ").trim()}function SJ(e,t){const n=bJ(e);if(n.length===0||t.length===0)return null;const a=new Map;for(const i of n)for(const s of t)aR(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:yJ(e,o.mention)}}function wX(e){return fJ(e)}function IX(e){return e.description||tR(e)}const qv=[{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 xJ(e){return qv.filter(t=>t.id!=="goal"||e==="codex")}function oR(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 xJ(e).filter(n=>oR(n,t))}const kJ=new Set(qv.map(e=>e.id));function CX(e){return e.subcommands?.length?e.subcommands.join(", "):e.description}function wJ(e){return[e.id,e.command,e.label,e.description].join(" ")}function IJ(e){return(e.subcommands??[]).flatMap(t=>[t,`${e.id} ${t}`,`${e.command} ${t}`]).join(" ")}function _J(e){const t=/^\/([a-z][a-z0-9_-]*)(?:\s+([\s\S]*))?$/.exec(e.trim());if(!t)return null;const n=t[1];return kJ.has(n)?{command:n,args:t[2]?.trim()??""}:null}function CJ(e){const t=e.trim();if(!t.startsWith("!"))return null;const n=t.slice(1).trim();return n?{command:n}:null}function RX({commands:e=qv,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=>wJ(l).toLowerCase().includes(a));return(i.length>0?i:e.filter(l=>IJ(l).toLowerCase().includes(a))).slice(0,n)}function PX(e){return e==="owner"?"Owner":e==="admin"?"Admin":"Member"}function Yu(e){return e?.role==="owner"||e?.role==="admin"}function AX(e){const t=Qu(e.organizations,e.defaultTeamId),n=Yu(t),a=e.localProject??null;if(!a)return RJ("Open a local project to set up an Agent.");const o=PJ(a,e.projects),i=AJ(a,o,e.agents),s=!!a.sandboxTemplate?.detected,l=t&&!n?"Ask an owner or admin to connect this project.":null;return s?o?TJ(a,o)?dd({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}:dd({state:"needs_agent",actionLabel:"Create Agent",project:o,agent:null,canManage:n,actionBlockedReason:l}):dd({state:"needs_project",actionLabel:"Connect Project",project:null,agent:null,canManage:n,actionBlockedReason:l}):dd({state:"missing_config",actionLabel:"Add Agent config",project:o,agent:i,canManage:n,actionBlockedReason:l})}function dd(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 RJ(e){return{state:"blocked",actionLabel:"Ask admin",canAct:!1,reason:e,project:null,agent:null}}function Qu(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 PJ(e,t){const n=e.linkedSandboxProject;return n?.projectId?t.find(a=>a.id===n.projectId)??null:null}function AJ(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 TJ(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 Or=e=>e.slice(0,2e4);function EJ({model:e,provider:t,providerSettings:n}){return{model:kv(t,e,n),modelRef:La(t,e,n)}}function MJ(e,t){return e.some(n=>n.id===t.id)?e:[...e,t]}function jJ(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 OJ(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 RS({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 $J({applyBootstrapPayload:e,connection:t,codexPermissionMode:n,codexReasoningEffort:a,openPondCommandAccessMode:o,draftModel:i,draftProvider:s,experience:l,expandProject:m,ensureCloudSessionReady:d,getPrompt:h,bootstrap:v,chatMessages:y,apps:w,connectedAppMentions:_,mentionedAppId:R,refreshWorkspace:M,refreshWorkspaceDiff:C,selectedApp:N,selectedActionCatalog:$,openPondActionCatalog:j,cloudProjects:k,accountScopeKey:P,selectedCloudProject:T,selectedProject:U,selectedProjectLinkedOpenPondApp:B,selectedSession:D,workspaceTarget:W,subagentDelegationMode:se,setDraftModel:me,setDraftProvider:Te,setError:ke,setPrompt:V,setMentionedAppId:Re,setCodexHistoryEvents:be,setCodexHistorySessions:ce,onCodexHistoryTurnActivityChange:ye,onCodexHistoryTurnPayload:ne,onPendingUserMessage:ge,setEvents:xe,setSelectedAppId:De,setSelectedProjectId:we,setSelectedSessionId:ae,setSessions:Se,setView:ze,setWorkspaceBusy:Qe}){function We(F){Y.bootstrap(F).then(e).catch(I=>{console.warn("[chat] Message was accepted, but the post-send bootstrap refresh failed.",I);const G=I instanceof Error?I.message:String(I);ke(`Message sent, but the chat list could not refresh: ${G}`)})}const nt=g.useRef(new Set),qe=v?.providers??null;function Ze(F,I){return F==="codex"?void 0:I}function He(F){return!!(F&&F.provider!=="codex"&&(F.workspaceKind==="local_project"&&F.cwd?.trim()||(F.workspaceKind==="sandbox"||F.workspaceKind==="sandbox_template"||F.workspaceKind==="sandbox_app")&&F.workspaceId))}function L(F){Te(F),me(I=>Sr(F,I,qe)),ze("chat")}async function O(F,I){return(LC(I,P)??await $v({teamId:I,accountKey:P,fetchAgents:async te=>(await Y.listSandboxAgents(t,{teamId:te})).agents})).find(te=>te.projectId===F)??null}async function z(){if(!t)throw new Error("OpenPond App server is not connected.");if(v?.account.state!=="signed_in")throw new Error("Add an OpenPond account before syncing a Project to Cloud.");const F=await Y.organizations(t),I=Qu(F.organizations.map(Ku).filter(G=>!!G).filter(G=>G.status==="active"),v?.preferences.defaultTeamId??null);if(!I)throw new Error("Add an OpenPond account before syncing a Project to Cloud.");if(!Yu(I))throw new Error(`You need owner or admin access to create projects in ${I.displayName}.`);return I}async function X(F){if(!t)return!1;const I=U;if(!I)throw new Error("Select a local Project before using /sync-cloud.");const G=await z(),ie=I.linkedSandboxProject?.defaultBranch?.trim()||"main",te=yt("local",I.id),oe=ka(I,k),ue=await Y.createSession(t,{provider:"openpond",modelRef:La("openpond",ds,qe),openPondCommandAccessMode:Ze("openpond",o),appId:null,appName:null,workspaceKind:"local_project",workspaceId:I.id,workspaceName:I.name,localProjectId:I.id,cloudProjectId:oe?.id??null,cloudTeamId:oe?.teamId??null,cwd:I.workspacePath,title:`Sync ${I.name} to Cloud`});Se(pe=>[ue,...pe]),F.onSessionCreated?.(ue),F.selectSession&&(ae(ue.id),we(te),De(null),ze("chat"),m(te)),F.clearPromptForTurn(),Qe(!0);try{const pe=await Y.uploadLocalProjectCloudSource(t,I.id,{teamId:G.teamId,projectName:I.name,branch:ie,chatSessionId:ue.id,displayPrompt:F.displayPrompt});return e(pe.bootstrap),m(te),m(yt("cloud",pe.project.id)),!0}catch(pe){const Ie=await Y.bootstrap(t).catch(()=>null);throw Ie&&e(Ie),pe}finally{Qe(!1)}}async function fe(F){if(!t||F.providerForTurn==="codex"||F.selectedSessionForTurn?.provider==="codex")return!1;let I=He(F.selectedSessionForTurn)?F.selectedSessionForTurn:null;if(!I&&F.selectedSessionForTurn)throw new Error("Select a project to use this.");if(!I)if(T){const ie=yt("cloud",T.id),te=F.providerForTurn;I=await Y.createSession(t,{provider:te,modelRef:La(te,F.modelForTurnValue,qe),openPondCommandAccessMode:Ze(te,F.openPondCommandAccessModeForTurn),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:T.id,workspaceName:T.name,localProjectId:null,cloudProjectId:T.id,cloudTeamId:T.teamId,cwd:null,autoTitlePrompt:Or(F.command)}),Se(oe=>[I,...oe]),F.onSessionCreated?.(I),F.selectSession&&(ae(I.id),we(ie),De(null),ze("chat"),m(ie))}else{const ie=U;if(!ie)throw new Error("Select a project to use this.");const te=ka(ie,k),oe=yt("local",ie.id),ue=F.providerForTurn;I=await Y.createSession(t,{provider:ue,modelRef:La(ue,F.modelForTurnValue,qe),openPondCommandAccessMode:Ze(ue,F.openPondCommandAccessModeForTurn),appId:null,appName:null,workspaceKind:"local_project",workspaceId:ie.id,workspaceName:ie.name,localProjectId:ie.id,cloudProjectId:te?.id??null,cloudTeamId:te?.teamId??null,cwd:ie.workspacePath,autoTitlePrompt:Or(F.command)}),Se(pe=>[I,...pe]),F.onSessionCreated?.(I),F.selectSession&&(ae(I.id),we(oe),De(null),ze("chat"),m(oe))}if(!I)throw new Error("Select a project to use this.");F.clearPromptForTurn();const G=await Y.runSessionCommand(t,I.id,{command:F.command,cwd:I.cwd});return Se(ie=>kl(ie,G.session)),xe(ie=>To(ie,G.events)),!0}async function Me(F=[],I=null,G,ie={}){const te=G??h();let oe=te.trim()||(F.length>0?"Please review the attached files.":"");if(!t||!oe)return!1;const ue=ie.displayPrompt?.trim()||oe,pe=ie.provider??s,Ie=ie.model??i,je=ie.openPondCommandAccessMode??o,Ne=ie.session!==void 0,$e=Ne?ie.session??null:D,at=ie.experience??$e?.experience??l,pt=at==="development"||at==="work"&&($e?.workspaceKind==="local_project"||!!$e?.localProjectId||!!$e?.cloudProjectId||!Ne&&!!(U||T||N||W==="hybrid"||W==="local")),sn=Ne||!pt?null:N,At=Ne||!pt?null:U,nn=Ne||!pt?null:T,un=Ne||!pt?null:B,mn=!Ne&&pt&&W==="hybrid",qt=ie.selectSession??!0,_a=ie.chatMessages??y,Cn=ie.session!==void 0?null:R,Tt=ie.clearPrompt===void 0?()=>{V(""),Re(null)}:ie.clearPrompt,Wt=I?null:SJ(oe,$),ut=I??Wt?.action??null,lt=Wt?.prompt||oe,Fn=pt&&!ut?CJ(oe):null,Gt=ut||Fn?null:_J(oe),Ca=Gt&&!oR({id:Gt.command},at)?Gt:null,Ra=ie.usageAttribution??(Gt?{surface:"chat",workflowKind:"slash_command",commandName:`/${Gt.command}`,commandSource:"prompt_parse"}:void 0);ke(null);let Qt=null,pn=null;try{if(!pt&&pe==="codex")throw new Error("The Codex provider requires repository-aware Work.");if(Ca)throw new Error(`/${Ca.command} isn't available in ${at}.`);if(Fn&&pe!=="codex"&&$e?.provider!=="codex"){if(F.length>0)throw new Error("Direct commands do not accept attachments.");return await fe({command:Fn.command,clearPromptForTurn:Tt,modelForTurnValue:Ie,onSessionCreated:ie.onSessionCreated,openPondCommandAccessModeForTurn:je,providerForTurn:pe,selectedSessionForTurn:$e,selectSession:qt})}if(!Ne&&Gt?.command==="sync-cloud")return await X({clearPromptForTurn:Tt,displayPrompt:ue,onSessionCreated:ie.onSessionCreated,selectSession:qt});if(ut){const K=H7(ut);if(K){let Ke=$e;if(!Ke||Ke.cloudProjectId!==K.projectId){Ke=await Y.createSession(t,{provider:"openpond",modelRef:La("openpond",Ie,qe),openPondCommandAccessMode:Ze("openpond",je),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:K.projectId,workspaceName:K.projectName??K.agentName,localProjectId:null,cloudProjectId:K.projectId,cloudTeamId:K.teamId,cwd:null,autoTitlePrompt:Or(ue)}),Se(Ma=>[Ke,...Ma]),ie.onSessionCreated?.(Ke),qt&&ae(Ke.id);const Rn=yt("cloud",K.projectId);qt&&we(Rn),qt&&m(Rn)}const Dn=await Y.runSandboxAgent(t,K.agentId,V7({agent:K,attachments:F,displayPrompt:ue,prompt:lt})),St=await Y.bootstrap(t);return e(St),Tt(),xe(Rn=>To(Rn,RS({action:ut,prompt:ue,runPayload:Dn,sessionId:Ke.id}))),!0}const Ue=Uv(ut);if(Ue){let Ke=$e;(!Ke||Ke.provider!=="openpond")&&(Ke=await Y.createSession(t,{provider:"openpond",modelRef:La("openpond",Ie,qe),openPondCommandAccessMode:Ze("openpond",je),appId:null,appName:null,workspaceId:null,workspaceName:"OpenPond profile",localProjectId:null,cloudProjectId:null,cloudTeamId:null,cwd:null,autoTitlePrompt:Or(ue)}),Se(St=>[Ke,...St]),ie.onSessionCreated?.(Ke),qt&&ae(Ke.id)),await Y.runProfileAction(t,B7({action:Ue,attachments:F,displayPrompt:ue,prompt:lt,sessionId:Ke.id}));const Dn=await Y.bootstrap(t);return e(Dn),Tt(),!0}const _e=FC({cloudProjects:k,selectedCloudProject:T,selectedProject:U});if(!_e)throw new Error("Select a Project linked to an OpenPond Cloud Project before running an action.");let Be=$e;(!Be||Be.cloudProjectId!==_e.id)&&(Be=await Y.createSession(t,{provider:"openpond",modelRef:La("openpond",Ie,qe),openPondCommandAccessMode:Ze("openpond",je),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:_e.id,workspaceName:_e.name,localProjectId:_e.localProjectId,cloudProjectId:_e.id,cloudTeamId:_e.teamId,cwd:null,autoTitlePrompt:Or(ue)}),Se(Ke=>[Be,...Ke]),ie.onSessionCreated?.(Be),qt&&(ae(Be.id),we(_e.selectionKey),m(_e.selectionKey)));const vt=await O(_e.id,_e.teamId);if(!vt)throw new Error("No OpenPond Agent is available for this Project.");Tt();const kn=await Y.runSandboxAgent(t,vt.id,F7({action:ut,attachments:F,displayPrompt:ue,prompt:lt,teamId:_e.teamId})),Xt=await Y.bootstrap(t);return e(Xt),xe(Ke=>To(Ke,RS({action:ut,prompt:ue,runPayload:kn,sessionId:Be.id}))),!0}let rt=$e;if(rt&&Lt(rt.id)){pn=L0({afterMessageId:_a.at(-1)?.id??null,attachments:F,content:oe,sessionId:rt.id}),Tt(),Qt=rt.id,nt.current.add(Qt),ge?.(pn),ye?.(Qt,!0);const K=jJ(rt.id,oe),Ue=Be=>{(!Ne||D?.id===rt.id)&&be(vt=>MJ(vt,Be)),ie.onCodexHistoryOptimisticEvent?.(Be)};Ue(K),ce(Be=>Be.map(vt=>vt.id===rt.id?{...vt,status:"active"}:vt));const _e=await Y.sendCodexHistoryTurn(t,rt.id,{prompt:oe,attachments:F.length>0?F:void 0,model:kv("codex",Ie,qe),modelRef:La("codex",Ie,qe),...t0(n),codexPermissionMode:n,codexReasoningEffort:a}).catch(Be=>{throw Ue(OJ(K,Be)),Be});return(!Ne||D?.id===rt.id)&&be(Be=>To(Be,_e.events)),ce(Be=>kl(Be,_e.session)),ne?.(_e),We(t),!0}const Pa=(Cn?w.find(K=>K.id===Cn&&N9(te,K)&&K.sandbox)??null:null)??D9(te,lC(w)),Aa=at==="chat"?[]:Q9(te,_).map(K=>K.ref);if(!rt){const K=un?.appId??sn?.id??null,Ue=un?.appName??sn?.name??null,_e=nn,Be=Ne?null:ka(At,k),vt=mn?nC({cloudProjects:k,selectedCloudProject:_e,selectedProject:At}):null;if(vt?.kind==="missing_cloud_project")throw new Error(vt.message);const kn=vt?.kind==="ready",Xt=kn?pe:_e?"openpond":pe,Ke=La(Xt,Ie,qe),Dn=Ze(Xt,je),St=kn?aC({modelRef:Ke,provider:Xt,target:vt,title:oe.slice(0,64)}):null;rt=await Y.createSession(t,St?{...St,subagentDelegationMode:se,metadata:{...St.metadata,...ie.sessionMetadata??{}},...Dn?{openPondCommandAccessMode:Dn}:{},autoTitlePrompt:Or(oe)}:{experience:at,provider:Xt,modelRef:Ke,subagentDelegationMode:se,...Dn?{openPondCommandAccessMode:Dn}:{},appId:K,appName:Ue,workspaceKind:_e?"sandbox":At?"local_project":sn?"sandbox_app":void 0,workspaceId:At?.id??(sn?K:void 0),workspaceName:_e?.name??At?.name??Ue,localProjectId:At?.id??null,cloudProjectId:_e?.id??Be?.id??null,cloudTeamId:_e?.teamId??Be?.teamId??null,...!_e&&!At&&!sn&&W==="local"?{metadata:{...h9(),...ie.sessionMetadata??{}}}:{cwd:At?At.workspacePath:null,...ie.sessionMetadata?{metadata:ie.sessionMetadata}:{}},autoTitlePrompt:Or(oe)}),Se(Rn=>[rt,...Rn]),ie.onSessionCreated?.(rt),qt&&(ae(rt.id),_e&&we(yt("cloud",_e.id)),rt.workspaceKind==="local_project"&&rt.workspaceId&&m(yt("local",rt.workspaceId)),_e&&m(yt("cloud",_e.id)))}if(PS(rt)&&go(rt.workspaceKind)&&rt.provider!=="openpond"&&!vo(rt))throw new Error("Cloud workspaces use OpenPond Chat. Switch to Local to use local providers.");if(PS(rt)&&go(rt.workspaceKind)&&d)try{rt=await d(rt)}catch(K){const Ue=K instanceof Error?K.message:String(K);throw await Y.recordPreflightTurnFailure(t,rt.id,{prompt:oe,error:Ue,target:vo(rt)?"hybrid_sandbox":"cloud_workspace"}).then(e).catch(()=>{}),K}pn=L0({afterMessageId:_a.at(-1)?.id??null,attachments:F,content:oe,sessionId:rt.id}),Tt(),Qt=rt.id,nt.current.add(Qt),ge?.(pn),Se(K=>K.map(Ue=>Ue.id===Qt?{...Ue,status:"active"}:Ue));const ea=pe,Ta=EJ({provider:ea,model:Ie,providerSettings:qe}),Nn=s6(ea,Ta.model??Ie,qe),yo=ea==="codex"?t0(n):{approvalPolicy:"on-request",sandbox:"workspace-write"};await Y.sendTurn(t,rt.id,{prompt:oe,metadata:ie.turnMetadata,attachments:F.length>0?F:void 0,mentionedAppIds:Pa?[Pa.id]:void 0,mentionedConnectedApps:Aa.length>0?Aa:void 0,openPondActionCatalog:j.length>0?j:void 0,usageAttribution:Ra,...Ta,...yo,codexPermissionMode:ea==="codex"?n:"default",codexReasoningEffort:Nn?i6(ea,Ta.model??Ie,a,qe):void 0}),We(t);const Ea=rt.workspaceId??rt.appId;return Ea&&rt.workspaceKind!=="sandbox"&&rt.workspaceKind!=="sandbox_template"&&M(Ea,!1).then(K=>{K?.initialized&&C(Ea)}),!0}catch(rt){return ke(rt instanceof Error?rt.message:String(rt)),!1}finally{Qt&&nt.current.delete(Qt),Qt&&Lt(Qt)&&ye?.(Qt,!1),Qt&&(Lt(Qt)?ce(rt=>rt.map(xn=>xn.id===Qt&&xn.status==="active"?{...xn,status:"idle"}:xn)):Se(rt=>rt.map(xn=>xn.id===Qt&&xn.status==="active"?{...xn,status:"idle"}:xn)))}}async function Le(F,I){const G=nt.current.values().next().value??null,ie=F??D?.id??G;if(!t||!ie)return!1;if(ke(null),Lt(ie))try{const te=await Y.interruptCodexHistoryTurn(t,ie);if(!te.interrupted){if(te.reason==="no_active_openpond_turn"){const ue=await Y.codexHistoryThread(t,ie,{tail:!0}),pe={...ue.session,status:"idle"};return D?.id===ie&&be(Ie=>To(Ie,ue.events)),ce(Ie=>kl(Ie,pe)),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 oe=await Y.codexHistoryThread(t,ie,{tail:!0});return D?.id===ie&&be(ue=>To(ue,oe.events)),ce(ue=>kl(ue,oe.session)),!0}catch(te){const oe=te instanceof Error?te.message:String(te);return ke(oe==="Not found"?"OpenPond could not find this Codex history session, so it cannot interrupt it here.":oe),!1}try{await Y.interruptTurn(t,ie,I);const te=await Y.bootstrap(t);return e(te),!0}catch(te){return ke(te instanceof Error?te.message:String(te)),!1}}async function et(F,I){if(!t){ke("OpenPond App server is not connected.");return}ke(null),await Y.applyCreateImproveAction(t,F.id,{...I,runId:F.id,expectedRevision:F.revision,actionId:`web:${I.type}:${crypto.randomUUID()}`});const G=await Y.bootstrap(t);e(G)}async function Xe(F){await et(F.run,{type:"approve_plan"})}async function st(F){await et(F.run,{type:"cancel",reason:null})}async function mt(F,I){await et(F.run,{type:"revise_plan",revision:I})}async function Oe(F,I,G){await et(F.run,{type:"answer_question",questionId:I,value:G})}async function Ge(F){await et(F.run,{type:"pause"})}async function f(F){await et(F.run,{type:"resume"})}async function H(F,I){await et(F.run,{type:"open_pull_request",candidateId:I})}async function Z(F,I){await et(F.run,{type:"apply_candidate",candidateId:I})}async function le(F,I){await et(F.run,{type:"reject_candidate",candidateId:I,reason:null})}async function ee(F,I){await et(F.run,{type:"reconcile_pull_request",candidateId:I})}return{answerCreateImproveQuestion:Oe,approveCreateImproveRun:Xe,applyCreateImproveCandidate:Z,cancelCreateImproveRun:st,changeDraftProvider:L,openCreateImprovePullRequest:H,pauseCreateImproveRun:Ge,reconcileCreateImprovePullRequest:ee,rejectCreateImproveCandidate:le,resumeCreateImproveRun:f,reviseCreateImproveRun:mt,sendPrompt:Me,stopTurn:Le}}function PS(e){return e.experience==="development"||e.experience==="work"&&(e.workspaceKind==="local_project"||!!e.localProjectId||!!e.cloudProjectId||e.metadata?.workspaceTarget==="local")}async function NJ({branch:e,connection:t,session:n}){if(!go(n.workspaceKind))return{sandbox:null,session:n,status:"already_running"};const a=await Y.ensureCloudWorkspaceReady(t,n.id,{branch:e,surface:"desktop"});return{bootstrap:await Y.bootstrap(t),output:a.output,sandbox:null,session:a.session,status:a.status}}function DJ(e){return vo(e)?"Preparing Hybrid sandbox...":"Starting Cloud workspace..."}function LJ(e,t){if(e==="already_running")return null;const n=vo(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 UJ(e,t){return!e.cloudProjectId||!e.cloudTeamId?!0:t.some(n=>n.id===e.cloudProjectId&&n.teamId===e.cloudTeamId)}function HJ({applyBootstrapPayload:e,cloudProjects:t,connection:n,localProjectById:a,selectedCloudProject:o,selectedProject:i,setWorkspaceBusy:s,showToast:l,visibleWorkspaceState:m}){return g.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&&!UJ(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(DJ(d),"info"),s(!0);try{const v=await NJ({branch:i?.linkedSandboxProject?.defaultBranch??o?.defaultBranch??m?.currentBranch??null,connection:n,localProject:h,session:d,source:vo(d)?"openpond-app-hybrid-chat-preflight":"openpond-app-cloud-chat-preflight"});v.bootstrap&&e(v.bootstrap);const y=LJ(v.status,d);return y&&l(y,"success"),v.session}finally{s(!1)}},[e,t,n,a,o,i,s,l,m?.currentBranch])}function zJ(){return{diffPanelOpen:!1,diffPanelExpanded:!1,rightPanelMode:"changes",rightChatPanels:[]}}function qJ(e){return{diffPanelOpen:e.diffPanelOpen,diffPanelExpanded:e.diffPanelExpanded,rightPanelMode:e.rightPanelMode,rightChatPanels:e.rightChatPanels}}function AS(e){return{...e,rightChatPanels:e.rightChatPanels.map(t=>({...t}))}}function BJ(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 FJ(e){return`${e.conversationId}\0${e.workspaceSourceKey||"none"}`}function VJ(e){const{appDispatch:t,diffPanelExpanded:n,diffPanelOpen:a,rightChatPanels:o,rightPanelMode:i,selectedAppId:s,selectedCloudProject:l,selectedProjectId:m,selectedSession:d,selectedSessionId:h,setWorkspaceDiffPanelViewState:v,view:y,viewWorkspaceAppId:w,viewWorkspaceId:_,viewWorkspaceKind:R,workspaceDiffPanelViewState:M}=e,C=g.useRef(new Map),N=g.useRef(new Map),$=g.useRef(null),j=g.useRef(null),k=h??`draft:${m??s??l?.id??"general"}`,P=g.useMemo(()=>_?`${R??"workspace"}:${_}`:w?`app:${w}`:d?.cwd&&!go(d.workspaceKind)?`cwd:${d.cwd}`:"none",[d?.cwd,d?.workspaceKind,y,w,_,R]),T=FJ({conversationId:k,workspaceSourceKey:P}),U=g.useMemo(()=>qJ({diffPanelExpanded:n,diffPanelOpen:a,rightChatPanels:o,rightPanelMode:i}),[n,a,o,i]);g.useEffect(()=>{const D=$.current;D&&C.current.set(D,AS(U))},[k,U]),g.useEffect(()=>{if($.current===k)return;$.current=k;const W=C.current.get(k)??zJ();BJ(U,W)||t({type:"patch",patch:AS(W)})},[k,U]),g.useEffect(()=>{const D=j.current;D&&N.current.set(D,tf(M))},[T,M]),g.useEffect(()=>{if(j.current===T)return;j.current=T;const W=N.current.get(T)??oC();v(se=>C0(se,W)?se:tf(W))},[T]);const B=g.useCallback(D=>{v(W=>C0(W,D)?W:tf(D))},[]);return{browserConversationId:k,handleWorkspaceDiffPanelViewStateChange:B}}function KJ({account:e,accountPending:t,accountSignedOut:n,activeWorkspaceKind:a,activeWorkspaceLocation:o,appDispatch:i,applyBootstrapPayload:s,busy:l,cloudSetupDialog:m,cloudProjects:d,connection:h,defaultTeamId:v,expandProject:y,localProjectById:w,selectedCloudProject:_,selectedProject:R,selectedSession:M,selectedSessionProjectId:C,setCloudSetupDialog:N,setDiffPanelOpen:$,setError:j,setSessions:k,setWorkspaceBusy:P,showToast:T,visibleWorkspaceState:U,workspaceBusy:B}){const D=e?.baseUrl??e?.activeProfile?.baseUrl??null,W=g.useCallback(async(V,Re)=>{if(h)try{const be=await Y.previewLocalProjectCloudSource(h,V.id,{branch:Re});N(ce=>!ce||ce.status!=="confirm"||ce.localProjectId!==V.id||ce.branch!==Re?ce:{...ce,branch:be.preview.branch,cloudProjectId:be.preview.targetProjectId,preview:be.preview,previewLoading:!1,previewError:null})}catch(be){const ce=be instanceof Error?be.message:String(be);N(ye=>!ye||ye.status!=="confirm"||ye.localProjectId!==V.id||ye.branch!==Re?ye:{...ye,preview:null,previewLoading:!1,previewError:ce})}},[h,N]),se=g.useCallback(async()=>{const V=m;if(!V||V.status==="uploading")return;if(V.projectKind==="cloud"){N(ye=>ye&&{...ye,status:"ready",error:null});return}if(!h){N(ye=>ye&&{...ye,status:"error",error:"OpenPond App server is not connected."});return}const Re=V.localProjectId??"",be=w.get(Re);if(!be){N(ye=>ye&&{...ye,status:"error",error:"Project is no longer available."});return}P(!0);const ce=ka(be,d);N(ye=>ye&&{...ye,status:"uploading",error:null,previewLoading:!1});try{const ye=await Y.organizations(h),ne=Qu(ye.organizations.map(Ku).filter(ze=>!!ze).filter(ze=>ze.status==="active"),v);if(!ne)throw new Error("Add an OpenPond account before creating a Cloud environment.");if(!Yu(ne))throw new Error(`You need owner or admin access to create projects in ${ne.displayName}.`);const ge=V.branch||be.linkedSandboxProject?.defaultBranch||"main",xe=yt("local",be.id),De=await Y.createSession(h,{provider:"openpond",appId:null,appName:null,workspaceKind:"local_project",workspaceId:be.id,workspaceName:be.name,localProjectId:be.id,cloudProjectId:ce?.id??null,cloudTeamId:ce?.teamId??null,cwd:be.workspacePath,title:`Sync ${be.name} to Cloud`});k(ze=>[De,...ze]),i({type:"selectSession",sessionId:De.id,projectId:xe}),y(xe);const we=await Y.uploadLocalProjectCloudSource(h,be.id,{teamId:ne.teamId,projectName:be.name,branch:ge,chatSessionId:De.id,displayPrompt:`/sync-cloud ${be.name}`});s(we.bootstrap),y(xe),y(yt("cloud",we.project.id));const ae=Ch({accountBaseUrl:D,teamId:we.project.teamId,projectId:we.project.id,projectName:we.project.name,baseBranch:we.upload.branch,localProjectId:be.id,source:"openpond-app"}),Se=IS({accountBaseUrl:D,organizationSlug:we.project.organizationSlug,projectSlug:we.project.slug});N({status:"ready",localProjectId:be.id,cloudProjectId:we.project.id,teamId:we.project.teamId,projectName:we.project.name,projectKind:"local",projectUrl:Se,setupUrl:ae,branch:we.upload.branch,preview:V.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}),T("Source uploaded to OpenPond Git. Cloud setup link is ready.","success")}catch(ye){const ne=ye instanceof Error?ye.message:String(ye),ge=h?await Y.bootstrap(h).catch(()=>null):null;ge&&s(ge),j(ne),N(xe=>xe&&{...xe,status:"error",error:ne})}finally{P(!1)}},[D,i,s,m,d,h,v,y,w,N,j,k,P,T]),me=g.useCallback((V,Re)=>{if(!h){T("OpenPond App server is not connected.","error");return}if(t){T("Checking OpenPond account. Try again in a moment.","info");return}if(n){T("Add an OpenPond account before using Cloud.","error");return}const be=Re||V.linkedSandboxProject?.defaultBranch||"main";N({status:"confirm",localProjectId:V.id,projectName:V.name,projectKind:"local",projectUrl:null,setupUrl:null,branch:be,preview:null,previewLoading:!0,previewError:null,upload:null,error:null}),W(V,be)},[t,n,h,W,N,T]),Te=g.useCallback(async V=>{if(V===o||B||l)return;if(j(null),V==="upload_cloud"){if(!R){T("Select a local Project before uploading source.","error");return}me(R,U?.currentBranch??null);return}if(V==="local"){const ce=M?.localProjectId??R?.id??C??null,ye=ce?w.get(ce)??null:null;if(!ye){T("No linked local workspace for this Cloud chat.","error");return}if(go(a)&&!window.confirm("Switch to Local? Cloud changes will stay in the hosted workspace until you preserve or export them."))return;const ne=yt("local",ye.id);i({type:"selectProject",projectId:ne}),y(ne),$(!1),T(`Switched to Local: ${ye.name}`,"info");return}if(!h){T("OpenPond App server is not connected.","error");return}if(t){T("Checking OpenPond account. Try again in a moment.","info");return}if(n){T("Add an OpenPond account before using Cloud.","error");return}if(_){N({status:"ready",cloudProjectId:_.id,teamId:_.teamId,projectName:_.name,projectKind:"cloud",projectUrl:IS({accountBaseUrl:D,organizationSlug:_.organizationSlug,projectSlug:_.slug}),setupUrl:Ch({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 Re=R;if(!Re){T("Select a Project before Cloud coding.","error");return}const be=U?.currentBranch||Re.linkedSandboxProject?.defaultBranch||"main";me(Re,be)},[D,t,n,a,o,i,l,h,d,y,w,me,_,R,M,C,N,$,j,T,U?.currentBranch,B]),ke=g.useCallback(V=>{yv(V)&&me(V.project)},[me]);return{changeWorkspaceTarget:Te,moveProjectToCloud:ke,openCloudSetupForLocalProject:me,startCloudSetupUpload:se}}function WJ({advanceTrainingTurn:e,bindTrainingSession:t,composerDraftStore:n,onSessionCreated:a,onSubmitted:o,prepareTrainingTurn:i,sendPrompt:s,setMentionedAppId:l,showToast:m}){return g.useCallback(async(d=[],h=null,v,y={})=>{const w=v??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 R=await s(d,h,v,{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 R&&await o?.(),R&&_.metadata&&e(),R},[e,t,n,a,o,i,s,l,m])}function GJ({appDispatch:e,connection:t,sessions:n,setDiffPanelOpen:a,setRightPanelMode:o,setSessions:i,setView:s}){return g.useCallback(async l=>{if(!t)return;const m=n.find(v=>!v.archived&&v.workspaceKind==="sandbox"&&v.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 Y.createSession(t,{provider:"openpond",appId:null,appName:null,workspaceKind:"sandbox",workspaceId:l.sandboxId,workspaceName:d,cwd:null,title:d});i(v=>[h,...v]),e({type:"selectSession",sessionId:h.id,appId:null,projectId:null}),o("changes"),a(!0),s("chat")},[e,t,n,a,o,i,s])}function ZJ({connection:e,defaultTeamId:t,sessions:n,selectedProjectId:a,confirmProjectAction:o,applyBootstrapPayload:i,expandProject:s,setExpandedProjectIds:l,setSelectedAppId:m,setSelectedProjectId:d,setSelectedSessionId:h,setError:v,setView:y,showToast:w}){function _($){const j=yt("local",$.id);m(null),d(j),h(null),y("chat"),s(j)}async function R($){if(!e)return!1;v(null);try{const j=await Y.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 k=j instanceof Error?j.message:String(j);return v(k),w(k,"error"),!1}}async function M($){if(!e)return!1;const j=$.trim();if(!j)return!1;v(null);try{const k=await Y.createLocalProject(e,{createNew:!0,name:j});return i(k.bootstrap),_(k.project),w(`Created ${k.project.name}`,"success"),!0}catch(k){return v(k instanceof Error?k.message:String(k)),w("Project could not be created","error"),!1}}async function C($){if(!e)return!1;const j=$.trim();if(!j)return!1;v(null);try{const k=await Y.organizations(e),P=Qu(k.organizations.map(Ku).filter(W=>!!W).filter(W=>W.status==="active"),t);if(!P)throw new Error("Add an OpenPond account before creating a Cloud Project.");if(!Yu(P))throw new Error(`You need owner or admin access to create projects in ${P.displayName}.`);const T=`${rC(j)}-${Date.now().toString(36)}`;let U=(await Y.upsertSandboxProject(e,{teamId:P.teamId,name:j,sourceType:"internal_repo",normalizedSourceIdentity:T,internalRepoPath:T,defaultBranch:"main",sourceConfig:{sourceType:"internal_repo",sourceValue:T},metadata:{source:"openpond-app-new-cloud-project"}})).project;U=(await Y.uploadSandboxProjectSource(e,U.id,{teamId:P.teamId,branch:"main",commitMessage:"Initialize cloud project",entries:[{path:"README.md",type:"file",contentsBase64:C9(`# ${j}
|
|
211
|
+
|
|
212
|
+
Created in OpenPond Cloud.
|
|
213
|
+
`)}]})).project;const B=await Y.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(k){const P=k instanceof Error?k.message:String(k);return v(P),w(P,"error"),!1}}async function N($){if(!e)return;if(e6($)){const T=`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(T)))return;v(null);try{await Y.archiveSandboxProject(e,$.project.id,{teamId:$.project.teamId}),i(await Y.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){v(B instanceof Error?B.message:String(B)),w("Cloud Project could not be archived","error")}return}if(!yv($))return;const j=$.project,k=`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(k)){v(null);try{const T=await Y.deleteLocalProject(e,j.id);i(T),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(T){v(T instanceof Error?T.message:String(T)),w("Project could not be removed","error")}}}return{createCloudProjectFromScratch:C,createProjectFromScratch:M,createProjectCollection:R,removeProject:N}}function JJ({appDispatch:e,busy:t,cloudProjectById:n,createCloudProjectFromScratch:a,createProjectFromScratch:o,createProjectCollection:i,expandProject:s,localProjectById:l,onCreateCloudEnvironment:m,onNewCloudProject:d,onNewLocalProject:h,onUseExistingFolderPath:v,newProjectBusy:y,newProjectMode:w,newProjectName:_,projectTargetValue:R,setDiffPanelOpen:M,setDraftModel:C,setDraftProvider:N,setError:$,setNewProjectBusy:j,setNewProjectDialogOpen:k,setNewProjectName:P,setNewProjectPath:T,showToast:U,workspaceBusy:B}){const D=g.useCallback(se=>{if(se===R||t||B)return;if($(null),se==="action:new-local-project"){h();return}if(se==="action:add-local-project"){v();return}if(se==="action:add-local-project-path"){v();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 me=se.indexOf(":"),Te=me>=0?se.slice(0,me):"",ke=me>=0?se.slice(me+1):"";if(Te==="local"){const V=l.get(ke);if(!V){U("Project is no longer available.","error");return}const Re=yt("local",V.id);e({type:"selectProject",projectId:Re}),s(Re),M(!1);return}if(Te==="cloud"){const V=n.get(ke);if(!V){U("Cloud Project is no longer available.","error");return}const Re=yt("cloud",V.id);e({type:"selectProject",projectId:Re}),s(Re),N("openpond"),C(be=>Sr("openpond",be)),M(!1)}},[e,t,n,s,l,m,d,h,v,R,M,C,N,$,U,B]),W=g.useCallback(async se=>{const me=_.trim();if(!y){if(w==="existing-local"?!se?.name.trim()||!se.sourceFolders.length:!me)return!1;j(!0);try{const Te=w==="cloud"?await a(me):w==="existing-local"?await i(se):await o(me);return Te&&(k(!1),P(""),T("")),!!Te}finally{j(!1)}}},[a,o,i,y,w,_,j,k,P,T]);return{changeProjectTarget:D,submitNewProjectDialog:W}}function YJ(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 TX(e){return e.reduce((t,n)=>!t||n.activationVersion>=t.activationVersion?n:t,null)}function QJ(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 XJ(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 rR(e){return!!(e.parentSessionId&&e.subagentRunId)}function eY(e){const t=e.sessions.filter(rR);return{knownSessionIds:new Set(t.map(n=>n.id)),newSessions:t.filter(n=>!e.knownSessionIds.has(n.id))}}function tY(e,t){const n=new Set(e.map(o=>o.sessionId).filter(Boolean)),a=t.filter(rR).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 TS="openpond/openpond",nY="github.issue.write";function aY(e){return e.some(t=>t.provider==="github"&&(t.ref.capabilities??[]).includes(nY))}function EX(e){return[`Title: ${e.title.trim()}`,"","Description:",e.description.trim()].join(`
|
|
214
|
+
`)}function oY(e){const t=e.trim();return[`@github Submit this request as a new GitHub issue in ${TS}.`,`Use the GitHub connected app write operation github.issue.create with input.repo set to ${TS}, 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 rY(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:oY(n),requiresInstructions:!0};case"sync-cloud":return{kind:"send_prompt",prompt:`/sync-cloud ${n}`,requiresInstructions:!1}}}const ES=[];function iY(e){const{approvals:t,codexHistoryEvents:n,contextCompaction:a,pendingChatUserMessages:o,rightChatHistoryEvents:i,rightChatPanels:s,runningSessionIds:l,selectedSessionId:m,sidebarSessions:d}=e;return g.useMemo(()=>{const h=new Map(d.map(y=>[y.id,y])),v=sY(t);return s.map(y=>{const w=y.sessionId?h.get(y.sessionId)??null:null,_=Lt(y.sessionId),R=_?(y.sessionId?i[y.sessionId]:void 0)??(y.sessionId===m?n:ES):ES,M=ph(R,[]),C=y.sessionId?v.get(y.sessionId)??null:null,N=!!(w&&l.has(w.id)),$=_?OK({events:R}):null,j=w?.cwd??null,k=w?.appId??w?.localProjectId??(w?.workspaceKind==="local_project"?w.workspaceId??null:null)??(w?.cwd&&!go(w.workspaceKind)?dk(w.cwd):null),P=y.sessionId?o[y.sessionId]??null:null;return{...y,session:w,title:$K($,w?.title??"New task"),messages:_?vC(Zu(R),P):[],createImproveRun:$,contextWindowStatus:$_({provider:y.provider,snapshot:Y_(M,y.sessionId),preferences:a}),goalRuntime:Q_(M,y.sessionId),pendingApproval:C,running:N,workspaceRootPath:j,activeWorkspaceAppId:k,pendingUserMessage:P,runtimeSource:_?"history":"live"}})},[t,n,a,o,i,s,l,m,d])}function sY(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 lY(e){const{applyPayload:t,connection:n,locallyActiveSessionIds:a,panels:o,sessions:i,setError:s}=e,l=g.useMemo(()=>{const h=new Set,v=[];for(const y of o)!Lt(y.sessionId)||!y.sessionId||h.has(y.sessionId)||(h.add(y.sessionId),v.push(y.sessionId));return v.join(`
|
|
219
|
+
`)},[o]),m=g.useMemo(()=>{if(!l)return"";const h=new Set(l.split(`
|
|
220
|
+
`).filter(Boolean));return i.filter(v=>h.has(v.id)&&v.status==="active").map(v=>v.id).join(`
|
|
221
|
+
`)},[l,i]),d=g.useMemo(()=>l?l.split(`
|
|
222
|
+
`).filter(h=>a.has(h)).join(`
|
|
223
|
+
`):"",[a,l]);g.useEffect(()=>{if(!n||!l)return;const h=l.split(`
|
|
224
|
+
`).filter(Boolean),v=new Set(m.split(`
|
|
225
|
+
`).filter(Boolean)),y=new Set(d.split(`
|
|
226
|
+
`).filter(Boolean)),w=h.map(_=>Mv({connection:n,locallyActive:y.has(_),onError:R=>s(R instanceof Error?R.message:String(R)),onPayload:R=>t(Ev(R,y.has(_))),reportedActive:v.has(_),sessionId:_,surface:"thread"}));return()=>w.forEach(_=>_())},[m,t,n,d,l,s])}const MS=[];function cY(e){const{activeModel:t,activeProvider:n,approvals:a,applyRightCodexHistoryPayload:o,codexHistoryEvents:i,connectedAppMentions:s,connection:l,contextCompaction:m,openLabTraining:d,locallyActiveCodexHistorySessionIds:h,openPondCommandAccessMode:v,pendingChatUserMessages:y,providerSettings:w,rightChatHistoryEvents:_,rightChatPanels:R,rightPanelMode:M,runtimeIndexes:C,runtimeEventStore:N,runningSessionIds:$,selectedSession:j,selectedSessionId:k,sendPrompt:P,setDiffPanelOpen:T,setError:U,setRightChatHistoryEvents:B,setRightChatPanels:D,setRightPanelMode:W,setRightPanelTabRequest:se,setView:me,showChangesPanel:Te,showToast:ke,sidebarSessions:V,startupReady:Re}=e,be=g.useRef(null),ce=g.useRef(new Map),ye=g.useRef(new Set);g.useEffect(()=>{if(!l)return;const qe=R.flatMap(Ze=>Ze.sessionId&&!Lt(Ze.sessionId)?[Ze.sessionId]:[]);for(const Ze of qe)Object.hasOwn(_,Ze)||ye.current.has(Ze)||(ye.current.add(Ze),Y.runtimeEventsPage(l,{sessionId:Ze,beforeSequence:Number.MAX_SAFE_INTEGER,limit:500}).then(He=>{const L=He.events.map(O=>O.event);B(O=>({...O,[Ze]:Mo(O[Ze]??MS,L)}))}).catch(He=>{U(He instanceof Error?He.message:String(He))}).finally(()=>{ye.current.delete(Ze)}))},[l,_,R,U,B]);const ne=g.useCallback(qe=>{se(Ze=>({id:(Ze?.id??0)+1,tab:qe})),Te()},[Te]),ge=g.useCallback((qe=null,Ze={})=>{const He=qe?.id?R.find(O=>O.sessionId===qe.id)??null:null;if(He)return D(O=>XJ(O,{sessionId:qe.id,prompt:Ze.prompt})),T(!0),W("chat"),Ze.preserveView||me("chat"),He.id;const L=YJ({sessionId:qe?.id??null,provider:qe?.provider??n,model:qe?.modelRef?.modelId??t,prompt:Ze.prompt});return D(O=>[...O,L]),T(!0),W("chat"),Ze.preserveView||me("chat"),L.id},[t,n,R,T,D,W,me]);g.useEffect(()=>{if(!Re)return;const qe=be.current;if(!qe){be.current=new Set(V.filter(O=>!!(O.parentSessionId&&O.subagentRunId)).map(O=>O.id));return}const Ze=eY({sessions:V,knownSessionIds:qe});be.current=Ze.knownSessionIds;for(const O of Ze.newSessions)ce.current.set(O.id,O);const He=j?.parentSessionId??j?.id??null;if(!He)return;const L=[...ce.current.values()].filter(O=>O.parentSessionId===He);if(L.length!==0){for(const O of L)ce.current.delete(O.id);D(O=>tY(O,L)),T(!0),W("chat")}},[j?.id,j?.parentSessionId,T,D,W,V,Re]);const xe=g.useCallback(()=>{if(R.length===0){ge(null);return}T(!0),W("chat"),me("chat")},[ge,R.length,T,W,me]),De=g.useCallback(qe=>{const Ze=R.length<=1&&R.some(L=>L.id===qe),He=()=>{D(L=>L.filter(O=>O.id!==qe))};if(Ze&&M==="chat"){if(ne("files"),typeof window>"u"){He();return}window.requestAnimationFrame(He);return}He()},[R,M,D,ne]),we=g.useCallback((qe,Ze)=>{D(He=>He.map(L=>L.id===qe?{...L,prompt:Ze}:L))},[D]),ae=g.useCallback(qe=>{D(Ze=>QJ(Ze,qe))},[D]),Se=g.useCallback((qe,Ze)=>{D(He=>He.map(L=>L.id===qe?{...L,...Ze}:L))},[D]),ze=g.useCallback((qe,Ze)=>{D(He=>He.map(L=>L.id===qe?{...L,model:Ze}:L))},[D]),Qe=g.useCallback((qe,Ze)=>{D(He=>He.map(L=>L.id===qe?{...L,provider:Ze,model:Sr(Ze,L.model,w)}:L))},[w,D]);lY({applyPayload:o,connection:l,locallyActiveSessionIds:h,panels:R,sessions:V,setError:U});const We=iY({approvals:a,codexHistoryEvents:i,contextCompaction:m,pendingChatUserMessages:y,rightChatHistoryEvents:_,rightChatPanels:R,runningSessionIds:$,selectedSessionId:k,sidebarSessions:V}),nt=g.useCallback(async(qe,Ze=[],He=null,L=null,O={})=>{const z=R.find(mt=>mt.id===qe);if(!z)return!1;const X=O.promptOverride??z.prompt,fe=L?rY(L,X):null;if(fe?.kind==="open_training")return Ze.length>0?(ke("/train uses this chat; add other chats from Models.","error"),!1):(d({objective:fe.objective,sessionId:z.sessionId}),O.preservePrompt||we(qe,""),!0);if(L&&fe?.kind==="send_prompt"&&fe.requiresInstructions&&!X.trim())return ke(`Add instructions after ${L.command}.`,"info"),!1;if(L&&Ze.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"&&!aY(s))return ke("Connect the GitHub app before using /submit-issue.","error"),!1;const Me=z.sessionId?V.find(mt=>mt.id===z.sessionId)??null:null,Le=z.provider==="codex"?v:Me?.openPondCommandAccessMode??v,et=fe?.kind==="send_prompt"?fe.prompt:X,Xe=Lt(z.sessionId)?(z.sessionId?_[z.sessionId]:void 0)??(z.sessionId===k?i:MS):N.getSessionEvents(z.sessionId),st=Lt(z.sessionId)&&z.sessionId?mt=>{const Oe=z.sessionId;B(Ge=>({...Ge,[Oe]:Mo(Ge[Oe]??Xe,[mt])}))}:void 0;return P(Ze,He,et,{session:Me,selectSession:!1,provider:z.provider,model:z.model,openPondCommandAccessMode:Le,chatMessages:Zu(Xe),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:st,clearPrompt:O.preservePrompt?()=>{}:()=>we(qe,""),onSessionCreated:mt=>{D(Oe=>Oe.map(Ge=>Ge.id===qe?{...Ge,sessionId:mt.id,provider:mt.provider,model:mt.modelRef?.modelId??Ge.model}:Ge))}})},[i,s,_,R,C,N,k,d,v,P,D,me,V,ke,we]);return{activateRightChatPanel:ae,closeRightChatPanel:De,openRightChatPanel:ge,rightChatPanelViews:We,showRightChatPanel:xe,showRightPanelDiffTab:ne,submitRightChatPrompt:nt,updateRightChatModel:ze,updateRightChatPrompt:we,updateRightChatProvider:Qe,updateRightChatScrollState:Se}}function dY(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(k=>({...k,[C]:j}));try{const k=await Y.patchSidebarAppPreference(n,C,N);o(P=>({...P,[C]:k}))}catch(k){s(k instanceof Error?k.message:String(k)),o(P=>({...P,[C]:$}))}}function h(C){d(C.id,{pinned:!C.pinned,archived:!1})}async function v(C,N){if(!n)return;const $=Lt(C.id)?i:m,j={...C,...N};$(k=>k.some(P=>P.id===C.id)?k.map(P=>P.id===C.id?j:P):[j,...k]);try{const k=await Y.patchSession(n,C.id,N);$(P=>P.some(T=>T.id===k.id)?P.map(T=>T.id===k.id?k:T):[k,...P])}catch(k){s(k instanceof Error?k.message:String(k)),$(P=>P.map(T=>T.id===C.id?C:T))}}function y(C){v(C,{pinned:!1,savedForLater:!C.savedForLater,archived:!1})}function w(C){v(C,{pinned:!C.pinned,savedForLater:!1,archived:!1})}function _(C){v(C,{pinned:!1,savedForLater:!1,archived:!0}),a===C.id&&l(null)}function R(C){v(C,{archived:!1})}function M(C,N){const $=N.trim();!$||$===C.title||v(C,{title:$})}return{archiveSession:_,renameSession:M,restoreSession:R,toggleProjectPinned:h,toggleSessionPinned:w,toggleSessionSavedForLater:y}}function uY(e){return e.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,72)||"new-branch"}function mY({connection:e,activeWorkspaceAppId:t,appDefaults:n,bootstrap:a,branchDialogName:o,commitIncludeUnstaged:i,commitMessage:s,commitNextStep:l,draftModel:m,draftProvider:d,cloudProjects:h,selectedApp:v,selectedProject:y,selectedProjectLinkedOpenPondApp:w,selectedSession:_,sessions:R,title:M,visibleWorkspaceDiff:C,visibleWorkspaceState:N,workspaceBusy:$,workspaceName:j,appDispatch:k,applyBootstrapPayload:P,expandProject:T,refreshWorkspace:U,refreshWorkspaceDiff:B,rememberWorkspaceState:D,setBranchDialogOpen:W,setCommitDialogOpen:se,setError:me,setSessions:Te,setSettingsSection:ke,setSyncingWorkspaceAppId:V,setView:Re,setWorkspaceBusy:be,showToast:ce}){function ye(){return`${p_(n.defaultBranchPrefix)}${uY(j??M??"new-branch")}`}function ne(){return j?`Update ${j}`:(C?.filesChanged??N?.changedFilesCount??0)===1?"Update workspace file":"Update workspace files"}function ge(He="commit"){k({type:"openCommitDialog",nextStep:He})}function xe(){k({type:"openBranchDialog",branchName:ye()})}function De(){$||W(!1),ke("configuration"),Re("settings"),en({kind:"settings",section:"configuration"})}async function we(He){if(!(!e||!t)){be(!0),me(null);try{const L=await Y.checkoutWorkspaceBranch(e,t,{branch:He});D(L),L.initialized&&B(t)}catch(L){me(L instanceof Error?L.message:String(L))}finally{be(!1)}}}async function ae(){if(!e||!t)return;const He=o.trim();if(He){be(!0),me(null);try{const L=await Y.createWorkspaceBranch(e,t,{branch:He});D(L),L.initialized&&B(t),W(!1),ce(`Checked out ${He}`,"success")}catch(L){me(L instanceof Error?L.message:String(L))}finally{be(!1)}}}async function Se(He){V(He);const L=a?.apps.find(O=>O.id===He)?.name??a?.localProjects.find(O=>O.id===He)?.name??"Workspace";try{const O=await U(He,!0);O?.initialized&&He===t&&B(He),O?.initialized&&!O.error?ce(`${L} synced locally`,"success"):O?.error&&ce("Workspace sync failed","error")}finally{V(O=>O===He?null:O)}}async function ze(){t&&await Se(t)}async function Qe(He,L,O={}){if(!e)return null;const z=_&&!Lt(_.id)?_:null;if(gY(L,z,O)||z&&pY(z,y,v))return z;const X=z?await We(z):null;if(X)return X;const fe=fY(R,y,v);if(fe){const Xe=fe.workspaceKind==="local_project"&&fe.workspaceId?yt("local",fe.workspaceId):null;return k({type:"selectSession",sessionId:fe.id,appId:fe.appId,projectId:Xe}),fe.workspaceKind==="local_project"&&fe.workspaceId&&T(yt("local",fe.workspaceId)),fe}const Me=ka(y,h),Le=await Y.createSession(e,{provider:d,modelRef:La(d,m,a?.providers??null),appId:w?.appId??v?.id??null,appName:w?.appName??v?.name??null,workspaceKind:y?"local_project":v?"sandbox_app":void 0,workspaceId:y?.id??v?.id??null,workspaceName:y?.name??v?.name??null,localProjectId:y?.id??null,cloudProjectId:Me?.id??null,cloudTeamId:Me?.teamId??null,cwd:y?y.workspacePath:null,title:He});Te(Xe=>[Le,...Xe]);const et=Le.workspaceKind==="local_project"&&Le.workspaceId?yt("local",Le.workspaceId):null;return k({type:"selectSession",sessionId:Le.id,appId:Le.appId,projectId:et}),Le.workspaceKind==="local_project"&&Le.workspaceId&&T(yt("local",Le.workspaceId)),Le}async function We(He){if(!e||!y||!w?.appId||Lt(He.id)||He.workspaceKind==="local_project"||He.appId!==w.appId)return null;const L=ka(y,h),O=await Y.patchSession(e,He.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 Te(z=>z.map(X=>X.id===O.id?O:X)),k({type:"selectSession",sessionId:O.id,appId:O.appId,projectId:yt("local",y.id)}),T(yt("local",y.id)),O}async function nt(He,L={}){if(!e)return null;const O=await Qe(j?`${j} workspace`:"Workspace action",He,L);if(!O)return null;const z=await Y.workspaceTool(e,O.id,{action:He,args:L,source:"ui_button"});ce(z.output,z.ok?"success":"error"),P(await Y.bootstrap(e));const X=z.appId??hY(O);return X&&(await U(X,!1))?.initialized&&await B(X),z}async function qe(He,L={}){if(He==="git_commit"&&typeof L.message!="string")return ge("commit"),null;be(!0),me(null);try{return await nt(He,L)}catch(O){return me(O instanceof Error?O.message:String(O)),null}finally{be(!1)}}async function Ze(){const He=s.trim()||ne(),L=l==="commit_publish",O=L&&!!N?.remoteUrl;if(!(O&&!window.confirm("Replace the current origin remote with the new OpenPond repo after committing?"))){be(!0),me(null);try{if(!(await nt("git_commit",{message:He,includeUnstaged:i}))?.ok||l==="commit_push"&&!(await nt("git_push",{runChecks:!1}))?.ok||L&&!(await nt("publish_openpond_repo",{replaceOrigin:O}))?.ok)return;se(!1)}catch(z){me(z instanceof Error?z.message:String(z))}finally{be(!1)}}}return{changeWorkspaceBranch:we,openCommitDialog:ge,openCreateWorkspaceBranchDialog:xe,openDefaultsSettingsFromBranchDialog:De,runWorkspaceTool:qe,submitCommitDialog:Ze,submitCreateWorkspaceBranch:ae,syncWorkspaceLocally:ze,syncWorkspaceLocallyForApp:Se}}function pY(e,t,n){return!t&&!n?!0:iR(e,t,n)}function fY(e,t,n){if(!t&&!n)return null;let a=null,o=Number.NEGATIVE_INFINITY;for(const i of e){if(i.archived||!iR(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 iR(e,t,n){return t?e.workspaceKind==="local_project"&&e.workspaceId===t.id:n?e.appId===n.id||e.workspaceId===n.id:!1}function hY(e){return e.workspaceKind==="sandbox"?e.localProjectId??null:e.workspaceId??e.appId??null}function gY(e,t,n={}){return(vY(e)||yY(e,n))&&bY(t)}function vY(e){return e.startsWith("sandbox_")?e!=="sandbox_create"&&e!=="sandbox_templates"&&e!=="sandbox_template_launch":!1}function bY(e){return e?.workspaceKind==="sandbox"||e?.workspaceKind==="sandbox_template"}function yY(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 SY(e,t){return e.kind==="general"?"# general":e.title?e.title:e.participants.find(a=>a.userId!==t)?.name??"Direct message"}const xY=[];function kY(e){const{composerDraftStore:t,appDispatch:n,mentionedAppId:a,setMentionedAppId:o,cloudSetupDialog:i,setCloudSetupDialog:s,setRightPanelTabRequest:l,workspaceDiffPanelViewState:m,setWorkspaceDiffPanelViewState:d,rightChatHistoryEvents:h,setRightChatHistoryEvents:v,locallyActiveCodexHistorySessionIds:y,setCodexHistoryTurnLocallyActive:w,draftSubagentDelegationMode:_,setDraftSubagentDelegationMode:R,confirmProjectAction:M,view:C,selectedAppId:N,selectedProjectId:$,selectedSessionId:j,draftProvider:k,draftModel:P,activeExperience:T,codexPermissionMode:U,codexReasoningEffort:B,openPondCommandAccessMode:D,busy:W,diffPanelOpen:se,diffPanelExpanded:me,rightPanelMode:Te,rightChatPanels:ke,newProjectMode:V,newProjectName:Re,newProjectBusy:be,commitMessage:ce,commitIncludeUnstaged:ye,commitNextStep:ne,branchDialogName:ge,setSectionMenuOpen:xe,setView:De,setSelectedAppId:we,setSelectedProjectId:ae,setSelectedSessionId:Se,setPrompt:ze,setDraftProvider:Qe,setDraftModel:We,setDiffPanelOpen:nt,setRightPanelMode:qe,setRightChatPanels:Ze,setSyncingWorkspaceAppId:He,setSettingsSection:L,setNewProjectDialogOpen:O,setNewProjectMode:z,setNewProjectName:X,setNewProjectPath:fe,setNewProjectBusy:Me,setCommitDialogOpen:Le,setBranchDialogOpen:et,setError:Xe,showToast:st,appPreferences:mt,applyBootstrapPayload:Oe,approvals:Ge,bootstrap:f,connection:H,events:Z,runtimeEventStore:le,sessions:ee,startup:F,setAppPreferences:I,setCodexHistorySessions:G,setEvents:ie,setSessions:te,cloudProjectById:oe,localProjectById:ue,selectedApp:pe,selectedCloudProject:Ie,selectedProject:je,selectedProjectLinkedOpenPondApp:Ne,selectedSession:$e,sidebarSessions:at,runtimeIndexes:pt,connectedAppMentions:sn,codexHistoryEvents:At,setCodexHistoryEvents:nn,account:un,accountPending:mn,accountSignedOut:qt,activeModel:_a,activeProvider:Cn,activeWorkspaceAppId:Tt,activeWorkspaceKind:Wt,activeWorkspaceLocation:ut,appDefaults:lt,selectedSessionProjectId:Fn,workspaceName:Gt,accountScopeKey:Ca,teamChat:Ra,communities:Qt,selectedProjectConfirmedCloudProject:pn,activeOpenPondCommandAccessMode:rt,viewWorkspaceAppId:xn,viewWorkspaceId:Pa,viewWorkspaceKind:Aa,openPondActionCatalog:ea,selectedActionCatalog:Ta,expandProject:Nn,setExpandedProjectIds:yo,advanceTrainingModelChatAfterTurn:Ea,bindTrainingModelChatSession:K,prepareTrainingModelChatTurn:Ue,chatMessages:_e,pendingChatUserMessages:Be,recordPendingChatUserMessage:vt,runningSessionIds:kn,workspaceBusy:Xt,visibleWorkspaceState:Ke,visibleWorkspaceDiff:Dn,rememberWorkspaceState:St,refreshWorkspace:Rn,setWorkspaceBusy:Ma,refreshWorkspaceDiffWhenNeeded:Yo,setPendingWorkspaceTarget:wn,pendingSidebarWorkspaceTarget:Vn,setPendingSidebarWorkspaceTarget:ta,projectTarget:Ga,workspaceTarget:Za}=e,ii=C==="apps"?"Apps":C==="get-started"?"Walkthroughs":C==="labs"?"Models":C==="scheduled"?"Workflows":C==="outputs"?"Outputs":C==="projects"?"Projects":C==="team"?Ra.detail?SY(Ra.detail.thread,Ra.currentUserId):"Team Chat":C==="community"?Qt.preview?.displayName??"Communities":$e?.title??e_(T),{browserConversationId:na,handleWorkspaceDiffPanelViewStateChange:ja}=VJ({appDispatch:n,diffPanelExpanded:me,diffPanelOpen:se,rightChatPanels:ke,rightPanelMode:Te,selectedAppId:N,selectedCloudProject:Ie,selectedProjectId:$,selectedSession:$e,selectedSessionId:j,setWorkspaceDiffPanelViewState:d,view:C,viewWorkspaceAppId:xn,viewWorkspaceId:Pa,viewWorkspaceKind:Aa,workspaceDiffPanelViewState:m}),bt=g.useCallback(ct=>{en({kind:"chat",sessionId:ct}),Se(ct),we(null),ae(null),De("chat")},[we,ae,Se,De]),si=g.useCallback(()=>{z("existing-local"),X(""),fe(""),O(!0)},[O,z,X,fe]),kr=g.useCallback(()=>{z("local"),X(""),fe(""),O(!0)},[O,z,X,fe]),{createCloudProjectFromScratch:Ts,createProjectFromScratch:li,createProjectCollection:Es,removeProject:So}=ZJ({connection:H,defaultTeamId:lt.defaultTeamId,sessions:ee,selectedProjectId:$,confirmProjectAction:M,applyBootstrapPayload:Oe,expandProject:Nn,setExpandedProjectIds:yo,setSelectedAppId:we,setSelectedProjectId:ae,setSelectedSessionId:Se,setError:Xe,setView:De,showToast:st}),{changeWorkspaceBranch:Ms,openCommitDialog:ci,openCreateWorkspaceBranchDialog:di,openDefaultsSettingsFromBranchDialog:ui,runWorkspaceTool:js,submitCommitDialog:Os,submitCreateWorkspaceBranch:Ja,syncWorkspaceLocally:$s}=mY({connection:H,activeWorkspaceAppId:Tt,appDefaults:lt,bootstrap:f,branchDialogName:ge,commitIncludeUnstaged:ye,commitMessage:ce,commitNextStep:ne,draftModel:P,draftProvider:k,cloudProjects:f?.cloudProjects??[],selectedApp:pe,selectedProject:je,selectedProjectLinkedOpenPondApp:Ne,selectedSession:$e,sessions:ee,title:ii,visibleWorkspaceDiff:Dn,visibleWorkspaceState:Ke,workspaceBusy:Xt,workspaceName:Gt,appDispatch:n,applyBootstrapPayload:Oe,expandProject:Nn,refreshWorkspace:Rn,refreshWorkspaceDiff:Yo,rememberWorkspaceState:St,setBranchDialogOpen:et,setCommitDialogOpen:Le,setError:Xe,setSessions:te,setSettingsSection:L,setSyncingWorkspaceAppId:He,setView:De,setWorkspaceBusy:Ma,showToast:st}),mi=HJ({applyBootstrapPayload:Oe,cloudProjects:f?.cloudProjects??[],connection:H,localProjectById:ue,selectedCloudProject:Ie,selectedProject:je,setWorkspaceBusy:Ma,showToast:st,visibleWorkspaceState:Ke}),pi=f?.preferences.subagents.delegationMode??"manual",fi=$e?.subagentDelegationMode??_,Ns=!!(T==="development"&&f?.preferences.subagents.enabled&&Cn!=="codex"&&!Lt(j)&&!$e?.subagentRunId),aa=g.useCallback(ct=>{if(!$e){R(ct);return}if(!H||Lt($e.id)||$e.subagentRunId)return;const Zt=$e.id,to=$e.subagentDelegationMode??null;te(vn=>vn.map(Pn=>Pn.id===Zt?{...Pn,subagentDelegationMode:ct}:Pn)),Y.patchSession(H,Zt,{subagentDelegationMode:ct}).then(vn=>{te(Pn=>Pn.map(oa=>oa.id===vn.id?vn:oa))}).catch(vn=>{te(Pn=>Pn.map(oa=>oa.id===Zt?{...oa,subagentDelegationMode:to}:oa)),Xe(vn instanceof Error?vn.message:String(vn))})},[H,$e,Xe,te]),wr=g.useCallback(ct=>{v(Zt=>Zt[ct.session.id]===ct.events?Zt:{...Zt,[ct.session.id]:ct.events}),G(Zt=>Wu(Zt,ct.session))},[G]),{answerCreateImproveQuestion:hi,applyCreateImproveCandidate:Ds,approveCreateImproveRun:Ls,cancelCreateImproveRun:Ir,changeDraftProvider:xo,openCreateImprovePullRequest:Kn,reconcileCreateImprovePullRequest:Qo,rejectCreateImproveCandidate:Us,pauseCreateImproveRun:gn,resumeCreateImproveRun:Hs,reviseCreateImproveRun:ca,sendPrompt:Oa,stopTurn:Xo}=$J({applyBootstrapPayload:Oe,bootstrap:f,chatMessages:_e,connection:H,codexPermissionMode:U,codexReasoningEffort:B,openPondCommandAccessMode:rt,draftModel:P,draftProvider:k,experience:T,expandProject:Nn,getPrompt:t.getSnapshot,apps:f?.apps??[],connectedAppMentions:sn,mentionedAppId:a,ensureCloudSessionReady:mi,refreshWorkspace:Rn,refreshWorkspaceDiff:Yo,selectedApp:pe,selectedActionCatalog:Ta,openPondActionCatalog:ea,cloudProjects:f?.cloudProjects??[],accountScopeKey:Ca,selectedCloudProject:Ie,selectedProject:je,selectedProjectLinkedOpenPondApp:Ne,selectedSession:$e,sessions:ee,workspaceTarget:Za.value,subagentDelegationMode:$e?.subagentDelegationMode??_,setDraftModel:We,setDraftProvider:Qe,setError:Xe,setPrompt:ze,setMentionedAppId:o,setCodexHistoryEvents:nn,setCodexHistorySessions:G,onCodexHistoryTurnActivityChange:w,onCodexHistoryTurnPayload:wr,onPendingUserMessage:vt,setEvents:ie,setSelectedAppId:we,setSelectedProjectId:ae,setSelectedSessionId:Se,setSessions:te,setView:De,setWorkspaceBusy:Ma}),{archiveSession:Ya,restoreSession:_r,renameSession:Cr,toggleProjectPinned:zs,toggleSessionPinned:Rr,toggleSessionSavedForLater:gi}=dY({appPreferences:mt,connection:H,selectedSessionId:j,setAppPreferences:I,setCodexHistorySessions:G,setError:Xe,setSelectedSessionId:Se,setSessions:te}),{changeWorkspaceTarget:da,moveProjectToCloud:vi,startCloudSetupUpload:bi}=KJ({account:un,accountPending:mn,accountSignedOut:qt,activeWorkspaceKind:Wt,activeWorkspaceLocation:ut,appDispatch:n,applyBootstrapPayload:Oe,busy:W,cloudSetupDialog:i,cloudProjects:f?.cloudProjects??[],connection:H,defaultTeamId:lt.defaultTeamId,expandProject:Nn,localProjectById:ue,selectedCloudProject:Ie,selectedProject:je,selectedSession:$e,selectedSessionProjectId:Fn,setCloudSetupDialog:s,setDiffPanelOpen:nt,setError:Xe,setSessions:te,setWorkspaceBusy:Ma,showToast:st,visibleWorkspaceState:Ke,workspaceBusy:Xt}),er=g.useCallback(async ct=>{if(T==="work"&&!$e){if(ct==="local"){wn("local"),st(je?`Next task will use the local ${je.name} checkout.`:"Next task will use an app-managed local workspace.","info");return}if(ct==="cloud"&&!je&&!Ie){if(mn){st("Checking OpenPond account. Try again in a moment.","info");return}if(qt){st("Add an OpenPond account before using Hosted.","error");return}wn("cloud"),st("Next task will use Hosted without a Project.","info");return}}if(ct==="hybrid"){const Zt=Ie?.id??pn?.id??$e?.cloudProjectId??null,to=Ie?.teamId??pn?.teamId??$e?.cloudTeamId??null;if(mn){st("Checking OpenPond account. Try again in a moment.","info");return}if(qt){st("Add an OpenPond account before using Hybrid.","error");return}if(!Zt||!to){wn(null),st("Upload/sync this Project to Cloud before using Hybrid.","error");return}if($e&&!Lt($e.id)){if(vo($e))return;if(!H){st("OpenPond App server is not connected.","error");return}const vn=await Y.patchSession(H,$e.id,{provider:k,modelRef:La(k,P,f?.providers??null),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:null,workspaceName:Ie?.name??pn?.name??je?.name??$e.workspaceName??"Hybrid workspace",localProjectId:je?.id??$e.localProjectId??null,cloudProjectId:Zt,cloudTeamId:to,metadata:tC($e.metadata),cwd:je?.workspacePath??$e.cwd??null});te(Pn=>Pn.map(oa=>oa.id===vn.id?vn:oa)),wn(null),st("Hybrid will use your selected model with hosted sandbox edits.","info");return}wn("hybrid"),st("Next message will use Hybrid with a hosted sandbox.","info");return}wn(null),await da(ct)},[mn,qt,T,f?.providers,da,H,P,k,Ie?.id,Ie?.name,Ie?.teamId,je?.id,pn?.id,pn?.name,pn?.teamId,je?.name,je?.workspacePath,$e,wn,te,st]),ua=g.useCallback((ct,Zt)=>{we(null),ae(ct),Se(null),De("chat"),Nn(ct),ta({projectId:ct,target:Zt})},[Nn,we,ae,Se,De]);g.useEffect(()=>{if(!Vn||C!=="chat"||$!==Vn.projectId||j!==null)return;const ct=Vn.target;ta(null),er(ct)},[er,Vn,$,j,C]);const yi=WJ({advanceTrainingTurn:Ea,bindTrainingSession:K,composerDraftStore:t,onSessionCreated:ct=>{Se(ct.id),De("chat"),en({kind:"chat",sessionId:ct.id}),R(null)},onSubmitted:async()=>{const ct=$e;if(!(!H||!ct||!Jl(ct)))try{const Zt=await Y.patchSession(H,ct.id,{metadata:u6(ct.metadata)});te(to=>to.map(vn=>vn.id===Zt.id?Zt:vn))}catch(Zt){st(Zt instanceof Error?`Task started, but its Draft label could not be cleared: ${Zt.message}`:"Task started, but its Draft label could not be cleared.","error")}},prepareTrainingTurn:Ue,sendPrompt:Oa,setMentionedAppId:o,showToast:st}),Pr=GJ({appDispatch:n,connection:H,sessions:ee,setDiffPanelOpen:nt,setRightPanelMode:qe,setSessions:te,setView:De}),{createCloudEnvironmentFromSidebar:Qa,openCloudProjectDialog:Ar,openUrlInBrowserPanel:ko,showBrowserPanel:Si,showChangesPanel:xi,showGoalSidebarTab:ki}=aJ({account:un,browserConversationId:na,cloudProjectById:oe,cloudProjects:f?.cloudProjects??[],diffPanelOpen:se,rightPanelMode:Te,selectedProjectId:$,setDiffPanelOpen:nt,setNewProjectDialogOpen:O,setNewProjectMode:z,setNewProjectName:X,setRightPanelMode:qe}),{changeProjectTarget:qs,submitNewProjectDialog:wi}=JJ({appDispatch:n,busy:W,cloudProjectById:oe,createCloudProjectFromScratch:Ts,createProjectFromScratch:li,createProjectCollection:Es,expandProject:Nn,localProjectById:ue,newProjectBusy:be,newProjectMode:V,newProjectName:Re,onCreateCloudEnvironment:Qa,onNewCloudProject:Ar,onNewLocalProject:kr,onUseExistingFolderPath:si,projectTargetValue:Ga.value,setDiffPanelOpen:nt,setDraftModel:We,setDraftProvider:Qe,setError:Xe,setNewProjectBusy:Me,setNewProjectDialogOpen:O,setNewProjectName:X,setNewProjectPath:fe,showToast:st,workspaceBusy:Xt}),Ii=g.useMemo(()=>ee.map(ct=>ct.id),[ee]);rJ({browserConversationId:na,sessionIds:Ii,onOpenSession:bt,onShowBrowserPanel:Si});const[Bs,tr]=g.useState(null),_i=g.useCallback(ct=>{tr({id:Date.now(),objective:ct.objective,initialSessionIds:ct.sessionId?[ct.sessionId]:[]}),os(po()),De("labs")},[De]),{activateRightChatPanel:Tr,closeRightChatPanel:Xa,openRightChatPanel:Fs,rightChatPanelViews:Vs,showRightChatPanel:Ks,showRightPanelDiffTab:Ws,submitRightChatPrompt:eo,updateRightChatModel:Ci,updateRightChatPrompt:Gs,updateRightChatProvider:Ri,updateRightChatScrollState:Zs}=cY({activeModel:_a,activeProvider:Cn,approvals:Ge,applyRightCodexHistoryPayload:wr,codexHistoryEvents:At,connectedAppMentions:sn,connection:H,contextCompaction:lt.contextCompaction,openLabTraining:_i,locallyActiveCodexHistorySessionIds:y,openPondCommandAccessMode:D,pendingChatUserMessages:Be,providerSettings:f?.providers??null,rightChatHistoryEvents:h,rightChatPanels:ke,rightPanelMode:Te,runtimeIndexes:pt,runtimeEventStore:le,runningSessionIds:kn,selectedSession:$e,selectedSessionId:j,sendPrompt:Oa,setDiffPanelOpen:nt,setError:Xe,setRightChatHistoryEvents:v,setRightChatPanels:Ze,setRightPanelMode:qe,setRightPanelTabRequest:l,setView:De,showChangesPanel:xi,showToast:st,sidebarSessions:at,startupReady:F.ready}),Ln=g.useCallback(()=>{xe(null),L("profile"),De("settings"),en({kind:"settings",section:"profile"})},[xe,L,De]),Js=g.useMemo(()=>To(f?.diagnostics??xY,Z.filter(ct=>ct.name==="diagnostic")),[f?.diagnostics,Z]),wo=g.useCallback(()=>{if(se){nt(!1);return}if(C==="labs"){qe("changes"),l({id:Date.now(),tab:"summary"}),nt(!0);return}qe("home"),nt(!0)},[se,nt,qe,l,C]);return{title:ii,browserConversationId:na,handleWorkspaceDiffPanelViewStateChange:ja,openSessionInChat:bt,openExistingProjectPathDialog:si,removeProject:So,changeProjectTarget:qs,submitNewProjectDialog:wi,changeWorkspaceBranch:Ms,openCommitDialog:ci,openCreateWorkspaceBranchDialog:di,openDefaultsSettingsFromBranchDialog:ui,runWorkspaceTool:js,submitCommitDialog:Os,submitCreateWorkspaceBranch:Ja,syncWorkspaceLocally:$s,subagentDelegationDefaultMode:pi,subagentDelegationMode:fi,subagentDelegationAvailable:Ns,changeSubagentDelegationMode:aa,answerCreateImproveQuestion:hi,applyCreateImproveCandidate:Ds,approveCreateImproveRun:Ls,cancelCreateImproveRun:Ir,changeDraftProvider:xo,openCreateImprovePullRequest:Kn,reconcileCreateImprovePullRequest:Qo,rejectCreateImproveCandidate:Us,pauseCreateImproveRun:gn,resumeCreateImproveRun:Hs,reviseCreateImproveRun:ca,sendPrompt:Oa,stopTurn:Xo,archiveSession:Ya,restoreSession:_r,renameSession:Cr,toggleProjectPinned:zs,toggleSessionPinned:Rr,toggleSessionSavedForLater:gi,moveProjectToCloud:vi,startCloudSetupUpload:bi,changeWorkspaceTarget:er,switchProjectWorkspaceTarget:ua,sendPromptFromMainComposer:yi,openSandboxWorkspace:Pr,createCloudEnvironmentFromSidebar:Qa,openCloudProjectDialog:Ar,openUrlInBrowserPanel:ko,showBrowserPanel:Si,showChangesPanel:xi,showGoalSidebarTab:ki,rightChatTrainingLaunchRequest:Bs,setRightChatTrainingLaunchRequest:tr,closeRightChatPanel:Xa,openRightChatPanel:Fs,rightChatPanelViews:Vs,showRightChatPanel:Ks,showRightPanelDiffTab:Ws,submitRightChatPrompt:eo,activateRightChatPanel:Tr,updateRightChatModel:Ci,updateRightChatPrompt:Gs,updateRightChatProvider:Ri,updateRightChatScrollState:Zs,openProfileSettings:Ln,diagnosticEvents:Js,toggleRightSidebar:wo}}const wY=QR();function IY(){return x.jsx(pR,{client:wY,children:x.jsx(_Y,{})})}function _Y(){const e=JZ(),t=kY(e);return x.jsx(y9,{primary:e,secondary:t})}const MX=Object.freeze(Object.defineProperty({__proto__:null,App:IY},Symbol.toStringTag,{value:"Module"}));export{QQ as $,Z4 as A,Jy as B,Wo as C,E3 as D,wQ as E,WI as F,XI as G,Zl as H,Zd as I,r6 as J,e3 as K,TS as L,zr as M,qv as N,_V as O,v3 as P,$n as Q,kX as R,_3 as S,iC as T,eX as U,RX as V,Sr as W,yc as X,_X as Y,lh as Z,RQ as _,t0 as a,fh as a$,N9 as a0,EX as a1,_J as a2,YQ as a3,XQ as a4,fX as a5,sX as a6,mK as a7,La as a8,OK as a9,Mo as aA,vC as aB,zQ as aC,s9 as aD,q7 as aE,HQ as aF,n9 as aG,pX as aH,z7 as aI,fa as aJ,go as aK,oR as aL,aY as aM,oY as aN,eJ as aO,qQ as aP,e6 as aQ,sv as aR,FI as aS,zu as aT,aX as aU,yv as aV,G3 as aW,SQ as aX,v0 as aY,YI as aZ,sK as a_,zi as aa,lS as ab,iX as ac,_S as ad,Rh as ae,Yf as af,Q5 as ag,nX as ah,Qf as ai,ch as aj,aK as ak,SC as al,U5 as am,qu as an,r3 as ao,x3 as ap,ZI as aq,WY as ar,oX as as,rX as at,xX as au,q5 as av,a3 as aw,qp as ax,q as ay,Lt as az,eG as b,OQ as b$,R9 as b0,PX as b1,S9 as b2,_0 as b3,Ku as b4,lK as b5,$v as b6,p_ as b7,F5 as b8,IQ as b9,AX as bA,Qu as bB,c3 as bC,uu as bD,lv as bE,VI as bF,bc as bG,FQ as bH,ZQ as bI,JQ as bJ,R0 as bK,KQ as bL,tf as bM,GQ as bN,WQ as bO,VQ as bP,C0 as bQ,BQ as bR,Et as bS,UO as bT,KY as bU,oC as bV,GY as bW,gQ as bX,Op as bY,VY as bZ,jQ as b_,_Q as ba,oj as bb,i9 as bc,r9 as bd,GI as be,s3 as bf,qh as bg,CQ as bh,PQ as bi,y3 as bj,KI as bk,FY as bl,Qh as bm,xQ as bn,Bu as bo,cv as bp,en as bq,T3 as br,yC as bs,Jn as bt,BY as bu,Vh as bv,Kh as bw,zp as bx,qY as by,k5 as bz,dt as c,bQ as c$,$Q as c0,NQ as c1,Z3 as c2,EQ as c3,MQ as c4,Tg as c5,QY as c6,Go as c7,PL as c8,Ew as c9,yL as cA,RL as cB,OL as cC,EL as cD,J as cE,A as cF,Bw as cG,eQ as cH,XY as cI,ZY as cJ,SL as cK,wL as cL,zw as cM,UL as cN,LL as cO,$L as cP,Vw as cQ,Eg as cR,Fw as cS,Cu as cT,Ru as cU,HL as cV,TL as cW,Fe as cX,bx as cY,Zo as cZ,xu as c_,JY as ca,rn as cb,c as cc,Iu as cd,_u as ce,xt as cf,p as cg,Ht as ch,r as ci,wu as cj,S as ck,Ee as cl,Q as cm,E as cn,u as co,b as cp,NL as cq,It as cr,mc as cs,bL as ct,Nt as cu,Ww as cv,zL as cw,Kw as cx,IL as cy,qw as cz,b7 as d,TQ as d$,za as d0,tQ as d1,YL as d2,Kg as d3,vq as d4,rQ as d5,cQ as d6,lQ as d7,sQ as d8,UQ as d9,oQ as dA,Fu as dB,uX as dC,mX as dD,LQ as dE,M5 as dF,IS as dG,XZ as dH,ph as dI,Q_ as dJ,$_ as dK,Y_ as dL,TX as dM,vX as dN,hX as dO,gX as dP,pZ as dQ,SY as dR,bX as dS,yX as dT,SX as dU,Yy as dV,S_ as dW,AQ as dX,Yl as dY,fQ as dZ,hQ as d_,lX as da,cX as db,dX as dc,nQ as dd,YY as de,n1 as df,ai as dg,Lo as dh,vH as di,mU as dj,iQ as dk,u4 as dl,vc as dm,dQ as dn,pQ as dp,mQ as dq,uQ as dr,ZF as ds,l1 as dt,$3 as du,os as dv,po as dw,q3 as dx,vQ as dy,aQ as dz,YR as e,Kr as e0,yQ as e1,MX as e2,Yr as f,C5 as g,Ao as h,Hu as i,i6 as j,tX as k,DQ as l,iv as m,fJ as n,wX as o,CX as p,tR as q,u_ as r,t5 as s,IX as t,OS as u,xc as v,Y as w,kc as x,s6 as y,kQ as z};
|