openpond 0.2.50 → 0.2.52
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.js +1 -1
- package/dist/chunks/{app-server-runtime-OG7GYIIA.js → app-server-runtime-NITNSHYS.js} +1 -1
- package/dist/chunks/{chunk-42GOV5ZU.js → chunk-AV3WI7JZ.js} +1 -1
- package/dist/chunks/{chunk-OC6UWKBL.js → chunk-CFLMKFOE.js} +1 -1
- package/dist/chunks/{chunk-UBFRWC6I.js → chunk-FQZFLNLY.js} +1 -1
- package/dist/chunks/{chunk-JCCU3VFK.js → chunk-HJEY5LBD.js} +1 -1
- package/dist/chunks/{chunk-TBNBCOW7.js → chunk-L3V4QKRV.js} +1 -1
- package/dist/chunks/chunk-PVSUQGWK.js +9 -0
- package/dist/chunks/{chunk-ZCWHVLJ4.js → chunk-T5T7NCHJ.js} +1 -1
- package/dist/chunks/{chunk-2ZJJFBIA.js → chunk-USMZT5FZ.js} +12 -12
- package/dist/chunks/{chunk-V67DJQQ3.js → chunk-XC7AHL57.js} +114 -113
- package/dist/chunks/{chunk-O7VGFMDO.js → chunk-ZBZBV5TB.js} +1 -1
- package/dist/chunks/{cli-ZLDLOKPL.js → cli-ZYFSCHZK.js} +1 -1
- package/dist/chunks/{dist-BLBZENVB.js → dist-5VFPYEIV.js} +1 -1
- package/dist/chunks/{hosted-experiment-improvement-NTYYSPQX.js → hosted-experiment-improvement-MGBPXXW2.js} +1 -1
- package/dist/chunks/{hosted-harness-runtime-FZZLWLBR.js → hosted-harness-runtime-WOLADXXP.js} +1 -1
- package/dist/chunks/{hosted-profile-compiler-JODGZCA7.js → hosted-profile-compiler-NBMUCZVS.js} +1 -1
- package/dist/chunks/{hosted-profile-evaluation-preparation-F2SPAEKK.js → hosted-profile-evaluation-preparation-I6H6RFT6.js} +1 -1
- package/dist/chunks/{src-4RLFNNVK.js → src-MGP3OYHL.js} +115 -115
- package/dist/chunks/{workspaces-XIQNPAP7.js → workspaces-MFZ3OO6O.js} +1 -1
- package/dist/cli.js +1 -1
- package/dist/web/assets/App-Dg6mZIQk.js +234 -0
- package/dist/web/assets/{AppDialog-1iGodoot.js → AppDialog-gcj3rrTZ.js} +1 -1
- package/dist/web/assets/{AppTerminalPanel-udtBdWFn.js → AppTerminalPanel-Be-E4qZF.js} +2 -2
- package/dist/web/assets/{AppsView-DhKsU4yi.js → AppsView-BdyPNSpT.js} +1 -1
- package/dist/web/assets/{BrowserSidebar-BnOyqIQT.js → BrowserSidebar-CcQxU0uO.js} +1 -1
- package/dist/web/assets/{CartesianChart-C24DAywn.js → CartesianChart-CN5hB6rV.js} +1 -1
- package/dist/web/assets/{CollaborationTabs-DgmOF5Fe.js → CollaborationTabs-BiDPHgXG.js} +1 -1
- package/dist/web/assets/{CommandMenu-CUNGtHwS.js → CommandMenu-B2qJCgWH.js} +1 -1
- package/dist/web/assets/{CommunityView-CE7qeJnr.js → CommunityView-D1aOQKfS.js} +1 -1
- package/dist/web/assets/{ComposerCreateImproveStrip-BixNsg2a.js → ComposerCreateImproveStrip-f1tdD0QS.js} +1 -1
- package/dist/web/assets/{GetStartedView-B8gCwmBX.js → GetStartedView-CPYs0fYN.js} +1 -1
- package/dist/web/assets/{HostedModelLearningReview-CitgUNfC.js → HostedModelLearningReview-DVfJyUW_.js} +1 -1
- package/dist/web/assets/{HostedModelLearningSettings-WUaqzNsa.js → HostedModelLearningSettings-IEKRXOkG.js} +1 -1
- package/dist/web/assets/{LabModelVersionDetailPage-Cx0kL69J.js → LabModelVersionDetailPage-DkIa0oG_.js} +1 -1
- package/dist/web/assets/{LabSkillSidebar-DRggqZ1j.js → LabSkillSidebar-BUlU1Ti-.js} +1 -1
- package/dist/web/assets/{LabsRoute-BujTZhqC.js → LabsRoute-8cKFNq19.js} +4 -4
- package/dist/web/assets/{MainChatThread-CyA_644R.js → MainChatThread-C5GwaIl_.js} +2 -2
- package/dist/web/assets/MainPane-SMqq5YAM.js +19 -0
- package/dist/web/assets/{MarkdownText-DJI5LwT0.js → MarkdownText-CLnvdLVg.js} +21 -21
- package/dist/web/assets/{NativeSkillSidebar-CkFpWxjd.js → NativeSkillSidebar-B9bVb00x.js} +1 -1
- package/dist/web/assets/{NewExperienceSwitcher-DXcRHHsu.js → NewExperienceSwitcher-CelgG7Ua.js} +1 -1
- package/dist/web/assets/{NewProjectDialog-gDzX_ZIJ.js → NewProjectDialog-eEnsg9s2.js} +1 -1
- package/dist/web/assets/{OutputsPage-J_k-_N82.js → OutputsPage-ByvsTUW-.js} +1 -1
- package/dist/web/assets/{ProjectsPage-BsyZmvlg.js → ProjectsPage-Cl2zFh8X.js} +1 -1
- package/dist/web/assets/{RightChatPanelStack-Bz8puMUB.js → RightChatPanelStack-MnGscF87.js} +1 -1
- package/dist/web/assets/{RightSidebarHomePanel-DmorYb6p.js → RightSidebarHomePanel-C6NXMYuy.js} +1 -1
- package/dist/web/assets/{ScheduledWorkPage-BFDzQUyL.js → ScheduledWorkPage-DCb6d7Lg.js} +1 -1
- package/dist/web/assets/{SettingsView-BB7wCdbr.js → SettingsView-BMFfrxmo.js} +3 -3
- package/dist/web/assets/{TeamChatView-CZ3b7rq2.js → TeamChatView-DW_v2B9E.js} +1 -1
- package/dist/web/assets/{TerminalOverlay-Ck43Qri3.js → TerminalOverlay-BJ7qsr9F.js} +1 -1
- package/dist/web/assets/{TrainingCreationPanel-ejqPZm3g.js → TrainingCreationPanel-GSIwP6f1.js} +1 -1
- package/dist/web/assets/{TrainingDraftPanel-Cy2AQxxL.js → TrainingDraftPanel-DorY6I29.js} +1 -1
- package/dist/web/assets/{UsageSettingsSection-B7nyMItm.js → UsageSettingsSection-DmzStI9q.js} +1 -1
- package/dist/web/assets/{WorkSidebarPanel-BfjAc097.js → WorkSidebarPanel-zsJrGaaL.js} +1 -1
- package/dist/web/assets/WorkspaceDiffPanel-CiFsZjMm.js +14 -0
- package/dist/web/assets/{WorkspaceEnvironmentMenu-B-K9XgFB.js → WorkspaceEnvironmentMenu-vJw9hE0y.js} +1 -1
- package/dist/web/assets/{WorkspaceGitDialogs-BJVFx_L3.js → WorkspaceGitDialogs-BpL-xtRX.js} +1 -1
- package/dist/web/assets/{WorkspaceMonacoEditor-p-FWMXoZ.js → WorkspaceMonacoEditor-CJ3x0GHH.js} +3 -3
- package/dist/web/assets/{arrow-up-right-CFGI2YSt.js → arrow-up-right-C60QSULo.js} +1 -1
- package/dist/web/assets/{chunk-UHVJOMWN-BAlur2vw.js → chunk-UHVJOMWN-BxgPi0yP.js} +1 -1
- package/dist/web/assets/{clipboard-DIIxBort.js → clipboard-QIy0Jd_K.js} +1 -1
- package/dist/web/assets/{cloud-upload-BaQFNCTp.js → cloud-upload-B9L-_gy0.js} +1 -1
- package/dist/web/assets/{cssMode-6LOkSggB.js → cssMode-ffPyPUW9.js} +1 -1
- package/dist/web/assets/{folder-open-DZSxfPtr.js → folder-open-BFy7KXWm.js} +1 -1
- package/dist/web/assets/{folder-plus-21v4D_Vx.js → folder-plus-C3iGtUOI.js} +1 -1
- package/dist/web/assets/{git-commit-horizontal-CgGixL64.js → git-commit-horizontal-DsTniKvi.js} +1 -1
- package/dist/web/assets/{htmlMode-B5uRraNd.js → htmlMode-7ytlsiyK.js} +1 -1
- package/dist/web/assets/{index-DOMrqhcz.js → index-BK8GmZmB.js} +2 -2
- package/dist/web/assets/index-C0H85uUI.css +1 -0
- package/dist/web/assets/{info-BGTcmow7.js → info-C8mwoaIJ.js} +1 -1
- package/dist/web/assets/{jsonMode-D3m8N4Gi.js → jsonMode-BT35NJi4.js} +1 -1
- package/dist/web/assets/{lspLanguageFeatures-DoyipLsB.js → lspLanguageFeatures-BKAwIewO.js} +1 -1
- package/dist/web/assets/{minimize-2-B01qSko4.js → minimize-2-34MApatV.js} +1 -1
- package/dist/web/assets/{monaco.contribution-BJyfaGX2.js → monaco.contribution-9diduNNi.js} +2 -2
- package/dist/web/assets/{monaco.contribution-Bc22foTx.js → monaco.contribution-CxtX0z-m.js} +2 -2
- package/dist/web/assets/{monaco.contribution-DuRhJ6zU.js → monaco.contribution-DVnPUDsR.js} +2 -2
- package/dist/web/assets/{monaco.contribution--U8v3jpa.js → monaco.contribution-Dj4R5U8Z.js} +2 -2
- package/dist/web/assets/{monitor-eZP8ZTHe.js → monitor-4JxqJ7wz.js} +1 -1
- package/dist/web/assets/{play-CGsWFR_B.js → play-C4PtpamL.js} +1 -1
- package/dist/web/assets/{python-BNrLZWud.js → python-0GVncePC.js} +1 -1
- package/dist/web/assets/{save-BLgjrccP.js → save-DjB16eou.js} +1 -1
- package/dist/web/assets/{square-CI1qNtvE.js → square-Coz7UQqd.js} +1 -1
- package/dist/web/assets/{toggleHighContrast-B_GcTCnw.js → toggleHighContrast-D-3108_3.js} +1 -1
- package/dist/web/assets/{tsMode-CmruH_ys.js → tsMode-CV4ktqqR.js} +1 -1
- package/dist/web/assets/{upload-DnlgGS2x.js → upload-D007T9Hm.js} +1 -1
- package/dist/web/assets/{useLocalAgentSchedules-BBhGUfK-.js → useLocalAgentSchedules-BXjFbAVS.js} +1 -1
- package/dist/web/assets/{useProviderSettings-DfhdkKdC.js → useProviderSettings-SY7mp-5B.js} +1 -1
- package/dist/web/assets/{useSessionTurnCache-BwscKl5i.js → useSessionTurnCache-Bee6zbC_.js} +1 -1
- package/dist/web/assets/{wifi-off-Dz-4EDCc.js → wifi-off-BbNZc0za.js} +1 -1
- package/dist/web/assets/{workers-Bi9u46cp.js → workers-DNQ5ne3z.js} +1 -1
- package/dist/web/assets/{yaml-DVTkiRnh.js → yaml-BfAho-gB.js} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/chunks/chunk-7K72KS5C.js +0 -9
- package/dist/web/assets/App-BI-uOpnP.js +0 -234
- package/dist/web/assets/MainPane-LaEtxydD.js +0 -19
- package/dist/web/assets/WorkspaceDiffPanel-D9hAV8l7.js +0 -14
- package/dist/web/assets/index-DJcUXSsN.css +0 -1
|
@@ -1,234 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TerminalOverlay-Ck43Qri3.js","assets/index-DOMrqhcz.js","assets/index-DJcUXSsN.css","assets/TerminalOverlay-DwBiZLwk.css","assets/CommandMenu-CUNGtHwS.js","assets/CommandMenu-Cb3vNGJr.css","assets/SettingsView-BB7wCdbr.js","assets/useProviderSettings-DfhdkKdC.js","assets/save-BLgjrccP.js","assets/MarkdownText-DJI5LwT0.js","assets/useProviderSettings-Bw-csWbH.css","assets/folder-open-DZSxfPtr.js","assets/play-CGsWFR_B.js","assets/wifi-off-Dz-4EDCc.js","assets/cloud-upload-BaQFNCTp.js","assets/git-commit-horizontal-CgGixL64.js","assets/useLocalAgentSchedules-BBhGUfK-.js","assets/folder-plus-21v4D_Vx.js","assets/AppDialog-1iGodoot.js","assets/WorkspaceDiffPanel-D9hAV8l7.js","assets/training-model-data-CKOkpBBL.js","assets/info-BGTcmow7.js","assets/minimize-2-B01qSko4.js","assets/clipboard-DIIxBort.js","assets/SettingsView-BnANbPLS.css","assets/git-dialogs-C-F47S10.css","assets/NewProjectDialog-gDzX_ZIJ.js","assets/monitor-eZP8ZTHe.js","assets/WorkspaceGitDialogs-BJVFx_L3.js","assets/upload-DnlgGS2x.js","assets/WorkspaceEnvironmentMenu-B-K9XgFB.js","assets/square-CI1qNtvE.js","assets/WorkspaceEnvironmentMenu-DGIFdG3o.css","assets/MainPane-LaEtxydD.js","assets/arrow-up-right-CFGI2YSt.js","assets/MainPane-DOWsSew1.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{r as y,j as S,a as qT,g as o1,_ as Zo}from"./index-DOMrqhcz.js";const r1=y.createContext(void 0),s1=e=>{const t=y.useContext(r1);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},UT=({client:e,children:t})=>(y.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),S.jsx(r1.Provider,{value:e,children:t})),zT={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)};var BT=class{#e=zT;#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 br=new BT;function FT(e){setTimeout(e,0)}const VT=typeof window>"u"||"Deno"in globalThis;function va(){}function KT(e,t){return typeof e=="function"?e(t):e}function l1(e){return typeof e=="number"&&e>=0&&e!==1/0}function c1(e,t){return Math.max(e+(t||0)-Date.now(),0)}function fn(e,t){return typeof e=="function"?e(t):e}function Jy(e,t){const{type:n="all",exact:a,fetchStatus:o,predicate:r,queryKey:s,stale:l}=e;if(s){if(a){if(t.queryHash!==uv(s,t.options))return!1}else if(!Fs(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||r&&!r(t))}function Zy(e,t){const{exact:n,status:a,predicate:o,mutationKey:r}=e;if(r){if(!t.options.mutationKey)return!1;if(n){if(bc(t.options.mutationKey)!==bc(r))return!1}else if(!Fs(t.options.mutationKey,r))return!1}return!(a&&t.state.status!==a||o&&!o(t))}function uv(e,t){return(t?.queryKeyHashFn||bc)(e)}function bc(e){return JSON.stringify(e,(t,n)=>tg(n)?Object.keys(n).sort().reduce((a,o)=>(a[o]=n[o],a),{}):n)}function Fs(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(!Fs(e[a],t[a]))return!1;return!0}const n=Object.keys(t);for(const a of n)if(!Fs(e[a],t[a]))return!1;return!0}return!1}const WT=Object.prototype.hasOwnProperty;function d1(e,t,n=0){if(e===t)return e;if(n>500)return t;const a=Yy(e)&&Yy(t);if(!a&&!(tg(e)&&tg(t)))return t;const o=(a?e:Object.keys(e)).length,r=a?t:Object.keys(t),s=r.length,l=a?new Array(s):{};let m=0;for(let d=0;d<s;d++){const f=a?d:r[d],g=e[f],x=t[f];if(g===x){l[f]=g,(a?d<o:WT.call(e,f))&&m++;continue}if(g===null||x===null||typeof g!="object"||typeof x!="object"){l[f]=x;continue}const k=d1(g,x,n+1);l[f]=k,k===g&&m++}return o===s&&m===o?e:l}function Ef(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 Yy(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function tg(e){if(!Qy(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!Qy(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Qy(e){return Object.prototype.toString.call(e)==="[object Object]"}function GT(e){return new Promise(t=>{br.setTimeout(t,e)})}function ng(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?d1(e,t):t}function JT(e,t,n=0){const a=[...e,t];return n&&a.length>n?a.slice(1):a}function ZT(e,t,n=0){const a=[t,...e];return n&&a.length>n?a.slice(0,-1):a}const mv=Symbol();function u1(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===mv?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function m1(e,t){return typeof e=="function"?e(...t):!!e}function YT(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 QT=()=>VT;const pv=()=>QT();var Vc=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(){}},XT=class extends Vc{#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 fv=new XT,eE=FT;function tE(){let e=[],t=0,n=l=>{l()},a=l=>{l()},o=eE;const r=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)=>{r(()=>{l(...m)})},schedule:r,setNotifyFunction:l=>{n=l},setBatchNotifyFunction:l=>{a=l},setScheduler:l=>{o=l}}}const Fn=tE();var nE=class extends Vc{#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 Bu=new nE;function aE(e){return Math.min(1e3*2**e,3e4)}function p1(e){return(e??"online")==="online"?Bu.isOnline():!0}var ag=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function f1(e){let t=!1,n=0,a,o="pending",r,s;const l=new Promise((O,$)=>{r=O,s=$});l.catch(va);const m=()=>o!=="pending",d=O=>{if(!m()){const $=new ag(O);R($),e.onCancel?.($)}},f=()=>{t=!0},g=()=>{t=!1},x=()=>fv.isFocused()&&(e.networkMode==="always"||Bu.isOnline())&&e.canRun(),k=()=>p1(e.networkMode)&&e.canRun(),C=O=>{m()||(a?.(),o="resolved",r(O))},R=O=>{m()||(a?.(),o="rejected",s(O))},E=()=>new Promise(O=>{a=$=>{(m()||x())&&O($)},e.onPause?.()}).then(()=>{a=void 0,m()||e.onContinue?.()}),A=()=>{if(m())return;let O;const $=n===0?e.initialPromise:void 0;try{O=$??e.fn()}catch(M){O=Promise.reject(M)}Promise.resolve(O).then(C).catch(M=>{if(m())return;const w=e.retry??(pv()?0:3),P=e.retryDelay??aE,j=typeof P=="function"?P(n,M):P,N=w===!0||typeof w=="number"&&n<w||typeof w=="function"&&w(n,M);if(t||!N){R(M);return}n++,e.onFail?.(n,M),GT(j).then(()=>x()?void 0:E()).then(()=>{t?R(M):A()})})};return{promise:l,status:()=>o,cancel:d,continue:()=>(a?.(),l),cancelRetry:f,continueRetry:g,canStart:k,start:()=>(k()?A():E().then(A),l)}}var h1=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),l1(this.gcTime)&&(this.#e=br.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(pv()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(br.clearTimeout(this.#e),this.#e=void 0)}};function iE(e){return{onFetch:(t,n)=>{const a=t.options,o=t.fetchOptions?.meta?.fetchMore?.direction,r=t.state.data?.pages||[],s=t.state.data?.pageParams||[];let l={pages:[],pageParams:[]},m=0;const d=async()=>{let f=!1;const g=C=>{YT(C,()=>t.signal,()=>f=!0)},x=u1(t.options,t.fetchOptions),k=async(C,R,E)=>{if(f)return Promise.reject(t.signal.reason);if(R==null&&C.pages.length)return Promise.resolve(C);const O=(()=>{const P={client:t.client,queryKey:t.queryKey,pageParam:R,direction:E?"backward":"forward",meta:t.options.meta};return g(P),P})(),$=await x(O),{maxPages:M}=t.options,w=E?ZT:JT;return{pages:w(C.pages,$,M),pageParams:w(C.pageParams,R,M)}};if(o&&r.length){const C=o==="backward",R=C?g1:ig,E={pages:r,pageParams:s};l=await k(E,R(a,E),C)}else{const C=e??r.length;do{const R=m===0?s[0]??a.initialPageParam:ig(a,l);if(m>0&&R==null)break;l=await k(l,R),m++}while(m<C)}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 ig(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 g1(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function Aae(e,t){return t?ig(e,t)!=null:!1}function Tae(e,t){return!t||!e.getPreviousPageParam?!1:g1(e,t)!=null}var oE=class extends h1{#e;#t;#n;#a;#o;#i;#r;#l;constructor(e){super(),this.#l=!1,this.#r=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#o=e.client,this.#a=this.#o.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=e0(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.#i?.promise}setOptions(e){if(this.options={...this.#r,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=e0(this.options);t.data!==void 0&&(this.setState(Xy(t.data,t.dataUpdatedAt)),this.#t=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#a.remove(this)}setData(e,t){const n=ng(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.#i?.promise;return this.#i?.cancel(e),t?t.then(va).catch(va):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=>fn(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===mv||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>fn(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:!c1(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#i?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#i?.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.#i&&(this.#l||this.state.fetchStatus==="paused"&&this.state.status==="pending"?this.#i.cancel({revert:!0}):this.#i.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.#i?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#i)return this.#i.continueRetry(),this.#i.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=u1(this.options,t),f=(()=>{const g={client:this.#o,queryKey:this.queryKey,meta:this.meta};return a(g),g})();return this.#l=!1,this.options.persister?this.options.persister(m,f,this):m(f)},s=(()=>{const m={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#o,state:this.state,fetchFn:o};return a(m),m})();(this.#e==="infinite"?iE(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.#i=f1({initialPromise:t?.initialPromise,fn:s.fetchFn,onCancel:m=>{m instanceof ag&&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 ag){if(m.silent)return this.#i.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.#i===l&&(this.#i=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,...v1(n.data,this.options),fetchMeta:e.meta??null};case"success":const a={...n,...Xy(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),Fn.batch(()=>{this.observers.slice().forEach(n=>{n.onQueryUpdate()}),this.#a.notify({query:this,type:"updated",action:e})})}};function v1(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:p1(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Xy(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function e0(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 rE=class extends Vc{#e;#t=void 0;#n=void 0;#a=void 0;#o;#i;#r;#l;#s;#p;#d;#u;#c;#f=new Set;constructor(e,t){super(),this.options=t,this.#e=e,this.#r=null,this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),t0(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return og(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return og(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 fn(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&&!Ef(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const a=this.hasListeners();a&&n0(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),a&&(this.#t!==n||fn(this.options.enabled,this.#t)!==fn(t.enabled,this.#t)||fn(this.options.staleTime,this.#t)!==fn(t.staleTime,this.#t))&&this.#g();const o=this.#v();a&&(this.#t!==n||fn(this.options.enabled,this.#t)!==fn(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 Ef(this.getCurrentResult(),n)||(this.#a=n,this.#i=this.options,this.#o=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 r=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()}),r])}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(va)),t}#h(e){return!pv()&&fn(this.options.enabled,this.#t)!==!1&&l1(e)}#g(){this.#S();const e=fn(this.options.staleTime,this.#t);if(this.#a.isStale||!this.#h(e))return;const t=c1(this.#a.dataUpdatedAt,e)+1;this.#d=br.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=br.setInterval(()=>{(this.options.refetchIntervalInBackground||fv.isFocused())&&this.#m()},this.#c))}#y(){this.#g(),this.#b(this.#v())}#S(){this.#d!==void 0&&(br.clearTimeout(this.#d),this.#d=void 0)}#x(){this.#u!==void 0&&(br.clearInterval(this.#u),this.#u=void 0)}createResult(e,t){const n=this.#t,a=this.options,o=this.#a,r=this.#o,s=this.#i,l=e!==n?e.state:this.#n,{state:m}=e;let d={...m},f=!1,g;if(t._optimisticResults){const w=this.hasListeners(),P=!w&&t0(e,t),j=w&&n0(e,n,t,a);(P||j)&&(d={...d,...v1(m.data,e.options)}),t._optimisticResults==="isRestoring"&&(d.fetchStatus="idle")}let{error:x,errorUpdatedAt:k,status:C}=d;g=d.data;let R=!1;if(t.placeholderData!==void 0&&g===void 0&&C==="pending"){let w;o?.isPlaceholderData&&t.placeholderData===s?.placeholderData?(w=o.data,R=!0):w=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,w!==void 0&&(C="success",g=ng(o?.data,w,t),f=!0)}if(t.select&&g!==void 0&&!R)if(o&&g===r?.data&&t.select===this.#l)g=this.#s;else try{this.#l=t.select,g=t.select(g),g=ng(o?.data,g,t),this.#s=g,this.#r=null}catch(w){this.#r=w}else g===void 0&&(this.#r=null);this.#r&&(x=this.#r,g=this.#s,k=Date.now(),C="error",f=!1);const E=d.fetchStatus==="fetching",A=C==="pending",O=C==="error",$=A&&E,M=g!==void 0;return{status:C,fetchStatus:d.fetchStatus,isPending:A,isSuccess:C==="success",isError:O,isInitialLoading:$,isLoading:$,data:g,dataUpdatedAt:d.dataUpdatedAt,error:x,errorUpdatedAt:k,failureCount:d.fetchFailureCount,failureReason:d.fetchFailureReason,errorUpdateCount:d.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:d.dataUpdateCount>l.dataUpdateCount||d.errorUpdateCount>l.errorUpdateCount,isFetching:E,isRefetching:E&&!A,isLoadingError:O&&!M,isPaused:d.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:O&&M,isStale:hv(e,t),refetch:this.refetch,isEnabled:fn(t.enabled,e)!==!1}}updateResult(){const e=this.#a,t=this.createResult(this.#t,this.options);if(this.#o=this.#t.state,this.#i=this.options,this.#o.data!==void 0&&(this.#p=this.#t),Ef(t,e))return;this.#a=t;const a=(()=>{if(!e)return!0;const{notifyOnChangeProps:o}=this.options,r=typeof o=="function"?o():o;if(r==="all"||!r&&!this.#f.size)return!0;const s=new Set(r??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)})})();Fn.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 sE(e,t){return fn(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&fn(t.retryOnMount,e)===!1)}function t0(e,t){return sE(e,t)||e.state.data!==void 0&&og(e,t,t.refetchOnMount)}function og(e,t,n){if(fn(t.enabled,e)!==!1&&fn(t.staleTime,e)!=="static"){const a=typeof n=="function"?n(e):n;return a==="always"||a!==!1&&hv(e,t)}return!1}function n0(e,t,n,a){return(e!==t||fn(a.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&hv(e,n)}function hv(e,t){return fn(t.enabled,e)!==!1&&e.isStaleByTime(fn(t.staleTime,e))}var lE=class extends h1{#e;#t;#n;#a;constructor(t){super(),this.#e=t.client,this.mutationId=t.mutationId,this.#n=t.mutationCache,this.#t=[],this.state=t.state||cE(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){this.#t.includes(t)||(this.#t.push(t),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){this.#t=this.#t.filter(n=>n!==t),this.scheduleGc(),this.#n.notify({type:"observerRemoved",mutation:this,observer:t})}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(t){const n=()=>{this.#o({type:"continue"})},a={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey},o=this.#a=f1({fn:()=>this.options.mutationFn?this.options.mutationFn(t,a):Promise.reject(new Error("No mutationFn found")),onFail:(l,m)=>{this.#o({type:"failed",failureCount:l,error:m})},onPause:()=>{this.#o({type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)}),r=this.state.status==="pending",s=!o.canStart();try{if(r)n();else{this.#o({type:"pending",variables:t,isPaused:s}),this.#n.config.onMutate&&await this.#n.config.onMutate(t,this,a);const m=await this.options.onMutate?.(t,a);m!==this.state.context&&this.#o({type:"pending",context:m,variables:t,isPaused:s})}const l=await o.start();return await this.#n.config.onSuccess?.(l,t,this.state.context,this,a),await this.options.onSuccess?.(l,t,this.state.context,a),await this.#n.config.onSettled?.(l,null,this.state.variables,this.state.context,this,a),await this.options.onSettled?.(l,null,t,this.state.context,a),this.#o({type:"success",data:l}),l}catch(l){try{await this.#n.config.onError?.(l,t,this.state.context,this,a)}catch(m){Promise.reject(m)}try{await this.options.onError?.(l,t,this.state.context,a)}catch(m){Promise.reject(m)}try{await this.#n.config.onSettled?.(void 0,l,this.state.variables,this.state.context,this,a)}catch(m){Promise.reject(m)}try{await this.options.onSettled?.(void 0,l,t,this.state.context,a)}catch(m){Promise.reject(m)}throw this.#o({type:"error",error:l}),l}finally{this.#a===o&&(this.#a=void 0),this.#n.runNext(this)}}#o(t){const n=a=>{switch(t.type){case"failed":return{...a,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...a,isPaused:!0};case"continue":return{...a,isPaused:!1};case"pending":return{...a,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...a,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...a,data:void 0,error:t.error,failureCount:a.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),Fn.batch(()=>{this.#t.forEach(a=>{a.onMutationUpdate(t)}),this.#n.notify({mutation:this,type:"updated",action:t})})}};function cE(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var dE=class extends Vc{#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 lE({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=Fd(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=Fd(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=Fd(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=Fd(e);return typeof t=="string"?this.#t.get(t)?.find(n=>n!==e&&n.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){Fn.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=>Zy(t,n))}findAll(e={}){return this.getAll().filter(t=>Zy(e,t))}notify(e){Fn.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return Fn.batch(()=>Promise.all(e.map(t=>t.continue().catch(va))))}};function Fd(e){return e.options.scope?.id}var uE=class extends Vc{#e;constructor(e={}){super(),this.config=e,this.#e=new Map}build(e,t,n){const a=t.queryKey,o=t.queryHash??uv(a,t);let r=this.get(o);return r||(r=new oE({client:e,queryKey:a,queryHash:o,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(a)}),this.add(r)),r}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(){Fn.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=>Jy(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>Jy(e,n)):t}notify(e){Fn.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){Fn.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Fn.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},mE=class{#e;#t;#n;#a;#o;#i;#r;#l;constructor(e={}){this.#e=e.queryCache||new uE,this.#t=e.mutationCache||new dE,this.#n=e.defaultOptions||{},this.#a=new Map,this.#o=new Map,this.#i=0}mount(){this.#i++,this.#i===1&&(this.#r=fv.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#l=Bu.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#i--,this.#i===0&&(this.#r?.(),this.#r=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(fn(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,r=KT(t,o);if(r!==void 0)return this.#e.build(this,a).setData(r,{...n,manual:!0})}setQueriesData(e,t,n){return Fn.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;Fn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return Fn.batch(()=>{const a=n.findAll(e),o=new Set(a);return a.forEach(r=>{r.reset()}),this.refetchQueries({type:"active",predicate:r=>o.has(r)},t)})}cancelQueries(e,t={}){const n={revert:!0,...t},a=Fn.batch(()=>this.#e.findAll(e).map(o=>o.cancel(n)));return Promise.all(a).then(va).catch(va)}invalidateQueries(e,t={}){return Fn.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=Fn.batch(()=>this.#e.findAll(e).filter(o=>!o.isDisabled()&&!o.isStatic()).map(o=>{let r=o.fetch(void 0,n);return n.throwOnError||(r=r.catch(va)),o.state.fetchStatus==="paused"?Promise.resolve():r}));return Promise.all(a).then(va)}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(fn(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(fn(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(va).catch(va)}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(va).catch(va)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return Bu.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(bc(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#a.values()],n={};return t.forEach(a=>{Fs(e,a.queryKey)&&Object.assign(n,a.defaultOptions)}),n}setMutationDefaults(e,t){this.#o.set(bc(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#o.values()],n={};return t.forEach(a=>{Fs(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=uv(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===mv&&(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 b1=y.createContext(!1),pE=()=>y.useContext(b1);b1.Provider;function fE(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}const hE=y.createContext(fE()),gE=()=>y.useContext(hE),vE=(e,t,n)=>{const a=n?.state.error&&typeof e.throwOnError=="function"?m1(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||a)&&(t.isReset()||(e.retryOnMount=!1))},bE=e=>{y.useEffect(()=>{e.clearReset()},[e])},yE=({result:e,errorResetBoundary:t,throwOnError:n,query:a,suspense:o})=>e.isError&&!t.isReset()&&!e.isFetching&&a&&(o&&e.data===void 0||m1(n,[e.error,a])),SE=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))}},xE=(e,t)=>e?.suspense&&t.isPending,kE=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function wE(e,t,n){const a=pE(),o=gE(),r=s1(),s=r.defaultQueryOptions(e),l=r.getQueryCache().get(s.queryHash),m=e.subscribed!==!1;s._optimisticResults=a?"isRestoring":m?"optimistic":void 0,SE(s),vE(s,o,l),bE(o);const[d]=y.useState(()=>new t(r,s)),f=d.getOptimisticResult(s),g=!a&&m;if(y.useSyncExternalStore(y.useCallback(x=>{const k=g?d.subscribe(Fn.batchCalls(x)):va;return d.updateResult(),k},[d,g]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),y.useEffect(()=>{d.setOptions(s)},[s,d]),xE(s,f))throw kE(s,d,o);if(yE({result:f,errorResetBoundary:o,throwOnError:s.throwOnError,query:l,suspense:s.suspense}))throw f.error;return s.notifyOnChangeProps?f:d.trackResult(f)}function IE(e,t){return wE(e,rE)}function _E(){return new mE({defaultOptions:{queries:{staleTime:6e4,gcTime:15*6e4,retry:1,refetchOnWindowFocus:!1}}})}const CE=new Set(["turn.started","turn.completed","turn.failed","turn.interrupted","approval.requested","approval.resolved","task.input","task.wait"]);function RE(e){const t={};for(const n of e)n.sessionId&&CE.has(n.name)&&(Date.parse(n.timestamp)>Date.parse(t[n.sessionId]??"")||!t[n.sessionId]&&Number.isFinite(Date.parse(n.timestamp)))&&(t[n.sessionId]=n.timestamp);return t}function PE(e,t,n){return[...new Map(e.map(a=>[a.id,a])).values()].sort((a,o)=>Number(n.has(o.id))-Number(n.has(a.id))||Fu(o,t)-Fu(a,t)||a.id.localeCompare(o.id))}function Fu(e,t){const n=typeof e.metadata?.sidebarActivityAt=="string"?e.metadata.sidebarActivityAt:null;return Math.max(Date.parse(t[e.id]??"")||0,Date.parse(n??e.createdAt)||0)}function AE(e,t,n,a=new Date){const o=l=>`${l.getFullYear()}-${l.getMonth()}-${l.getDate()}`,r=new Date(a);r.setDate(a.getDate()-1);const s=[];for(const l of e){const m=new Date(Fu(l,t)),d=n.has(l.id),f=d?"running":o(m);let g=s.at(-1);g?.key!==f&&(g={key:f,label:d||f===o(a)?null:f===o(r)?"Yesterday":m.toLocaleDateString(void 0,{month:"short",day:"numeric",...m.getFullYear()!==a.getFullYear()?{year:"numeric"}:{}}),sessions:[]},s.push(g)),g.sessions.push(l)}return s}function TE(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 EE(e){return Math.min(500*2**Math.max(0,e),1e4)}async function ME(e,t,n,a){y1(e);const o=e.body.getReader(),r=new TextDecoder;let s="";for(;!a?.aborted;){const{done:l,value:m}=await o.read();if(l){s+=r.decode();break}s+=r.decode(m,{stream:!0});let d=s.indexOf(`
|
|
3
|
-
|
|
4
|
-
`);for(;d>=0;){const f=s.slice(0,d);s=s.slice(d+2),i0(f,t,n),d=s.indexOf(`
|
|
5
|
-
|
|
6
|
-
`)}}!a?.aborted&&s.trim()&&i0(s,t,n)}function y1(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 jE(e,t,n,a,o={}){const r=new AbortController,s=o.fetchImpl??fetch,l=o.reconnectDelayMs??EE;let m=a0(o.afterSequence),d=!1;return(async()=>{let f=0;for(;!r.signal.aborted;)try{const g=TE(e,r.signal,m),x=await s(g.url,g.init);if(y1(x),d=!0,f=0,await ME(x,k=>{const C=a0(k.sequence);C>0&&C<=m||(C>0&&(m=C),t(k))},a,r.signal),d=!1,r.signal.aborted)break;throw new Error("event stream ended")}catch(g){if(d=!1,r.signal.aborted)break;n(g),await OE(l(f),r.signal),f+=1}})().catch(()=>{}),{close(){r.abort()},isOpen(){return d}}}function a0(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0?e:0}function i0(e,t,n){let a="message";const o=[];for(const r of e.split(`
|
|
7
|
-
`))r.startsWith(":")||(r.startsWith("event: ")&&(a=r.slice(7).trim()),r.startsWith("data: ")&&o.push(r.slice(6)));if(a==="ready"){n?.();return}if(!(a!=="runtime"||o.length===0))try{t(JSON.parse(o.join(`
|
|
8
|
-
`)))}catch{}}async function OE(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 $E extends Error{constructor(t,n){super(t),this.status=n,this.name="ApiRequestError"}status}function o0(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 r0=new WeakMap,s0=new WeakMap,Vd=new WeakMap;let NE=0;async function B(e,t,n){if(t==="/v1/preferences"&&typeof n?.body=="string"){const o=(Vd.get(e)??Promise.resolve()).catch(()=>{}).then(()=>l0(e,t,n));Vd.set(e,o);try{return await o}finally{Vd.get(e)===o&&Vd.delete(e)}}return l0(e,t,n)}async function l0(e,t,n){const a=++NE;if(t==="/v1/preferences"&&typeof n?.body=="string"){const m=r0.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 r=await fetch(`${e.serverUrl}${t}`,{...n,headers:o});if(!r.ok){const m=await r.json().catch(()=>({})),d=m&&typeof m=="object"&&"error"in m?String(m.error):r.statusText;throw new $E(d,r.status)}if(r.status===204)return;const s=await r.json(),l=s?.configuration?.rawRevision??(t==="/v1/preferences"?s?.rawRevision:void 0);return typeof l=="string"&&a>=(s0.get(e)??0)&&(r0.set(e,l),s0.set(e,a)),s}function Mae(e){const t=new URL("/v1/terminal",e.serverUrl);return t.protocol=t.protocol==="https:"?"wss:":"ws:",t.toString()}function jae(e){return["openpond-terminal",`openpond-token.${HE(e.token)}`]}function DE(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 HE(e){return DE(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function LE(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)}function qE(e,t,n){const a=y.useRef(n);a.current=n,y.useEffect(()=>{if(!e||!t)return;let o=!1,r=!1,s=null;const l=new Set,m=new Map,d=R=>`openpond:ponder-notification-delivery:${t}:${R}`;async function f(R){if(!(o||!s))try{const E=await B(e,"/v1/ponder/notifications");if(o||E.bindingId!==s||!E.items.some(A=>A.id===R)||(await B(e,`/v1/ponder/notifications/${encodeURIComponent(R)}/read`,{method:"POST",body:"{}"}),o))return;window.focus(),a.current?.()}catch{}}const g=window.openpond?.onPonderNotification?.(R=>{f(R.id)});async function x(){if(!(o||r)){r=!0;try{const[R,E]=await Promise.all([B(e,"/v1/ponder/settings"),B(e,"/v1/ponder/notifications")]);if(o||R.bindingId!==E.bindingId)return;if(s!==E.bindingId){s=E.bindingId,l.clear();try{const O=JSON.parse(localStorage.getItem(d(s))??"[]");if(Array.isArray(O))for(const $ of O)typeof $=="string"&&l.add($)}catch{}}const A=new Set(E.items.filter(O=>!O.readAt).map(O=>O.id));for(const[O,$]of m)A.has(O)||($.close(),m.delete(O));if(localStorage.getItem("openpond:ponder-notifications")!=="on"||R.settings.notifications==="off")return;for(const O of E.items){if(o||O.readAt||l.has(O.id))continue;const $={id:O.id,title:O.title.slice(0,160),body:O.body.slice(0,500),ponder:!0};let M=!1;if(window.openpond?.notify)M=await window.openpond.notify($);else if("Notification"in window&&Notification.permission==="granted"){const w=new Notification($.title,{body:$.body,tag:$.id});w.onclick=()=>{w.close(),f(O.id)},m.set(O.id,w),M=!0}if(o)return;M&&l.add(O.id)}for(;l.size>500;)l.delete(l.values().next().value);try{localStorage.setItem(d(s),JSON.stringify([...l]))}catch{}}catch{}finally{r=!1}}}x();const k=window.setInterval(()=>{x()},1e4),C=()=>{x()};return window.addEventListener("ponder-settings-changed",C),()=>{o=!0,window.clearInterval(k),g?.(),window.removeEventListener("ponder-settings-changed",C);for(const R of m.values())R.close()}},[e,t])}var c0;function _e(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,f=Object.keys(d);for(let g=0;g<f.length;g++){const x=f[g];x in l||(l[x]=d[x].bind(l))}}const o=n?.Parent??Object;class r extends o{}Object.defineProperty(r,"name",{value:e});function s(l){var m;const d=n?.Parent?new r:this;a(d,l),(m=d._zod).deferred??(m.deferred=[]);for(const f of d._zod.deferred)f();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 Hs extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class S1 extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(c0=globalThis).__zod_globalConfig??(c0.__zod_globalConfig={});const gv=globalThis.__zod_globalConfig;function yo(e){return gv}function x1(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 rg(e,t){return typeof t=="bigint"?t.toString():t}function Im(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function vv(e){return e==null}function bv(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function UE(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 d0=Symbol("evaluating");function Et(e,t,n){let a;Object.defineProperty(e,t,{get(){if(a!==d0)return a===void 0&&(a=d0,a=n()),a},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function $r(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Yo(...e){const t={};for(const n of e){const a=Object.getOwnPropertyDescriptors(n);Object.assign(t,a)}return Object.defineProperties({},t)}function u0(e){return JSON.stringify(e)}function zE(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const k1="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function yc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const BE=Im(()=>{if(gv.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Vs(e){if(yc(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(yc(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function w1(e){return Vs(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const FE=new Set(["string","number","symbol"]);function Ks(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Qo(e,t,n){const a=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(a._zod.parent=e),a}function at(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 VE(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const KE={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 WE(e,t){const n=e._zod.def,a=n.checks;if(a&&a.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const r=Yo(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 $r(this,"shape",s),s},checks:[]});return Qo(e,r)}function GE(e,t){const n=e._zod.def,a=n.checks;if(a&&a.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const r=Yo(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 $r(this,"shape",s),s},checks:[]});return Qo(e,r)}function JE(e,t){if(!Vs(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const r=e._zod.def.shape;for(const s in t)if(Object.getOwnPropertyDescriptor(r,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const o=Yo(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return $r(this,"shape",r),r}});return Qo(e,o)}function ZE(e,t){if(!Vs(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Yo(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t};return $r(this,"shape",a),a}});return Qo(e,n)}function YE(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=Yo(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t._zod.def.shape};return $r(this,"shape",a),a},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Qo(e,n)}function QE(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=Yo(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 $r(this,"shape",m),m},checks:[]});return Qo(t,s)}function XE(e,t,n){const a=Yo(t._zod.def,{get shape(){const o=t._zod.def.shape,r={...o};if(n)for(const s in n){if(!(s in r))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(r[s]=new e({type:"nonoptional",innerType:o[s]}))}else for(const s in o)r[s]=new e({type:"nonoptional",innerType:o[s]});return $r(this,"shape",r),r}});return Qo(t,a)}function ws(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 eM(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 Is(e,t){return t.map(n=>{var a;return(a=n).path??(a.path=[]),n.path.unshift(e),n})}function Kd(e){return typeof e=="string"?e:e?.message}function So(e,t,n){const a=e.message?e.message:Kd(e.inst?._zod.def?.error?.(e))??Kd(t?.error?.(e))??Kd(n.customError?.(e))??Kd(n.localeError?.(e))??"Invalid input",{inst:o,continue:r,input:s,...l}=e;return l.path??(l.path=[]),l.message=a,t?.reportInput&&(l.input=s),l}function yv(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Sc(...e){const[t,n,a]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:a}:{...t}}const I1=(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,rg,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},_1=_e("$ZodError",I1),C1=_e("$ZodError",I1,{Parent:Error});function tM(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 nM(e,t=n=>n.message){const n={_errors:[]},a=(o,r=[])=>{for(const s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(l=>a({issues:l},[...r,...s.path]));else if(s.code==="invalid_key")a({issues:s.issues},[...r,...s.path]);else if(s.code==="invalid_element")a({issues:s.issues},[...r,...s.path]);else{const l=[...r,...s.path];if(l.length===0)n._errors.push(t(s));else{let m=n,d=0;for(;d<l.length;){const f=l[d];d===l.length-1?(m[f]=m[f]||{_errors:[]},m[f]._errors.push(t(s))):m[f]=m[f]||{_errors:[]},m=m[f],d++}}}};return a(e),n}const Sv=e=>(t,n,a,o)=>{const r=a?{...a,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},r);if(s instanceof Promise)throw new Hs;if(s.issues.length){const l=new(o?.Err??e)(s.issues.map(m=>So(m,r,yo())));throw k1(l,o?.callee),l}return s.value},xv=e=>async(t,n,a,o)=>{const r=a?{...a,async:!0}:{async:!0};let s=t._zod.run({value:n,issues:[]},r);if(s instanceof Promise&&(s=await s),s.issues.length){const l=new(o?.Err??e)(s.issues.map(m=>So(m,r,yo())));throw k1(l,o?.callee),l}return s.value},_m=e=>(t,n,a)=>{const o=a?{...a,async:!1}:{async:!1},r=t._zod.run({value:n,issues:[]},o);if(r instanceof Promise)throw new Hs;return r.issues.length?{success:!1,error:new(e??_1)(r.issues.map(s=>So(s,o,yo())))}:{success:!0,data:r.value}},aM=_m(C1),Cm=e=>async(t,n,a)=>{const o=a?{...a,async:!0}:{async:!0};let r=t._zod.run({value:n,issues:[]},o);return r instanceof Promise&&(r=await r),r.issues.length?{success:!1,error:new e(r.issues.map(s=>So(s,o,yo())))}:{success:!0,data:r.value}},iM=Cm(C1),oM=e=>(t,n,a)=>{const o=a?{...a,direction:"backward"}:{direction:"backward"};return Sv(e)(t,n,o)},rM=e=>(t,n,a)=>Sv(e)(t,n,a),sM=e=>async(t,n,a)=>{const o=a?{...a,direction:"backward"}:{direction:"backward"};return xv(e)(t,n,o)},lM=e=>async(t,n,a)=>xv(e)(t,n,a),cM=e=>(t,n,a)=>{const o=a?{...a,direction:"backward"}:{direction:"backward"};return _m(e)(t,n,o)},dM=e=>(t,n,a)=>_m(e)(t,n,a),uM=e=>async(t,n,a)=>{const o=a?{...a,direction:"backward"}:{direction:"backward"};return Cm(e)(t,n,o)},mM=e=>async(t,n,a)=>Cm(e)(t,n,a),pM=/^[cC][0-9a-z]{6,}$/,fM=/^[0-9a-z]+$/,hM=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,gM=/^[0-9a-vA-V]{20}$/,vM=/^[A-Za-z0-9]{27}$/,bM=/^[a-zA-Z0-9_-]{21}$/,yM=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,SM=/^([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})$/,m0=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)$/,xM=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,kM="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function wM(){return new RegExp(kM,"u")}const IM=/^(?:(?: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])$/,_M=/^(([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}|:))$/,CM=/^((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])$/,RM=/^(([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])$/,PM=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,R1=/^[A-Za-z0-9_-]*$/,AM=/^https?$/,TM=/^\+[1-9]\d{6,14}$/,P1="(?:(?:\\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])))",EM=new RegExp(`^${P1}$`);function A1(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 MM(e){return new RegExp(`^${A1(e)}$`)}function jM(e){const t=A1({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(`^${P1}T(?:${a})$`)}const OM=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},$M=/^-?\d+$/,T1=/^-?\d+(?:\.\d+)?$/,NM=/^(?:true|false)$/i,DM=/^null$/i,HM=/^[^A-Z]*$/,LM=/^[^a-z]*$/,ka=_e("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),E1={number:"number",bigint:"bigint",object:"date"},M1=_e("$ZodCheckLessThan",(e,t)=>{ka.init(e,t);const n=E1[typeof t.value];e._zod.onattach.push(a=>{const o=a._zod.bag,r=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<r&&(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})}}),j1=_e("$ZodCheckGreaterThan",(e,t)=>{ka.init(e,t);const n=E1[typeof t.value];e._zod.onattach.push(a=>{const o=a._zod.bag,r=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>r&&(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})}}),qM=_e("$ZodCheckMultipleOf",(e,t)=>{ka.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):UE(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})}}),UM=_e("$ZodCheckNumberFormat",(e,t)=>{ka.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),a=n?"int":"number",[o,r]=KE[t.format];e._zod.onattach.push(s=>{const l=s._zod.bag;l.format=t.format,l.minimum=o,l.maximum=r,n&&(l.pattern=$M)}),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>r&&s.issues.push({origin:"number",input:l,code:"too_big",maximum:r,inclusive:!0,inst:e,continue:!t.abort})}}),zM=_e("$ZodCheckMaxLength",(e,t)=>{var n;ka.init(e,t),(n=e._zod.def).when??(n.when=a=>{const o=a.value;return!vv(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=yv(o);a.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),BM=_e("$ZodCheckMinLength",(e,t)=>{var n;ka.init(e,t),(n=e._zod.def).when??(n.when=a=>{const o=a.value;return!vv(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=yv(o);a.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),FM=_e("$ZodCheckLengthEquals",(e,t)=>{var n;ka.init(e,t),(n=e._zod.def).when??(n.when=a=>{const o=a.value;return!vv(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,r=o.length;if(r===t.length)return;const s=yv(o),l=r>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})}}),Rm=_e("$ZodCheckStringFormat",(e,t)=>{var n,a;ka.init(e,t),e._zod.onattach.push(o=>{const r=o._zod.bag;r.format=t.format,t.pattern&&(r.patterns??(r.patterns=new Set),r.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=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=()=>{})}),VM=_e("$ZodCheckRegex",(e,t)=>{Rm.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})}}),KM=_e("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=HM),Rm.init(e,t)}),WM=_e("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=LM),Rm.init(e,t)}),GM=_e("$ZodCheckIncludes",(e,t)=>{ka.init(e,t);const n=Ks(t.includes),a=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=a,e._zod.onattach.push(o=>{const r=o._zod.bag;r.patterns??(r.patterns=new Set),r.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})}}),JM=_e("$ZodCheckStartsWith",(e,t)=>{ka.init(e,t);const n=new RegExp(`^${Ks(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})}}),ZM=_e("$ZodCheckEndsWith",(e,t)=>{ka.init(e,t);const n=new RegExp(`.*${Ks(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})}}),YM=_e("$ZodCheckOverwrite",(e,t)=>{ka.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class QM{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(`
|
|
9
|
-
`).filter(s=>s),o=Math.min(...a.map(s=>s.length-s.trimStart().length)),r=a.map(s=>s.slice(o)).map(s=>" ".repeat(this.indent*2)+s);for(const s of r)this.content.push(s)}compile(){const t=Function,n=this?.args,o=[...(this?.content??[""]).map(r=>` ${r}`)];return new t(...n,o.join(`
|
|
10
|
-
`))}}const XM={major:4,minor:4,patch:3},rn=_e("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=XM;const a=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&a.unshift(e);for(const o of a)for(const r of o._zod.onattach)r(e);if(a.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=(s,l,m)=>{let d=ws(s),f;for(const g of l){if(g._zod.def.when){if(eM(s)||!g._zod.def.when(s))continue}else if(d)continue;const x=s.issues.length,k=g._zod.check(s);if(k instanceof Promise&&m?.async===!1)throw new Hs;if(f||k instanceof Promise)f=(f??Promise.resolve()).then(async()=>{await k,s.issues.length!==x&&(d||(d=ws(s,x)))});else{if(s.issues.length===x)continue;d||(d=ws(s,x))}}return f?f.then(()=>s):s},r=(s,l,m)=>{if(ws(s))return s.aborted=!0,s;const d=o(l,a,m);if(d instanceof Promise){if(m.async===!1)throw new Hs;return d.then(f=>e._zod.parse(f,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(f=>r(f,s,l)):r(d,s,l)}const m=e._zod.parse(s,l);if(m instanceof Promise){if(l.async===!1)throw new Hs;return m.then(d=>o(d,a,l))}return o(m,a,l)}}Et(e,"~standard",()=>({validate:o=>{try{const r=aM(e,o);return r.success?{value:r.data}:{issues:r.error?.issues}}catch{return iM(e,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),kv=_e("$ZodString",(e,t)=>{rn.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??OM(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}}),un=_e("$ZodStringFormat",(e,t)=>{Rm.init(e,t),kv.init(e,t)}),ej=_e("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=SM),un.init(e,t)}),tj=_e("$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=m0(a))}else t.pattern??(t.pattern=m0());un.init(e,t)}),nj=_e("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=xM),un.init(e,t)}),aj=_e("$ZodURL",(e,t)=>{un.init(e,t),e._zod.check=n=>{try{const a=n.value.trim();if(!t.normalize&&t.protocol?.source===AM.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})}}}),ij=_e("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=wM()),un.init(e,t)}),oj=_e("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=bM),un.init(e,t)}),rj=_e("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=pM),un.init(e,t)}),sj=_e("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=fM),un.init(e,t)}),lj=_e("$ZodULID",(e,t)=>{t.pattern??(t.pattern=hM),un.init(e,t)}),cj=_e("$ZodXID",(e,t)=>{t.pattern??(t.pattern=gM),un.init(e,t)}),dj=_e("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=vM),un.init(e,t)}),uj=_e("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=jM(t)),un.init(e,t)}),mj=_e("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=EM),un.init(e,t)}),pj=_e("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=MM(t)),un.init(e,t)}),fj=_e("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=yM),un.init(e,t)}),hj=_e("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=IM),un.init(e,t),e._zod.bag.format="ipv4"}),gj=_e("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=_M),un.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})}}}),vj=_e("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=CM),un.init(e,t)}),bj=_e("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=RM),un.init(e,t),e._zod.check=n=>{const a=n.value.split("/");try{if(a.length!==2)throw new Error;const[o,r]=a;if(!r)throw new Error;const s=Number(r);if(`${s}`!==r)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${o}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function O1(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const yj=_e("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=PM),un.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{O1(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function Sj(e){if(!R1.test(e))return!1;const t=e.replace(/[-_]/g,a=>a==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return O1(n)}const xj=_e("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=R1),un.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{Sj(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),kj=_e("$ZodE164",(e,t)=>{t.pattern??(t.pattern=TM),un.init(e,t)});function wj(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 Ij=_e("$ZodJWT",(e,t)=>{un.init(e,t),e._zod.check=n=>{wj(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),$1=_e("$ZodNumber",(e,t)=>{rn.init(e,t),e._zod.pattern=e._zod.bag.pattern??T1,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 r=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,...r?{received:r}:{}}),n}}),_j=_e("$ZodNumberFormat",(e,t)=>{UM.init(e,t),$1.init(e,t)}),Cj=_e("$ZodBoolean",(e,t)=>{rn.init(e,t),e._zod.pattern=NM,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}}),Rj=_e("$ZodNull",(e,t)=>{rn.init(e,t),e._zod.pattern=DM,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}}),Pj=_e("$ZodUnknown",(e,t)=>{rn.init(e,t),e._zod.parse=n=>n}),Aj=_e("$ZodNever",(e,t)=>{rn.init(e,t),e._zod.parse=(n,a)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function p0(e,t,n){e.issues.length&&t.issues.push(...Is(n,e.issues)),t.value[n]=e.value}const Tj=_e("$ZodArray",(e,t)=>{rn.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 r=[];for(let s=0;s<o.length;s++){const l=o[s],m=t.element._zod.run({value:l,issues:[]},a);m instanceof Promise?r.push(m.then(d=>p0(d,n,s))):p0(m,n,s)}return r.length?Promise.all(r).then(()=>n):n}});function Vu(e,t,n,a,o,r){const s=n in a;if(e.issues.length){if(o&&r&&!s)return;t.issues.push(...Is(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 N1(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=VE(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function D1(e,t,n,a,o,r){const s=[],l=o.keySet,m=o.catchall._zod,d=m.def.type,f=m.optin==="optional",g=m.optout==="optional";for(const x in t){if(x==="__proto__"||l.has(x))continue;if(d==="never"){s.push(x);continue}const k=m.run({value:t[x],issues:[]},a);k instanceof Promise?e.push(k.then(C=>Vu(C,n,x,t,f,g))):Vu(k,n,x,t,f,g)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:r}),e.length?Promise.all(e).then(()=>n):n}const Ej=_e("$ZodObject",(e,t)=>{if(rn.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=Im(()=>N1(t));Et(e._zod,"propValues",()=>{const l=t.shape,m={};for(const d in l){const f=l[d]._zod;if(f.values){m[d]??(m[d]=new Set);for(const g of f.values)m[d].add(g)}}return m});const o=yc,r=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 f=[],g=s.shape;for(const x of s.keys){const k=g[x],C=k._zod.optin==="optional",R=k._zod.optout==="optional",E=k._zod.run({value:d[x],issues:[]},m);E instanceof Promise?f.push(E.then(A=>Vu(A,l,x,d,C,R))):Vu(E,l,x,d,C,R)}return r?D1(f,d,l,m,a.value,e):f.length?Promise.all(f).then(()=>l):l}}),Mj=_e("$ZodObjectJIT",(e,t)=>{Ej.init(e,t);const n=e._zod.parse,a=Im(()=>N1(t)),o=x=>{const k=new QM(["shape","payload","ctx"]),C=a.value,R=$=>{const M=u0($);return`shape[${M}]._zod.run({ value: input[${M}], issues: [] }, ctx)`};k.write("const input = payload.value;");const E=Object.create(null);let A=0;for(const $ of C.keys)E[$]=`key_${A++}`;k.write("const newResult = {};");for(const $ of C.keys){const M=E[$],w=u0($),P=x[$],j=P?._zod?.optin==="optional",N=P?._zod?.optout==="optional";k.write(`const ${M} = ${R($)};`),j&&N?k.write(`
|
|
11
|
-
if (${M}.issues.length) {
|
|
12
|
-
if (${w} in input) {
|
|
13
|
-
payload.issues = payload.issues.concat(${M}.issues.map(iss => ({
|
|
14
|
-
...iss,
|
|
15
|
-
path: iss.path ? [${w}, ...iss.path] : [${w}]
|
|
16
|
-
})));
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
if (${M}.value === undefined) {
|
|
21
|
-
if (${w} in input) {
|
|
22
|
-
newResult[${w}] = undefined;
|
|
23
|
-
}
|
|
24
|
-
} else {
|
|
25
|
-
newResult[${w}] = ${M}.value;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
`):j?k.write(`
|
|
29
|
-
if (${M}.issues.length) {
|
|
30
|
-
payload.issues = payload.issues.concat(${M}.issues.map(iss => ({
|
|
31
|
-
...iss,
|
|
32
|
-
path: iss.path ? [${w}, ...iss.path] : [${w}]
|
|
33
|
-
})));
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
if (${M}.value === undefined) {
|
|
37
|
-
if (${w} in input) {
|
|
38
|
-
newResult[${w}] = undefined;
|
|
39
|
-
}
|
|
40
|
-
} else {
|
|
41
|
-
newResult[${w}] = ${M}.value;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
`):k.write(`
|
|
45
|
-
const ${M}_present = ${w} in input;
|
|
46
|
-
if (${M}.issues.length) {
|
|
47
|
-
payload.issues = payload.issues.concat(${M}.issues.map(iss => ({
|
|
48
|
-
...iss,
|
|
49
|
-
path: iss.path ? [${w}, ...iss.path] : [${w}]
|
|
50
|
-
})));
|
|
51
|
-
}
|
|
52
|
-
if (!${M}_present && !${M}.issues.length) {
|
|
53
|
-
payload.issues.push({
|
|
54
|
-
code: "invalid_type",
|
|
55
|
-
expected: "nonoptional",
|
|
56
|
-
input: undefined,
|
|
57
|
-
path: [${w}]
|
|
58
|
-
});
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
if (${M}_present) {
|
|
62
|
-
if (${M}.value === undefined) {
|
|
63
|
-
newResult[${w}] = undefined;
|
|
64
|
-
} else {
|
|
65
|
-
newResult[${w}] = ${M}.value;
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
`)}k.write("payload.value = newResult;"),k.write("return payload;");const O=k.compile();return($,M)=>O(x,$,M)};let r;const s=yc,l=!gv.jitless,d=l&&BE.value,f=t.catchall;let g;e._zod.parse=(x,k)=>{g??(g=a.value);const C=x.value;return s(C)?l&&d&&k?.async===!1&&k.jitless!==!0?(r||(r=o(t.shape)),x=r(x,k),f?D1([],C,x,k,g,e):x):n(x,k):(x.issues.push({expected:"object",code:"invalid_type",input:C,inst:e}),x)}});function f0(e,t,n,a){for(const r of e)if(r.issues.length===0)return t.value=r.value,t;const o=e.filter(r=>!ws(r));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(r=>r.issues.map(s=>So(s,a,yo())))}),t)}const H1=_e("$ZodUnion",(e,t)=>{rn.init(e,t),Et(e._zod,"optin",()=>t.options.some(a=>a._zod.optin==="optional")?"optional":void 0),Et(e._zod,"optout",()=>t.options.some(a=>a._zod.optout==="optional")?"optional":void 0),Et(e._zod,"values",()=>{if(t.options.every(a=>a._zod.values))return new Set(t.options.flatMap(a=>Array.from(a._zod.values)))}),Et(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=>bv(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 r=!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),r=!0;else{if(m.issues.length===0)return m;s.push(m)}}return r?Promise.all(s).then(l=>f0(l,a,e,o)):f0(s,a,e,o)}}),jj=_e("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,H1.init(e,t);const n=e._zod.parse;Et(e._zod,"propValues",()=>{const o={};for(const r of t.options){const s=r._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(const[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=Im(()=>{const o=t.options,r=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(r.has(m))throw new Error(`Duplicate discriminator value "${String(m)}"`);r.set(m,s)}}return r});e._zod.parse=(o,r)=>{const s=o.value;if(!yc(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,r):t.unionFallback||r.direction==="backward"?n(o,r):(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)}}),Oj=_e("$ZodIntersection",(e,t)=>{rn.init(e,t),e._zod.parse=(n,a)=>{const o=n.value,r=t.left._zod.run({value:o,issues:[]},a),s=t.right._zod.run({value:o,issues:[]},a);return r instanceof Promise||s instanceof Promise?Promise.all([r,s]).then(([m,d])=>h0(n,m,d)):h0(n,r,s)}});function sg(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(Vs(e)&&Vs(t)){const n=Object.keys(t),a=Object.keys(e).filter(r=>n.indexOf(r)!==-1),o={...e,...t};for(const r of a){const s=sg(e[r],t[r]);if(!s.valid)return{valid:!1,mergeErrorPath:[r,...s.mergeErrorPath]};o[r]=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],r=t[a],s=sg(o,r);if(!s.valid)return{valid:!1,mergeErrorPath:[a,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function h0(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 r=[...a].filter(([,l])=>l.l&&l.r).map(([l])=>l);if(r.length&&o&&e.issues.push({...o,keys:r}),ws(e))return e;const s=sg(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 $j=_e("$ZodRecord",(e,t)=>{rn.init(e,t),e._zod.parse=(n,a)=>{const o=n.value;if(!Vs(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;const r=[],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 f=t.keyType._zod.run({value:d,issues:[]},a);if(f instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(f.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:f.issues.map(k=>So(k,a,yo())),input:d,path:[d],inst:e});continue}const g=f.value,x=t.valueType._zod.run({value:o[d],issues:[]},a);x instanceof Promise?r.push(x.then(k=>{k.issues.length&&n.issues.push(...Is(d,k.issues)),n.value[g]=k.value})):(x.issues.length&&n.issues.push(...Is(d,x.issues)),n.value[g]=x.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"&&T1.test(l)&&m.issues.length){const g=t.keyType._zod.run({value:Number(l),issues:[]},a);if(g instanceof Promise)throw new Error("Async schemas not supported in object keys currently");g.issues.length===0&&(m=g)}if(m.issues.length){t.mode==="loose"?n.value[l]=o[l]:n.issues.push({code:"invalid_key",origin:"record",issues:m.issues.map(g=>So(g,a,yo())),input:l,path:[l],inst:e});continue}const f=t.valueType._zod.run({value:o[l],issues:[]},a);f instanceof Promise?r.push(f.then(g=>{g.issues.length&&n.issues.push(...Is(l,g.issues)),n.value[m.value]=g.value})):(f.issues.length&&n.issues.push(...Is(l,f.issues)),n.value[m.value]=f.value)}}return r.length?Promise.all(r).then(()=>n):n}}),Nj=_e("$ZodEnum",(e,t)=>{rn.init(e,t);const n=x1(t.entries),a=new Set(n);e._zod.values=a,e._zod.pattern=new RegExp(`^(${n.filter(o=>FE.has(typeof o)).map(o=>typeof o=="string"?Ks(o):o.toString()).join("|")})$`),e._zod.parse=(o,r)=>{const s=o.value;return a.has(s)||o.issues.push({code:"invalid_value",values:n,input:s,inst:e}),o}}),Dj=_e("$ZodLiteral",(e,t)=>{if(rn.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"?Ks(a):a?Ks(a.toString()):String(a)).join("|")})$`),e._zod.parse=(a,o)=>{const r=a.value;return n.has(r)||a.issues.push({code:"invalid_value",values:t.values,input:r,inst:e}),a}}),Hj=_e("$ZodTransform",(e,t)=>{rn.init(e,t),e._zod.optin="optional",e._zod.parse=(n,a)=>{if(a.direction==="backward")throw new S1(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 Hs;return n.value=o,n.fallback=!0,n}});function g0(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const L1=_e("$ZodOptional",(e,t)=>{rn.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Et(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Et(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${bv(n.source)})?$`):void 0}),e._zod.parse=(n,a)=>{if(t.innerType._zod.optin==="optional"){const o=n.value,r=t.innerType._zod.run(n,a);return r instanceof Promise?r.then(s=>g0(s,o)):g0(r,o)}return n.value===void 0?n:t.innerType._zod.run(n,a)}}),Lj=_e("$ZodExactOptional",(e,t)=>{L1.init(e,t),Et(e._zod,"values",()=>t.innerType._zod.values),Et(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,a)=>t.innerType._zod.run(n,a)}),qj=_e("$ZodNullable",(e,t)=>{rn.init(e,t),Et(e._zod,"optin",()=>t.innerType._zod.optin),Et(e._zod,"optout",()=>t.innerType._zod.optout),Et(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${bv(n.source)}|null)$`):void 0}),Et(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)}),Uj=_e("$ZodDefault",(e,t)=>{rn.init(e,t),e._zod.optin="optional",Et(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(r=>v0(r,t)):v0(o,t)}});function v0(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const zj=_e("$ZodPrefault",(e,t)=>{rn.init(e,t),e._zod.optin="optional",Et(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))}),Bj=_e("$ZodNonOptional",(e,t)=>{rn.init(e,t),Et(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(r=>b0(r,e)):b0(o,e)}});function b0(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 Fj=_e("$ZodCatch",(e,t)=>{rn.init(e,t),e._zod.optin="optional",Et(e._zod,"optout",()=>t.innerType._zod.optout),Et(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(r=>(n.value=r.value,r.issues.length&&(n.value=t.catchValue({...n,error:{issues:r.issues.map(s=>So(s,a,yo()))},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(r=>So(r,a,yo()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),q1=_e("$ZodPipe",(e,t)=>{rn.init(e,t),Et(e._zod,"values",()=>t.in._zod.values),Et(e._zod,"optin",()=>t.in._zod.optin),Et(e._zod,"optout",()=>t.out._zod.optout),Et(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,a)=>{if(a.direction==="backward"){const r=t.out._zod.run(n,a);return r instanceof Promise?r.then(s=>Wd(s,t.in,a)):Wd(r,t.in,a)}const o=t.in._zod.run(n,a);return o instanceof Promise?o.then(r=>Wd(r,t.out,a)):Wd(o,t.out,a)}});function Wd(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 Vj=_e("$ZodPreprocess",(e,t)=>{q1.init(e,t)}),Kj=_e("$ZodReadonly",(e,t)=>{rn.init(e,t),Et(e._zod,"propValues",()=>t.innerType._zod.propValues),Et(e._zod,"values",()=>t.innerType._zod.values),Et(e._zod,"optin",()=>t.innerType?._zod?.optin),Et(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(y0):y0(o)}});function y0(e){return e.value=Object.freeze(e.value),e}const Wj=_e("$ZodLazy",(e,t)=>{rn.init(e,t),Et(e._zod,"innerType",()=>{const n=t;return n._cachedInner||(n._cachedInner=t.getter()),n._cachedInner}),Et(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),Et(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),Et(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),Et(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(n,a)=>e._zod.innerType._zod.run(n,a)}),Gj=_e("$ZodCustom",(e,t)=>{ka.init(e,t),rn.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(r=>S0(r,n,a,e));S0(o,n,a,e)}});function S0(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(Sc(o))}}var x0;class Jj{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 Zj(){return new Jj}(x0=globalThis).__zod_globalRegistry??(x0.__zod_globalRegistry=Zj());const Ql=globalThis.__zod_globalRegistry;function Yj(e,t){return new e({type:"string",...at(t)})}function Qj(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...at(t)})}function k0(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...at(t)})}function U1(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...at(t)})}function Xj(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...at(t)})}function eO(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...at(t)})}function tO(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...at(t)})}function nO(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...at(t)})}function aO(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...at(t)})}function iO(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...at(t)})}function oO(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...at(t)})}function rO(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...at(t)})}function sO(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...at(t)})}function lO(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...at(t)})}function cO(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...at(t)})}function dO(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...at(t)})}function uO(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...at(t)})}function mO(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...at(t)})}function pO(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...at(t)})}function fO(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...at(t)})}function hO(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...at(t)})}function gO(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...at(t)})}function vO(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...at(t)})}function bO(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...at(t)})}function yO(e,t){return new e({type:"string",format:"date",check:"string_format",...at(t)})}function SO(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...at(t)})}function xO(e,t){return new e({type:"string",format:"duration",check:"string_format",...at(t)})}function kO(e,t){return new e({type:"number",checks:[],...at(t)})}function Oae(e,t){return new e({type:"number",coerce:!0,checks:[],...at(t)})}function wO(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...at(t)})}function IO(e,t){return new e({type:"boolean",...at(t)})}function _O(e,t){return new e({type:"null",...at(t)})}function CO(e){return new e({type:"unknown"})}function RO(e,t){return new e({type:"never",...at(t)})}function w0(e,t){return new M1({check:"less_than",...at(t),value:e,inclusive:!1})}function Mf(e,t){return new M1({check:"less_than",...at(t),value:e,inclusive:!0})}function I0(e,t){return new j1({check:"greater_than",...at(t),value:e,inclusive:!1})}function jf(e,t){return new j1({check:"greater_than",...at(t),value:e,inclusive:!0})}function _0(e,t){return new qM({check:"multiple_of",...at(t),value:e})}function z1(e,t){return new zM({check:"max_length",...at(t),maximum:e})}function Ku(e,t){return new BM({check:"min_length",...at(t),minimum:e})}function B1(e,t){return new FM({check:"length_equals",...at(t),length:e})}function PO(e,t){return new VM({check:"string_format",format:"regex",...at(t),pattern:e})}function AO(e){return new KM({check:"string_format",format:"lowercase",...at(e)})}function TO(e){return new WM({check:"string_format",format:"uppercase",...at(e)})}function EO(e,t){return new GM({check:"string_format",format:"includes",...at(t),includes:e})}function MO(e,t){return new JM({check:"string_format",format:"starts_with",...at(t),prefix:e})}function jO(e,t){return new ZM({check:"string_format",format:"ends_with",...at(t),suffix:e})}function ll(e){return new YM({check:"overwrite",tx:e})}function OO(e){return ll(t=>t.normalize(e))}function $O(){return ll(e=>e.trim())}function NO(){return ll(e=>e.toLowerCase())}function DO(){return ll(e=>e.toUpperCase())}function HO(){return ll(e=>zE(e))}function LO(e,t,n){return new e({type:"array",element:t,...at(n)})}function qO(e,t,n){const a=at(n);return a.abort??(a.abort=!0),new e({type:"custom",check:"custom",fn:t,...a})}function UO(e,t,n){return new e({type:"custom",check:"custom",fn:t,...at(n)})}function zO(e,t){const n=BO(a=>(a.addIssue=o=>{if(typeof o=="string")a.issues.push(Sc(o,a.value,n._zod.def));else{const r=o;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=a.value),r.inst??(r.inst=n),r.continue??(r.continue=!n._zod.def.abort),a.issues.push(Sc(r))}},e(a.value,a)),t);return n}function BO(e,t){const n=new ka({check:"custom",...at(t)});return n._zod.check=e,n}function F1(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??Ql,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 yn(e,t,n={path:[],schemaPath:[]}){var a;const o=e._zod.def,r=t.seen.get(e);if(r)return r.count++,n.schemaPath.includes(e)&&(r.cycle=n.path),r.schema;const s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s);const l=e._zod.toJSONSchema?.();if(l)s.schema=l;else{const f={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,f);else{const x=s.schema,k=t.processors[o.type];if(!k)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);k(e,t,x,f)}const g=e._zod.parent;g&&(s.ref||(s.ref=g),yn(g,t,f),t.seen.get(g).isParent=!0)}const m=t.metadataRegistry.get(e);return m&&Object.assign(s.schema,m),t.io==="input"&&aa(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 V1(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const a=new Map;for(const s of e.seen.entries()){const l=e.metadataRegistry.get(s[0])?.id;if(l){const m=a.get(l);if(m&&m!==s[0])throw new Error(`Duplicate schema id "${l}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);a.set(l,s[0])}}const o=s=>{const l=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const g=e.external.registry.get(s[0])?.id,x=e.external.uri??(C=>C);if(g)return{ref:x(g)};const k=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=k,{defId:k,ref:`${x("__shared")}#/${l}/${k}`}}if(s[1]===n)return{ref:"#"};const d=`#/${l}/`,f=s[1].schema.id??`__schema${e.counter++}`;return{defId:f,ref:d+f}},r=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 f=l.schema;for(const g in f)delete f[g];f.$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>
|
|
70
|
-
|
|
71
|
-
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]){r(s);continue}if(e.external){const d=e.external.registry.get(s[0])?.id;if(t!==s[0]&&d){r(s);continue}}if(e.metadataRegistry.get(s[0])?.id){r(s);continue}if(l.cycle){r(s);continue}if(l.count>1&&e.reused==="ref"){r(s);continue}}}function K1(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,f={...d},g=m.ref;if(m.ref=null,g){a(g);const k=e.seen.get(g),C=k.schema;if(C.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(d.allOf=d.allOf??[],d.allOf.push(C)):Object.assign(d,C),Object.assign(d,f),l._zod.parent===g)for(const E in d)E==="$ref"||E==="allOf"||E in f||delete d[E];if(C.$ref&&k.def)for(const E in d)E==="$ref"||E==="allOf"||E in k.def&&JSON.stringify(d[E])===JSON.stringify(k.def[E])&&delete d[E]}const x=l._zod.parent;if(x&&x!==g){a(x);const k=e.seen.get(x);if(k?.schema.$ref&&(d.$ref=k.schema.$ref,k.def))for(const C in d)C==="$ref"||C==="allOf"||C in k.def&&JSON.stringify(d[C])===JSON.stringify(k.def[C])&&delete d[C]}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 r=e.metadataRegistry.get(t)?.id;r!==void 0&&o.id===r&&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:Wu(t,"input",e.processors),output:Wu(t,"output",e.processors)}},enumerable:!1,writable:!1}),l}catch{throw new Error("Error converting schema to JSON.")}}function aa(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 aa(a.element,n);if(a.type==="set")return aa(a.valueType,n);if(a.type==="lazy")return aa(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 aa(a.innerType,n);if(a.type==="intersection")return aa(a.left,n)||aa(a.right,n);if(a.type==="record"||a.type==="map")return aa(a.keyType,n)||aa(a.valueType,n);if(a.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:aa(a.in,n)||aa(a.out,n);if(a.type==="object"){for(const o in a.shape)if(aa(a.shape[o],n))return!0;return!1}if(a.type==="union"){for(const o of a.options)if(aa(o,n))return!0;return!1}if(a.type==="tuple"){for(const o of a.items)if(aa(o,n))return!0;return!!(a.rest&&aa(a.rest,n))}return!1}const FO=(e,t={})=>n=>{const a=F1({...n,processors:t});return yn(e,a),V1(a,e),K1(a,e)},Wu=(e,t,n={})=>a=>{const{libraryOptions:o,target:r}=a??{},s=F1({...o??{},target:r,io:t,processors:n});return yn(e,s),V1(s,e),K1(s,e)},VO={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},KO=(e,t,n,a)=>{const o=n;o.type="string";const{minimum:r,maximum:s,format:l,patterns:m,contentEncoding:d}=e._zod.bag;if(typeof r=="number"&&(o.minLength=r),typeof s=="number"&&(o.maxLength=s),l&&(o.format=VO[l]??l,o.format===""&&delete o.format,l==="time"&&delete o.format),d&&(o.contentEncoding=d),m&&m.size>0){const f=[...m];f.length===1?o.pattern=f[0].source:f.length>1&&(o.allOf=[...f.map(g=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:g.source}))])}},WO=(e,t,n,a)=>{const o=n,{minimum:r,maximum:s,format:l,multipleOf:m,exclusiveMaximum:d,exclusiveMinimum:f}=e._zod.bag;typeof l=="string"&&l.includes("int")?o.type="integer":o.type="number";const g=typeof f=="number"&&f>=(r??Number.NEGATIVE_INFINITY),x=typeof d=="number"&&d<=(s??Number.POSITIVE_INFINITY),k=t.target==="draft-04"||t.target==="openapi-3.0";g?k?(o.minimum=f,o.exclusiveMinimum=!0):o.exclusiveMinimum=f:typeof r=="number"&&(o.minimum=r),x?k?(o.maximum=d,o.exclusiveMaximum=!0):o.exclusiveMaximum=d:typeof s=="number"&&(o.maximum=s),typeof m=="number"&&(o.multipleOf=m)},GO=(e,t,n,a)=>{n.type="boolean"},JO=(e,t,n,a)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},ZO=(e,t,n,a)=>{n.not={}},YO=(e,t,n,a)=>{},QO=(e,t,n,a)=>{const o=e._zod.def,r=x1(o.entries);r.every(s=>typeof s=="number")&&(n.type="number"),r.every(s=>typeof s=="string")&&(n.type="string"),n.enum=r},XO=(e,t,n,a)=>{const o=e._zod.def,r=[];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");r.push(Number(s))}else r.push(s);if(r.length!==0)if(r.length===1){const s=r[0];n.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[s]:n.const=s}else r.every(s=>typeof s=="number")&&(n.type="number"),r.every(s=>typeof s=="string")&&(n.type="string"),r.every(s=>typeof s=="boolean")&&(n.type="boolean"),r.every(s=>s===null)&&(n.type="null"),n.enum=r},e2=(e,t,n,a)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},t2=(e,t,n,a)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},n2=(e,t,n,a)=>{const o=n,r=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=yn(r.element,t,{...a,path:[...a.path,"items"]})},a2=(e,t,n,a)=>{const o=n,r=e._zod.def;o.type="object",o.properties={};const s=r.shape;for(const d in s)o.properties[d]=yn(s[d],t,{...a,path:[...a.path,"properties",d]});const l=new Set(Object.keys(s)),m=new Set([...l].filter(d=>{const f=r.shape[d]._zod;return t.io==="input"?f.optin===void 0:f.optout===void 0}));m.size>0&&(o.required=Array.from(m)),r.catchall?._zod.def.type==="never"?o.additionalProperties=!1:r.catchall?r.catchall&&(o.additionalProperties=yn(r.catchall,t,{...a,path:[...a.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},i2=(e,t,n,a)=>{const o=e._zod.def,r=o.inclusive===!1,s=o.options.map((l,m)=>yn(l,t,{...a,path:[...a.path,r?"oneOf":"anyOf",m]}));r?n.oneOf=s:n.anyOf=s},o2=(e,t,n,a)=>{const o=e._zod.def,r=yn(o.left,t,{...a,path:[...a.path,"allOf",0]}),s=yn(o.right,t,{...a,path:[...a.path,"allOf",1]}),l=d=>"allOf"in d&&Object.keys(d).length===1,m=[...l(r)?r.allOf:[r],...l(s)?s.allOf:[s]];n.allOf=m},r2=(e,t,n,a)=>{const o=n,r=e._zod.def;o.type="object";const s=r.keyType,m=s._zod.bag?.patterns;if(r.mode==="loose"&&m&&m.size>0){const f=yn(r.valueType,t,{...a,path:[...a.path,"patternProperties","*"]});o.patternProperties={};for(const g of m)o.patternProperties[g.source]=f}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(o.propertyNames=yn(r.keyType,t,{...a,path:[...a.path,"propertyNames"]})),o.additionalProperties=yn(r.valueType,t,{...a,path:[...a.path,"additionalProperties"]});const d=s._zod.values;if(d){const f=[...d].filter(g=>typeof g=="string"||typeof g=="number");f.length>0&&(o.required=f)}},s2=(e,t,n,a)=>{const o=e._zod.def,r=yn(o.innerType,t,a),s=t.seen.get(e);t.target==="openapi-3.0"?(s.ref=o.innerType,n.nullable=!0):n.anyOf=[r,{type:"null"}]},l2=(e,t,n,a)=>{const o=e._zod.def;yn(o.innerType,t,a);const r=t.seen.get(e);r.ref=o.innerType},c2=(e,t,n,a)=>{const o=e._zod.def;yn(o.innerType,t,a);const r=t.seen.get(e);r.ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))},d2=(e,t,n,a)=>{const o=e._zod.def;yn(o.innerType,t,a);const r=t.seen.get(e);r.ref=o.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},u2=(e,t,n,a)=>{const o=e._zod.def;yn(o.innerType,t,a);const r=t.seen.get(e);r.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},m2=(e,t,n,a)=>{const o=e._zod.def,r=o.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?r?o.out:o.in:o.out;yn(s,t,a);const l=t.seen.get(e);l.ref=s},p2=(e,t,n,a)=>{const o=e._zod.def;yn(o.innerType,t,a);const r=t.seen.get(e);r.ref=o.innerType,n.readOnly=!0},W1=(e,t,n,a)=>{const o=e._zod.def;yn(o.innerType,t,a);const r=t.seen.get(e);r.ref=o.innerType},f2=(e,t,n,a)=>{const o=e._zod.innerType;yn(o,t,a);const r=t.seen.get(e);r.ref=o},h2=_e("ZodISODateTime",(e,t)=>{uj.init(e,t),mn.init(e,t)});function on(e){return bO(h2,e)}const g2=_e("ZodISODate",(e,t)=>{mj.init(e,t),mn.init(e,t)});function v2(e){return yO(g2,e)}const b2=_e("ZodISOTime",(e,t)=>{pj.init(e,t),mn.init(e,t)});function y2(e){return SO(b2,e)}const S2=_e("ZodISODuration",(e,t)=>{fj.init(e,t),mn.init(e,t)});function x2(e){return xO(S2,e)}const G1=(e,t)=>{_1.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>nM(e,n)},flatten:{value:n=>tM(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,rg,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,rg,2)}},isEmpty:{get(){return e.issues.length===0}}})},k2=_e("ZodError",G1),Za=_e("ZodError",G1,{Parent:Error}),w2=Sv(Za),I2=xv(Za),_2=_m(Za),C2=Cm(Za),R2=oM(Za),P2=rM(Za),A2=sM(Za),T2=lM(Za),E2=cM(Za),M2=dM(Za),j2=uM(Za),O2=mM(Za),C0=new WeakMap;function Kc(e,t,n){const a=Object.getPrototypeOf(e);let o=C0.get(a);if(o||(o=new Set,C0.set(a,o)),!o.has(t)){o.add(t);for(const r in n){const s=n[r];Object.defineProperty(a,r,{configurable:!0,enumerable:!1,get(){const l=s.bind(this);return Object.defineProperty(this,r,{configurable:!0,writable:!0,enumerable:!0,value:l}),l},set(l){Object.defineProperty(this,r,{configurable:!0,writable:!0,enumerable:!0,value:l})}})}}}const sn=_e("ZodType",(e,t)=>(rn.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Wu(e,"input"),output:Wu(e,"output")}}),e.toJSONSchema=FO(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,a)=>w2(e,n,a,{callee:e.parse}),e.safeParse=(n,a)=>_2(e,n,a),e.parseAsync=async(n,a)=>I2(e,n,a,{callee:e.parseAsync}),e.safeParseAsync=async(n,a)=>C2(e,n,a),e.spa=e.safeParseAsync,e.encode=(n,a)=>R2(e,n,a),e.decode=(n,a)=>P2(e,n,a),e.encodeAsync=async(n,a)=>A2(e,n,a),e.decodeAsync=async(n,a)=>T2(e,n,a),e.safeEncode=(n,a)=>E2(e,n,a),e.safeDecode=(n,a)=>M2(e,n,a),e.safeEncodeAsync=async(n,a)=>j2(e,n,a),e.safeDecodeAsync=async(n,a)=>O2(e,n,a),Kc(e,"ZodType",{check(...n){const a=this.def;return this.clone(Yo(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 Qo(this,n,a)},brand(){return this},register(n,a){return n.add(this,a),this},refine(n,a){return this.check(I$(n,a))},superRefine(n,a){return this.check(_$(n,a))},overwrite(n){return this.check(ll(n))},optional(){return T0(this)},exactOptional(){return u$(this)},nullable(){return E0(this)},nullish(){return T0(E0(this))},nonoptional(n){return v$(this,n)},array(){return p(this)},or(n){return vt([this,n])},and(n){return s$(this,n)},transform(n){return M0(this,ew(n))},default(n){return f$(this,n)},prefault(n){return g$(this,n)},catch(n){return y$(this,n)},pipe(n){return M0(this,n)},readonly(){return k$(this)},describe(n){const a=this.clone();return Ql.add(a,{description:n}),a},meta(...n){if(n.length===0)return Ql.get(this);const a=this.clone();return Ql.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 Ql.get(e)?.description},configurable:!0}),e)),J1=_e("_ZodString",(e,t)=>{kv.init(e,t),sn.init(e,t),e._zod.processJSONSchema=(a,o,r)=>KO(e,a,o);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Kc(e,"_ZodString",{regex(...a){return this.check(PO(...a))},includes(...a){return this.check(EO(...a))},startsWith(...a){return this.check(MO(...a))},endsWith(...a){return this.check(jO(...a))},min(...a){return this.check(Ku(...a))},max(...a){return this.check(z1(...a))},length(...a){return this.check(B1(...a))},nonempty(...a){return this.check(Ku(1,...a))},lowercase(a){return this.check(AO(a))},uppercase(a){return this.check(TO(a))},trim(){return this.check($O())},normalize(...a){return this.check(OO(...a))},toLowerCase(){return this.check(NO())},toUpperCase(){return this.check(DO())},slugify(){return this.check(HO())}})}),$2=_e("ZodString",(e,t)=>{kv.init(e,t),J1.init(e,t),e.email=n=>e.check(Qj(N2,n)),e.url=n=>e.check(nO(D2,n)),e.jwt=n=>e.check(vO(Q2,n)),e.emoji=n=>e.check(aO(H2,n)),e.guid=n=>e.check(k0(R0,n)),e.uuid=n=>e.check(U1(Xl,n)),e.uuidv4=n=>e.check(Xj(Xl,n)),e.uuidv6=n=>e.check(eO(Xl,n)),e.uuidv7=n=>e.check(tO(Xl,n)),e.nanoid=n=>e.check(iO(L2,n)),e.guid=n=>e.check(k0(R0,n)),e.cuid=n=>e.check(oO(q2,n)),e.cuid2=n=>e.check(rO(U2,n)),e.ulid=n=>e.check(sO(z2,n)),e.base64=n=>e.check(fO(J2,n)),e.base64url=n=>e.check(hO(Z2,n)),e.xid=n=>e.check(lO(B2,n)),e.ksuid=n=>e.check(cO(F2,n)),e.ipv4=n=>e.check(dO(V2,n)),e.ipv6=n=>e.check(uO(K2,n)),e.cidrv4=n=>e.check(mO(W2,n)),e.cidrv6=n=>e.check(pO(G2,n)),e.e164=n=>e.check(gO(Y2,n)),e.datetime=n=>e.check(on(n)),e.date=n=>e.check(v2(n)),e.time=n=>e.check(y2(n)),e.duration=n=>e.check(x2(n))});function i(e){return Yj($2,e)}const mn=_e("ZodStringFormat",(e,t)=>{un.init(e,t),J1.init(e,t)}),N2=_e("ZodEmail",(e,t)=>{nj.init(e,t),mn.init(e,t)}),R0=_e("ZodGUID",(e,t)=>{ej.init(e,t),mn.init(e,t)}),Xl=_e("ZodUUID",(e,t)=>{tj.init(e,t),mn.init(e,t)});function Pm(e){return U1(Xl,e)}const D2=_e("ZodURL",(e,t)=>{aj.init(e,t),mn.init(e,t)}),H2=_e("ZodEmoji",(e,t)=>{ij.init(e,t),mn.init(e,t)}),L2=_e("ZodNanoID",(e,t)=>{oj.init(e,t),mn.init(e,t)}),q2=_e("ZodCUID",(e,t)=>{rj.init(e,t),mn.init(e,t)}),U2=_e("ZodCUID2",(e,t)=>{sj.init(e,t),mn.init(e,t)}),z2=_e("ZodULID",(e,t)=>{lj.init(e,t),mn.init(e,t)}),B2=_e("ZodXID",(e,t)=>{cj.init(e,t),mn.init(e,t)}),F2=_e("ZodKSUID",(e,t)=>{dj.init(e,t),mn.init(e,t)}),V2=_e("ZodIPv4",(e,t)=>{hj.init(e,t),mn.init(e,t)}),K2=_e("ZodIPv6",(e,t)=>{gj.init(e,t),mn.init(e,t)}),W2=_e("ZodCIDRv4",(e,t)=>{vj.init(e,t),mn.init(e,t)}),G2=_e("ZodCIDRv6",(e,t)=>{bj.init(e,t),mn.init(e,t)}),J2=_e("ZodBase64",(e,t)=>{yj.init(e,t),mn.init(e,t)}),Z2=_e("ZodBase64URL",(e,t)=>{xj.init(e,t),mn.init(e,t)}),Y2=_e("ZodE164",(e,t)=>{kj.init(e,t),mn.init(e,t)}),Q2=_e("ZodJWT",(e,t)=>{Ij.init(e,t),mn.init(e,t)}),Z1=_e("ZodNumber",(e,t)=>{$1.init(e,t),sn.init(e,t),e._zod.processJSONSchema=(a,o,r)=>WO(e,a,o),Kc(e,"ZodNumber",{gt(a,o){return this.check(I0(a,o))},gte(a,o){return this.check(jf(a,o))},min(a,o){return this.check(jf(a,o))},lt(a,o){return this.check(w0(a,o))},lte(a,o){return this.check(Mf(a,o))},max(a,o){return this.check(Mf(a,o))},int(a){return this.check(P0(a))},safe(a){return this.check(P0(a))},positive(a){return this.check(I0(0,a))},nonnegative(a){return this.check(jf(0,a))},negative(a){return this.check(w0(0,a))},nonpositive(a){return this.check(Mf(0,a))},multipleOf(a,o){return this.check(_0(a,o))},step(a,o){return this.check(_0(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 kO(Z1,e)}const X2=_e("ZodNumberFormat",(e,t)=>{_j.init(e,t),Z1.init(e,t)});function P0(e){return wO(X2,e)}const e$=_e("ZodBoolean",(e,t)=>{Cj.init(e,t),sn.init(e,t),e._zod.processJSONSchema=(n,a,o)=>GO(e,n,a)});function I(e){return IO(e$,e)}const t$=_e("ZodNull",(e,t)=>{Rj.init(e,t),sn.init(e,t),e._zod.processJSONSchema=(n,a,o)=>JO(e,n,a)});function cl(e){return _O(t$,e)}const n$=_e("ZodUnknown",(e,t)=>{Pj.init(e,t),sn.init(e,t),e._zod.processJSONSchema=(n,a,o)=>YO()});function ce(){return CO(n$)}const a$=_e("ZodNever",(e,t)=>{Aj.init(e,t),sn.init(e,t),e._zod.processJSONSchema=(n,a,o)=>ZO(e,n,a)});function Y1(e){return RO(a$,e)}const i$=_e("ZodArray",(e,t)=>{Tj.init(e,t),sn.init(e,t),e._zod.processJSONSchema=(n,a,o)=>n2(e,n,a,o),e.element=t.element,Kc(e,"ZodArray",{min(n,a){return this.check(Ku(n,a))},nonempty(n){return this.check(Ku(1,n))},max(n,a){return this.check(z1(n,a))},length(n,a){return this.check(B1(n,a))},unwrap(){return this.element}})});function p(e,t){return LO(i$,e,t)}const Q1=_e("ZodObject",(e,t)=>{Mj.init(e,t),sn.init(e,t),e._zod.processJSONSchema=(n,a,o)=>a2(e,n,a,o),Et(e,"shape",()=>t.shape),Kc(e,"ZodObject",{keyof(){return v(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:ce()})},loose(){return this.clone({...this._zod.def,catchall:ce()})},strict(){return this.clone({...this._zod.def,catchall:Y1()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return JE(this,n)},safeExtend(n){return ZE(this,n)},merge(n){return YE(this,n)},pick(n){return WE(this,n)},omit(n){return GE(this,n)},partial(...n){return QE(tw,this,n[0])},required(...n){return XE(nw,this,n[0])}})});function c(e,t){const n={type:"object",shape:e??{},...at(t)};return new Q1(n)}function Of(e,t){return new Q1({type:"object",shape:e,catchall:Y1(),...at(t)})}const X1=_e("ZodUnion",(e,t)=>{H1.init(e,t),sn.init(e,t),e._zod.processJSONSchema=(n,a,o)=>i2(e,n,a,o),e.options=t.options});function vt(e,t){return new X1({type:"union",options:e,...at(t)})}const o$=_e("ZodDiscriminatedUnion",(e,t)=>{X1.init(e,t),jj.init(e,t)});function ot(e,t,n){return new o$({type:"union",options:t,discriminator:e,...at(n)})}const r$=_e("ZodIntersection",(e,t)=>{Oj.init(e,t),sn.init(e,t),e._zod.processJSONSchema=(n,a,o)=>o2(e,n,a,o)});function s$(e,t){return new r$({type:"intersection",left:e,right:t})}const A0=_e("ZodRecord",(e,t)=>{$j.init(e,t),sn.init(e,t),e._zod.processJSONSchema=(n,a,o)=>r2(e,n,a,o),e.keyType=t.keyType,e.valueType=t.valueType});function le(e,t,n){return!t||!t._zod?new A0({type:"record",keyType:i(),valueType:e,...at(t)}):new A0({type:"record",keyType:e,valueType:t,...at(n)})}const lg=_e("ZodEnum",(e,t)=>{Nj.init(e,t),sn.init(e,t),e._zod.processJSONSchema=(a,o,r)=>QO(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 r={};for(const s of a)if(n.has(s))r[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new lg({...t,checks:[],...at(o),entries:r})},e.exclude=(a,o)=>{const r={...t.entries};for(const s of a)if(n.has(s))delete r[s];else throw new Error(`Key ${s} not found in enum`);return new lg({...t,checks:[],...at(o),entries:r})}});function v(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(a=>[a,a])):e;return new lg({type:"enum",entries:n,...at(t)})}const l$=_e("ZodLiteral",(e,t)=>{Dj.init(e,t),sn.init(e,t),e._zod.processJSONSchema=(n,a,o)=>XO(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 b(e,t){return new l$({type:"literal",values:Array.isArray(e)?e:[e],...at(t)})}const c$=_e("ZodTransform",(e,t)=>{Hj.init(e,t),sn.init(e,t),e._zod.processJSONSchema=(n,a,o)=>t2(e,n),e._zod.parse=(n,a)=>{if(a.direction==="backward")throw new S1(e.constructor.name);n.addIssue=r=>{if(typeof r=="string")n.issues.push(Sc(r,n.value,t));else{const s=r;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=e),n.issues.push(Sc(s))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(r=>(n.value=r,n.fallback=!0,n)):(n.value=o,n.fallback=!0,n)}});function ew(e){return new c$({type:"transform",transform:e})}const tw=_e("ZodOptional",(e,t)=>{L1.init(e,t),sn.init(e,t),e._zod.processJSONSchema=(n,a,o)=>W1(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function T0(e){return new tw({type:"optional",innerType:e})}const d$=_e("ZodExactOptional",(e,t)=>{Lj.init(e,t),sn.init(e,t),e._zod.processJSONSchema=(n,a,o)=>W1(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function u$(e){return new d$({type:"optional",innerType:e})}const m$=_e("ZodNullable",(e,t)=>{qj.init(e,t),sn.init(e,t),e._zod.processJSONSchema=(n,a,o)=>s2(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function E0(e){return new m$({type:"nullable",innerType:e})}const p$=_e("ZodDefault",(e,t)=>{Uj.init(e,t),sn.init(e,t),e._zod.processJSONSchema=(n,a,o)=>c2(e,n,a,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function f$(e,t){return new p$({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():w1(t)}})}const h$=_e("ZodPrefault",(e,t)=>{zj.init(e,t),sn.init(e,t),e._zod.processJSONSchema=(n,a,o)=>d2(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function g$(e,t){return new h$({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():w1(t)}})}const nw=_e("ZodNonOptional",(e,t)=>{Bj.init(e,t),sn.init(e,t),e._zod.processJSONSchema=(n,a,o)=>l2(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function v$(e,t){return new nw({type:"nonoptional",innerType:e,...at(t)})}const b$=_e("ZodCatch",(e,t)=>{Fj.init(e,t),sn.init(e,t),e._zod.processJSONSchema=(n,a,o)=>u2(e,n,a,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function y$(e,t){return new b$({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const aw=_e("ZodPipe",(e,t)=>{q1.init(e,t),sn.init(e,t),e._zod.processJSONSchema=(n,a,o)=>m2(e,n,a,o),e.in=t.in,e.out=t.out});function M0(e,t){return new aw({type:"pipe",in:e,out:t})}const S$=_e("ZodPreprocess",(e,t)=>{aw.init(e,t),Vj.init(e,t)}),x$=_e("ZodReadonly",(e,t)=>{Kj.init(e,t),sn.init(e,t),e._zod.processJSONSchema=(n,a,o)=>p2(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function k$(e){return new x$({type:"readonly",innerType:e})}const w$=_e("ZodLazy",(e,t)=>{Wj.init(e,t),sn.init(e,t),e._zod.processJSONSchema=(n,a,o)=>f2(e,n,a,o),e.unwrap=()=>e._zod.def.getter()});function iw(e){return new w$({type:"lazy",getter:e})}const ow=_e("ZodCustom",(e,t)=>{Gj.init(e,t),sn.init(e,t),e._zod.processJSONSchema=(n,a,o)=>e2(e,n)});function $f(e,t){return qO(ow,(()=>!0),t)}function I$(e,t={}){return UO(ow,e,t)}function _$(e,t){return zO(e,t)}function Ko(e){const t=iw(()=>vt([i(e),u(),I(),cl(),p(t),le(i(),t)]));return t}function C$(e,t){return new S$({type:"pipe",in:ew(e),out:t})}const oa={custom:"custom"},R$=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),P$=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]);let A$=class rw{state=new Uint32Array(R$);pending=new Uint8Array(64);pendingLength=0;byteLength=0;words=new Uint32Array(64);update(t){const n=typeof t=="string"?new TextEncoder().encode(t):t;if(!Number.isSafeInteger(this.byteLength+n.length))throw new RangeError("SHA-256 input is too large");this.byteLength+=n.length;let a=0;if(this.pendingLength){const o=Math.min(64-this.pendingLength,n.length);this.pending.set(n.subarray(0,o),this.pendingLength),this.pendingLength+=o,a+=o,this.pendingLength===64&&(this.compress(this.pending),this.pendingLength=0)}for(;a+64<=n.length;)this.compress(n.subarray(a,a+64)),a+=64;return a<n.length&&(this.pending.set(n.subarray(a)),this.pendingLength=n.length-a),this}clone(){const t=new rw;return t.state.set(this.state),t.pending.set(this.pending),t.pendingLength=this.pendingLength,t.byteLength=this.byteLength,t}digestHex(){const t=this.clone(),n=new Uint8Array(t.pendingLength<56?64:128);n.set(t.pending.subarray(0,t.pendingLength)),n[t.pendingLength]=128;const a=t.byteLength*8,o=new DataView(n.buffer);return o.setUint32(n.length-8,Math.floor(a/4294967296),!1),o.setUint32(n.length-4,a>>>0,!1),t.compress(n.subarray(0,64)),n.length===128&&t.compress(n.subarray(64)),Array.from(t.state,r=>r.toString(16).padStart(8,"0")).join("")}compress(t){const n=new DataView(t.buffer,t.byteOffset,64),a=this.state,o=this.words;for(let k=0;k<16;k+=1)o[k]=n.getUint32(k*4,!1);for(let k=16;k<64;k+=1){const C=o[k-15],R=o[k-2],E=Ii(C,7)^Ii(C,18)^C>>>3,A=Ii(R,17)^Ii(R,19)^R>>>10;o[k]=o[k-16]+E+o[k-7]+A>>>0}let r=a[0],s=a[1],l=a[2],m=a[3],d=a[4],f=a[5],g=a[6],x=a[7];for(let k=0;k<64;k+=1){const C=d&f^~d&g,R=r&s^r&l^s&l,E=Ii(r,2)^Ii(r,13)^Ii(r,22),A=Ii(d,6)^Ii(d,11)^Ii(d,25),O=x+A+C+P$[k]+o[k]>>>0,$=E+R>>>0;x=g,g=f,f=d,d=m+O>>>0,m=l,l=s,s=r,r=O+$>>>0}a[0]=a[0]+r>>>0,a[1]=a[1]+s>>>0,a[2]=a[2]+l>>>0,a[3]=a[3]+m>>>0,a[4]=a[4]+d>>>0,a[5]=a[5]+f>>>0,a[6]=a[6]+g>>>0,a[7]=a[7]+x>>>0}};function T$(e){return new A$().update(e).digestHex()}function Ii(e,t){return e>>>t|e<<32-t}const E$=2e3,sw=25e7,T=i().trim().min(1).max(240),H=i().regex(/^[a-f0-9]{64}$/),ye=i().datetime({offset:!0}),Nn=le(i(),ce()).default({}),W=c({id:T,contentHash:H}).strict(),Xt=W.extend({revision:u().int().positive()}).strict(),bn=c({id:T,path:i().trim().min(1).max(E$).refine(O$),contentHash:H,sizeBytes:u().int().nonnegative().max(sw),mediaType:i().trim().min(1).max(200),visibility:v(["policy","verifier","host_private"])}).strict(),Ma=c({id:T,contentHash:H,mediaType:i().trim().min(1).max(200).nullable().default(null),sizeBytes:u().int().nonnegative().max(sw).nullable().default(null)}).strict(),Wc=v(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]);function M$(e){return`${JSON.stringify(cg(e),null,2)}
|
|
72
|
-
`}function wv(e){return T$(e)}function ct(e){return wv(M$(e))}function j$(e,t){const{contentHash:n,...a}=e,o=ct(a);if(n!==o)throw new Error(`${t} contentHash is ${n}; expected ${o}.`)}function O$(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function cg(e){return Array.isArray(e)?e.map(cg):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,cg(n)]))}const Am=c({provider:T,model:T,revision:i().trim().min(1).max(500).nullable().default(null),artifactHash:H.nullable().default(null),tokenizerRevision:i().trim().min(1).max(500).nullable().default(null),chatTemplateHash:H.nullable().default(null)}).strict(),Iv=["openpond","codex","claude-code","grok-build","opencode","anthropic","openai","xai","google","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],Nr=v(Iv),Sn=c({providerId:Nr,modelId:i().trim().min(1).max(300)}),Tm=v(["active","preview","planned","deprecated"]),lw=v(["openpond-account","openpond-managed","codex-login","native-agent-login","chatgpt-subscription","local-byok","hosted-byok","custom"]),$$=v(["none","local_secret","env","openpond_account","codex_login","native_agent_login","chatgpt_subscription","hosted"]),j0=c({connected:I().default(!1),source:$$.default("none"),redacted:i().nullable().default(null),lastValidatedAt:i().nullable().default(null),lastError:i().nullable().default(null)}),dg=c({hostedOpChat:I().default(!1),localRuntime:I().default(!0),localByok:I().default(!1),hostedByok:I().default(!1)}),N$=v(["hosted","provider","manual","none"]),ug=c({chatCompletions:I().default(!0),streaming:I().default(!0),modelDiscovery:N$.default("none"),toolCalling:I().default(!1),reasoning:I().default(!1),imageInput:I().default(!1),structuredOutput:I().default(!1)}),D$=v(["hosted","provider","curated","manual","cache"]),mg=c({streaming:I().default(!0),toolCalling:I().default(!1),reasoning:I().default(!1),reasoningEfforts:p(v(["off","low","medium","high","xhigh","max"])).default([]),vision:I().default(!1),structuredOutput:I().default(!1)}),H$=c({id:i().trim().min(1).max(300),providerId:Nr,displayName:i().trim().min(1).max(300),contextWindow:u().int().positive().nullable().default(null),outputLimit:u().int().positive().nullable().default(null),lifecycleStatus:Tm.default("active"),source:D$,capabilities:mg.default(()=>mg.parse({})),raw:le(i(),ce()).optional()}),L$=c({providerId:Nr,models:p(H$).default([]),fetchedAt:i().nullable().default(null),lastError:i().nullable().default(null),source:v(["none","hosted","provider","curated","manual"]).default("none")}),q$=c({nativeMode:i().max(200).nullable().default(null),nativeOptions:le(i().max(200),i().max(300)).default({}),binaryPath:i().trim().min(1).max(4096).nullable().default(null),sourceHome:i().trim().min(1).max(4096).nullable().default(null),enabled:I().default(!1),baseUrl:i().trim().min(1).max(2048).nullable().default(null),defaultModel:i().trim().min(1).max(300).nullable().default(null),modelOverrides:p(i().trim().min(1).max(300)).max(500).default([]),updatedAt:i().nullable().default(null)}),U$=c({nativeMode:i().max(200).nullable().optional(),nativeOptions:le(i().max(200),i().max(300)).optional(),binaryPath:i().trim().min(1).max(4096).nullable().optional(),sourceHome:i().trim().min(1).max(4096).nullable().optional(),enabled:I().optional(),baseUrl:i().trim().min(1).max(2048).nullable().optional(),defaultModel:i().trim().min(1).max(300).nullable().optional(),modelOverrides:p(i().trim().min(1).max(300)).max(500).optional()}),z$=c({id:i().trim().min(1).max(300),displayName:i().trim().min(1).max(300),contextWindow:u().int().positive().nullable().optional(),outputLimit:u().int().positive().nullable().optional(),lifecycleStatus:Tm.optional(),capabilities:mg.partial().optional()}),B$=c({id:Nr,displayName:i().trim().min(1).max(160),lifecycleStatus:Tm.default("active"),credentialModes:p(lw).default([]),routing:dg,capabilities:ug,defaultEnabled:I().optional(),defaultBaseUrl:i().trim().min(1).max(2048).nullable().optional(),defaultModel:i().trim().min(1).max(300).nullable().optional(),modelCacheSource:v(["none","hosted","provider","curated","manual"]),models:p(z$).default([])});c({version:b(1).default(1),generatedAt:i().datetime(),providers:p(B$)});const F$=c({id:Nr,displayName:i().trim().min(1).max(160),lifecycleStatus:Tm.default("active"),credentialModes:p(lw).default([]),routing:dg.default(()=>dg.parse({})),capabilities:ug.default(()=>ug.parse({})),credential:j0.default(()=>j0.parse({})),enabled:I().default(!1),available:I().default(!1),defaultModel:i().trim().min(1).max(300).nullable().default(null),modelIds:p(i().trim().min(1).max(300)).max(1e3).default([]),lastError:i().nullable().default(null)}),O0=c({version:b(1).default(1),providers:le(i(),q$).default({}),statuses:le(i(),F$).default({}),modelCaches:le(i(),L$).default({}),updatedAt:i().nullable().default(null)});c({providers:le(i(),U$).optional()});c({source:v(["local_secret","env"]).default("local_secret"),value:i().min(1).max(2e4).optional(),envVar:i().trim().min(1).max(160).optional()}).superRefine((e,t)=>{e.source==="env"&&!e.envVar&&t.addIssue({code:"custom",path:["envVar"],message:"envVar is required when provider credential source is env."}),e.source==="local_secret"&&!e.value&&t.addIssue({code:"custom",path:["value"],message:"value is required when provider credential source is local_secret."})});c({source:v(["local_secret","env","chatgpt_subscription"]).optional()});c({modelId:i().trim().min(1).max(300).optional(),baseUrl:i().trim().min(1).max(2048).optional()});c({query:i().trim().max(200).optional(),refresh:I().default(!1),limit:u().int().positive().max(500).default(100)});c({query:i().trim().max(200).optional(),force:I().default(!1)});const V$=["coding","research","review","test","docs","planner","summarizer"];v(V$);const dl=i().trim().min(1).max(80).regex(/^[a-z][a-z0-9_-]*$/),cw=v(["none","worktree","copy_on_write"]),dw=v(["read_only","workspace_write","full_tools"]),uw=v(["disabled","parent_scoped"]),Em=v(["manual","balanced","proactive"]),K$=v(["queued","running","completed","failed","cancelled","needs_resume"]),mw=["subagent.started","subagent.reported","subagent.completed","subagent.progress","subagent.failed","subagent.cancelled","subagent.cleanup","subagent.workspace_retained","subagent.workspace_retention_expiring","subagent.archived","subagent.message"];v(mw);const W$=[{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"}],_v=c({id:dl,enabled:I().default(!0),modelRef:Sn.nullable().default(null),isolationMode:cw.default("none"),maxConcurrentRuns:u().int().min(1).max(16).default(1),toolPolicy:dw.default("read_only"),background:I().default(!0),peerMessages:uw.default("parent_scoped")}),xc=c({enabled:I().default(!0),workspaceDefaultsVersion:b(1).default(1),toolDefaultsVersion:b(1).default(1),delegationMode:Em.default("manual"),defaultModelRef:Sn.nullable().default(null),roles:p(_v).max(64).default(()=>hw()),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:iN(e.roles)})),sc=c({kind:v(["session","turn","file","diff","artifact"]),id:i().trim().min(1).max(500),label:i().trim().min(1).max(500)}),G$=c({kind:v(["retain_with_parent"]).default("retain_with_parent"),messageRetentionDays:u().int().min(1).max(3650).nullable().default(null),artifactRetentionDays:u().int().min(1).max(3650).nullable().default(null),cleanupAfterExpiry:I().default(!1)}).default(()=>({kind:"retain_with_parent",messageRetentionDays:null,artifactRetentionDays:null,cleanupAfterExpiry:!1})),J$=v(["orient","edit","validate","report"]),Z$=c({command:i().trim().min(1).max(2e3),status:v(["passed","failed","unknown"]).default("unknown"),exitCode:u().int().nullable().default(null),outputSummary:i().trim().max(5e3).nullable().default(null),startedAt:i().nullable().default(null),completedAt:i().nullable().default(null)}),Y$=c({phase:J$.default("orient"),inspectedFiles:p(i().trim().min(1).max(1e3)).max(500).default([]),inspectedResources:p(i().trim().min(1).max(1e3)).max(500).default([]),repeatedSearches:p(i().trim().min(1).max(1e3)).max(200).default([]),repeatedReads:p(i().trim().min(1).max(1e3)).max(200).default([]),repeatedCommands:p(i().trim().min(1).max(1e3)).max(200).default([]),changedFiles:p(i().trim().min(1).max(1e3)).max(500).default([]),patchRefs:p(sc).max(100).default([]),validationAttempts:p(Z$).max(100).default([]),latestMeaningfulActivity:i().trim().max(5e3).nullable().default(null),currentBlocker:i().trim().max(5e3).nullable().default(null),updatedAt:i().nullable().default(null)}).default(()=>({phase:"orient",inspectedFiles:[],inspectedResources:[],repeatedSearches:[],repeatedReads:[],repeatedCommands:[],changedFiles:[],patchRefs:[],validationAttempts:[],latestMeaningfulActivity:null,currentBlocker:null,updatedAt:null})),Q$=c({summary:i().trim().max(2e4).default(""),findings:p(i().trim().min(1).max(5e3)).max(200).default([]),artifacts:p(sc).max(200).default([]),patchRef:sc.nullable().default(null),diffRef:sc.nullable().default(null),testsRun:p(i().trim().min(1).max(2e3)).max(100).default([]),blockers:p(i().trim().min(1).max(5e3)).max(100).default([]),confidence:v(["low","medium","high"]).nullable().default(null),followUpNeeded:I().default(!1)}),pw=c({id:i().trim().min(1).max(200),parentSessionId:i().trim().min(1).max(200),parentTurnId:i().trim().min(1).max(200).nullable().default(null),childSessionId:i().trim().min(1).max(200).nullable().default(null),roleId:dl,objective:i().trim().min(1).max(5e4),modelRef:Sn.nullable().default(null),isolationMode:cw.default("none"),toolPolicy:dw.default("read_only"),background:I().default(!0),peerMessages:uw.default("parent_scoped"),status:K$.default("queued"),progress:Y$,evidenceRetention:G$,createdAt:i(),startedAt:i().nullable().default(null),completedAt:i().nullable().default(null),updatedAt:i().nullable().default(null),error:i().nullable().default(null),report:Q$.nullable().default(null),metadata:le(i(),ce()).optional().default({})}),fw=v(["cleanup","archive","cleanup_and_archive"]);c({action:fw,reason:i().trim().min(1).max(2e3).nullable().default(null)});c({action:fw,run:pw,workspaceCleanup:le(i(),ce()).nullable().default(null),sessionArchive:le(i(),ce()).nullable().default(null),nextStep:i()});const X$=v(["question","answer","handoff","artifact","status","blocker"]),eN=v(["normal","interrupt"]),tN=c({inputIds:p(i()).default([]),status:v(["pending","delivered","undelivered"]).default("pending"),deliveredRunIds:p(i().trim().min(1).max(200)).max(200).default([]),acknowledgedRunIds:p(i().trim().min(1).max(200)).max(200).default([]),deliveredParentSessionId:i().trim().min(1).max(200).nullable().default(null),acknowledgedParentSessionId:i().trim().min(1).max(200).nullable().default(null),wakeRequestedParentSessionId:i().trim().min(1).max(200).nullable().default(null),wakeQueuedParentSessionId:i().trim().min(1).max(200).nullable().default(null),wakeDeferredParentSessionId:i().trim().min(1).max(200).nullable().default(null),wakeParentReason:i().trim().min(1).max(1e3).nullable().default(null),wakeRequestedRunIds:p(i().trim().min(1).max(200)).max(200).default([]),wakeInterruptedRunIds:p(i().trim().min(1).max(200)).max(200).default([]),wakeDeferredRunIds:p(i().trim().min(1).max(200)).max(200).default([]),reason:i().trim().min(1).max(1e3).nullable().default(null)}),nN=c({id:i().trim().min(1).max(200),fromRunId:i().trim().min(1).max(200),toRunId:i().trim().min(1).max(200).nullable().default(null),toRole:dl.nullable().default(null),kind:X$,priority:eN.optional(),body:i().trim().min(1).max(5e4),refs:p(sc).max(100).default([]),delivery:tN.optional(),createdAt:i()});function hw(){return W$.map(e=>_v.parse({id:e.id,toolPolicy:e.defaultToolPolicy}))}function aN(){return xc.parse({})}function iN(e){const t=hw(),n=new Map(t.map(o=>[o.id,o])),a=[];for(const o of e??[]){const r=_v.parse(o);n.has(r.id)?n.set(r.id,r):a.push(r)}return[...t.map(o=>n.get(o.id)??o),...a]}const oN=v(["task.inbox","task.input","task.wait","session.started","session.updated","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",...mw,"diagnostic"]),$0=c({id:i(),sequence:u().int().positive().optional(),sessionId:i().optional(),turnId:i().optional(),name:oN,timestamp:i(),source:v(["ui_button","chat_action","terminal_command","hook","provider","server"]).optional(),action:i().optional(),appId:i().nullable().optional(),args:le(i(),ce()).optional(),status:v(["started","completed","failed","pending"]).optional(),output:i().optional(),error:i().optional(),relatedDeploymentId:i().optional(),data:ce().optional()}),rN=c({id:i().trim().min(1).max(80),label:i().trim().min(1).max(160),description:i().trim().max(500).nullable().optional().default(null)}),sN=c({id:i().trim().min(1),sessionId:i().trim().min(1),turnId:i().trim().min(1),toolCallId:i().trim().min(1),question:i().trim().min(1).max(2e3),reason:i().trim().max(1e3).nullable().optional().default(null),options:p(rN).max(5).default([]),allowFreeform:I().default(!0),status:v(["pending","answered","dismissed"]),answer:c({optionId:i().trim().min(1).nullable(),text:i().max(4e3)}).nullable(),createdAt:i(),answeredAt:i().nullable()}),lN=c({questionId:i().trim().min(1),action:v(["answer","dismiss"]),optionId:i().trim().min(1).nullable().optional().default(null),text:i().trim().max(4e3).optional().default("")});c({kind:v(["session","project","draft"]),id:i().trim().min(1).max(300)});v(["unknown","idle","running","success","failed"]);v(["none","idle","running","success","failed","unknown"]);function cN(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Zn={},Gd={},Mo={},N0;function Gc(){if(N0)return Mo;N0=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,f=m.length;d<f;d+=1){const g=m[d];s[g]=l[g]}}return s}function o(s,l){let m="";for(let d=0;d<l;d+=1)m+=s;return m}function r(s){return s===0&&Number.NEGATIVE_INFINITY===1/s}return Mo.isNothing=e,Mo.isObject=t,Mo.toArray=n,Mo.repeat=o,Mo.isNegativeZero=r,Mo.extend=a,Mo}var Nf,D0;function Jc(){if(D0)return Nf;D0=1;function e(n,a){let o="";const r=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+=`
|
|
73
|
-
|
|
74
|
-
`+n.mark.snippet),r+" "+o):r}function t(n,a){Error.call(this),this.name="YAMLException",this.reason=n,this.mark=a,this.message=e(this,!1),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||""}return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t.prototype.toString=function(a){return this.name+": "+e(this,a)},Nf=t,Nf}var Df,H0;function dN(){if(H0)return Df;H0=1;const e=Gc();function t(o,r,s,l,m){let d="",f="";const g=Math.floor(m/2)-1;return l-r>g&&(d=" ... ",r=l-g+d.length),s-l>g&&(f=" ...",s=l+g-f.length),{str:d+o.slice(r,s).replace(/\t/g,"→")+f,pos:l-r+d.length}}function n(o,r){return e.repeat(" ",r-o.length)+o}function a(o,r){if(r=Object.create(r||null),!o.buffer)return null;r.maxLength||(r.maxLength=79),typeof r.indent!="number"&&(r.indent=1),typeof r.linesBefore!="number"&&(r.linesBefore=3),typeof r.linesAfter!="number"&&(r.linesAfter=2);const s=/\r?\n|\r|\0/g,l=[0],m=[];let d,f=-1;for(;d=s.exec(o.buffer);)m.push(d.index),l.push(d.index+d[0].length),o.position<=d.index&&f<0&&(f=l.length-2);f<0&&(f=l.length-1);let g="";const x=Math.min(o.line+r.linesAfter,m.length).toString().length,k=r.maxLength-(r.indent+x+3);for(let R=1;R<=r.linesBefore&&!(f-R<0);R++){const E=t(o.buffer,l[f-R],m[f-R],o.position-(l[f]-l[f-R]),k);g=e.repeat(" ",r.indent)+n((o.line-R+1).toString(),x)+" | "+E.str+`
|
|
75
|
-
`+g}const C=t(o.buffer,l[f],m[f],o.position,k);g+=e.repeat(" ",r.indent)+n((o.line+1).toString(),x)+" | "+C.str+`
|
|
76
|
-
`,g+=e.repeat("-",r.indent+x+3+C.pos)+`^
|
|
77
|
-
`;for(let R=1;R<=r.linesAfter&&!(f+R>=m.length);R++){const E=t(o.buffer,l[f+R],m[f+R],o.position-(l[f]-l[f+R]),k);g+=e.repeat(" ",r.indent)+n((o.line+R+1).toString(),x)+" | "+E.str+`
|
|
78
|
-
`}return g.replace(/\n$/,"")}return Df=a,Df}var Hf,L0;function ca(){if(L0)return Hf;L0=1;const e=Jc(),t=["kind","multi","resolve","construct","instanceOf","predicate","represent","representName","defaultStyle","styleAliases"],n=["scalar","sequence","mapping"];function a(r){const s={};return r!==null&&Object.keys(r).forEach(function(l){r[l].forEach(function(m){s[String(m)]=l})}),s}function o(r,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 "'+r+'" YAML type.')}),this.options=s,this.tag=r,this.kind=s.kind||null,this.resolve=s.resolve||function(){return!0},this.construct=s.construct||function(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 "'+r+'" YAML type.')}return Hf=o,Hf}var Lf,q0;function gw(){if(q0)return Lf;q0=1;const e=Jc(),t=ca();function n(r,s){const l=[];return r[s].forEach(function(m){let d=l.length;l.forEach(function(f,g){f.tag===m.tag&&f.kind===m.kind&&f.multi===m.multi&&(d=g)}),l[d]=m}),l}function a(){const r={scalar:{},sequence:{},mapping:{},fallback:{},multi:{scalar:[],sequence:[],mapping:[],fallback:[]}};function s(l){l.multi?(r.multi[l.kind].push(l),r.multi.fallback.push(l)):r[l.kind][l.tag]=r.fallback[l.tag]=l}for(let l=0,m=arguments.length;l<m;l+=1)arguments[l].forEach(s);return r}function o(r){return this.extend(r)}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(f){if(!(f instanceof t))throw new e("Specified list of YAML types (or a single Type object) contains a non-Type object.");if(f.loadKind&&f.loadKind!=="scalar")throw new e("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");if(f.multi)throw new e("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.")}),m.forEach(function(f){if(!(f instanceof t))throw new e("Specified list of YAML types (or a single Type object) contains a non-Type object.")});const 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},Lf=o,Lf}var qf,U0;function vw(){if(U0)return qf;U0=1;const e=ca();return qf=new e("tag:yaml.org,2002:str",{kind:"scalar",construct:function(t){return t!==null?t:""}}),qf}var Uf,z0;function bw(){if(z0)return Uf;z0=1;const e=ca();return Uf=new e("tag:yaml.org,2002:seq",{kind:"sequence",construct:function(t){return t!==null?t:[]}}),Uf}var zf,B0;function yw(){if(B0)return zf;B0=1;const e=ca();return zf=new e("tag:yaml.org,2002:map",{kind:"mapping",construct:function(t){return t!==null?t:{}}}),zf}var Bf,F0;function Sw(){if(F0)return Bf;F0=1;const e=gw();return Bf=new e({explicit:[vw(),bw(),yw()]}),Bf}var Ff,V0;function xw(){if(V0)return Ff;V0=1;const e=ca();function t(o){if(o===null)return!0;const r=o.length;return r===1&&o==="~"||r===4&&(o==="null"||o==="Null"||o==="NULL")}function n(){return null}function a(o){return o===null}return Ff=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"}),Ff}var Vf,K0;function kw(){if(K0)return Vf;K0=1;const e=ca();function t(o){if(o===null)return!1;const r=o.length;return r===4&&(o==="true"||o==="True"||o==="TRUE")||r===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 Vf=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"}),Vf}var Kf,W0;function ww(){if(W0)return Kf;W0=1;const e=Gc(),t=ca();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 r(d){if(d===null)return!1;const f=d.length;let g=0,x=!1;if(!f)return!1;let k=d[g];if((k==="-"||k==="+")&&(k=d[++g]),k==="0"){if(g+1===f)return!0;if(k=d[++g],k==="b"){for(g++;g<f;g++){if(k=d[g],k!=="0"&&k!=="1")return!1;x=!0}return x&&isFinite(s(d))}if(k==="x"){for(g++;g<f;g++){if(!n(d.charCodeAt(g)))return!1;x=!0}return x&&isFinite(s(d))}if(k==="o"){for(g++;g<f;g++){if(!a(d.charCodeAt(g)))return!1;x=!0}return x&&isFinite(s(d))}}for(;g<f;g++){if(!o(d.charCodeAt(g)))return!1;x=!0}return x?isFinite(s(d)):!1}function s(d){let f=d,g=1,x=f[0];if((x==="-"||x==="+")&&(x==="-"&&(g=-1),f=f.slice(1),x=f[0]),f==="0")return 0;if(x==="0"){if(f[1]==="b")return g*parseInt(f.slice(2),2);if(f[1]==="x")return g*parseInt(f.slice(2),16);if(f[1]==="o")return g*parseInt(f.slice(2),8)}return g*parseInt(f,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 Kf=new t("tag:yaml.org,2002:int",{kind:"scalar",resolve:r,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"]}}),Kf}var Wf,G0;function Iw(){if(G0)return Wf;G0=1;const e=Gc(),t=ca(),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 r(d){let f=d.toLowerCase();const g=f[0]==="-"?-1:1;return"+-".indexOf(f[0])>=0&&(f=f.slice(1)),f===".inf"?g===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:f===".nan"?NaN:g*parseFloat(f,10)}const s=/^[-+]?[0-9]+e/;function l(d,f){if(isNaN(d))switch(f){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===d)switch(f){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===d)switch(f){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(e.isNegativeZero(d))return"-0.0";const g=d.toString(10);return s.test(g)?g.replace("e",".e"):g}function m(d){return Object.prototype.toString.call(d)==="[object Number]"&&(d%1!==0||e.isNegativeZero(d))}return Wf=new t("tag:yaml.org,2002:float",{kind:"scalar",resolve:o,construct:r,predicate:m,represent:l,defaultStyle:"lowercase"}),Wf}var Gf,J0;function _w(){return J0||(J0=1,Gf=Sw().extend({implicit:[xw(),kw(),ww(),Iw()]})),Gf}var Jf,Z0;function Cw(){return Z0||(Z0=1,Jf=_w()),Jf}var Zf,Y0;function Rw(){if(Y0)return Zf;Y0=1;const e=ca(),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 f=+d[1],g=+d[2]-1,x=+d[3];if(!d[4])return new Date(Date.UTC(f,g,x));const k=+d[4],C=+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 A=+d[10],O=+(d[11]||0);m=(A*60+O)*6e4,d[9]==="-"&&(m=-m)}const E=new Date(Date.UTC(f,g,x,k,C,R,l));return m&&E.setTime(E.getTime()-m),E}function r(s){return s.toISOString()}return Zf=new e("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:a,construct:o,instanceOf:Date,represent:r}),Zf}var Yf,Q0;function Pw(){if(Q0)return Yf;Q0=1;const e=ca();function t(n){return n==="<<"||n===null}return Yf=new e("tag:yaml.org,2002:merge",{kind:"scalar",resolve:t}),Yf}var Qf,X0;function Aw(){if(X0)return Qf;X0=1;const e=ca(),t=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
|
|
79
|
-
\r`;function n(s){if(s===null)return!1;let l=0;const m=s.length,d=t;for(let f=0;f<m;f++){const g=d.indexOf(s.charAt(f));if(!(g>64)){if(g<0)return!1;l+=6}}return l%8===0}function a(s){const l=s.replace(/[\r\n=]/g,""),m=l.length,d=t;let f=0;const g=[];for(let k=0;k<m;k++)k%4===0&&k&&(g.push(f>>16&255),g.push(f>>8&255),g.push(f&255)),f=f<<6|d.indexOf(l.charAt(k));const x=m%4*6;return x===0?(g.push(f>>16&255),g.push(f>>8&255),g.push(f&255)):x===18?(g.push(f>>10&255),g.push(f>>2&255)):x===12&&g.push(f>>4&255),new Uint8Array(g)}function o(s){let l="",m=0;const d=s.length,f=t;for(let x=0;x<d;x++)x%3===0&&x&&(l+=f[m>>18&63],l+=f[m>>12&63],l+=f[m>>6&63],l+=f[m&63]),m=(m<<8)+s[x];const g=d%3;return g===0?(l+=f[m>>18&63],l+=f[m>>12&63],l+=f[m>>6&63],l+=f[m&63]):g===2?(l+=f[m>>10&63],l+=f[m>>4&63],l+=f[m<<2&63],l+=f[64]):g===1&&(l+=f[m>>2&63],l+=f[m<<4&63],l+=f[64],l+=f[64]),l}function r(s){return Object.prototype.toString.call(s)==="[object Uint8Array]"}return Qf=new e("tag:yaml.org,2002:binary",{kind:"scalar",resolve:n,construct:a,predicate:r,represent:o}),Qf}var Xf,eS;function Tw(){if(eS)return Xf;eS=1;const e=ca(),t=Object.prototype.hasOwnProperty,n=Object.prototype.toString;function a(r){if(r===null)return!0;const s=[],l=r;for(let m=0,d=l.length;m<d;m+=1){const f=l[m];let g=!1;if(n.call(f)!=="[object Object]")return!1;let x;for(x in f)if(t.call(f,x))if(!g)g=!0;else return!1;if(!g)return!1;if(s.indexOf(x)===-1)s.push(x);else return!1}return!0}function o(r){return r!==null?r:[]}return Xf=new e("tag:yaml.org,2002:omap",{kind:"sequence",resolve:a,construct:o}),Xf}var eh,tS;function Ew(){if(tS)return eh;tS=1;const e=ca(),t=Object.prototype.toString;function n(o){if(o===null)return!0;const r=o,s=new Array(r.length);for(let l=0,m=r.length;l<m;l+=1){const d=r[l];if(t.call(d)!=="[object Object]")return!1;const f=Object.keys(d);if(f.length!==1)return!1;s[l]=[f[0],d[f[0]]]}return!0}function a(o){if(o===null)return[];const r=o,s=new Array(r.length);for(let l=0,m=r.length;l<m;l+=1){const d=r[l],f=Object.keys(d);s[l]=[f[0],d[f[0]]]}return s}return eh=new e("tag:yaml.org,2002:pairs",{kind:"sequence",resolve:n,construct:a}),eh}var th,nS;function Mw(){if(nS)return th;nS=1;const e=ca(),t=Object.prototype.hasOwnProperty;function n(o){if(o===null)return!0;const r=o;for(const s in r)if(t.call(r,s)&&r[s]!==null)return!1;return!0}function a(o){return o!==null?o:{}}return th=new e("tag:yaml.org,2002:set",{kind:"mapping",resolve:n,construct:a}),th}var nh,aS;function Cv(){return aS||(aS=1,nh=Cw().extend({implicit:[Rw(),Pw()],explicit:[Aw(),Tw(),Ew(),Mw()]})),nh}var iS;function uN(){if(iS)return Gd;iS=1;const e=Gc(),t=Jc(),n=dN(),a=Cv(),o=Object.prototype.hasOwnProperty,r=1,s=2,l=3,m=4,d=1,f=2,g=3,x=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,k=/[\x85\u2028\u2029]/,C=/[,\[\]{}]/,R=/^(?:!|!!|![0-9A-Za-z-]+!)$/,E=/^(?:!|[^,\[\]{}])(?:%[0-9a-f]{2}|[0-9a-z\-#;/?:@&=+$,_.!~*'()\[\]])*$/i;function A(h){return Object.prototype.toString.call(h)}function O(h){return h===10||h===13}function $(h){return h===9||h===32}function M(h){return h===9||h===32||h===10||h===13}function w(h){return h===44||h===91||h===93||h===123||h===125}function P(h){if(h>=48&&h<=57)return h-48;const V=h|32;return V>=97&&V<=102?V-97+10:-1}function j(h){return h===120?2:h===117?4:h===85?8:0}function N(h){return h>=48&&h<=57?h-48:-1}function z(h){switch(h){case 48:return"\0";case 97:return"\x07";case 98:return"\b";case 116:return" ";case 9:return" ";case 110:return`
|
|
80
|
-
`;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(h){return h<=65535?String.fromCharCode(h):String.fromCharCode((h-65536>>10)+55296,(h-65536&1023)+56320)}function F(h,V,ae){V==="__proto__"?Object.defineProperty(h,V,{configurable:!0,enumerable:!0,writable:!0,value:ae}):h[V]=ae}const te=new Array(256),ve=new Array(256);for(let h=0;h<256;h++)te[h]=z(h)?1:0,ve[h]=z(h);function re(h,V){this.input=h,this.filename=V.filename||null,this.schema=V.schema||a,this.onWarning=V.onWarning||null,this.legacy=V.legacy||!1,this.json=V.json||!1,this.listener=V.listener||null,this.maxDepth=typeof V.maxDepth=="number"?V.maxDepth:100,this.maxTotalMergeKeys=typeof V.maxTotalMergeKeys=="number"?V.maxTotalMergeKeys:1e4,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=h.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 K(h,V){const ae={name:h.filename,buffer:h.input.slice(0,-1),position:h.position,line:h.line,column:h.position-h.lineStart};return ae.snippet=n(ae),new t(V,ae)}function L(h,V){throw K(h,V)}function de(h,V){h.onWarning&&h.onWarning.call(null,K(h,V))}function X(h,V,ae){const we=h.anchorMapTransactions;if(we.length!==0){const fe=we[we.length-1];o.call(fe,V)||(fe[V]={existed:o.call(h.anchorMap,V),value:h.anchorMap[V]})}h.anchorMap[V]=ae}function Z(h){h.anchorMapTransactions.push(Object.create(null))}function pe(h){const V=h.anchorMapTransactions.pop(),ae=h.anchorMapTransactions;if(ae.length===0)return;const we=ae[ae.length-1],fe=Object.keys(V);for(let Y=0,_=fe.length;Y<_;Y+=1){const G=fe[Y];o.call(we,G)||(we[G]=V[G])}}function ee(h){const V=h.anchorMapTransactions.pop(),ae=Object.keys(V);for(let we=ae.length-1;we>=0;we-=1){const fe=V[ae[we]];fe.existed?h.anchorMap[ae[we]]=fe.value:delete h.anchorMap[ae[we]]}}function me(h){return{position:h.position,line:h.line,lineStart:h.lineStart,lineIndent:h.lineIndent,firstTabInLine:h.firstTabInLine,tag:h.tag,anchor:h.anchor,kind:h.kind,result:h.result}}function be(h,V){h.position=V.position,h.line=V.line,h.lineStart=V.lineStart,h.lineIndent=V.lineIndent,h.firstTabInLine=V.firstTabInLine,h.tag=V.tag,h.anchor=V.anchor,h.kind=V.kind,h.result=V.result}const je={YAML:function(V,ae,we){V.version!==null&&L(V,"duplication of %YAML directive"),we.length!==1&&L(V,"YAML directive accepts exactly one argument");const fe=/^([0-9]+)\.([0-9]+)$/.exec(we[0]);fe===null&&L(V,"ill-formed argument of the YAML directive");const Y=parseInt(fe[1],10),_=parseInt(fe[2],10);Y!==1&&L(V,"unacceptable YAML version of the document"),V.version=we[0],V.checkLineBreaks=_<2,_!==1&&_!==2&&de(V,"unsupported YAML version of the document")},TAG:function(V,ae,we){let fe;we.length!==2&&L(V,"TAG directive accepts exactly two arguments");const Y=we[0];fe=we[1],R.test(Y)||L(V,"ill-formed tag handle (first argument) of the TAG directive"),o.call(V.tagMap,Y)&&L(V,'there is a previously declared suffix for "'+Y+'" tag handle'),E.test(fe)||L(V,"ill-formed tag prefix (second argument) of the TAG directive");try{fe=decodeURIComponent(fe)}catch{L(V,"tag prefix is malformed: "+fe)}V.tagMap[Y]=fe}};function ke(h,V,ae,we){if(V<ae){const fe=h.input.slice(V,ae);if(we)for(let Y=0,_=fe.length;Y<_;Y+=1){const G=fe.charCodeAt(Y);G===9||G>=32&&G<=1114111||L(h,"expected valid JSON character")}else x.test(fe)&&L(h,"the stream contains non-printable characters");h.result+=fe}}function ue(h,V,ae,we){e.isObject(ae)||L(h,"cannot merge mappings; the provided source object is unacceptable");const fe=Object.keys(ae);for(let Y=0,_=fe.length;Y<_;Y+=1){const G=fe[Y];h.maxTotalMergeKeys!==-1&&++h.totalMergeKeys>h.maxTotalMergeKeys&&L(h,"merge keys exceeded maxTotalMergeKeys ("+h.maxTotalMergeKeys+")"),o.call(V,G)||(F(V,G,ae[G]),we[G]=!0)}}function Ie(h,V,ae,we,fe,Y,_,G,se){if(Array.isArray(fe)){fe=Array.prototype.slice.call(fe);for(let ne=0,ge=fe.length;ne<ge;ne+=1)Array.isArray(fe[ne])&&L(h,"nested arrays are not supported inside keys"),typeof fe=="object"&&A(fe[ne])==="[object Object]"&&(fe[ne]="[object Object]")}if(typeof fe=="object"&&A(fe)==="[object Object]"&&(fe="[object Object]"),fe=String(fe),V===null&&(V={}),we==="tag:yaml.org,2002:merge")if(Array.isArray(Y))for(let ne=0,ge=Y.length;ne<ge;ne+=1)ue(h,V,Y[ne],ae);else ue(h,V,Y,ae);else!h.json&&!o.call(ae,fe)&&o.call(V,fe)&&(h.line=_||h.line,h.lineStart=G||h.lineStart,h.position=se||h.position,L(h,"duplicated mapping key")),F(V,fe,Y),delete ae[fe];return V}function Le(h){const V=h.input.charCodeAt(h.position);V===10?h.position++:V===13?(h.position++,h.input.charCodeAt(h.position)===10&&h.position++):L(h,"a line break is expected"),h.line+=1,h.lineStart=h.position,h.firstTabInLine=-1}function Fe(h,V,ae){let we=0,fe=h.input.charCodeAt(h.position);for(;fe!==0;){for(;$(fe);)fe===9&&h.firstTabInLine===-1&&(h.firstTabInLine=h.position),fe=h.input.charCodeAt(++h.position);if(V&&fe===35)do fe=h.input.charCodeAt(++h.position);while(fe!==10&&fe!==13&&fe!==0);if(O(fe))for(Le(h),fe=h.input.charCodeAt(h.position),we++,h.lineIndent=0;fe===32;)h.lineIndent++,fe=h.input.charCodeAt(++h.position);else break}return ae!==-1&&we!==0&&h.lineIndent<ae&&de(h,"deficient indentation"),we}function Xe(h){let V=h.position,ae=h.input.charCodeAt(V);return!!((ae===45||ae===46)&&ae===h.input.charCodeAt(V+1)&&ae===h.input.charCodeAt(V+2)&&(V+=3,ae=h.input.charCodeAt(V),ae===0||M(ae)))}function Ze(h,V){V===1?h.result+=" ":V>1&&(h.result+=e.repeat(`
|
|
81
|
-
`,V-1))}function Be(h,V,ae){let we,fe,Y,_,G,se;const ne=h.kind,ge=h.result;let Se=h.input.charCodeAt(h.position);if(M(Se)||w(Se)||Se===35||Se===38||Se===42||Se===33||Se===124||Se===62||Se===39||Se===34||Se===37||Se===64||Se===96)return!1;if(Se===63||Se===45){const xe=h.input.charCodeAt(h.position+1);if(M(xe)||ae&&w(xe))return!1}for(h.kind="scalar",h.result="",we=fe=h.position,Y=!1;Se!==0;){if(Se===58){const xe=h.input.charCodeAt(h.position+1);if(M(xe)||ae&&w(xe))break}else if(Se===35){const xe=h.input.charCodeAt(h.position-1);if(M(xe))break}else{if(h.position===h.lineStart&&Xe(h)||ae&&w(Se))break;if(O(Se))if(_=h.line,G=h.lineStart,se=h.lineIndent,Fe(h,!1,-1),h.lineIndent>=V){Y=!0,Se=h.input.charCodeAt(h.position);continue}else{h.position=fe,h.line=_,h.lineStart=G,h.lineIndent=se;break}}Y&&(ke(h,we,fe,!1),Ze(h,h.line-_),we=fe=h.position,Y=!1),$(Se)||(fe=h.position+1),Se=h.input.charCodeAt(++h.position)}return ke(h,we,fe,!1),h.result?!0:(h.kind=ne,h.result=ge,!1)}function Ge(h,V){let ae,we,fe=h.input.charCodeAt(h.position);if(fe!==39)return!1;for(h.kind="scalar",h.result="",h.position++,ae=we=h.position;(fe=h.input.charCodeAt(h.position))!==0;)if(fe===39)if(ke(h,ae,h.position,!0),fe=h.input.charCodeAt(++h.position),fe===39)ae=h.position,h.position++,we=h.position;else return!0;else O(fe)?(ke(h,ae,we,!0),Ze(h,Fe(h,!1,V)),ae=we=h.position):h.position===h.lineStart&&Xe(h)?L(h,"unexpected end of the document within a single quoted scalar"):(h.position++,$(fe)||(we=h.position));L(h,"unexpected end of the stream within a single quoted scalar")}function Ve(h,V){let ae,we,fe,Y=h.input.charCodeAt(h.position);if(Y!==34)return!1;for(h.kind="scalar",h.result="",h.position++,ae=we=h.position;(Y=h.input.charCodeAt(h.position))!==0;){if(Y===34)return ke(h,ae,h.position,!0),h.position++,!0;if(Y===92){if(ke(h,ae,h.position,!0),Y=h.input.charCodeAt(++h.position),O(Y))Fe(h,!1,V);else if(Y<256&&te[Y])h.result+=ve[Y],h.position++;else if((fe=j(Y))>0){let _=fe,G=0;for(;_>0;_--)Y=h.input.charCodeAt(++h.position),(fe=P(Y))>=0?G=(G<<4)+fe:L(h,"expected hexadecimal character");h.result+=D(G),h.position++}else L(h,"unknown escape sequence");ae=we=h.position}else O(Y)?(ke(h,ae,we,!0),Ze(h,Fe(h,!1,V)),ae=we=h.position):h.position===h.lineStart&&Xe(h)?L(h,"unexpected end of the document within a double quoted scalar"):(h.position++,$(Y)||(we=h.position))}L(h,"unexpected end of the stream within a double quoted scalar")}function U(h,V){let ae=!0,we,fe,Y;const _=h.tag;let G;const se=h.anchor;let ne,ge,Se,xe;const Oe=Object.create(null);let Te,Ue,Ee,tt=h.input.charCodeAt(h.position);if(tt===91)ne=93,xe=!1,G=[];else if(tt===123)ne=125,xe=!0,G={};else return!1;for(h.anchor!==null&&X(h,h.anchor,G),tt=h.input.charCodeAt(++h.position);tt!==0;){if(Fe(h,!0,V),tt=h.input.charCodeAt(h.position),tt===ne)return h.position++,h.tag=_,h.anchor=se,h.kind=xe?"mapping":"sequence",h.result=G,!0;if(ae?tt===44&&L(h,"expected the node content, but found ','"):L(h,"missed comma between flow collection entries"),Ue=Te=Ee=null,ge=Se=!1,tt===63){const ht=h.input.charCodeAt(h.position+1);M(ht)&&(ge=Se=!0,h.position++,Fe(h,!0,V))}we=h.line,fe=h.lineStart,Y=h.position,et(h,V,r,!1,!0),Ue=h.tag,Te=h.result,Fe(h,!0,V),tt=h.input.charCodeAt(h.position),(Se||h.line===we)&&tt===58&&(ge=!0,tt=h.input.charCodeAt(++h.position),Fe(h,!0,V),et(h,V,r,!1,!0),Ee=h.result),xe?Ie(h,G,Oe,Ue,Te,Ee,we,fe,Y):ge?G.push(Ie(h,null,Oe,Ue,Te,Ee,we,fe,Y)):G.push(Te),Fe(h,!0,V),tt=h.input.charCodeAt(h.position),tt===44?(ae=!0,tt=h.input.charCodeAt(++h.position)):ae=!1}L(h,"unexpected end of the stream within a flow collection")}function J(h,V){let ae,we=d,fe=!1,Y=!1,_=V,G=0,se=!1,ne,ge=h.input.charCodeAt(h.position);if(ge===124)ae=!1;else if(ge===62)ae=!0;else return!1;for(h.kind="scalar",h.result="";ge!==0;)if(ge=h.input.charCodeAt(++h.position),ge===43||ge===45)d===we?we=ge===43?g:f:L(h,"repeat of a chomping mode identifier");else if((ne=N(ge))>=0)ne===0?L(h,"bad explicit indentation width of a block scalar; it cannot be less than one"):Y?L(h,"repeat of an indentation width identifier"):(_=V+ne-1,Y=!0);else break;if($(ge)){do ge=h.input.charCodeAt(++h.position);while($(ge));if(ge===35)do ge=h.input.charCodeAt(++h.position);while(!O(ge)&&ge!==0)}for(;ge!==0;){for(Le(h),h.lineIndent=0,ge=h.input.charCodeAt(h.position);(!Y||h.lineIndent<_)&&ge===32;)h.lineIndent++,ge=h.input.charCodeAt(++h.position);if(!Y&&h.lineIndent>_&&(_=h.lineIndent),O(ge)){G++;continue}if(!Y&&_===0&&L(h,"missing indentation for block scalar"),h.lineIndent<_){we===g?h.result+=e.repeat(`
|
|
82
|
-
`,fe?1+G:G):we===d&&fe&&(h.result+=`
|
|
83
|
-
`);break}ae?$(ge)?(se=!0,h.result+=e.repeat(`
|
|
84
|
-
`,fe?1+G:G)):se?(se=!1,h.result+=e.repeat(`
|
|
85
|
-
`,G+1)):G===0?fe&&(h.result+=" "):h.result+=e.repeat(`
|
|
86
|
-
`,G):h.result+=e.repeat(`
|
|
87
|
-
`,fe?1+G:G),fe=!0,Y=!0,G=0;const Se=h.position;for(;!O(ge)&&ge!==0;)ge=h.input.charCodeAt(++h.position);ke(h,Se,h.position,!1)}return!0}function q(h,V){const ae=h.tag,we=h.anchor,fe=[];let Y=!1;if(h.firstTabInLine!==-1)return!1;h.anchor!==null&&X(h,h.anchor,fe);let _=h.input.charCodeAt(h.position);for(;_!==0&&(h.firstTabInLine!==-1&&(h.position=h.firstTabInLine,L(h,"tab characters must not be used in indentation")),_===45);){const G=h.input.charCodeAt(h.position+1);if(!M(G))break;if(Y=!0,h.position++,Fe(h,!0,-1)&&h.lineIndent<=V){fe.push(null),_=h.input.charCodeAt(h.position);continue}const se=h.line;if(et(h,V,l,!1,!0),fe.push(h.result),Fe(h,!0,-1),_=h.input.charCodeAt(h.position),(h.line===se||h.lineIndent>V)&&_!==0)L(h,"bad indentation of a sequence entry");else if(h.lineIndent<V)break}return Y?(h.tag=ae,h.anchor=we,h.kind="sequence",h.result=fe,!0):!1}function oe(h,V,ae){let we,fe,Y,_;const G=h.tag,se=h.anchor,ne={},ge=Object.create(null);let Se=null,xe=null,Oe=null,Te=!1,Ue=!1;if(h.firstTabInLine!==-1)return!1;h.anchor!==null&&X(h,h.anchor,ne);let Ee=h.input.charCodeAt(h.position);for(;Ee!==0;){!Te&&h.firstTabInLine!==-1&&(h.position=h.firstTabInLine,L(h,"tab characters must not be used in indentation"));const tt=h.input.charCodeAt(h.position+1),ht=h.line;if((Ee===63||Ee===58)&&M(tt))Ee===63?(Te&&(Ie(h,ne,ge,Se,xe,null,fe,Y,_),Se=xe=Oe=null),Ue=!0,Te=!0,we=!0):Te?(Te=!1,we=!0):L(h,"incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line"),h.position+=1,Ee=tt;else{if(fe=h.line,Y=h.lineStart,_=h.position,!et(h,ae,s,!1,!0))break;if(h.line===ht){for(Ee=h.input.charCodeAt(h.position);$(Ee);)Ee=h.input.charCodeAt(++h.position);if(Ee===58)Ee=h.input.charCodeAt(++h.position),M(Ee)||L(h,"a whitespace character is expected after the key-value separator within a block mapping"),Te&&(Ie(h,ne,ge,Se,xe,null,fe,Y,_),Se=xe=Oe=null),Ue=!0,Te=!1,we=!1,Se=h.tag,xe=h.result;else if(Ue)L(h,"can not read an implicit mapping pair; a colon is missed");else return h.tag=G,h.anchor=se,!0}else if(Ue)L(h,"can not read a block mapping entry; a multiline key may not be an implicit key");else return h.tag=G,h.anchor=se,!0}if((h.line===ht||h.lineIndent>V)&&(Te&&(fe=h.line,Y=h.lineStart,_=h.position),et(h,V,m,!0,we)&&(Te?xe=h.result:Oe=h.result),Te||(Ie(h,ne,ge,Se,xe,Oe,fe,Y,_),Se=xe=Oe=null),Fe(h,!0,-1),Ee=h.input.charCodeAt(h.position)),(h.line===ht||h.lineIndent>V)&&Ee!==0)L(h,"bad indentation of a mapping entry");else if(h.lineIndent<V)break}return Te&&Ie(h,ne,ge,Se,xe,null,fe,Y,_),Ue&&(h.tag=G,h.anchor=se,h.kind="mapping",h.result=ne),Ue}function he(h){let V=!1,ae=!1,we,fe,Y=h.input.charCodeAt(h.position);if(Y!==33)return!1;h.tag!==null&&L(h,"duplication of a tag property"),Y=h.input.charCodeAt(++h.position),Y===60?(V=!0,Y=h.input.charCodeAt(++h.position)):Y===33?(ae=!0,we="!!",Y=h.input.charCodeAt(++h.position)):we="!";let _=h.position;if(V){do Y=h.input.charCodeAt(++h.position);while(Y!==0&&Y!==62);h.position<h.length?(fe=h.input.slice(_,h.position),Y=h.input.charCodeAt(++h.position)):L(h,"unexpected end of the stream within a verbatim tag")}else{for(;Y!==0&&!M(Y);)Y===33&&(ae?L(h,"tag suffix cannot contain exclamation marks"):(we=h.input.slice(_-1,h.position+1),R.test(we)||L(h,"named tag handle cannot contain such characters"),ae=!0,_=h.position+1)),Y=h.input.charCodeAt(++h.position);fe=h.input.slice(_,h.position),C.test(fe)&&L(h,"tag suffix cannot contain flow indicator characters")}fe&&!E.test(fe)&&L(h,"tag name cannot contain such characters: "+fe);try{fe=decodeURIComponent(fe)}catch{L(h,"tag name is malformed: "+fe)}return V?h.tag=fe:o.call(h.tagMap,we)?h.tag=h.tagMap[we]+fe:we==="!"?h.tag="!"+fe:we==="!!"?h.tag="tag:yaml.org,2002:"+fe:L(h,'undeclared tag handle "'+we+'"'),!0}function Re(h){let V=h.input.charCodeAt(h.position);if(V!==38)return!1;h.anchor!==null&&L(h,"duplication of an anchor property"),V=h.input.charCodeAt(++h.position);const ae=h.position;for(;V!==0&&!M(V)&&!w(V);)V=h.input.charCodeAt(++h.position);return h.position===ae&&L(h,"name of an anchor node must contain at least one character"),h.anchor=h.input.slice(ae,h.position),!0}function qe(h){let V=h.input.charCodeAt(h.position);if(V!==42)return!1;V=h.input.charCodeAt(++h.position);const ae=h.position;for(;V!==0&&!M(V)&&!w(V);)V=h.input.charCodeAt(++h.position);h.position===ae&&L(h,"name of an alias node must contain at least one character");const we=h.input.slice(ae,h.position);return o.call(h.anchorMap,we)||L(h,'unidentified alias "'+we+'"'),h.result=h.anchorMap[we],Fe(h,!0,-1),!0}function Je(h,V,ae,we){const fe=me(h);return Z(h),be(h,V),h.tag=null,h.anchor=null,h.kind=null,h.result=null,oe(h,ae,we)&&h.kind==="mapping"?(pe(h),!0):(ee(h),be(h,fe),!1)}function et(h,V,ae,we,fe){let Y,_,G=1,se=!1,ne=!1,ge=null,Se,xe,Oe;h.depth>=h.maxDepth&&L(h,"nesting exceeded maxDepth ("+h.maxDepth+")"),h.depth+=1,h.listener!==null&&h.listener("open",h),h.tag=null,h.anchor=null,h.kind=null,h.result=null;const Te=Y=_=m===ae||l===ae;if(we&&Fe(h,!0,-1)&&(se=!0,h.lineIndent>V?G=1:h.lineIndent===V?G=0:h.lineIndent<V&&(G=-1)),G===1)for(;;){const Ue=h.input.charCodeAt(h.position),Ee=me(h);if(se&&(Ue===33&&h.tag!==null||Ue===38&&h.anchor!==null)||!he(h)&&!Re(h))break;ge===null&&(ge=Ee),Fe(h,!0,-1)?(se=!0,_=Te,h.lineIndent>V?G=1:h.lineIndent===V?G=0:h.lineIndent<V&&(G=-1)):_=!1}if(_&&(_=se||fe),G===1||m===ae)if(r===ae||s===ae?xe=V:xe=V+1,Oe=h.position-h.lineStart,G===1)if(_&&(q(h,Oe)||oe(h,Oe,xe))||U(h,xe))ne=!0;else{const Ue=h.input.charCodeAt(h.position);ge!==null&&Te&&!_&&Ue!==124&&Ue!==62&&Je(h,ge,ge.position-ge.lineStart,xe)||Y&&J(h,xe)||Ge(h,xe)||Ve(h,xe)?ne=!0:qe(h)?(ne=!0,(h.tag!==null||h.anchor!==null)&&L(h,"alias node should not have any properties")):Be(h,xe,r===ae)&&(ne=!0,h.tag===null&&(h.tag="?")),h.anchor!==null&&X(h,h.anchor,h.result)}else G===0&&(ne=_&&q(h,Oe));if(h.tag===null)h.anchor!==null&&X(h,h.anchor,h.result);else if(h.tag==="?"){h.result!==null&&h.kind!=="scalar"&&L(h,'unacceptable node kind for !<?> tag; it should be "scalar", not "'+h.kind+'"');for(let Ue=0,Ee=h.implicitTypes.length;Ue<Ee;Ue+=1)if(Se=h.implicitTypes[Ue],Se.resolve(h.result)){h.result=Se.construct(h.result),h.tag=Se.tag,h.anchor!==null&&X(h,h.anchor,h.result);break}}else if(h.tag!=="!"){if(o.call(h.typeMap[h.kind||"fallback"],h.tag))Se=h.typeMap[h.kind||"fallback"][h.tag];else{Se=null;const Ue=h.typeMap.multi[h.kind||"fallback"];for(let Ee=0,tt=Ue.length;Ee<tt;Ee+=1)if(h.tag.slice(0,Ue[Ee].tag.length)===Ue[Ee].tag){Se=Ue[Ee];break}}Se||L(h,"unknown tag !<"+h.tag+">"),h.result!==null&&Se.kind!==h.kind&&L(h,"unacceptable node kind for !<"+h.tag+'> tag; it should be "'+Se.kind+'", not "'+h.kind+'"'),Se.resolve(h.result,h.tag)?(h.result=Se.construct(h.result,h.tag),h.anchor!==null&&X(h,h.anchor,h.result)):L(h,"cannot resolve a node with !<"+h.tag+"> explicit tag")}return h.listener!==null&&h.listener("close",h),h.depth-=1,h.tag!==null||h.anchor!==null||ne}function dt(h){const V=h.position;let ae=!1,we;for(h.version=null,h.checkLineBreaks=h.legacy,h.tagMap=Object.create(null),h.anchorMap=Object.create(null);(we=h.input.charCodeAt(h.position))!==0&&(Fe(h,!0,-1),we=h.input.charCodeAt(h.position),!(h.lineIndent>0||we!==37));){ae=!0,we=h.input.charCodeAt(++h.position);let fe=h.position;for(;we!==0&&!M(we);)we=h.input.charCodeAt(++h.position);const Y=h.input.slice(fe,h.position),_=[];for(Y.length<1&&L(h,"directive name must not be less than one character in length");we!==0;){for(;$(we);)we=h.input.charCodeAt(++h.position);if(we===35){do we=h.input.charCodeAt(++h.position);while(we!==0&&!O(we));break}if(O(we))break;for(fe=h.position;we!==0&&!M(we);)we=h.input.charCodeAt(++h.position);_.push(h.input.slice(fe,h.position))}we!==0&&Le(h),o.call(je,Y)?je[Y](h,Y,_):de(h,'unknown document directive "'+Y+'"')}if(Fe(h,!0,-1),h.lineIndent===0&&h.input.charCodeAt(h.position)===45&&h.input.charCodeAt(h.position+1)===45&&h.input.charCodeAt(h.position+2)===45?(h.position+=3,Fe(h,!0,-1)):ae&&L(h,"directives end mark is expected"),et(h,h.lineIndent-1,m,!1,!0),Fe(h,!0,-1),h.checkLineBreaks&&k.test(h.input.slice(V,h.position))&&de(h,"non-ASCII line breaks are interpreted as content"),h.documents.push(h.result),h.position===h.lineStart&&Xe(h)){h.input.charCodeAt(h.position)===46&&(h.position+=3,Fe(h,!0,-1));return}h.position<h.length-1&&L(h,"end of the stream or a document separator is expected")}function _t(h,V){h=String(h),V=V||{},h.length!==0&&(h.charCodeAt(h.length-1)!==10&&h.charCodeAt(h.length-1)!==13&&(h+=`
|
|
88
|
-
`),h.charCodeAt(0)===65279&&(h=h.slice(1)));const ae=new re(h,V),we=h.indexOf("\0");for(we!==-1&&(ae.position=we,L(ae,"null byte is not allowed in input")),ae.input+="\0";ae.input.charCodeAt(ae.position)===32;)ae.lineIndent+=1,ae.position+=1;for(;ae.position<ae.length-1;)dt(ae);return ae.documents}function Ne(h,V,ae){V!==null&&typeof V=="object"&&typeof ae>"u"&&(ae=V,V=null);const we=_t(h,ae);if(typeof V!="function")return we;for(let fe=0,Y=we.length;fe<Y;fe+=1)V(we[fe])}function Ye(h,V){const ae=_t(h,V);if(ae.length!==0){if(ae.length===1)return ae[0];throw new t("expected a single document in the stream, but found more")}}return Gd.loadAll=Ne,Gd.load=Ye,Gd}var ah={},oS;function mN(){if(oS)return ah;oS=1;const e=Gc(),t=Jc(),n=Cv(),a=Object.prototype.toString,o=Object.prototype.hasOwnProperty,r=65279,s=9,l=10,m=13,d=32,f=33,g=34,x=35,k=37,C=38,R=39,E=42,A=44,O=45,$=58,M=61,w=62,P=63,j=64,N=91,z=93,D=96,F=123,te=124,ve=125,re={};re[0]="\\0",re[7]="\\a",re[8]="\\b",re[9]="\\t",re[10]="\\n",re[11]="\\v",re[12]="\\f",re[13]="\\r",re[27]="\\e",re[34]='\\"',re[92]="\\\\",re[133]="\\N",re[160]="\\_",re[8232]="\\L",re[8233]="\\P";const K=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"],L=/^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;function de(_,G){if(G===null)return{};const se={},ne=Object.keys(G);for(let ge=0,Se=ne.length;ge<Se;ge+=1){let xe=ne[ge],Oe=String(G[xe]);xe.slice(0,2)==="!!"&&(xe="tag:yaml.org,2002:"+xe.slice(2));const Te=_.compiledTypeMap.fallback[xe];Te&&o.call(Te.styleAliases,Oe)&&(Oe=Te.styleAliases[Oe]),se[xe]=Oe}return se}function X(_){let G,se;const ne=_.toString(16).toUpperCase();if(_<=255)G="x",se=2;else if(_<=65535)G="u",se=4;else if(_<=4294967295)G="U",se=8;else throw new t("code point within a string may not be greater than 0xFFFFFFFF");return"\\"+G+e.repeat("0",se-ne.length)+ne}const Z=1,pe=2;function ee(_){this.schema=_.schema||n,this.indent=Math.max(1,_.indent||2),this.noArrayIndent=_.noArrayIndent||!1,this.skipInvalid=_.skipInvalid||!1,this.flowLevel=e.isNothing(_.flowLevel)?-1:_.flowLevel,this.styleMap=de(this.schema,_.styles||null),this.sortKeys=_.sortKeys||!1,this.lineWidth=_.lineWidth||80,this.noRefs=_.noRefs||!1,this.noCompatMode=_.noCompatMode||!1,this.condenseFlow=_.condenseFlow||!1,this.quotingType=_.quotingType==='"'?pe:Z,this.forceQuotes=_.forceQuotes||!1,this.replacer=typeof _.replacer=="function"?_.replacer:null,this.implicitTypes=this.schema.compiledImplicit,this.explicitTypes=this.schema.compiledExplicit,this.tag=null,this.result="",this.duplicates=[],this.usedDuplicates=null}function me(_,G){const se=e.repeat(" ",G);let ne=0,ge="";const Se=_.length;for(;ne<Se;){let xe;const Oe=_.indexOf(`
|
|
89
|
-
`,ne);Oe===-1?(xe=_.slice(ne),ne=Se):(xe=_.slice(ne,Oe+1),ne=Oe+1),xe.length&&xe!==`
|
|
90
|
-
`&&(ge+=se),ge+=xe}return ge}function be(_,G){return`
|
|
91
|
-
`+e.repeat(" ",_.indent*G)}function je(_,G){for(let se=0,ne=_.implicitTypes.length;se<ne;se+=1)if(_.implicitTypes[se].resolve(G))return!0;return!1}function ke(_){return _===d||_===s}function ue(_){return _>=32&&_<=126||_>=161&&_<=55295&&_!==8232&&_!==8233||_>=57344&&_<=65533&&_!==r||_>=65536&&_<=1114111}function Ie(_){return ue(_)&&_!==r&&_!==m&&_!==l}function Le(_,G,se){const ne=Ie(_),ge=ne&&!ke(_);return(se?ne:ne&&_!==A&&_!==N&&_!==z&&_!==F&&_!==ve)&&_!==x&&!(G===$&&!ge)||Ie(G)&&!ke(G)&&_===x||G===$&&ge}function Fe(_){return ue(_)&&_!==r&&!ke(_)&&_!==O&&_!==P&&_!==$&&_!==A&&_!==N&&_!==z&&_!==F&&_!==ve&&_!==x&&_!==C&&_!==E&&_!==f&&_!==te&&_!==M&&_!==w&&_!==R&&_!==g&&_!==k&&_!==j&&_!==D}function Xe(_){return!ke(_)&&_!==$}function Ze(_,G){const se=_.charCodeAt(G);let ne;return se>=55296&&se<=56319&&G+1<_.length&&(ne=_.charCodeAt(G+1),ne>=56320&&ne<=57343)?(se-55296)*1024+ne-56320+65536:se}function Be(_){return/^\n* /.test(_)}const Ge=1,Ve=2,U=3,J=4,q=5;function oe(_,G,se,ne,ge,Se,xe,Oe){let Te,Ue=0,Ee=null,tt=!1,ht=!1;const xn=ne!==-1;let xt=-1,Xn=Fe(Ze(_,0))&&Xe(Ze(_,_.length-1));if(G||xe)for(Te=0;Te<_.length;Ue>=65536?Te+=2:Te++){if(Ue=Ze(_,Te),!ue(Ue))return q;Xn=Xn&&Le(Ue,Ee,Oe),Ee=Ue}else{for(Te=0;Te<_.length;Ue>=65536?Te+=2:Te++){if(Ue=Ze(_,Te),Ue===l)tt=!0,xn&&(ht=ht||Te-xt-1>ne&&_[xt+1]!==" ",xt=Te);else if(!ue(Ue))return q;Xn=Xn&&Le(Ue,Ee,Oe),Ee=Ue}ht=ht||xn&&Te-xt-1>ne&&_[xt+1]!==" "}return!tt&&!ht?Xn&&!xe&&!ge(_)?Ge:Se===pe?q:Ve:se>9&&Be(_)?q:xe?Se===pe?q:Ve:ht?J:U}function he(_,G,se,ne,ge){_.dump=(function(){if(G.length===0)return _.quotingType===pe?'""':"''";if(!_.noCompatMode&&(K.indexOf(G)!==-1||L.test(G)))return _.quotingType===pe?'"'+G+'"':"'"+G+"'";const Se=_.indent*Math.max(1,se),xe=_.lineWidth===-1?-1:Math.max(Math.min(_.lineWidth,40),_.lineWidth-Se),Oe=ne||_.flowLevel>-1&&se>=_.flowLevel;function Te(Ue){return je(_,Ue)}switch(oe(G,Oe,_.indent,xe,Te,_.quotingType,_.forceQuotes&&!ne,ge)){case Ge:return G;case Ve:return"'"+G.replace(/'/g,"''")+"'";case U:return"|"+Re(G,_.indent)+qe(me(G,Se));case J:return">"+Re(G,_.indent)+qe(me(Je(G,xe),Se));case q:return'"'+dt(G)+'"';default:throw new t("impossible error: invalid scalar style")}})()}function Re(_,G){const se=Be(_)?String(G):"",ne=_[_.length-1]===`
|
|
92
|
-
`,Se=ne&&(_[_.length-2]===`
|
|
93
|
-
`||_===`
|
|
94
|
-
`)?"+":ne?"":"-";return se+Se+`
|
|
95
|
-
`}function qe(_){return _[_.length-1]===`
|
|
96
|
-
`?_.slice(0,-1):_}function Je(_,G){const se=/(\n+)([^\n]*)/g;let ne=(function(){let Oe=_.indexOf(`
|
|
97
|
-
`);return Oe=Oe!==-1?Oe:_.length,se.lastIndex=Oe,et(_.slice(0,Oe),G)})(),ge=_[0]===`
|
|
98
|
-
`||_[0]===" ",Se,xe;for(;xe=se.exec(_);){const Oe=xe[1],Te=xe[2];Se=Te[0]===" ",ne+=Oe+(!ge&&!Se&&Te!==""?`
|
|
99
|
-
`:"")+et(Te,G),ge=Se}return ne}function et(_,G){if(_===""||_[0]===" ")return _;const se=/ [^ ]/g;let ne,ge=0,Se,xe=0,Oe=0,Te="";for(;ne=se.exec(_);)Oe=ne.index,Oe-ge>G&&(Se=xe>ge?xe:Oe,Te+=`
|
|
100
|
-
`+_.slice(ge,Se),ge=Se+1),xe=Oe;return Te+=`
|
|
101
|
-
`,_.length-ge>G&&xe>ge?Te+=_.slice(ge,xe)+`
|
|
102
|
-
`+_.slice(xe+1):Te+=_.slice(ge),Te.slice(1)}function dt(_){let G="",se=0;for(let ne=0;ne<_.length;se>=65536?ne+=2:ne++){se=Ze(_,ne);const ge=re[se];!ge&&ue(se)?(G+=_[ne],se>=65536&&(G+=_[ne+1])):G+=ge||X(se)}return G}function _t(_,G,se){let ne="";const ge=_.tag;for(let Se=0,xe=se.length;Se<xe;Se+=1){let Oe=se[Se];_.replacer&&(Oe=_.replacer.call(se,String(Se),Oe)),(ae(_,G,Oe,!1,!1)||typeof Oe>"u"&&ae(_,G,null,!1,!1))&&(ne!==""&&(ne+=","+(_.condenseFlow?"":" ")),ne+=_.dump)}_.tag=ge,_.dump="["+ne+"]"}function Ne(_,G,se,ne){let ge="";const Se=_.tag;for(let xe=0,Oe=se.length;xe<Oe;xe+=1){let Te=se[xe];_.replacer&&(Te=_.replacer.call(se,String(xe),Te)),(ae(_,G+1,Te,!0,!0,!1,!0)||typeof Te>"u"&&ae(_,G+1,null,!0,!0,!1,!0))&&((!ne||ge!=="")&&(ge+=be(_,G)),_.dump&&l===_.dump.charCodeAt(0)?ge+="-":ge+="- ",ge+=_.dump)}_.tag=Se,_.dump=ge||"[]"}function Ye(_,G,se){let ne="";const ge=_.tag,Se=Object.keys(se);for(let xe=0,Oe=Se.length;xe<Oe;xe+=1){let Te="";ne!==""&&(Te+=", "),_.condenseFlow&&(Te+='"');const Ue=Se[xe];let Ee=se[Ue];_.replacer&&(Ee=_.replacer.call(se,Ue,Ee)),ae(_,G,Ue,!1,!1)&&(_.dump.length>1024&&(Te+="? "),Te+=_.dump+(_.condenseFlow?'"':"")+":"+(_.condenseFlow?"":" "),ae(_,G,Ee,!1,!1)&&(Te+=_.dump,ne+=Te))}_.tag=ge,_.dump="{"+ne+"}"}function h(_,G,se,ne){let ge="";const Se=_.tag,xe=Object.keys(se);if(_.sortKeys===!0)xe.sort();else if(typeof _.sortKeys=="function")xe.sort(_.sortKeys);else if(_.sortKeys)throw new t("sortKeys must be a boolean or a function");for(let Oe=0,Te=xe.length;Oe<Te;Oe+=1){let Ue="";(!ne||ge!=="")&&(Ue+=be(_,G));const Ee=xe[Oe];let tt=se[Ee];if(_.replacer&&(tt=_.replacer.call(se,Ee,tt)),!ae(_,G+1,Ee,!0,!0,!0))continue;const ht=_.tag!==null&&_.tag!=="?"||_.dump&&_.dump.length>1024;ht&&(_.dump&&l===_.dump.charCodeAt(0)?Ue+="?":Ue+="? "),Ue+=_.dump,ht&&(Ue+=be(_,G)),ae(_,G+1,tt,!0,ht)&&(_.dump&&l===_.dump.charCodeAt(0)?Ue+=":":Ue+=": ",Ue+=_.dump,ge+=Ue)}_.tag=Se,_.dump=ge||"{}"}function V(_,G,se){const ne=se?_.explicitTypes:_.implicitTypes;for(let ge=0,Se=ne.length;ge<Se;ge+=1){const xe=ne[ge];if((xe.instanceOf||xe.predicate)&&(!xe.instanceOf||typeof G=="object"&&G instanceof xe.instanceOf)&&(!xe.predicate||xe.predicate(G))){if(se?xe.multi&&xe.representName?_.tag=xe.representName(G):_.tag=xe.tag:_.tag="?",xe.represent){const Oe=_.styleMap[xe.tag]||xe.defaultStyle;let Te;if(a.call(xe.represent)==="[object Function]")Te=xe.represent(G,Oe);else if(o.call(xe.represent,Oe))Te=xe.represent[Oe](G,Oe);else throw new t("!<"+xe.tag+'> tag resolver accepts not "'+Oe+'" style');_.dump=Te}return!0}}return!1}function ae(_,G,se,ne,ge,Se,xe){_.tag=null,_.dump=se,V(_,se,!1)||V(_,se,!0);const Oe=a.call(_.dump),Te=ne;ne&&(ne=_.flowLevel<0||_.flowLevel>G);const Ue=Oe==="[object Object]"||Oe==="[object Array]";let Ee,tt;if(Ue&&(Ee=_.duplicates.indexOf(se),tt=Ee!==-1),(_.tag!==null&&_.tag!=="?"||tt||_.indent!==2&&G>0)&&(ge=!1),tt&&_.usedDuplicates[Ee])_.dump="*ref_"+Ee;else{if(Ue&&tt&&!_.usedDuplicates[Ee]&&(_.usedDuplicates[Ee]=!0),Oe==="[object Object]")ne&&Object.keys(_.dump).length!==0?(h(_,G,_.dump,ge),tt&&(_.dump="&ref_"+Ee+_.dump)):(Ye(_,G,_.dump),tt&&(_.dump="&ref_"+Ee+" "+_.dump));else if(Oe==="[object Array]")ne&&_.dump.length!==0?(_.noArrayIndent&&!xe&&G>0?Ne(_,G-1,_.dump,ge):Ne(_,G,_.dump,ge),tt&&(_.dump="&ref_"+Ee+_.dump)):(_t(_,G,_.dump),tt&&(_.dump="&ref_"+Ee+" "+_.dump));else if(Oe==="[object String]")_.tag!=="?"&&he(_,_.dump,G,Se,Te);else{if(Oe==="[object Undefined]")return!1;if(_.skipInvalid)return!1;throw new t("unacceptable kind of an object to dump "+Oe)}if(_.tag!==null&&_.tag!=="?"){let ht=encodeURI(_.tag[0]==="!"?_.tag.slice(1):_.tag).replace(/!/g,"%21");_.tag[0]==="!"?ht="!"+ht:ht.slice(0,18)==="tag:yaml.org,2002:"?ht="!!"+ht.slice(18):ht="!<"+ht+">",_.dump=ht+" "+_.dump}}return!0}function we(_,G){const se=[],ne=[];fe(_,se,ne);const ge=ne.length;for(let Se=0;Se<ge;Se+=1)G.duplicates.push(se[ne[Se]]);G.usedDuplicates=new Array(ge)}function fe(_,G,se){if(_!==null&&typeof _=="object"){const ne=G.indexOf(_);if(ne!==-1)se.indexOf(ne)===-1&&se.push(ne);else if(G.push(_),Array.isArray(_))for(let ge=0,Se=_.length;ge<Se;ge+=1)fe(_[ge],G,se);else{const ge=Object.keys(_);for(let Se=0,xe=ge.length;Se<xe;Se+=1)fe(_[ge[Se]],G,se)}}}function Y(_,G){G=G||{};const se=new ee(G);se.noRefs||we(_,se);let ne=_;return se.replacer&&(ne=se.replacer.call({"":ne},"",ne)),ae(se,0,ne,!0,!0)?se.dump+`
|
|
103
|
-
`:""}return ah.dump=Y,ah}var rS;function pN(){if(rS)return Zn;rS=1;const e=uN(),t=mN();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 Zn.Type=ca(),Zn.Schema=gw(),Zn.FAILSAFE_SCHEMA=Sw(),Zn.JSON_SCHEMA=_w(),Zn.CORE_SCHEMA=Cw(),Zn.DEFAULT_SCHEMA=Cv(),Zn.load=e.load,Zn.loadAll=e.loadAll,Zn.dump=t.dump,Zn.YAMLException=Jc(),Zn.types={binary:Aw(),float:Iw(),map:yw(),null:xw(),pairs:Ew(),set:Mw(),timestamp:Rw(),bool:kw(),int:ww(),merge:Pw(),omap:Tw(),seq:bw(),str:vw()},Zn.safeLoad=n("safeLoad","load"),Zn.safeLoadAll=n("safeLoadAll","loadAll"),Zn.safeDump=n("safeDump","dump"),Zn}var fN=pN();const hN=cN(fN),{Type:$ae,Schema:Nae,FAILSAFE_SCHEMA:Dae,JSON_SCHEMA:Hae,CORE_SCHEMA:Lae,DEFAULT_SCHEMA:qae,load:Uae,loadAll:zae,dump:Bae,YAMLException:Fae,types:Vae,safeLoad:Kae,safeLoadAll:Wae,safeDump:Gae}=hN,Rv=3e3,Pv=9999,Jae="openpond.yaml",gN=["google","github","x"],Av=new Set([22,2222,2375,2376,3108,5900,5901,6080,7818]),sS=p(i().trim().min(1).max(1e3)).max(50),kc=i().trim().min(1).max(4096).refine(Nw,{message:"path must be a relative workspace path"}),vN=i().trim().min(1).max(500).refine(e=>!e.includes("\0")&&!/\s/.test(e),"image ref must be a single OCI reference"),bN=i().trim().regex(/^sha256:[0-9a-f]{64}$/i),jw=i().trim().min(1).max(500).refine(e=>e.startsWith("/")&&!e.includes("\0"),"workspaceRoot must be an absolute guest path"),yN=c({ref:vN,digest:bN.optional(),registrySecretRef:i().trim().min(1).max(500).optional(),platform:b("linux/amd64").optional(),workspaceRoot:jw.optional()}).strict(),SN=c({context:kc.default("."),path:kc.default("Dockerfile"),target:i().trim().min(1).max(191).optional(),buildArgs:le(i().max(191),i().max(500)).optional(),registrySecretRefs:p(i().trim().min(1).max(500)).max(10).optional(),platform:b("linux/amd64").optional(),workspaceRoot:jw.optional()}).strict(),xN=c({base:i().trim().min(1).max(120).optional(),snapshot:i().trim().min(1).max(191).optional(),image:yN.optional(),dockerfile:SN.optional()}).strict().superRefine((e,t)=>{[e.base,e.snapshot,e.image,e.dockerfile].filter(Boolean).length!==1&&t.addIssue({code:oa.custom,message:"runtime must declare exactly one of base, snapshot, image, or dockerfile"})}),Ow=c({cpu:u().positive().max(8).optional(),memoryGb:u().positive().max(32).optional(),diskGb:u().positive().max(100).optional()}).strict(),kN=c({provider:v(gN),scopes:p(i().trim().min(1).max(200)).max(100).default([]),capabilities:p(i().trim().min(1).max(200)).max(100).default([])}).strict(),wN=c({models:p(i().trim().min(1).max(200)).max(100).default([]),scopes:p(i().trim().min(1).max(200)).max(100).default([])}).strict(),IN=c({opchat:wN.optional()}).catchall(le(i(),ce())).default({}),_N=c({name:i().trim().regex(/^[A-Za-z_][A-Za-z0-9_-]*$/).max(63).optional(),mountPath:i().trim().min(1).max(256).optional(),storageGb:u().int().positive().max(100).optional(),deleteOnSandboxDelete:I().optional()}).strict(),CN=c({port:u().int().min(Rv).max(Pv).refine(e=>!Av.has(e),{message:"preview port is reserved"}),protocol:b("http").default("http"),label:i().trim().min(1).max(80).optional(),access:v(["private","public"]).default("private"),path:i().trim().min(1).max(512).refine(e=>e.startsWith("/"),{message:"preview path must start with /"}).default("/")}).strict(),$w=c({command:i().trim().min(1).max(1e3),cwd:kc.optional(),timeoutSeconds:u().int().positive().max(86400).optional(),requiresStart:I().default(!1),ports:p(CN).max(20).default([]),artifactPaths:p(kc).max(100).default([])}).strict(),lS=$w.extend({name:i().trim().min(1).max(80)}).strict(),RN=c({name:i().trim().min(1).max(80).optional(),service:i().trim().min(1).max(80).optional(),port:u().int().min(Rv).max(Pv).refine(e=>!Av.has(e),{message:"app MCP port is reserved"}),path:i().trim().min(1).max(512).refine(e=>e.startsWith("/"),{message:"app MCP path must start with /"}).default("/mcp")}).strict(),PN=c({name:i().trim().min(1).max(80).optional(),port:u().int().min(Rv).max(Pv).refine(e=>!Av.has(e),{message:"validation probe port is reserved"}),path:i().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(),AN=le(i(),ce()).refine(e=>e.type==="object","input schema must be a JSON schema object"),TN=c({name:i().trim().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).max(191),required:I().default(!1),secret:I().default(!0),description:i().trim().max(500).optional()}).strict(),ih=i().trim().min(1).max(120),EN=c({name:i().trim().min(1).max(120),description:i().trim().max(500).optional(),cron:i().trim().min(1).max(500).optional(),rate:i().trim().min(1).max(500).optional(),once:ih.optional(),scheduleType:v(["rate","cron","once"]).optional(),scheduleExpression:i().trim().min(1).max(500).optional(),timezone:i().trim().min(1).max(100).optional(),enabled:I().default(!0),startAt:ih.optional(),endAt:ih.optional(),maxRuns:u().int().positive().nullable().optional(),runtimePolicy:v(["run_and_stop","run_and_archive","run_and_delete","use_existing_running"]).default("run_and_stop"),action:i().trim().min(1).max(120).optional(),actionName:i().trim().min(1).max(120).optional(),command:i().trim().min(1).max(2e3).optional(),target:c({kind:v(["start","action","service","command"]).optional(),name:i().trim().min(1).max(120).optional(),actionName:i().trim().min(1).max(120).optional(),command:i().trim().min(1).max(2e3).optional(),requiresStart:I().optional()}).strict().optional(),requiresStart:I().optional(),budget:c({maxUsd:i().trim().min(1).max(40).optional()}).strict().optional(),resources:Ow.optional(),quotas:le(i(),ce()).optional(),lifecycle:le(i(),ce()).optional(),retentionPolicy:le(i(),ce()).optional(),env:p(c({name:i().trim().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).max(191),value:i().optional(),secretRef:i().optional()}).strict()).max(100).optional(),integrationLeases:p(le(i(),ce())).max(20).optional(),metadata:le(i(),ce()).optional()}).strict().superRefine((e,t)=>{[e.cron,e.rate,e.once,e.scheduleExpression].filter(l=>typeof l=="string"&&l.trim()).length!==1&&t.addIssue({code:oa.custom,path:["scheduleExpression"],message:"schedule must declare exactly one of cron, rate, once, or scheduleExpression"}),e.scheduleExpression&&!e.scheduleType&&t.addIssue({code:oa.custom,path:["scheduleType"],message:"scheduleType is required with scheduleExpression"});const a=e.command??e.target?.command??null,o=e.target?.name??null,r=e.actionName??e.action??e.target?.actionName??(e.target?.kind==="action"?o:null),s=e.target?.kind??(a?"command":"action");s==="action"&&!r&&t.addIssue({code:oa.custom,path:["action"],message:"schedule action target is required"}),s==="service"&&!o&&t.addIssue({code:oa.custom,path:["target","name"],message:"schedule service target name is required"}),s==="command"&&!a&&t.addIssue({code:oa.custom,path:["command"],message:"schedule command target is required"})}),MN=c({schemaVersion:b(1),name:i().trim().min(1).max(80).regex(/^[a-z0-9][a-z0-9-]*[a-z0-9]$/),version:i().trim().min(1).max(40),useCase:i().trim().min(1).max(80),description:i().trim().min(1).max(500),runtime:xN,resources:Ow.optional(),setup:c({commands:sS.default([])}).strict().default({commands:[]}),validation:c({commands:sS.min(1),probes:p(PN).max(20).default([])}).strict(),start:$w,actions:p(lS).max(20).default([]),services:p(lS).max(20).default([]),schedules:p(EN).max(20).default([]),mcp:c({endpoints:p(RN).max(10).default([])}).strict().default({endpoints:[]}),volumes:p(_N).max(5).default([]),integrations:c({requiredLeases:p(kN).max(20).default([])}).strict().default({requiredLeases:[]}),permissions:IN,inputs:c({schema:AN.default({type:"object"}),env:p(TN).max(100).default([])}).strict().default({schema:{type:"object"},env:[]}),artifacts:c({paths:p(kc).max(100).default([])}).strict().default({paths:[]}),network:c({egress:v(["restricted","allow","block"]).default("restricted")}).strict().default({egress:"restricted"})}).strict().superRefine((e,t)=>{ON(e,t),Tv(t,e.volumes.flatMap(n=>n.name?[n.name]:[]),"volume names must be unique","volumes"),$N(e,t),NN(e,t),DN(e,t),HN(e,t)}),jN=c({path:i(),message:i(),code:i()});function Zae(e){return[{kind:"start",name:"start",...e.start,artifactPaths:rh(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:rh(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:rh(t,e)}))]}function Nw(e){return!e.includes("\0")&&!e.startsWith("/")&&!e.split(/[\\/]+/).some(t=>t===".."||t==="")}function Tv(e,t,n,a){const o=new Set;for(const r of t){if(o.has(r)){e.addIssue({code:oa.custom,path:[a],message:n});return}o.add(r)}}function ON(e,t){const n=["start",...e.actions.map(a=>a.name),...e.services.map(a=>a.name)];Tv(t,n,"start, action, and service names must be unique","actions")}function $N(e,t){const n=oh(e.inputs.schema.properties),a=new Set(e.volumes.map(o=>o.name).filter(o=>!!o));for(const[o,r]of Object.entries(n)){const s=oh(r),l=oh(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(!Nw(d)){t.addIssue({code:oa.custom,path:["inputs","schema","properties",o,"x-openpond-upload","targetPath"],message:"upload target must be a relative workspace path"});continue}const f=d.split("/");f[0]==="volumes"&&(!f[1]||!a.has(f[1]))&&t.addIssue({code:oa.custom,path:["inputs","schema","properties",o,"x-openpond-upload","targetPath"],message:"upload target references an undeclared volume"})}}function NN(e,t){Tv(t,e.inputs.env.map(n=>n.name),"env input names must be unique","inputs")}function DN(e,t){const n=new Map(e.services.map(o=>[o.name,new Set(o.ports.map(r=>r.port))])),a=new Set([...e.start.ports.map(o=>o.port),...e.services.flatMap(o=>o.ports.map(r=>r.port))]);for(const[o,r]of e.mcp.endpoints.entries()){if(r.service){const s=n.get(r.service);if(!s){t.addIssue({code:oa.custom,path:["mcp","endpoints",o,"service"],message:`app MCP service does not exist: ${r.service}`});continue}s.has(r.port)||t.addIssue({code:oa.custom,path:["mcp","endpoints",o,"port"],message:`app MCP port ${r.port} is not declared on service ${r.service}`});continue}a.has(r.port)||t.addIssue({code:oa.custom,path:["mcp","endpoints",o,"port"],message:`app MCP port ${r.port} is not declared on start or services`})}}function HN(e,t){const n=new Set(e.actions.map(o=>o.name)),a=new Set(e.services.map(o=>o.name));for(const[o,r]of e.schedules.entries()){const s=r.command??r.target?.command??null;if(r.target?.kind==="command"||s)continue;const l=r.actionName??r.action??r.target?.actionName??(r.target?.kind==="action"?r.target?.name:null);if(l&&!n.has(l)&&t.addIssue({code:oa.custom,path:["schedules",o,"action"],message:`schedule action target does not exist: ${l}`}),r.target?.kind==="service"){const m=r.target.name??"";m&&!a.has(m)&&t.addIssue({code:oa.custom,path:["schedules",o,"target","name"],message:`schedule service target does not exist: ${m}`})}}}function oh(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function rh(e,t){return e.artifactPaths.length>0?e.artifactPaths:t.artifacts.paths}const LN=c({id:i(),name:i(),description:i().nullable(),scheduleType:i(),scheduleExpression:i(),enabled:I(),rawEnabled:I().optional(),syncStatus:i().nullable(),syncError:i().nullable().optional(),startAt:i().nullable(),endAt:i().nullable(),maxRuns:u().nullable(),executionCount:u().nullable(),lifecycleStatus:i().nullable(),lifecycleReason:i().nullable(),lastExecutionAt:i().nullable().optional(),lastExecutionStatus:i().nullable().optional(),lastRunNowAt:i().nullable().optional(),lastRunNowStatus:i().nullable().optional(),updatedAt:i(),deploymentId:i(),isProduction:I().optional(),payload:ce().optional()}).passthrough(),qN=c({total:u().int().nonnegative(),active:u().int().nonnegative(),paused:u().int().nonnegative(),enabled:u().int().nonnegative().optional(),disabled:u().int().nonnegative().optional(),nextRunAt:i().nullable().optional(),lastRunAt:i().nullable().optional(),schedules:p(LN).optional().default([]),truncated:I().optional()}).passthrough(),sh=c({name:i(),kind:v(["start","action","service"]),command:i(),cwd:i().nullable(),timeoutSeconds:u().nullable(),requiresStart:I(),ports:p(c({port:u(),protocol:i(),label:i().nullable(),access:i(),path:i()}).passthrough()).default([]),artifactPaths:p(i()).default([])}).passthrough(),UN=c({schemaVersion:b(1),source:b("openpond.yaml"),manifestName:i(),manifestVersion:i(),manifestUseCase:i(),manifestDescription:i(),manifestPath:i(),manifestHash:i(),inputSchema:le(i(),ce()).default({}),env:p(c({name:i(),required:I(),secret:I(),description:i().nullable()}).passthrough()).default([]),start:sh,actions:p(sh).default([]),services:p(sh).default([]),defaultActionName:i().nullable(),updatedAt:i()}).passthrough(),zN=c({id:i(),name:i(),description:i().nullable(),visibility:i().nullable().optional(),gitOwner:i().nullable().optional(),gitRepo:i().nullable().optional(),gitHost:i().nullable().optional(),defaultBranch:i().nullable().optional(),sandbox:I().optional().default(!1),sandboxActionRegistry:UN.nullable().optional(),sandboxManifestHash:i().nullable().optional(),sandboxManifestPath:i().nullable().optional(),sandboxManifestSyncedAt:i().nullable().optional(),sandboxManifestError:i().nullable().optional(),updatedAt:i().nullable().optional(),latestDeployment:c({id:i().optional(),status:i().optional(),deploymentDomain:i().nullable().optional(),createdAt:i().optional(),isProduction:I().nullable().optional(),gitBranch:i().nullable().optional()}).nullable().optional(),scheduleSummary:qN.nullable().optional()}),BN=c({detected:I(),rootPath:i(),manifestPath:i(),manifestHash:i().nullable().optional().default(null),manifest:le(i(),ce()).nullable().optional().default(null),normalizedManifest:MN.nullable().optional().default(null),valid:I().optional().default(!1),diagnostics:p(jN).optional().default([])}),FN=c({appId:i(),appName:i(),gitOwner:i().nullable(),gitRepo:i().nullable(),gitHost:i().nullable(),defaultBranch:i().nullable(),linkedAt:i()}),Dw=c({teamId:i(),projectId:i(),projectSlug:i().nullable().optional().default(null),projectName:i().nullable().optional().default(null),sourceRepoUrl:i().nullable().optional().default(null),defaultBranch:i().nullable().optional().default(null),lastUploadedCommit:i().nullable().optional().default(null),lastUploadTransport:v(["git_head","snapshot","api_source_upload"]).nullable().optional().default(null),manifestPath:i().nullable().optional().default(null),manifestHash:i().nullable().optional().default(null),syncedAt:i().nullable().optional().default(null),linkedAt:i()}),VN=v(["github_repo","internal_repo","template","manual"]),KN=c({id:i(),teamId:i(),name:i(),slug:i().nullable().optional().default(null),sourceType:VN.optional().default("manual"),sourceLabel:i().nullable().optional().default(null),defaultBranch:i().nullable().optional().default(null),internalRepoPath:i().nullable().optional().default(null),manifestPath:i().nullable().optional().default(null),manifestHash:i().nullable().optional().default(null),syncedAt:i().nullable().optional().default(null),organizationName:i().nullable().optional().default(null),organizationSlug:i().nullable().optional().default(null),createdAt:i().nullable().optional().default(null),updatedAt:i().nullable().optional().default(null)}),WN=c({id:i(),name:i(),path:i(),workspacePath:i(),repoPath:i().nullable(),source:v(["folder","git"]),sourceFolders:p(i().min(1)).min(1).optional(),hiddenFromDefaultSidebar:I().optional(),sandboxTemplate:BN.nullable().optional().default(null),linkedOpenPondApp:FN.nullable().optional().default(null),linkedSandboxProject:Dw.nullable().optional().default(null),preferredSandboxAgentId:i().nullable().optional().default(null),createdAt:i(),updatedAt:i()});c({path:i().trim().min(1).optional(),sourceFolders:p(i().trim().min(1)).min(1).optional(),primaryFolder:i().trim().min(1).optional(),name:i().trim().min(1).max(120).optional(),createNew:I().optional(),baseDirectory:i().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:Dw.nullable().optional(),preferredSandboxAgentId:i().nullable().optional(),hiddenFromDefaultSidebar:I().optional()});const GN=["connected_app_search","connected_app_read","connected_app_write"],lh="https://openpond.ai",Ev=["slack","google","github","turnkey","x","microsoft_teams","mcp"],Mv={slack:[tn("slack.channel.bind","Bind channels","Bind Slack channels or threads to OpenPond profiles.","setup",!1),tn("slack.message.ingest","Ingest messages","Ingest Slack channel or thread activity into OpenPond context.","setup",!1)],microsoft_teams:[tn("microsoft_teams.channel.bind","Bind channels","Bind Teams channels or chats to OpenPond profiles.","setup",!1),tn("microsoft_teams.message.ingest","Ingest messages","Ingest Teams channel or chat activity into OpenPond context.","setup",!1)],google:[tn("google.drive.file.read","Read Drive files","Find and read Google Drive files.","read",!0),tn("google.drive.file.write","Write Drive files","Create or update approved Google Drive files.","write",!0),tn("google.docs.read","Read Docs","Read Google Docs content and structure.","read",!0),tn("google.docs.write","Edit Docs","Apply approved Google Docs edits.","write",!0),tn("google.comments.read","Read comments","Read Google file comments.","read",!0),tn("google.comments.write","Write comments","Create or resolve approved Google comments.","write",!0)],github:[tn("github.repo.read","Read repositories","Read repository metadata and file context.","read",!0),tn("github.issue.read","Read issues","Read GitHub issues and comments.","read",!0),tn("github.issue.write","Update issues","Create or update approved GitHub issue content.","write",!0),tn("github.pull_request.read","Read pull requests","Read pull request metadata, diffs, checks, and reviews.","read",!0),tn("github.pull_request.write","Update pull requests","Create approved comments or pull request updates.","write",!0)],turnkey:[tn("turnkey.wallets.read","Read Agent Wallet","Read the connected OpenPond Agent Wallet address and metadata.","read",!0),tn("turnkey.balances.read","Read wallet balances","Read balances for the connected OpenPond Agent Wallet.","read",!0),tn("turnkey.activities.read","Read wallet activity","Read recent Turnkey activity for the connected OpenPond Agent Wallet.","read",!0)],x:[tn("x.profile.read","Read profile","Read the connected X profile.","read",!0),tn("x.search.read","Search X","Search public X posts when granted.","read",!0),tn("x.mentions.read","Read mentions","Read mentions for the connected X account.","read",!0),tn("x.post.write","Post","Create approved X posts.","write",!0),tn("x.reply.write","Reply","Create approved X replies.","write",!0)],mcp:[tn("mcp.tool.discover","Discover tools","Discover team-scoped MCP tools.","tooling",!1),tn("mcp.tool.call","Call tools","Call approved MCP tools through the team endpoint.","tooling",!1)]},jv={slack:[],microsoft_teams:[],google:[Ft("google.drive.search","search","Search Drive","Search Google Drive files by grounded query.",["google.drive.file.read"]),Ft("google.drive.read_file","read","Read Drive file","Read Drive file metadata or exported content by stable ref.",["google.drive.file.read"],{requiredKeys:["ref"]}),Ft("google.docs.read","read","Read Google Doc","Read Google Docs content and structure by stable ref.",["google.docs.read"],{requiredKeys:["ref"]}),Ft("google.comments.read","read","Read comments","Read comments for a grounded Google file ref.",["google.comments.read"],{requiredKeys:["ref"]}),Ft("google.docs.update","write","Update Google Doc","Apply an explicitly approved Google Docs edit and return readback verification.",["google.docs.write"],{requiredKeys:["ref","patch"]}),Ft("google.comments.create","write","Create comment","Create an explicitly approved Google file comment and return readback verification.",["google.comments.write"],{requiredKeys:["ref","body"]}),Ft("google.comments.resolve","write","Resolve comment","Resolve an explicitly approved Google comment and return readback verification.",["google.comments.write"],{requiredKeys:["ref","commentId"]})],github:[Ft("github.repo.search","search","Search repositories","Search accessible repositories by owner, name, or topic.",["github.repo.read"]),Ft("github.issue.search","search","Search issues","Search accessible GitHub issues.",["github.issue.read"]),Ft("github.pull_request.search","search","Search pull requests","Search accessible GitHub pull requests.",["github.pull_request.read"]),Ft("github.repo.read","read","Read repository","Read grounded repository metadata or file context.",["github.repo.read"],{requiredKeys:["ref"]}),Ft("github.issue.read","read","Read issue","Read a grounded GitHub issue and comments.",["github.issue.read"],{requiredKeys:["ref"]}),Ft("github.pull_request.read","read","Read pull request","Read a grounded pull request, checks, reviews, or diff summary.",["github.pull_request.read"],{requiredKeys:["ref"]}),Ft("github.issue.create","write","Create issue","Create an explicitly approved GitHub issue and return readback verification.",["github.issue.write"],{requiredKeys:["repo","title","body"]}),Ft("github.issue.comment","write","Comment on issue","Create an explicitly approved GitHub issue comment and return readback verification.",["github.issue.write"],{requiredKeys:["ref","body"]}),Ft("github.issue.update","write","Update issue","Apply an explicitly approved issue metadata/content update and return readback verification.",["github.issue.write"],{requiredKeys:["ref"]}),Ft("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"]}),Ft("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:[Ft("turnkey.wallets.read","read","Read Agent Wallet","Read the address and metadata for the connected OpenPond Agent Wallet.",["turnkey.wallets.read"]),Ft("turnkey.balances.read","read","Read wallet balances","Read supported-network balances for the connected OpenPond Agent Wallet.",["turnkey.balances.read"]),Ft("turnkey.activities.read","read","Read wallet activity","Read recent Turnkey activity for the connected OpenPond Agent Wallet.",["turnkey.activities.read"])],x:[Ft("x.profile.read","read","Read profile","Read the connected X account profile.",["x.profile.read"]),Ft("x.post.read","read","Read post","Read a public X post by stable ref, status URL, or post id.",["x.search.read"],{requiredKeys:["ref"]}),Ft("x.search.posts","search","Search recent posts","Search public X posts from the X recent-search window by grounded query.",["x.search.read"]),Ft("x.mentions.search","search","Search mentions","Search mentions for the connected X account.",["x.mentions.read"]),Ft("x.mention.read","read","Read mention","Read a grounded mention or post ref.",["x.mentions.read"],{requiredKeys:["ref"]}),Ft("x.post.create","write","Create post","Create an explicitly approved X post and return readback verification.",["x.post.write"],{requiredKeys:["text"]}),Ft("x.reply.create","write","Create reply","Create an explicitly approved X reply and return readback verification.",["x.reply.write"],{requiredKeys:["inReplyToRef","text"]})],mcp:[]},JN={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(`
|
|
104
|
-
`),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(`
|
|
105
|
-
`),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(`
|
|
106
|
-
`),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(`
|
|
107
|
-
`),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(`
|
|
108
|
-
`),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(`
|
|
109
|
-
`),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(`
|
|
110
|
-
`)},Yae=Ev.map(e=>{const t=Lw(e),n=JN[e];return{...t,provider:e,body:n,sourceHash:`connected-app-skill:${e}:${hD(n)}`,charCount:n.length}});function ZN(e){const t=Ov(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=dD(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)),r=e.capabilityIds.filter(l=>!o.has(l));if(r.length>0)return{ok:!1,error:`Connected app capability ${r[0]} is not allowed for ${e.provider} ${e.operation}.`};const s=QN(e);return s.ok?{ok:!0,request:e}:s}function YN(e){const t=jm(e);return t?jv[t]:[]}function QN(e){const t=nD(e.args),n=YN(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 r=iD(e.args,e.operation);for(const s of a.input?.requiredKeys??[]){const l=r[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 XN=[{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"}],Mm=XN,eD=Ev.map(e=>{const t=Mm.filter(a=>a.providerFamily===e),n=t[0];return{id:e,label:lc(e),shortLabel:n.shortLabel,category:n.category,icon:n.icon,description:n.description,setupSurfaces:t,capabilities:Mv[e],skills:lD(e),tools:cD(e),operations:jv[e],leasePolicy:uD(e)}});function Hw(e){const t=tD(e);return t?Mm.find(n=>n.id===t)??null:null}function Ov(e){const t=jm(e);return t?eD.find(n=>n.id===t)??null:null}function Qae(e){const t=Hw(e.appId),n=rD(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 r=e.teamId?.trim();return r&&o.searchParams.set("teamId",r),o.toString()}function tD(e){const t=e?.trim().toLowerCase().replace(/[-\s]+/g,"_");return t?t==="teams"||t==="microsoft"?"microsoft_teams":Mm.some(n=>n.id===t)?t:null:null}function jm(e){const t=e?.trim().toLowerCase().replace(/[-\s]+/g,"_");return t?t==="teams"||t==="microsoft"?"microsoft_teams":Ev.includes(t)?t:Hw(t)?.providerFamily??null:null}function ch(e={}){const t=mD(e.connections??[]);return Mm.map(n=>{const a=Ov(n.providerFamily),o=n.statusSource==="integration_connection"?t.filter(l=>l.provider===n.providerFamily):[],r=o.some(l=>l.status==="active"),s=pD(n,r);return{...n,providerLabel:a.label,setupSurfaceLabel:sD(n.setupSurface),status:s,statusLabel:fD(n,s,o),connections:o,connected:r,capabilities:cS(n,a.capabilities),capabilityLabels:cS(n,a.capabilities).map(l=>l.label),leasePolicy:a.leasePolicy}})}function tn(e,t,n,a,o){return{id:e,label:t,description:n,access:a,leaseable:o}}function Ft(e,t,n,a,o,r){return{id:e,operation:t,label:n,description:a,capabilityIds:o,...r?{input:r}:{},requiresReadback:t==="write",requiresRuntimeLease:!1}}function nD(e){return aD(e.operation)}function aD(e){return typeof e=="string"&&e.trim()?e.trim():null}function iD(e,t){return t==="write"?oD(e.input)?e.input:{}:e}function oD(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function rD(e){const t=e?.trim();if(!t)return lh;try{const n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?lh:(n.pathname="/",n.search="",n.hash="",n.toString())}catch{return lh}}function lc(e){return e==="microsoft_teams"?"Microsoft Teams":e==="mcp"?"OpenPond MCP":e==="x"?"X":e[0].toUpperCase()+e.slice(1)}function sD(e){return e==="native_bot"?"Native app":e==="oauth_connector"?"OAuth connector":e==="wallet_connector"?"Wallet connector":"MCP endpoint"}function lD(e){return[Lw(e)]}function Lw(e){return{name:`${e}-connected-app`,description:`Use ${lc(e)} safely through connected app tools.`,path:`integration_skills/${e}.md`}}function cD(e){if(e==="mcp")return[];const t=Mv[e],n=jv[e],a=t.filter(s=>s.access==="read").map(s=>s.id),o=t.filter(s=>s.access==="write").map(s=>s.id),r=[];return n.some(s=>s.operation==="search")&&r.push({name:"connected_app_search",description:`Search ${lc(e)} through a server-owned connected app connector.`,capabilityIds:a,write:!1}),n.some(s=>s.operation==="read")&&r.push({name:"connected_app_read",description:`Read a grounded ${lc(e)} object through a server-owned connected app connector.`,capabilityIds:a,write:!1}),o.length>0&&n.some(s=>s.operation==="write")&&r.push({name:"connected_app_write",description:`Perform an explicitly approved ${lc(e)} write through a server-owned connected app connector.`,capabilityIds:o,write:!0}),r}function dD(e){return e==="search"?"connected_app_search":e==="read"?"connected_app_read":"connected_app_write"}function uD(e){const t=Mv[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 cS(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 mD(e){return e.flatMap(t=>{const n=jm(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 pD(e,t){return e.statusSource==="integration_connection"?t?"connected":"disconnected":"setup_available"}function fD(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 hD(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 gD=v(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),vD=v(["search","read","write"]),bD=v(GN);c({provider:gD,operation:vD,toolName:bD,sessionId:i().trim().min(1).max(200),turnId:i().trim().min(1).max(200),toolCallId:i().trim().min(1).max(300),userPrompt:i().max(2e5),connectionIds:p(i().trim().min(1).max(300)).min(1).max(8),capabilityIds:p(i().trim().min(1).max(200)).min(1).max(64),args:le(i(),ce()).default({})}).strict().superRefine((e,t)=>{const n=ZN(e);n.ok||t.addIssue({code:oa.custom,message:n.error})});c({ok:I(),output:i().nullable().optional(),data:ce().optional()}).strict();const yD="local_path:";function qw(e){return`${yD}${e.trim()}`}c({appId:i(),source:v(["openpond","github","local_git","local_folder","unknown"]),workspacePath:i(),repoPath:i(),initialized:I(),remoteUrl:i().nullable(),expectedRemoteUrl:i().nullable(),currentBranch:i().nullable(),headCommit:i().nullable().optional().default(null),upstreamBranch:i().nullable().optional().default(null),ahead:u().int().nonnegative().optional().default(0),behind:u().int().nonnegative().optional().default(0),diverged:I().optional().default(!1),linkedSourceHeadCommit:i().nullable().optional().default(null),aheadOfLinkedSource:u().int().nonnegative().optional().default(0),behindLinkedSource:u().int().nonnegative().optional().default(0),divergedFromLinkedSource:I().optional().default(!1),linkedSourceComparisonError:i().nullable().optional().default(null),lastFetchAt:i().nullable().optional().default(null),defaultBranch:i().nullable(),branches:p(i()),dirty:I(),changedFilesCount:u(),untrackedFilesCount:u(),error:i().nullable(),updatedAt:i()});const SD=c({path:i(),status:i(),additions:u(),deletions:u(),patch:i(),content:i().nullable().optional().default(null)}),xD=c({appId:i(),repoPath:i(),initialized:I(),dirty:I(),filesChanged:u(),additions:u(),deletions:u(),repoFiles:p(i()).optional().default([]),files:p(SD),error:i().nullable(),updatedAt:i()});c({branch:i().trim().min(1).max(160)});c({path:i().trim().min(1),content:i()});const dS=c({line:u().int().nonnegative(),character:u().int().nonnegative()}),kD=c({start:dS,end:dS}),wD=c({path:i(),range:kD,severity:v(["error","warning","info","hint"]),message:i(),source:i().nullable().optional().default(null),code:i().nullable().optional().default(null)}),Uw=c({id:i(),root:i(),status:v(["connected","unavailable","error"]),message:i().nullable().optional().default(null)});c({path:i().trim().min(1),content:i().optional(),waitForDiagnostics:I().optional().default(!0)});c({appId:i(),path:i(),diagnostics:p(wD),servers:p(Uw),updatedAt:i()});const ID=c({operation:v(["hover","definition","references","documentSymbol"]),path:i().trim().min(1),content:i().optional(),line:u().int().nonnegative().optional(),character:u().int().nonnegative().optional()});c({appId:i(),operation:ID.shape.operation,path:i(),results:ce(),servers:p(Uw),updatedAt:i()});const _D=c({pinned:I().optional(),archived:I().optional(),order:u().optional()}),CD=le(i(),_D),zw=v(["local","sandbox"]),RD=v(["pinned","saved_for_later"]),Bw=c({id:i().min(1),workspaceKind:zw,workspaceId:i().min(1),workspaceName:i().min(1),path:i().min(1),status:RD,order:u().int().nonnegative().nullable().default(null),sourceSessionId:i().min(1).nullable().default(null),available:I().default(!0),createdAt:i().min(1),updatedAt:i().min(1)});c({items:p(Bw)});c({workspaceKind:zw,workspaceId:i().trim().min(1),workspaceName:i().trim().min(1),path:i().trim().min(1),status:v(["pinned","saved_for_later","none"]),order:u().int().nonnegative().nullable().optional(),sourceSessionId:i().trim().min(1).nullable().optional()});v(["pin","save_for_later","remove","list"]);function PD(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 Xae(e){return["sidebar-file",e.workspaceKind,encodeURIComponent(e.workspaceId),encodeURIComponent(PD(e.path))].join(":")}const AD=c({id:i(),name:i(),type:i(),status:i(),isActive:I().nullable(),price:i().nullable(),currency:i().nullable(),credits:i().nullable()}).passthrough(),TD=c({reachable:I(),authenticated:I().nullable(),apiBase:i(),latencyMs:u(),status:u().nullable(),service:i().nullable(),checkedAt:i(),error:i().nullable()}),ED=c({id:i().nullable(),email:i().nullable(),name:i().nullable(),handle:i().nullable(),image:i().nullable(),timezone:i().nullable(),isAdmin:I().nullable(),isVerified:I().nullable(),dailyAgentAppId:i().nullable(),dailyAgentDeploymentId:i().nullable(),credits:i().nullable()}),MD=c({handle:i(),baseUrl:i().nullable().optional()}),jD=c({state:v(["signed_out","signed_in","loading","switching","auth_error"]),activeProfile:MD.nullable(),label:i(),email:i().nullable(),avatarUrl:i().nullable(),environment:i().nullable(),baseUrl:i().nullable(),apiBaseUrl:i().nullable(),chatApiBaseUrl:i().nullable().optional().default(null),creditsLabel:i().nullable(),profile:ED.nullable(),products:p(AD),apiHealth:TD.nullable(),accounts:p(c({handle:i(),baseUrl:i().nullable(),apiBaseUrl:i().nullable().optional().default(null),chatApiBaseUrl:i().nullable().optional(),environment:i().nullable(),isActive:I(),authHealth:v(["signed_out","signed_in","auth_error","unknown"]),displayLabel:i().nullable(),email:i().nullable().optional().default(null),avatarUrl:i().nullable(),apiKeyHint:i().nullable().optional(),apiKeyAccess:c({ownerType:v(["user","team","organization","service"]).nullable(),teamId:i().nullable(),scopes:p(i())}).nullable().optional().default(null)})),error:i().nullable()}),uS=c({asOf:i().nullable(),refreshing:I(),lastRefreshError:i().nullable(),source:v(["fresh","cache","empty"])}),OD=c({available:I(),binaryPath:i().nullable(),version:i().nullable(),authHealth:v(["unknown","signed_in","signed_out","auth_error"]),account:c({type:i(),email:i().nullable(),planType:i().nullable(),label:i().nullable()}).nullable().default(null),appServer:c({status:v(["idle","starting","ready","error"]),lastError:i().nullable()})}),$v="gpt-5.6-sol",Ws="openpond-chat",Tr="openpond",wc=Ws,Nv="default",Dv="high",Om="ask",ul=Nr,Hv=v(["default","auto-review","full-access"]),Zc=v(["ask","full-access","disabled"]),$m=v(["off","low","medium","high","xhigh","max"]),Yc=v(["sandbox_app","local_project","sandbox","sandbox_template"]);v(["openpond"]);const $D=v(["provider_usage","provider_tokenizer","model_family","heuristic"]),ND=c({provider:ul,model:i().min(1),usedTokens:u().int().nonnegative(),maxContextTokens:u().int().positive(),usableContextTokens:u().int().positive(),percentFull:u().min(0).max(100),source:$D,updatedAtEventId:i().nullable()}),pg=c({pinned:I().default(!1),projects:I().default(!1),cloudProjects:I().default(!1),chats:I().default(!1),savedForLater:I().default(!0)}),DD=v(["auto","off"]),HD=v(["typescript","python","rust"]),Fw=v(["auto","disabled","custom"]),Xi=c({mode:Fw.default("auto"),customCommand:i().trim().max(4096).default("")}),Gu=c({languageServers:DD.default("auto"),diagnosticsWhileEditing:I().default(!0),checkOnSave:I().default(!0),languages:c({typescript:Xi.optional().default(()=>Xi.parse({})),python:Xi.optional().default(()=>Xi.parse({})),rust:Xi.optional().default(()=>Xi.parse({}))}).optional().default(()=>({typescript:Xi.parse({}),python:Xi.parse({}),rust:Xi.parse({})}))}),LD=c({language:HD,label:i(),mode:Fw,status:v(["found","missing","disabled","error"]),command:i().nullable(),message:i().nullable()});c({settings:Gu,languages:p(LD),updatedAt:i()});const qD=c({id:i(),root:i(),status:v(["starting","connected","unavailable","error"]),message:i().nullable().optional().default(null),openedDocuments:u().int().nonnegative(),pendingRequests:u().int().nonnegative(),lastUsedAt:i(),stderrTail:i()});c({clients:p(qD),maxClients:u().int().positive(),idleTimeoutMs:u().int().positive(),updatedAt:i()});const fg=c({autoEnabled:I().default(!0),triggerPercent:u().int().min(50).max(95).default(85),summaryModel:v(["same_model"]).default("same_model")}),hg=c({defaultModelRef:Sn.nullable().default(null),creationMode:v(["defaults","customize"]).default("customize"),autoApproveEvidence:I().default(!1)}),mS=c({defaultChatProvider:ul.default(Tr),defaultChatModel:i().min(1).default(wc),defaultChatModelRef:Sn.nullable().optional(),subagents:xc.optional().default(()=>xc.parse({})),codexPermissionMode:Hv.default(Nv),codexReasoningEffort:$m.default(Dv),openPondCommandAccessMode:Zc.default(Om),defaultBranchPrefix:i().trim().max(48).default("feat/"),defaultNewProjectDirectory:i().trim().max(4096).default(""),defaultTeamId:i().trim().max(191).nullable().default(null),advancedWorkspaceControls:I().default(!1),steerActiveResponses:I().default(!0),contextCompaction:fg.optional().default(()=>fg.parse({})),training:hg.optional().default(()=>hg.parse({})),sidebarWidth:u().int().min(244).max(560).default(332),diffPanelWidth:u().int().min(320).max(2400).default(560),sidebarSectionsCollapsed:pg.optional().default(()=>pg.parse({})),editor:Gu.optional().default(()=>Gu.parse({}))}),UD="default",Vw=[{id:"default",name:"Balanced",source:"built_in",description:"Clear, useful, and concise.",content:`You are OpenPond Chat, a clear and useful AI assistant.
|
|
111
|
-
Be concise, accurate, and direct.
|
|
112
|
-
Do not use emojis.
|
|
113
|
-
Ask only when missing information would materially change the answer.
|
|
114
|
-
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.
|
|
115
|
-
Be direct, concrete, and outcome-focused.
|
|
116
|
-
Do not use emojis.
|
|
117
|
-
Prefer simple working solutions over clever abstractions.
|
|
118
|
-
Call out weak assumptions plainly.`},{id:"friendly",name:"Friendly",source:"built_in",description:"Warm, conversational, and approachable.",content:`You are a friendly AI assistant.
|
|
119
|
-
Use a warm, conversational tone without filler.
|
|
120
|
-
Do not use emojis.
|
|
121
|
-
Explain decisions clearly and keep the user moving.
|
|
122
|
-
Be patient when clarifying tradeoffs.`},{id:"formal",name:"Formal",source:"built_in",description:"Polished, careful, and professional.",content:`You are a formal AI assistant.
|
|
123
|
-
Use precise, professional language.
|
|
124
|
-
Do not use emojis.
|
|
125
|
-
Structure answers clearly and avoid casual phrasing.
|
|
126
|
-
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.
|
|
127
|
-
Prioritize correctness, implementation detail, and edge cases.
|
|
128
|
-
Do not use emojis.
|
|
129
|
-
Use concise explanations, but include necessary specifics.
|
|
130
|
-
Surface risks, constraints, and verification steps.`}],Lv=i().trim().min(1).max(120),zD=c({id:Lv,name:i(),source:v(["built_in","custom"]).default("custom"),description:i(),content:i()}),pS=c({activeTemplateId:Lv.default(UD),customized:I().default(!1),soul:i(),soulPath:i().nullable(),updatedAt:i().nullable(),templates:p(zD).default(()=>[...Vw])}),BD=c({id:i(),host:i(),port:u(),startedAt:i(),storePath:i(),version:i(),runtimeVersion:i()}),qv=v(["chat","work","development"]);v(["chat","models","console","development"]);const FD="work",We=i().trim().min(1).nullable(),Ya=le(i(),ce()).default({}),VD=v(["direct_prompt_create","context_backed_create","create_as_agent","workflow_suggestion","local_extend","hosted_create","local_import","direct_prompt_improve","context_backed_improve","hosted_improve","lab_create","lab_improve","training"]),Kw=v(["/create","/edit","openpond extend","create_as_agent","suggest_workflow","local_import","lab_create","lab_improve","training"]),KD=v(["create","improve","import","promote"]),WD=v(["planning","awaiting_questions","awaiting_plan_approval","paused","applying_source","running_checks","evaluating","awaiting_promotion","opening_pull_request","pull_request_open","reconciling_release","released","rejected","ready","ready_local","pushing_hosted","running_hosted_checks","published_hosted","blocked","failed","cancelled"]),Jd=v(["always_require_plan_approval","approval_already_granted"]);v(["local_profile","hosted_profile","promote_local_to_hosted","managed_artifact"]);const GD=ot("kind",[c({kind:b("local"),sourceAuthority:b("local_profile"),activeProfile:i().trim().min(1).nullable(),repoPath:We,sourcePath:We,localHead:We,confirmationPolicy:Jd.default("always_require_plan_approval")}),c({kind:b("hosted"),sourceAuthority:b("hosted_profile"),teamId:We,projectId:We,activeProfile:i().trim().min(1).nullable(),sourceRef:We,baseSha:We,confirmationPolicy:Jd.default("always_require_plan_approval")}),c({kind:b("promote_local_to_hosted"),sourceAuthority:b("promote_local_to_hosted"),teamId:We,projectId:We,activeProfile:i().trim().min(1).nullable(),repoPath:We,sourcePath:We,localHead:We,hostedHead:We,sourceRef:We,confirmationPolicy:Jd.default("always_require_plan_approval")}),c({kind:b("managed_artifact"),sourceAuthority:b("managed_artifact"),activeProfile:i().trim().min(1).nullable(),confirmationPolicy:Jd.default("always_require_plan_approval")})]),JD=c({id:We,kind:v(["user","system","automation"]).default("user"),label:We}),ZD=c({profileId:i().trim().min(1),conversationId:We,originTurnId:We,projectId:We,targetProject:c({id:We,name:We,workspacePath:We,sourceRef:We,baseSha:We}).nullable()}),ec=c({messageIds:p(i().trim().min(1)).default([]),conversationExcerpts:p(c({messageId:We,role:i().trim().min(1).nullable(),excerpt:i().trim().min(1),reason:i().trim().min(1).nullable()})).default([]),attachments:p(c({id:We,name:i().trim().min(1),mediaType:We,ref:We})).default([]),apps:p(c({id:i().trim().min(1),name:i().trim().min(1),connectionId:We,required:I().default(!1)})).default([]),tools:p(c({name:i().trim().min(1),inputSummary:We,outputSummary:We,artifactRefs:p(i().trim().min(1)).default([]),sideEffects:p(i().trim().min(1)).default([])})).default([]),signalRefs:p(i().trim().min(1)).default([]),evalRefs:p(i().trim().min(1)).default([]),targetRepoAssumptions:p(i().trim().min(1)).default([])}),fs={id:We,displayName:We},Uv=ot("kind",[c({kind:b("unselected"),...fs}),c({kind:b("agent"),...fs,defaultActionKey:We}),c({kind:b("skill"),...fs,skillName:We}),c({kind:b("extension"),...fs,slot:We}),c({kind:b("model"),...fs,trainingPlanId:We,trainingJobId:We,artifactId:We}),c({kind:b("configuration"),...fs,key:We})]),gg=v(["agent","skill","extension","model","configuration"]),YD=c({schemaVersion:b("openpond.createImprove.evidenceSnapshot.v1"),id:i().trim().min(1),contentHash:i().trim().min(8),consent:c({status:v(["granted","denied","revoked"]),scope:v(["metadata_only","selected_turns","full_session","direct_intent"]),reviewedBy:We,reviewedAt:i().trim().min(1)}),sources:p(c({kind:v(["signal","conversation","direct_correction","manual_intent","artifact"]),id:i().trim().min(1),sourceHash:i().trim().min(8),excerptRef:We})).min(1),reviewerIntent:i().trim().min(1),createdAt:i().trim().min(1),metadata:Ya}),Ww=c({schemaVersion:b("openpond.createImprove.tasksetRef.v1"),id:i().trim().min(1),revision:u().int().positive(),contentHash:i().trim().min(8),evidenceSnapshotIds:p(i().trim().min(1)).min(1),policyBoundary:c({policyVisibleFields:p(i().trim().min(1)).default([]),privilegedFields:p(i().trim().min(1)).default([]),hiddenGraderRefs:p(i().trim().min(1)).default([]),connectedAppScopes:p(i().trim().min(1)).default([])}),targetRecommendation:c({kind:gg,rationale:p(i().trim().min(1)).min(1),confidence:u().min(0).max(1)}),authoringSplitRefs:p(i().trim().min(1)).default([]),privateSplitRefs:p(i().trim().min(1)).default([]),approvedBy:We,approvedAt:i().trim().min(1),metadata:Ya}),QD=c({kind:v(["npm_package","runtime_tool","setup_command","secret","integration","volume","target_project","external_service"]),name:i().trim().min(1),status:v(["declared","required","blocked","satisfied"]).default("declared"),detail:We,metadata:Ya}),XD=c({mode:v(["chat","direct_action","chat_and_direct_actions"]),label:i().trim().min(1),detail:i().trim().min(1),defaultActionKey:We,directActionHint:We,artifactPolicy:i().trim().min(1)}),eH=c({schemaVersion:b("openpond.createImprove.plan.v1"),id:i().trim().min(1),runId:i().trim().min(1),status:v(["draft","pending_approval","approved","rejected","cancelled","superseded"]).default("pending_approval"),objective:i().trim().min(1),summary:i().trim().min(1),capturedContextSummary:i().trim().min(1),defaultChatAction:c({key:We,label:We,required:I().default(!0)}),sourcePlan:p(c({path:i().trim().min(1),operation:v(["create","update","delete","inspect"]),reason:i().trim().min(1)})).default([]),requirements:p(QD).default([]),checks:p(c({name:i().trim().min(1),command:i().trim().min(1),required:I().default(!0)})).default([]),approvalId:We,approvedAt:We,editedFromPlanId:We,metadata:Ya,createdAt:i().trim().min(1),updatedAt:i().trim().min(1)}),tH=c({id:i().trim().min(1),label:i().trim().min(1),value:i().trim().min(1),description:We,metadata:Ya}),nH=c({value:i().trim().min(1),label:We,detail:We,answeredAt:i().trim().min(1),metadata:Ya}),aH=c({id:i().trim().min(1),kind:v(["single_choice","free_text"]).default("single_choice"),title:i().trim().min(1),prompt:i().trim().min(1),required:I().default(!0),status:v(["pending","answered","skipped"]).default("pending"),options:p(tH).default([]),answer:nH.nullable().default(null),metadata:Ya}),iH=c({schemaVersion:b("openpond.createImprove.workflowCapture.v1"),id:i().trim().min(1),runId:i().trim().min(1),command:Kw,objective:i().trim().min(1),conversationExcerpts:ec.shape.conversationExcerpts,attachments:ec.shape.attachments,apps:ec.shape.apps,tools:ec.shape.tools,sideEffects:p(i().trim().min(1)).default([]),profileActions:p(i().trim().min(1)).default([]),externalProviders:p(i().trim().min(1)).default([]),environmentVariables:p(i().trim().min(1)).default([]),files:p(i().trim().min(1)).default([]),schedules:p(i().trim().min(1)).default([]),webhooks:p(i().trim().min(1)).default([]),channelTargets:p(i().trim().min(1)).default([]),outputArtifacts:p(i().trim().min(1)).default([]),targetRepoAssumptions:p(i().trim().min(1)).default([]),traceRefs:p(i().trim().min(1)).default([]),metadata:Ya,createdAt:i().trim().min(1)}),Gw=c({provider:b("github"),number:u().int().positive(),url:i().url(),state:v(["open","merged","closed"]),baseBranch:i().trim().min(1),headBranch:i().trim().min(1),mergeCommit:We,openedAt:i().trim().min(1),updatedAt:i().trim().min(1)}),oH=c({baseBranch:i().trim().min(1),baseCommit:i().trim().min(1),branch:i().trim().min(1),headCommit:We,remoteName:i().trim().min(1).default("origin"),remoteUrl:We,worktreePath:We,changedPaths:p(i().trim().min(1)).default([]),diffStat:We,pullRequest:Gw.nullable().default(null)}),rH=c({id:i().trim().min(1),target:Uv,status:v(["draft","authored","checking","evaluated","accepted","rejected","failed"]),git:oH.nullable().default(null),parentCandidateId:We.default(null),tasksetRef:Ww.nullable().default(null),authoringModelRef:We.default(null),allowedPaths:p(i().trim().min(1)).default([]),sourceRefs:p(i().trim().min(1)).default([]),artifactRefs:p(i().trim().min(1)).default([]),checkRefs:p(i().trim().min(1)).default([]),evaluationReceiptRefs:p(i().trim().min(1)).default([]),createdAt:i().trim().min(1),updatedAt:i().trim().min(1),metadata:Ya}),sH=c({id:i().trim().min(1),candidateId:We,target:Uv,evaluatorKind:v(["agent_sdk","taskset","extension","skill","configuration","checks"]).default("checks"),subject:v(["active","candidate","post_release","standalone"]).default("standalone"),sourceCommit:We.default(null),sourceBranch:We.default(null),tasksetId:We.default(null),tasksetHash:We.default(null),taskAttemptRefs:p(i().trim().min(1)).default([]),status:v(["pending","passed","failed","blocked"]),publishGate:v(["passed","failed","not_applicable"]).default("not_applicable"),summaryCounts:c({total:u().int().nonnegative(),passed:u().int().nonnegative(),failed:u().int().nonnegative()}).nullable().default(null),evalRefs:p(i().trim().min(1)).default([]),artifactRefs:p(i().trim().min(1)).default([]),summary:We,createdAt:i().trim().min(1),metadata:Ya}),lH=c({mode:v(["foreground","background"]).default("background"),pauseAllowed:I().default(!0),cancellationAllowed:I().default(!0)}),cH=c({mode:v(["single","bounded","until_evals_pass"]).default("single"),maximumAttempts:u().int().min(1).max(20).default(1),currentAttempt:u().int().min(0).max(20).default(0)}),dH=c({kind:v(["candidate_authoring","local_apply","hosted_turn","training_job","evaluation","pull_request","release"]),id:i().trim().min(1),status:We,metadata:Ya}),uH=c({status:v(["not_requested","pending","released","rejected","rolled_back"]),profileCommit:We,profileTag:We,releaseReceiptRef:We,pullRequest:Gw.nullable().default(null),updatedAt:We}),Qc=c({schemaVersion:b("openpond.createImprove.run.v1"),id:i().trim().min(1),revision:u().int().nonnegative(),operation:KD,surface:VD,command:Kw,objective:i().trim().min(1),state:WD,adapter:GD,actor:JD,scope:ZD,context:ec,target:Uv,evidenceSnapshots:p(YD).default([]),tasksetRef:Ww.nullable().default(null),targetSelection:c({status:v(["open","recommended","confirmed"]),preselectedKind:gg.nullable(),confirmedKind:gg.nullable()}).nullable().default(null),plan:eH.nullable(),workflowCapture:iH.nullable(),executionPolicy:lH.default({mode:"background",pauseAllowed:!0,cancellationAllowed:!0}),iterationPolicy:cH.default({mode:"single",maximumAttempts:1,currentAttempt:0}),approvalIds:p(i().trim().min(1)).default([]),questionIds:p(i().trim().min(1)).default([]),questions:p(aH).default([]),candidates:p(rH).default([]),evaluationReceipts:p(sH).default([]),checkRefs:p(i().trim().min(1)).default([]),sourceRefs:p(i().trim().min(1)).default([]),externalExecutionRefs:p(dH).default([]),localProfileCommit:We,hostedSourceCommit:We,hostedSourceRef:We,releaseOutcome:uH.default({status:"not_requested",profileCommit:null,profileTag:null,releaseReceiptRef:null,pullRequest:null,updatedAt:null}),blockedReason:We,appliedActionIds:p(i().trim().min(1)).max(200).default([]),metadata:Ya,createdAt:i().trim().min(1),updatedAt:i().trim().min(1)}),_i={runId:i().trim().min(1),expectedRevision:u().int().nonnegative(),actionId:i().trim().min(1)};ot("type",[c({..._i,type:b("answer_question"),questionId:i().trim().min(1),value:i().trim().min(1)}),c({..._i,type:b("approve_plan")}),c({..._i,type:b("revise_plan"),revision:i().trim().min(1)}),c({..._i,type:b("cancel"),reason:We.optional().default(null)}),c({..._i,type:b("pause")}),c({..._i,type:b("resume")}),c({..._i,type:b("open_pull_request"),candidateId:i().trim().min(1)}),c({..._i,type:b("apply_candidate"),candidateId:i().trim().min(1)}),c({..._i,type:b("reject_candidate"),candidateId:i().trim().min(1),reason:We.optional().default(null)}),c({..._i,type:b("reconcile_pull_request"),candidateId:i().trim().min(1)})]);c({schemaVersion:b("openpond.createImprove.runList.v1"),runs:p(Qc),generatedAt:i().trim().min(1)});function eie(e){const t=XD.safeParse(e?.actionShape);return t.success?t.data:null}const Bi=c({source:v(["local","github","openpond_git"]),repositoryId:i().trim().min(1),profileId:i().trim().min(1)}),mH=c({ref:Bi,revision:i().nullable(),sourceHash:i()}),ml=le(i(),ce()).default({}),Ua=u().int().nonnegative(),Nm=i().trim().min(1).max(1e5),Jw=c({kind:v(["personal","team"]),id:T}).strict(),pH=c({name:T,release:W.nullable(),revision:Ua}).strict();c({schemaVersion:b("openpond.harnessWorkspace.v1"),id:T,ownerScope:Jw,name:i().trim().min(1).max(240),location:v(["local","hosted"]),sourceRevision:i().trim().min(1).max(500),revision:Ua,dirty:I(),currentChannel:pH,createdAt:ye,updatedAt:ye,metadata:ml}).strict();const Gs=v(["runtime","memory","prompt","skill","agent","product","taskset","training"]),Zw=v(["text_instruction","memory","dependency_selection","executable_code","business_logic","financial_logic","permission","connected_app","publication","deployment","training","model_binding","team_or_global"]),Yw=c({id:T,route:Gs,operation:v(["create","update","delete"]),target:i().trim().min(1).max(2e3),summary:i().trim().min(1).max(2e3),content:i().max(1e6).nullable(),contentHash:H.nullable(),effects:p(Zw).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=ct(e.content);e.contentHash!==n&&t.addIssue({code:"custom",message:`edit contentHash is ${e.contentHash}; expected ${n}`,path:["contentHash"]})}),Qw=c({workspaceId:T,revision:Ua,sourceRevision:i().trim().min(1).max(500),channelRevision:Ua}).strict(),so=c({id:T,revision:Ua,contentHash:H}).strict(),fH=c({schemaVersion:b("openpond.harnessTurnSnapshot.v1"),workspaceId:T,workspaceRevision:Ua,sourceRevision:i().trim().min(1).max(500),channelName:T,channelRevision:Ua,harnessRelease:W,toolCatalogHash:H.nullable().optional(),overlay:so.nullable().optional().default(null)}).strict(),hH=c({schemaVersion:b("openpond.harnessRunOverlay.v1"),id:T,runId:T,baseHarnessRelease:W,workspace:Qw,revision:Ua,status:v(["active","frozen","abandoned"]),edits:p(Yw).max(1e3),createdAt:ye,updatedAt:ye,metadata:ml}).strict();hH.extend({contentHash:H}).strict();const Xw=c({kind:v(["tool_event","recovery","validation","user_turn","work_output","work_receipt"]),id:T,contentHash:H.nullable()}).strict(),eI=c({id:T,kind:v(["dependency","schema","package","file_render","skill","prompt","business_formula","targeted_evaluation","observed_recovery","memory","component_activation"]),description:Nm,required:I()}).strict(),gH=c({schemaVersion:b("openpond.harnessImprovementProposal.v1"),id:T,overlay:so,baseHarnessRelease:W,expectedWorkspace:Qw,requestedScope:v(["personal","team","global"]),route:Gs,risk:v(["low","review","restricted"]),effects:p(Zw).min(1).max(20),evidence:p(Xw).min(1).max(1e3),edits:p(Yw).min(1).max(1e3),validationPlan:p(eI).min(1).max(100),expectedOutcome:Nm,createdAt:ye,metadata:ml}).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 r of o.effects)n.has(r)||t.addIssue({code:"custom",message:`edit effect ${r} is missing from proposal effects`,path:["edits",a,"effects"]})}new Set(e.validationPlan.map(a=>a.id)).size!==e.validationPlan.length&&t.addIssue({code:"custom",message:"validation plan ids must be unique",path:["validationPlan"]})});gH.extend({contentHash:H}).strict();const vH=c({schemaVersion:b("openpond.harnessTargetedValidationReceipt.v1"),id:T,proposal:W,validationId:T,kind:eI.shape.kind,status:v(["passed","failed","blocked","skipped"]),summary:Nm,evidenceRefs:p(Xw).max(1e3),createdAt:ye,metadata:ml}).strict();vH.extend({contentHash:H}).strict();const bH=v(["advanced","retained","conflict","rolled_back"]),yH=c({schemaVersion:b("openpond.harnessAdvanceReceipt.v1"),id:T,workspaceId:T,ownerScope:Jw,proposal:W.nullable(),expectedWorkspaceRevision:Ua,observedWorkspaceRevision:Ua,previousChannelRevision:Ua,nextChannelRevision:Ua,previousRelease:W.nullable(),nextRelease:W.nullable(),validationReceipts:p(W).max(100),decision:bH,reason:Nm,rollbackOf:W.nullable(),createdAt:ye,metadata:ml}).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"]})});yH.extend({contentHash:H}).strict();const SH=c({schemaVersion:b("openpond.harnessOverlayMergeReceipt.v1"),id:T,workspaceId:T,baseHarnessRelease:W,leftOverlay:so,rightOverlay:so,decision:v(["merged","conflict"]),mergedOverlay:so.nullable(),conflictTargets:p(i().trim().min(1).max(2e3)).max(1e3),requiresRevalidation:b(!0),createdAt:ye,metadata:ml}).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"]})});SH.extend({contentHash:H}).strict();const lo=i().trim().min(1).max(1e5),xH=v(["no_action","harness_maintenance","runtime","product","taskset","model_improvement"]),kH=v(["none","runtime_service","product_team","human_review","evaluation_system","training_system"]),tI=v(["observation","trigger","route_decision","refiner_outcome","proposal","validation","apply_receipt","harness_advance","rollback","work_outcome","taskset","evaluation","training_qualification","model_candidate"]),zv=c({kind:v(["personal","team"]),id:T}).strict(),nI=c({policy:W,state:v(["authorized","revoked","deleted","expired"]),checkedAt:ye}).strict(),Ic=c({evidence:W,kind:tI,sourceRef:T,sourcePolicy:nI,occurrenceKey:H,occurredAt:ye}).strict(),wH=c({evidence:W,sourcePolicy:nI.nullable(),reason:v(["outside_scope","before_watermark","duplicate","resolved","revoked","deleted","expired","sensitive","unverified","budget"])}).strict(),fS=c({cursor:H,throughCreatedAt:ye}).strict(),IH=c({fingerprint:H,recurrenceFamily:i().trim().min(1).max(1e3),statement:lo,candidateDisposition:v(["observe","confirm"]).optional(),independentOccurrences:u().int().positive().max(1e6),unresolvedOccurrences:u().int().positive().max(1e6)}).strict().refine(e=>e.unresolvedOccurrences<=e.independentOccurrences,"unresolved occurrences cannot exceed independent occurrences"),aI=v(["harness","runtime","product","retrieval","tools","evaluation","model"]),_H=c({layer:aI,status:v(["not_applicable","unresolved","resolved","blocked"]),reason:lo,evidenceRefs:p(W).max(1e3)}).strict(),CH=c({schemaVersion:b("openpond.harnessEvaluationReviewReceipt.v1"),id:T,ownerScope:zv,workspaceRef:T,harnessRelease:W,previousWatermark:fS.nullable(),nextWatermark:fS,selectedEvidence:p(Ic).max(1e4),excludedEvidence:p(wH).max(1e4),claim:IH.nullable(),classification:xH,triage:p(_H).max(16),reason:lo,nextAuthority:kH,maxEstimatedCostUsd:u().finite().nonnegative(),tasksetProposal:W.nullable(),evaluation:W.nullable(),trainingQualification:W.nullable(),policyVersion:T,createdAt:ye,metadata:Nn}).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"})});CH.extend({contentHash:H}).strict();c({id:T,evidence:W,kind:tI,sourceRef:T,occurredAt:ye,payload:le(i(),ce())}).strict();const RH=c({schemaVersion:b("openpond.harnessEvaluationReviewModelDecision.v2"),decision:b("no_action"),reason:lo,ignoredEvidence:p(c({id:T,reason:i().trim().min(1).max(2e3)}).strict()).max(1e3)}).strict(),PH=c({schemaVersion:b("openpond.harnessEvaluationReviewModelDecision.v2"),decision:b("review"),classification:v(["harness_maintenance","runtime","product","taskset"]),selectedEvidenceIds:p(T).min(1).max(1e3),ignoredEvidence:p(c({id:T,reason:i().trim().min(1).max(2e3)}).strict()).max(1e3),recurrenceFamily:i().trim().min(1).max(1e3),statement:lo,triageLayer:aI,expectedOutcome:lo,counterevidence:i().trim().max(1e4),confidence:u().min(0).max(1),candidateDisposition:v(["observe","confirm"]).nullable(),reason:lo}).strict().superRefine((e,t)=>{e.classification==="harness_maintenance"!==(e.candidateDisposition!==null)&&t.addIssue({code:"custom",message:"Harness maintenance requires a candidate disposition; external routes require null",path:["candidateDisposition"]})}),AH=c({schemaVersion:b("openpond.harnessEvaluationReviewModelDecision.v2"),decision:b("resolve_candidate"),candidateId:T,candidateFingerprint:H,selectedEvidenceIds:p(T).min(1).max(1e3),ignoredEvidence:p(c({id:T,reason:i().trim().min(1).max(2e3)}).strict()).max(1e3),confidence:u().min(0).max(1),reason:lo}).strict();ot("decision",[RH,PH,AH]);c({schemaVersion:b("openpond.harnessEvaluationReviewNavigationDecision.v1"),selectedEvidenceIds:p(T).min(1).max(50),reason:lo}).strict();const Xc=c({name:i().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:i().trim().min(1).max(2e3),inputSchema:le(i(),ce()),inputSchemaHash:H,sideEffect:v(["read","write"]),timeoutMs:u().int().positive().max(36e5)}).strict(),Bv=c({id:T,required:I(),scopes:p(i().trim().min(1).max(500)).max(100).default([]),portability:v(["portable","host_adapter","local_only","hosted_only"])}).strict(),TH=c({portable:I(),blockers:p(i().trim().min(1).max(2e3)).max(1e3),localOnlyAssetRefs:p(T).max(1e4),hostPrivateAssetRefs:p(T).max(1e4)}).strict(),EH=c({schemaVersion:b("openpond.agentSnapshot.v2"),id:T,sourceRelease:W.nullable(),instructions:p(bn).max(1e4),skills:p(bn).max(1e4),agents:p(bn).max(1e4),toolDeclarations:p(Xc).max(200),capabilityRequirements:p(Bv).max(200),dependencyLock:bn,portability:TH,metadata:Nn}).strict(),MH=EH.extend({contentHash:H}).strict(),iI=c({create:b(!0),reset:b(!0),step:b(!0),collect:b(!0),destroy:b(!0),resetScope:v(["task","attempt"])}).strict(),oI=c({visibleEvidence:p(T).max(1e3),privilegedEvidence:p(T).max(1e3),privateVerifierIsolation:I()}).strict(),jH=c({schemaVersion:b("openpond.harnessRelease.v2"),id:T,agentSnapshot:W,program:bn,tools:p(Xc).max(200),lifecycle:iI,graderInterface:oI,files:p(bn).max(1e5),metadata:Nn}).strict(),OH=jH.extend({contentHash:H}).strict(),$H=c({id:T,turn:u().int().nonnegative(),kind:v(["message","tool_call","terminal"]),name:T.nullable(),arguments:le(i(),ce()),content:i().max(1e6).nullable()}).strict(),NH=c({actionId:T,turn:u().int().nonnegative(),terminal:I(),output:le(i(),ce()),artifactRefs:p(Ma).max(1e5)}).strict(),DH=c({sequence:u().int().nonnegative(),type:v(["created","reset","action","observation","terminal","failure","collected","destroyed"]),payloadHash:H,metadata:Nn}).strict();c({schemaVersion:b("openpond.harnessTrace.v1"),manifest:W,taskId:T,seed:i().trim().min(1).max(500),events:p(DH).max(1e6),actions:p($H).max(1e5),observations:p(NH).max(1e5),terminal:I(),failureClass:Wc.nullable(),output:le(i(),ce()),contentHash:H}).strict();const Dm=i().trim().min(1).max(1e5),ed=le(i(),ce()).default({}),HH=v(["completed_tool_batch","before_model_step","turn_completed","turn_paused"]),rI=c({kind:HH,eventSequence:u().int().nonnegative(),occurredAt:ye}).strict(),sI=c({id:T,sequence:u().int().nonnegative().nullable(),contentHash:H}).strict(),LH=v(["tool_failure","retry","recovery","validation","user_turn","reusable_success","completion_detour"]),qH=v(["open","recovered","terminal"]),UH=c({name:i().trim().min(1).max(500),invocationKey:H}).strict(),zH=c({schemaVersion:b("openpond.improvementObservation.v1"),id:T,runRef:T,turnId:T,harnessRelease:W,overlay:so.nullable(),eventRefs:p(sI).min(1).max(100),kind:LH,state:qH,tool:UH.nullable(),deterministicClass:i().trim().min(1).max(500).nullable(),summary:Dm,createdAt:ye,metadata:ed}).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"]})});zH.extend({contentHash:H}).strict();const BH=c({schemaVersion:b("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(),FH=v(["no_action","route_deterministically","queue_refiner"]),VH=c({schemaVersion:b("openpond.refinementTriggerDecision.v1"),id:T,runRef:T,turnId:T,harnessRelease:W,overlay:so.nullable(),observations:p(W).max(100),decision:FH,deterministicRoute:Gs.nullable(),suggestedRoutes:p(Gs).max(8),reason:Dm,deduplicationKey:H,policy:BH,estimatedMaxCostUsd:u().finite().nonnegative(),pendingPlanCount:u().int().nonnegative(),boundary:rI,cooldownUntil:ye.nullable(),createdAt:ye,metadata:ed}).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"]})});VH.extend({contentHash:H}).strict();const KH=v(["runtime_service","refiner_model","human_review","evaluation_system","training_system"]),WH=c({schemaVersion:b("openpond.improvementRouteDecision.v1"),id:T,trigger:W,route:Gs,authority:KH,automatic:I(),reason:Dm,createdAt:ye,metadata:ed}).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"]})});WH.extend({contentHash:H}).strict();const GH=c({schemaVersion:b("openpond.harnessRefinerOutcome.v1"),id:T,trigger:W,decision:v(["no_action","proposed"]),proposal:W.nullable(),reason:Dm,evidenceRefs:p(W).max(100),estimatedCostUsd:u().finite().nonnegative(),createdAt:ye,metadata:ed}).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"]})});GH.extend({contentHash:H}).strict();const JH=v(["applied","retained","declined","conflict","rolled_back"]),ZH=c({schemaVersion:b("openpond.improvementApplyReceipt.v1"),id:T,proposal:W,beforeOverlay:so,afterOverlay:so.nullable(),decision:JH,boundary:rI,validationRefs:p(W).max(100),outcomeEvidenceRefs:p(sI).max(1e3),rollbackOf:W.nullable(),createdAt:ye,metadata:ed}).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"]})});ZH.extend({contentHash:H}).strict();const YH=v(["memory","prompt","skill","agent"]),QH=v(["runtime","product","taskset","training"]),XH=c({id:i().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),text:i().trim().min(1).max(1e4)}).strict(),lI=c({schemaVersion:b("openpond.refinerReviewProfile.v1"),id:i().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),version:i().trim().min(1).max(120),name:i().trim().min(1).max(200),objective:i().trim().min(1).max(1e4),instructions:p(XH).max(100),allowedProposalRoutes:p(YH).max(4),allowedExternalRoutes:p(QH).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"]})}),hS=c({schemaVersion:b("openpond.refinerRelease.v1"),id:i().trim().min(1).max(240),coreVersion:i().trim().min(1).max(120),coreHash:H,profile:lI,profileHash:H,composedPromptHash:H,createdAt:ye,contentHash:H}).strict(),eL=c({schemaVersion:b("openpond.refinerBinding.v1"),channel:b("active"),revision:u().int().nonnegative(),release:W,updatedAt:ye}).strict(),tL=c({schemaVersion:b("openpond.refinerTransitionReceipt.v1"),id:i().trim().min(1).max(240),operation:v(["initialize","update","activate","rollback"]),bindingChanged:I(),previousRelease:W.nullable(),nextRelease:W,actor:i().trim().min(1).max(240),reason:i().trim().min(1).max(1e4),authoringSkillHash:H.nullable(),validation:c({valid:I(),messages:p(i().max(2e3)).max(100)}).strict(),createdAt:ye,contentHash:H}).strict(),nL=c({schemaVersion:b("openpond.localHarnessRefinerDecision.v1"),decision:b("no_action"),reason:i().trim().min(1).max(1e4)}).strip(),aL=c({schemaVersion:b("openpond.localHarnessRefinerDecision.v1"),decision:b("route"),route:v(["runtime","product","taskset","training"]),summary:i().trim().min(1).max(2e3),expectedOutcome:i().trim().min(1).max(1e4),reason:i().trim().min(1).max(1e4)}).strip(),iL=c({schemaVersion:b("openpond.localHarnessRefinerDecision.v1"),decision:b("propose"),route:v(["memory","prompt","skill","agent"]),operation:v(["create","update","delete"]),target:i().trim().min(1).max(2e3),summary:i().trim().min(1).max(2e3),createContent:i().min(1).max(2e4).nullable(),find:i().min(1).max(8e3).nullable(),replace:i().max(8e3).nullable(),expectedOutcome:i().trim().min(1).max(1e4),reason:i().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"]})}),oL=ot("decision",[nL,aL,iL]),rL=oL,Fv=c({kind:v(["single_deterministic","recurrent_independent"]),supportingEvidenceIds:p(i().trim().min(1).max(2e3)).min(1).max(100),counterevidence:p(i().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"]})}),sL=c({schemaVersion:b("openpond.localHarnessRefinerDecision.v2"),decision:b("no_action"),reason:i().trim().min(1).max(1e4)}).strict(),lL=c({schemaVersion:b("openpond.localHarnessRefinerDecision.v2"),decision:b("route"),route:v(["runtime","product","taskset","training"]),summary:i().trim().min(1).max(2e3),evidenceBasis:Fv,expectedOutcome:i().trim().min(1).max(1e4),reason:i().trim().min(1).max(1e4)}).strict(),cL=c({schemaVersion:b("openpond.localHarnessRefinerDecision.v2"),decision:b("propose"),route:v(["memory","prompt","skill","agent"]),operation:v(["create","update","delete"]),target:i().trim().min(1).max(2e3),summary:i().trim().min(1).max(2e3),evidenceBasis:Fv,createContent:i().min(1).max(2e4).nullable(),find:i().min(1).max(8e3).nullable(),replace:i().max(8e3).nullable(),expectedOutcome:i().trim().min(1).max(1e4),reason:i().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"]})}),cI=ot("decision",[sL,lL,cL]);vt([rL,cI]);const Vv=c({memory:I(),prompt:I(),skill:I(),agent:I()}).strict(),dI=v(["memory","instruction","skill","agent"]),gS=c({path:i().trim().min(1).max(2e3),kind:dI,content:i().max(6e4),loaded:I()}).strict(),vS=c({path:i().trim().min(1).max(2e3),kind:dI,loaded:I()}).strict(),dL=c({capabilities:Vv,trigger:le(i(),ce()),observations:p(le(i(),ce())).max(20),admissibleEvidenceIds:p(i().trim().min(1).max(2e3)).max(1e4),reviewPacket:c({currentTurn:c({id:i().trim().min(1).max(2e3),status:i().trim().min(1).max(100).nullable(),error:i().max(2100).nullable(),prompt:i().max(8100).nullable(),assistantOutput:i().max(8100).nullable(),assistantOutputLinkCount:u().int().nonnegative()}).strict(),priorConversation:p(c({turnId:i().trim().min(1).max(2e3),status:i().trim().min(1).max(100).nullable(),prompt:i().max(3100).nullable(),assistantOutput:i().max(3100).nullable()}).strict()).max(3),timeline:p(le(i(),ce())).max(60),artifacts:p(le(i(),ce())).max(30),artifactDiagnostics:p(le(i(),ce())).max(20),executionProfile:c({modelRequestCount:u().int().nonnegative(),failedModelRequestCount:u().int().nonnegative(),promptTokens:u().int().nonnegative(),completionTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative(),toolFailureCount:u().int().nonnegative(),retryCount:u().int().nonnegative(),recoveryCount:u().int().nonnegative()}).strict(),priorIncidents:p(le(i(),ce())).max(3),truncation:c({timelineEventCount:u().int().nonnegative(),includedTimelineEventCount:u().int().nonnegative(),timelineTruncated:I()}).strict()}).strict(),runtimeActivation:c({admittedRelease:W,currentRelease:W,rebasedOntoCurrent:I(),admittedSourceFiles:p(gS).max(100),admittedSourceCatalog:p(vS).max(1e3)}).strict(),sourceFiles:p(gS).max(100),sourceCatalog:p(vS).max(1e3),additionalEvidence:ce().nullable().optional()}).strict(),uL=c({id:i().trim().min(1).max(240),revision:u().int().nonnegative(),contentHash:H}).strict();c({schemaVersion:b("openpond.hostedHarnessRefinerRequest.v2"),requestId:i().trim().min(1).max(240),idempotencyKey:i().trim().min(1).max(240),evidenceHash:H,harness:c({admittedRelease:W,currentRelease:W,overlay:uL,workspace:c({id:i().trim().min(1).max(240),revision:u().int().nonnegative(),sourceRevision:H,channelRevision:u().int().nonnegative()}).strict(),capabilities:Vv}).strict(),evidence:dL}).strict();const mL=c({promptTokens:u().int().nonnegative(),completionTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative()}).strict();c({schemaVersion:b("openpond.hostedHarnessRefinerResponse.v2"),requestId:i().trim().min(1).max(240),evidenceHash:H,admittedRelease:W,currentRelease:W,decision:cI,serviceRevision:i().trim().min(1).max(240),usage:mL}).strict();const pL=i().trim().min(1).max(2e3),Kv=i().trim().min(1).max(1e5),fL=v(["create","update","delete"]),hL=v(["memory","prompt","skill","agent"]),gL=v(["runtime","product","taskset","training"]),vL=v(["no_action","routed","applied","retained","failed"]),bL=v(["not_applicable","pending","passed","rejected","failed"]),yL=v(["not_applicable","pending","passed","failed"]),SL=c({schemaVersion:b("openpond.harnessRefinerActivityReceipt.v1"),id:T,runRef:T,turnId:T,result:vL,decision:v(["no_action","route","propose"]).nullable(),route:Gs.nullable(),operation:fL.nullable(),target:i().trim().min(1).max(2e3).nullable(),summary:pL,evidenceBasis:Fv.nullable(),critiqueStatus:bL,validationStatus:yL,trigger:W,outcome:W.nullable(),proposal:W.nullable(),applyReceipt:W.nullable(),inputHarness:W,outputHarness:W.nullable(),createdAt:ye}).strict().superRefine((e,t)=>{const n=e.result==="applied"||e.result==="retained";e.result==="no_action"?bS(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"||!gL.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"}),bS(t,e,{critiqueStatus:"not_applicable",validationStatus:"not_applicable"})):n?((e.decision!=="propose"||!hL.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"]})});SL.extend({contentHash:H}).strict();const xL=v(["unresolved","confirmed","resolved","rejected","expired"]),kL=c({kind:v(["applied_change","later_success","manual_rejection","source_revoked","expired"]),reason:Kv,evidenceRefs:p(W).max(1e3),resolvedAt:ye}).strict(),wL=c({schemaVersion:b("openpond.harnessRefinementCandidate.v1"),id:T,ownerScope:zv,workspaceRef:T,fingerprint:H,recurrenceFamily:i().trim().min(1).max(1e3),statement:Kv,status:xL,occurrences:p(Ic).max(1e3),counterevidence:p(Ic).max(1e3),sourceReviews:p(W).min(1).max(100),relatedHarnessReleases:p(W).max(100),firstSeenAt:ye,lastSeenAt:ye,lastReviewedAt:ye,expiresAt:ye,resolution:kL.nullable(),createdAt:ye,updatedAt:ye}).strict().superRefine((e,t)=>{yr(t,e.occurrences,"occurrences"),yr(t,e.counterevidence,"counterevidence"),yr(t,e.sourceReviews,"sourceReviews"),yr(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"]}),PL(t,e)});wL.extend({contentHash:H}).strict();const IL=v(["created","merged","rejected","expired","reopened","resolved"]),_L=c({schemaVersion:b("openpond.harnessRefinementCandidateLifecycleReceipt.v1"),id:T,candidateId:T,decision:IL,beforeCandidate:W.nullable(),afterCandidate:W,review:W,addedEvidence:p(Ic).max(1e3),removedEvidence:p(W).max(1e3),reason:Kv,createdAt:ye}).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"]}),yr(t,e.addedEvidence,"addedEvidence"),yr(t,e.removedEvidence,"removedEvidence");const n=new Set(e.removedEvidence.map(a=>vg(a)));e.addedEvidence.some(a=>n.has(vg(a.evidence)))&&t.addIssue({code:"custom",message:"candidate lifecycle evidence cannot be added and removed together",path:["removedEvidence"]})});_L.extend({contentHash:H}).strict();const CL=c({schemaVersion:b("openpond.harnessCrossRunRefinementRequest.v1"),id:T,ownerScope:zv,workspaceRef:T,candidate:W,candidateFingerprint:H,review:W,admittedHarness:W,evidence:p(Ic).min(1).max(1e3),capabilities:Vv,deduplicationKey:H,createdAt:ye}).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"]}),yr(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=RL(e);e.deduplicationKey!==n&&t.addIssue({code:"custom",message:`cross-run refinement deduplicationKey is ${e.deduplicationKey}; expected ${n}`,path:["deduplicationKey"]})});CL.extend({contentHash:H}).strict();function RL(e){return ct({schemaVersion:"openpond.harnessCrossRunRefinementIdentity.v1",workspaceRef:e.workspaceRef,candidateFingerprint:e.candidateFingerprint,admittedHarness:e.admittedHarness})}function bS(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 yr(e,t,n){const a=t.map(o=>vg(o));new Set(a).size!==a.length&&e.addIssue({code:"custom",message:`${n} references must be unique`,path:[n]})}function vg(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 PL(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],r=n[a];Date.parse(o[1])<=Date.parse(r[1])||e.addIssue({code:"custom",message:`${r[0]} must not precede ${o[0]}`,path:[r[0]]})}Date.parse(t.createdAt)>Date.parse(t.updatedAt)&&e.addIssue({code:"custom",message:"updatedAt must not precede createdAt",path:["updatedAt"]})}const AL=25*1024*1024,TL=c({path:bn.shape.path,base64:i().max(Math.ceil(AL/3)*4)}).strict(),uI=c({schemaVersion:b("openpond.harnessSourcePackage.v1"),agentSnapshot:MH,harnessRelease:OH,files:p(TL).max(1e4)}).strict();uI.extend({contentHash:H}).strict();uI.extend({schemaVersion:b("openpond.harnessPolicySourcePackage.v1"),contentHash:H}).strict();c({schemaVersion:b("openpond.harnessSourceSelection.v1"),mode:v(["taskset_owned","selected_release"]),harnessRelease:W,sourcePackageHash:H.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:i().min(1).max(2e3),offset:u().int().nonnegative().default(0),length:u().int().positive().max(65536).default(16384)}).strict();const mI=i().regex(/^[a-z][a-z0-9_-]{0,119}$/),pI=i().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"),EL=c({id:mI,label:i().trim().min(1).max(240),description:i().max(4e3),inputSchema:le(i(),ce()),invocation:ot("kind",[c({kind:b("instructions"),instructions:i().min(1).max(1e5).refine(e=>!!e.trim())}).strict(),c({kind:b("agent_action"),actionId:i().trim().min(1).max(240)}).strict()]),skillPaths:p(pI).max(100)}).strict();c({schemaVersion:b("openpond.profileWorkflows.v1"),workflows:p(EL).max(1e3)}).strict();const ML=c({id:i().trim().min(1).max(240),agentId:i().regex(/^[a-zA-Z0-9_-]{1,240}$/),sourceActionId:i().trim().min(1).max(240),inputSchema:le(i(),ce())}).strict();c({schemaVersion:b("openpond.profileWorkflowActions.v1"),actions:p(ML).max(200)}).strict();const jL=c({schemaVersion:b("openpond.profileWorkflowBinding.v1"),profileId:i().trim().min(1).max(240),sourceRevision:i().trim().min(1).max(240),harnessRelease:W,catalogHash:H,workflowId:mI}).strict(),OL=c({schemaVersion:b("openpond.profileComponentBinding.v1"),profileId:i().trim().min(1).max(240),sourceRevision:i().trim().min(1).max(240),harnessRelease:W,target:ot("kind",[c({kind:b("profile")}).strict(),c({kind:b("skill"),skillPath:pI}).strict(),c({kind:b("agent_action"),actionId:i().trim().min(1).max(240)}).strict()])}).strict(),Wv=Symbol.for("yaml.alias"),$L=Symbol.for("yaml.document"),Rr=Symbol.for("yaml.map"),fI=Symbol.for("yaml.pair"),Gv=Symbol.for("yaml.scalar"),td=Symbol.for("yaml.seq"),Fi=Symbol.for("yaml.node.type"),pl=e=>!!e&&typeof e=="object"&&e[Fi]===Wv,Hm=e=>!!e&&typeof e=="object"&&e[Fi]===$L,hI=e=>!!e&&typeof e=="object"&&e[Fi]===Rr,Kn=e=>!!e&&typeof e=="object"&&e[Fi]===fI,$n=e=>!!e&&typeof e=="object"&&e[Fi]===Gv,Jv=e=>!!e&&typeof e=="object"&&e[Fi]===td;function Ta(e){if(e&&typeof e=="object")switch(e[Fi]){case Rr:case td:return!0}return!1}function Yn(e){if(e&&typeof e=="object")switch(e[Fi]){case Wv:case Rr:case Gv:case td:return!0}return!1}const gI=e=>($n(e)||Ta(e))&&!!e.anchor,hr=Symbol("break visit"),NL=Symbol("skip children"),cc=Symbol("remove node");function Lm(e,t){const n=DL(t);Hm(e)?_s(null,e.contents,n,Object.freeze([e]))===cc&&(e.contents=null):_s(null,e,n,Object.freeze([]))}Lm.BREAK=hr;Lm.SKIP=NL;Lm.REMOVE=cc;function _s(e,t,n,a){const o=HL(e,t,n,a);if(Yn(o)||Kn(o))return LL(e,a,o),_s(e,o,n,a);if(typeof o!="symbol"){if(Ta(t)){a=Object.freeze(a.concat(t));for(let r=0;r<t.items.length;++r){const s=_s(r,t.items[r],n,a);if(typeof s=="number")r=s-1;else{if(s===hr)return hr;s===cc&&(t.items.splice(r,1),r-=1)}}}else if(Kn(t)){a=Object.freeze(a.concat(t));const r=_s("key",t.key,n,a);if(r===hr)return hr;r===cc&&(t.key=null);const s=_s("value",t.value,n,a);if(s===hr)return hr;s===cc&&(t.value=null)}}return o}function DL(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 HL(e,t,n,a){if(typeof n=="function")return n(e,t,a);if(hI(t))return n.Map?.(e,t,a);if(Jv(t))return n.Seq?.(e,t,a);if(Kn(t))return n.Pair?.(e,t,a);if($n(t))return n.Scalar?.(e,t,a);if(pl(t))return n.Alias?.(e,t,a)}function LL(e,t,n){const a=t[t.length-1];if(Ta(a))a.items[e]=n;else if(Kn(a))e==="key"?a.key=n:a.value=n;else if(Hm(a))a.contents=n;else{const o=pl(a)?"alias":"scalar";throw new Error(`Cannot replace node with ${o} parent`)}}function vI(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 tc(e,t,n,a){if(a&&typeof a=="object")if(Array.isArray(a))for(let o=0,r=a.length;o<r;++o){const s=a[o],l=tc(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 r=a.get(o),s=tc(e,a,o,r);s===void 0?a.delete(o):s!==r&&a.set(o,s)}else if(a instanceof Set)for(const o of Array.from(a)){const r=tc(e,a,o,o);r===void 0?a.delete(o):r!==o&&(a.delete(o),a.add(r))}else for(const[o,r]of Object.entries(a)){const s=tc(e,a,o,r);s===void 0?delete a[o]:s!==r&&(a[o]=s)}return e.call(t,n,a)}function ui(e,t,n){if(Array.isArray(e))return e.map((a,o)=>ui(a,String(o),n));if(e&&typeof e.toJSON=="function"){if(!n||!gI(e))return e.toJSON(t,n);const a={aliasCount:0,count:1,res:void 0};n.anchors.set(e,a),n.onCreate=r=>{a.res=r,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 Zv{constructor(t){Object.defineProperty(this,Fi,{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:r}={}){if(!Hm(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=ui(this,"",s);if(typeof o=="function")for(const{count:m,res:d}of s.anchors.values())o(d,m);return typeof r=="function"?tc(r,{"":l},"",l):l}}class qL extends Zv{constructor(t){super(Wv),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=[],Lm(t,{Node:(r,s)=>{(pl(s)||gI(s))&&a.push(s)}}),n&&(n.aliasResolveCache=a));let o;for(const r of a){if(r===this)break;r.anchor===this.source&&(o=r)}return o}toJSON(t,n){if(!n)return{source:this.source};const{anchors:a,doc:o,maxAliasCount:r}=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||(ui(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(r>=0&&(l.count+=1,l.aliasCount===0&&(l.aliasCount=wu(o,s,a)),l.count*l.aliasCount>r)){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(vI(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){const r=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(r)}if(t.implicitKey)return`${o} `}return o}}function wu(e,t,n){if(pl(t)){const a=t.resolve(e),o=n&&a&&n.get(a);return o?o.count*o.aliasCount:0}else if(Ta(t)){let a=0;for(const o of t.items){const r=wu(e,o,n);r>a&&(a=r)}return a}else if(Kn(t)){const a=wu(e,t.key,n),o=wu(e,t.value,n);return Math.max(a,o)}return 1}const bI=e=>!e||typeof e!="function"&&typeof e!="object";class hn extends Zv{constructor(t){super(Gv),this.value=t}toJSON(t,n){return n?.keep?this.value:ui(this.value,t,n)}toString(){return String(this.value)}}hn.BLOCK_FOLDED="BLOCK_FOLDED";hn.BLOCK_LITERAL="BLOCK_LITERAL";hn.PLAIN="PLAIN";hn.QUOTE_DOUBLE="QUOTE_DOUBLE";hn.QUOTE_SINGLE="QUOTE_SINGLE";function UL(e,t,n){return n.find(a=>a.identify?.(e)&&!a.format)}function Ju(e,t,n){if(Hm(e)&&(e=e.contents),Yn(e))return e;if(Kn(e)){const g=n.schema[Rr].createNode?.(n.schema,null,n);return g.items.push(e),g}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());const{aliasDuplicateObjects:a,onAnchor:o,onTagObj:r,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 qL(m.anchor);m={anchor:null,node:null},l.set(e,m)}let d=UL(e,t,s.tags);if(!d){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){const g=new hn(e);return m&&(m.node=g),g}d=e instanceof Map?s[Rr]:Symbol.iterator in Object(e)?s[td]:s[Rr]}r&&(r(d),delete n.onTagObj);const f=d?.createNode?d.createNode(n.schema,e,n):typeof d?.nodeClass?.from=="function"?d.nodeClass.from(n.schema,e,n):new hn(e);return d.default||(f.tag=d.tag),m&&(m.node=f),f}function yS(e,t,n){let a=n;for(let o=t.length-1;o>=0;--o){const r=t[o];if(typeof r=="number"&&Number.isInteger(r)&&r>=0){const s=[];s[r]=a,a=s}else a=new Map([[r,a]])}return Ju(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 zL=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done;class yI extends Zv{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=>Yn(a)||Kn(a)?a.clone(t):a),this.range&&(n.range=this.range.slice()),n}addIn(t,n){if(zL(t))this.add(n);else{const[a,...o]=t,r=this.get(a,!0);if(Ta(r))r.addIn(o,n);else if(r===void 0&&this.schema)this.set(a,yS(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(Ta(o))return o.deleteIn(a);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${a}`)}getIn(t,n){const[a,...o]=t,r=this.get(a,!0);return o.length===0?!n&&$n(r)?r.value:r:Ta(r)?r.getIn(o,n):void 0}hasAllNullValues(t){return this.items.every(n=>{if(!Kn(n))return!1;const a=n.value;return a==null||t&&$n(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 Ta(o)?o.hasIn(a):!1}setIn(t,n){const[a,...o]=t;if(o.length===0)this.set(a,n);else{const r=this.get(a,!0);if(Ta(r))r.setIn(o,n);else if(r===void 0&&this.schema)this.set(a,yS(this.schema,o,n));else throw new Error(`Expected YAML collection at ${a}. Remaining path: ${o}`)}}}const BL=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function _c(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}const Cs=(e,t,n)=>e.endsWith(`
|
|
131
|
-
`)?_c(n,t):n.includes(`
|
|
132
|
-
`)?`
|
|
133
|
-
`+_c(n,t):(e.endsWith(" ")?"":" ")+n,SI="flow",bg="block",Iu="quoted";function qm(e,t,n="flow",{indentAtStart:a,lineWidth:o=80,minContentWidth:r=20,onFold:s,onOverflow:l}={}){if(!o||o<0)return e;o<r&&(r=0);const m=Math.max(1+r,1+o-t.length);if(e.length<=m)return e;const d=[],f={};let g=o-t.length;typeof a=="number"&&(a>o-Math.max(2,r)?d.push(0):g=o-a);let x,k,C=!1,R=-1,E=-1,A=-1;n===bg&&(R=SS(e,R,t.length),R!==-1&&(g=R+m));for(let $;$=e[R+=1];){if(n===Iu&&$==="\\"){switch(E=R,e[R+1]){case"x":R+=3;break;case"u":R+=5;break;case"U":R+=9;break;default:R+=1}A=R}if($===`
|
|
134
|
-
`)n===bg&&(R=SS(e,R,t.length)),g=R+t.length+m,x=void 0;else{if($===" "&&k&&k!==" "&&k!==`
|
|
135
|
-
`&&k!==" "){const M=e[R+1];M&&M!==" "&&M!==`
|
|
136
|
-
`&&M!==" "&&(x=R)}if(R>=g)if(x)d.push(x),g=x+m,x=void 0;else if(n===Iu){for(;k===" "||k===" ";)k=$,$=e[R+=1],C=!0;const M=R>A+1?R-2:E-1;if(f[M])return e;d.push(M),f[M]=!0,g=M+m,x=void 0}else C=!0}k=$}if(C&&l&&l(),d.length===0)return e;s&&s();let O=e.slice(0,d[0]);for(let $=0;$<d.length;++$){const M=d[$],w=d[$+1]||e.length;M===0?O=`
|
|
137
|
-
${t}${e.slice(0,w)}`:(n===Iu&&f[M]&&(O+=`${e[M]}\\`),O+=`
|
|
138
|
-
${t}${e.slice(M+1,w)}`)}return O}function SS(e,t,n){let a=t,o=t+1,r=e[o];for(;r===" "||r===" ";)if(t<o+n)r=e[++t];else{do r=e[++t];while(r&&r!==`
|
|
139
|
-
`);a=t,o=t+1,r=e[o]}return a}const Um=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),zm=e=>/^(%|---|\.\.\.)/m.test(e);function FL(e,t,n){if(!t||t<0)return!1;const a=t-n,o=e.length;if(o<=a)return!1;for(let r=0,s=0;r<o;++r)if(e[r]===`
|
|
140
|
-
`){if(r-s>a)return!0;if(s=r+1,o-s<=a)return!1}return!0}function dc(e,t){const n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;const{implicitKey:a}=t,o=t.options.doubleQuotedMinMultiLineLength,r=t.indent||(zm(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 f=n.substr(m+2,4);switch(f){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:f.substr(0,2)==="00"?s+="\\x"+f.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)+`
|
|
141
|
-
|
|
142
|
-
`;n[m+2]==="\\"&&n[m+3]==="n"&&n[m+4]!=='"';)s+=`
|
|
143
|
-
`,m+=2;s+=r,n[m+2]===" "&&(s+="\\"),m+=1,l=m+1}break;default:m+=1}return s=l?s+n.slice(l):n,a?s:qm(s,r,Iu,Um(t,!1))}function yg(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
144
|
-
`)||/[ \t]\n|\n[ \t]/.test(e))return dc(e,t);const n=t.indent||(zm(e)?" ":""),a="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
145
|
-
${n}`)+"'";return t.implicitKey?a:qm(a,n,SI,Um(t,!1))}function Rs(e,t){const{singleQuote:n}=t.options;let a;if(n===!1)a=dc;else{const o=e.includes('"'),r=e.includes("'");o&&!r?a=yg:r&&!o?a=dc:a=n?yg:dc}return a(e,t)}let Sg;try{Sg=new RegExp(`(^|(?<!
|
|
146
|
-
))
|
|
147
|
-
+(?!
|
|
148
|
-
|$)`,"g")}catch{Sg=/\n+(?!\n|$)/g}function _u({comment:e,type:t,value:n},a,o,r){const{blockQuote:s,commentString:l,lineWidth:m}=a.options;if(!s||/\n[\t ]+$/.test(n))return Rs(n,a);const d=a.indent||(a.forceBlockIndent||zm(n)?" ":""),f=s==="literal"?!0:s==="folded"||t===hn.BLOCK_FOLDED?!1:t===hn.BLOCK_LITERAL?!0:!FL(n,m,d.length);if(!n)return f?`|
|
|
149
|
-
`:`>
|
|
150
|
-
`;let g,x;for(x=n.length;x>0;--x){const w=n[x-1];if(w!==`
|
|
151
|
-
`&&w!==" "&&w!==" ")break}let k=n.substring(x);const C=k.indexOf(`
|
|
152
|
-
`);C===-1?g="-":n===k||C!==k.length-1?(g="+",r&&r()):g="",k&&(n=n.slice(0,-k.length),k[k.length-1]===`
|
|
153
|
-
`&&(k=k.slice(0,-1)),k=k.replace(Sg,`$&${d}`));let R=!1,E,A=-1;for(E=0;E<n.length;++E){const w=n[E];if(w===" ")R=!0;else if(w===`
|
|
154
|
-
`)A=E;else break}let O=n.substring(0,A<E?A+1:E);O&&(n=n.substring(O.length),O=O.replace(/\n+/g,`$&${d}`));let M=(R?d?"2":"1":"")+g;if(e&&(M+=" "+l(e.replace(/ ?[\r\n]+/g," ")),o&&o()),!f){const w=n.replace(/\n+/g,`
|
|
155
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${d}`);let P=!1;const j=Um(a,!0);s!=="folded"&&t!==hn.BLOCK_FOLDED&&(j.onOverflow=()=>{P=!0});const N=qm(`${O}${w}${k}`,d,bg,j);if(!P)return`>${M}
|
|
156
|
-
${d}${N}`}return n=n.replace(/\n+/g,`$&${d}`),`|${M}
|
|
157
|
-
${d}${O}${n}${k}`}function VL(e,t,n,a){const{type:o,value:r}=e,{actualString:s,implicitKey:l,indent:m,indentStep:d,inFlow:f}=t;if(l&&r.includes(`
|
|
158
|
-
`)||f&&/[[\]{},]/.test(r))return Rs(r,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(r))return l||f||!r.includes(`
|
|
159
|
-
`)?Rs(r,t):_u(e,t,n,a);if(!l&&!f&&o!==hn.PLAIN&&r.includes(`
|
|
160
|
-
`))return _u(e,t,n,a);if(zm(r)){if(m==="")return t.forceBlockIndent=!0,_u(e,t,n,a);if(l&&m===d)return Rs(r,t)}const g=r.replace(/\n+/g,`$&
|
|
161
|
-
${m}`);if(s){const x=R=>R.default&&R.tag!=="tag:yaml.org,2002:str"&&R.test?.test(g),{compat:k,tags:C}=t.doc.schema;if(C.some(x)||k?.some(x))return Rs(r,t)}return l?g:qm(g,m,SI,Um(t,!1))}function KL(e,t,n,a){const{implicitKey:o,inFlow:r}=t,s=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)});let{type:l}=e;l!==hn.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(s.value)&&(l=hn.QUOTE_DOUBLE);const m=f=>{switch(f){case hn.BLOCK_FOLDED:case hn.BLOCK_LITERAL:return o||r?Rs(s.value,t):_u(s,t,n,a);case hn.QUOTE_DOUBLE:return dc(s.value,t);case hn.QUOTE_SINGLE:return yg(s.value,t);case hn.PLAIN:return VL(s,t,n,a);default:return null}};let d=m(l);if(d===null){const{defaultKeyType:f,defaultStringType:g}=t.options,x=o&&f||g;if(d=m(x),d===null)throw new Error(`Unsupported default string type ${x}`)}return d}function WL(e,t){const n=Object.assign({blockQuote:!0,commentString:BL,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 GL(e,t){if(t.tag){const o=e.filter(r=>r.tag===t.tag);if(o.length>0)return o.find(r=>r.format===t.format)??o[0]}let n,a;if($n(t)){a=t.value;let o=e.filter(r=>r.identify?.(a));if(o.length>1){const r=o.filter(s=>s.test);r.length>0&&(o=r)}n=o.find(r=>r.format===t.format)??o.find(r=>!r.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 JL(e,t,{anchors:n,doc:a}){if(!a.directives)return"";const o=[],r=($n(e)||Ta(e))&&e.anchor;r&&vI(r)&&(n.add(r),o.push(`&${r}`));const s=e.tag??(t.default?null:t.tag);return s&&o.push(a.directives.tagString(s)),o.join(" ")}function Zu(e,t,n,a){if(Kn(e))return e.toString(t,n,a);if(pl(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 r=Yn(e)?e:t.doc.createNode(e,{onTagObj:m=>o=m});o??(o=GL(t.doc.schema.tags,r));const s=JL(r,o,t);s.length>0&&(t.indentAtStart=(t.indentAtStart??0)+s.length+1);const l=typeof o.stringify=="function"?o.stringify(r,t,n,a):$n(r)?KL(r,t,n,a):r.toString(t,n,a);return s?$n(r)||l[0]==="{"||l[0]==="["?`${s} ${l}`:`${s}
|
|
162
|
-
${t.indent}${l}`:l}function ZL({key:e,value:t},n,a,o){const{allNullValues:r,doc:s,indent:l,indentStep:m,options:{commentString:d,indentSeq:f,simpleKeys:g}}=n;let x=Yn(e)&&e.comment||null;if(g){if(x)throw new Error("With simple keys, key nodes cannot have comments");if(Ta(e)||!Yn(e)&&typeof e=="object"){const j="With simple keys, collection cannot be used as a key value";throw new Error(j)}}let k=!g&&(!e||x&&t==null&&!n.inFlow||Ta(e)||($n(e)?e.type===hn.BLOCK_FOLDED||e.type===hn.BLOCK_LITERAL:typeof e=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!k&&(g||!r),indent:l+m});let C=!1,R=!1,E=Zu(e,n,()=>C=!0,()=>R=!0);if(!k&&!n.inFlow&&E.length>1024){if(g)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");k=!0}if(n.inFlow){if(r||t==null)return C&&a&&a(),E===""?"?":k?`? ${E}`:E}else if(r&&!g||t==null&&k)return E=`? ${E}`,x&&!C?E+=Cs(E,n.indent,d(x)):R&&o&&o(),E;C&&(x=null),k?(x&&(E+=Cs(E,n.indent,d(x))),E=`? ${E}
|
|
163
|
-
${l}:`):(E=`${E}:`,x&&(E+=Cs(E,n.indent,d(x))));let A,O,$;Yn(t)?(A=!!t.spaceBefore,O=t.commentBefore,$=t.comment):(A=!1,O=null,$=null,t&&typeof t=="object"&&(t=s.createNode(t))),n.implicitKey=!1,!k&&!x&&$n(t)&&(n.indentAtStart=E.length+1),R=!1,!f&&m.length>=2&&!n.inFlow&&!k&&Jv(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let M=!1;const w=Zu(t,n,()=>M=!0,()=>R=!0);let P=" ";if(x||A||O){if(P=A?`
|
|
164
|
-
`:"",O){const j=d(O);P+=`
|
|
165
|
-
${_c(j,n.indent)}`}w===""&&!n.inFlow?P===`
|
|
166
|
-
`&&$&&(P=`
|
|
167
|
-
|
|
168
|
-
`):P+=`
|
|
169
|
-
${n.indent}`}else if(!k&&Ta(t)){const j=w[0],N=w.indexOf(`
|
|
170
|
-
`),z=N!==-1,D=n.inFlow??t.flow??t.items.length===0;if(z||!D){let F=!1;if(z&&(j==="&"||j==="!")){let te=w.indexOf(" ");j==="&"&&te!==-1&&te<N&&w[te+1]==="!"&&(te=w.indexOf(" ",te+1)),(te===-1||N<te)&&(F=!0)}F||(P=`
|
|
171
|
-
${n.indent}`)}}else(w===""||w[0]===`
|
|
172
|
-
`)&&(P="");return E+=P+w,n.inFlow?M&&a&&a():$&&!M?E+=Cs(E,n.indent,d($)):R&&o&&o(),E}function YL(e,t){(e==="debug"||e==="warn")&&console.warn(t)}const Zd="<<",dh={identify:e=>e===Zd||typeof e=="symbol"&&e.description===Zd,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new hn(Symbol(Zd)),{addToJSMap:xI}),stringify:()=>Zd},QL=(e,t)=>(dh.identify(t)||$n(t)&&(!t.type||t.type===hn.PLAIN)&&dh.identify(t.value))&&e?.doc.schema.tags.some(n=>n.tag===dh.tag&&n.default);function xI(e,t,n){const a=kI(e,n);if(Jv(a))for(const o of a.items)uh(e,t,o);else if(Array.isArray(a))for(const o of a)uh(e,t,o);else uh(e,t,a)}function uh(e,t,n){const a=kI(e,n);if(!hI(a))throw new Error("Merge sources must be maps or map aliases");const o=a.toJSON(null,e,Map);for(const[r,s]of o)t instanceof Map?t.has(r)||t.set(r,s):t instanceof Set?t.add(r):Object.prototype.hasOwnProperty.call(t,r)||Object.defineProperty(t,r,{value:s,writable:!0,enumerable:!0,configurable:!0});return t}function kI(e,t){return e&&pl(t)?t.resolve(e.doc,e):t}function wI(e,t,{key:n,value:a}){if(Yn(n)&&n.addToJSMap)n.addToJSMap(e,t,a);else if(QL(e,n))xI(e,t,a);else{const o=ui(n,"",e);if(t instanceof Map)t.set(o,ui(a,o,e));else if(t instanceof Set)t.add(o);else{const r=XL(n,o,e),s=ui(a,r,e);r in t?Object.defineProperty(t,r,{value:s,writable:!0,enumerable:!0,configurable:!0}):t[r]=s}}return t}function XL(e,t,n){if(t===null)return"";if(typeof t!="object")return String(t);if(Yn(e)&&n?.doc){const a=WL(n.doc,{});a.anchors=new Set;for(const r of n.anchors.keys())a.anchors.add(r.anchor);a.inFlow=!0,a.inStringifyKey=!0;const o=e.toString(a);if(!n.mapKeyWarned){let r=JSON.stringify(o);r.length>40&&(r=r.substring(0,36)+'..."'),YL(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${r}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return o}return JSON.stringify(t)}function Yv(e,t,n){const a=Ju(e,void 0,n),o=Ju(t,void 0,n);return new co(a,o)}class co{constructor(t,n=null){Object.defineProperty(this,Fi,{value:fI}),this.key=t,this.value=n}clone(t){let{key:n,value:a}=this;return Yn(n)&&(n=n.clone(t)),Yn(a)&&(a=a.clone(t)),new co(n,a)}toJSON(t,n){const a=n?.mapAsMap?new Map:{};return wI(n,a,this)}toString(t,n,a){return t?.doc?ZL(this,t,n,a):JSON.stringify(this)}}function II(e,t,n){return(t.inFlow??e.flow?tq:eq)(e,t,n)}function eq({comment:e,items:t},n,{blockItemPrefix:a,flowChars:o,itemIndent:r,onChompKeep:s,onComment:l}){const{indent:m,options:{commentString:d}}=n,f=Object.assign({},n,{indent:r,type:null});let g=!1;const x=[];for(let C=0;C<t.length;++C){const R=t[C];let E=null;if(Yn(R))!g&&R.spaceBefore&&x.push(""),Yu(n,x,R.commentBefore,g),R.comment&&(E=R.comment);else if(Kn(R)){const O=Yn(R.key)?R.key:null;O&&(!g&&O.spaceBefore&&x.push(""),Yu(n,x,O.commentBefore,g))}g=!1;let A=Zu(R,f,()=>E=null,()=>g=!0);E&&(A+=Cs(A,r,d(E))),g&&E&&(g=!1),x.push(a+A)}let k;if(x.length===0)k=o.start+o.end;else{k=x[0];for(let C=1;C<x.length;++C){const R=x[C];k+=R?`
|
|
173
|
-
${m}${R}`:`
|
|
174
|
-
`}}return e?(k+=`
|
|
175
|
-
`+_c(d(e),m),l&&l()):g&&s&&s(),k}function tq({items:e},t,{flowChars:n,itemIndent:a}){const{indent:o,indentStep:r,flowCollectionPadding:s,options:{commentString:l}}=t;a+=r;const m=Object.assign({},t,{indent:a,inFlow:!0,type:null});let d=!1,f=0;const g=[];for(let C=0;C<e.length;++C){const R=e[C];let E=null;if(Yn(R))R.spaceBefore&&g.push(""),Yu(t,g,R.commentBefore,!1),R.comment&&(E=R.comment);else if(Kn(R)){const O=Yn(R.key)?R.key:null;O&&(O.spaceBefore&&g.push(""),Yu(t,g,O.commentBefore,!1),O.comment&&(d=!0));const $=Yn(R.value)?R.value:null;$?($.comment&&(E=$.comment),$.commentBefore&&(d=!0)):R.value==null&&O?.comment&&(E=O.comment)}E&&(d=!0);let A=Zu(R,m,()=>E=null);d||(d=g.length>f||A.includes(`
|
|
176
|
-
`)),C<e.length-1?A+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(d||(d=g.reduce((O,$)=>O+$.length+2,2)+(A.length+2)>t.options.lineWidth)),d&&(A+=",")),E&&(A+=Cs(A,a,l(E))),g.push(A),f=g.length}const{start:x,end:k}=n;if(g.length===0)return x+k;if(!d){const C=g.reduce((R,E)=>R+E.length+2,2);d=t.options.lineWidth>0&&C>t.options.lineWidth}if(d){let C=x;for(const R of g)C+=R?`
|
|
177
|
-
${r}${o}${R}`:`
|
|
178
|
-
`;return`${C}
|
|
179
|
-
${o}${k}`}else return`${x}${s}${g.join(" ")}${s}${k}`}function Yu({indent:e,options:{commentString:t}},n,a,o){if(a&&o&&(a=a.replace(/^\n+/,"")),a){const r=_c(t(a),e);n.push(r.trimStart())}}function Sr(e,t){const n=$n(t)?t.value:t;for(const a of e)if(Kn(a)&&(a.key===t||a.key===n||$n(a.key)&&a.key.value===n))return a}class ys extends yI{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Rr,t),this.items=[]}static from(t,n,a){const{keepUndefined:o,replacer:r}=a,s=new this(t),l=(m,d)=>{if(typeof r=="function")d=r.call(n,m,d);else if(Array.isArray(r)&&!r.includes(m))return;(d!==void 0||o)&&s.items.push(Yv(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;Kn(t)?a=t:!t||typeof t!="object"||!("key"in t)?a=new co(t,t?.value):a=new co(t.key,t.value);const o=Sr(this.items,a.key),r=this.schema?.sortMapEntries;if(o){if(!n)throw new Error(`Key ${a.key} already set`);$n(o.value)&&bI(a.value)?o.value.value=a.value:o.value=a.value}else if(r){const s=this.items.findIndex(l=>r(a,l)<0);s===-1?this.items.push(a):this.items.splice(s,0,a)}else this.items.push(a)}delete(t){const n=Sr(this.items,t);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(t,n){const o=Sr(this.items,t)?.value;return(!n&&$n(o)?o.value:o)??void 0}has(t){return!!Sr(this.items,t)}set(t,n){this.add(new co(t,n),!0)}toJSON(t,n,a){const o=a?new a:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(o);for(const r of this.items)wI(n,o,r);return o}toString(t,n,a){if(!t)return JSON.stringify(this);for(const o of this.items)if(!Kn(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})),II(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:a,onComment:n})}}class _I extends yI{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(td,t),this.items=[]}add(t){this.items.push(t)}delete(t){const n=Yd(t);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(t,n){const a=Yd(t);if(typeof a!="number")return;const o=this.items[a];return!n&&$n(o)?o.value:o}has(t){const n=Yd(t);return typeof n=="number"&&n<this.items.length}set(t,n){const a=Yd(t);if(typeof a!="number")throw new Error(`Expected a valid index, not ${t}.`);const o=this.items[a];$n(o)&&bI(n)?o.value=n:this.items[a]=n}toJSON(t,n){const a=[];n?.onCreate&&n.onCreate(a);let o=0;for(const r of this.items)a.push(ui(r,String(o++),n));return a}toString(t,n,a){return t?II(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,r=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)}r.items.push(Ju(l,void 0,a))}}return r}}function Yd(e){let t=$n(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}function nq(e,t,n){const{replacer:a}=n,o=new _I(e);o.tag="tag:yaml.org,2002:pairs";let r=0;if(t&&Symbol.iterator in Object(t))for(let s of t){typeof a=="function"&&(s=a.call(t,String(r++),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(Yv(l,m,n))}return o}class Qv extends _I{constructor(){super(),this.add=ys.prototype.add.bind(this),this.delete=ys.prototype.delete.bind(this),this.get=ys.prototype.get.bind(this),this.has=ys.prototype.has.bind(this),this.set=ys.prototype.set.bind(this),this.tag=Qv.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 r,s;if(Kn(o)?(r=ui(o.key,"",n),s=ui(o.value,r,n)):r=ui(o,"",n),a.has(r))throw new Error("Ordered maps must not include duplicate keys");a.set(r,s)}return a}static from(t,n,a){const o=nq(t,n,a),r=new this;return r.items=o.items,r}}Qv.tag="tag:yaml.org,2002:omap";class Xv extends ys{constructor(t){super(t),this.tag=Xv.tag}add(t){let n;Kn(t)?n=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?n=new co(t.key,null):n=new co(t,null),Sr(this.items,n.key)||this.items.push(n)}get(t,n){const a=Sr(this.items,t);return!n&&Kn(a)?$n(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=Sr(this.items,t);a&&!n?this.items.splice(this.items.indexOf(a),1):!a&&n&&this.items.push(new co(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,r=new this(t);if(n&&Symbol.iterator in Object(n))for(let s of n)typeof o=="function"&&(s=o.call(n,s,s)),r.items.push(Yv(s,null,a));return r}}Xv.tag="tag:yaml.org,2002:set";new Set("0123456789ABCDEFabcdef");new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()");new Set(",[]{}");new Set(` ,[]{}
|
|
180
|
-
\r `);const Qu=i().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");i().regex(/^[a-z][a-z0-9_-]{0,119}$/);const aq={type:"object",properties:{},additionalProperties:!1};c({name:i().trim().min(1).max(240).optional(),description:i().max(4e3).optional(),skillPaths:p(Qu).max(100).optional(),assetPaths:p(Qu).max(100).optional()}).strict();c({actionId:i().trim().min(1).max(240),name:i().trim().min(1).max(240),description:i().max(4e3).default(""),inputSchema:le(i(),ce()).default(aq),skillPaths:p(Qu).max(100).default([]),assetPaths:p(Qu).max(100).default([])}).strict();const CI=v(["openpond.lab"]),Cc=c({id:i(),experience:qv.default(FD),provider:ul,modelRef:Sn.nullable().optional(),openPondCommandAccessMode:Zc.default(Om),systemKind:CI.nullable().optional(),hiddenFromDefaultSidebar:I().optional(),parentSessionId:i().nullable().optional(),parentTurnId:i().nullable().optional(),subagentRunId:i().nullable().optional(),subagentRoleId:dl.nullable().optional(),subagentDelegationMode:Em.nullable().optional(),title:i(),appId:i().nullable(),appName:i().nullable(),workspaceKind:Yc.optional(),workspaceId:i().nullable().optional(),workspaceName:i().nullable().optional(),localProjectId:i().nullable().optional(),cloudProjectId:i().nullable().optional(),cloudTeamId:i().nullable().optional(),currentProfile:Bi.nullable().optional(),profileWorkflowBinding:jL.nullable().optional(),profileComponentBinding:OL.nullable().optional(),metadata:le(i(),ce()).optional(),cwd:i().nullable(),codexThreadId:i().nullable(),nativeAgent:c({provider:v(["claude-code","grok-build","opencode"]),instanceId:i().min(1),sessionId:i().min(1),cwd:i().min(1)}).nullable().optional(),createdAt:i(),updatedAt:i(),status:v(["idle","active","failed","closed"]),runtimeSeconds:u().int().nonnegative().optional(),runtimeRunningSince:i().nullable().optional(),pinned:I(),savedForLater:I().optional(),archived:I(),order:u()});c({id:i(),sessionId:i(),providerTurnId:i().nullable(),modelRef:Sn.nullable().optional(),prompt:i(),startedAt:i(),completedAt:i().nullable(),status:v(["in_progress","completed","failed","interrupted"]),error:i().nullable(),metadata:le(i(),ce()).optional().default({}),createImproveRun:Qc.nullable().optional().default(null),profileSnapshot:mH.nullable().optional(),harnessSnapshot:fH.nullable().optional()});const iq=c({id:i(),sessionId:i(),turnId:i().nullable(),providerRequestId:vt([i(),u()]),kind:v(["command","file_change","permissions","user_input","create_plan","subagent_patch_apply","legacy_exec","legacy_patch"]),title:i(),detail:i(),status:v(["pending","accepted","accepted_for_session","declined","cancelled"]),createdAt:i()}),oq=c({key:v(["files","diffs","checks","deploys","sources","schedules","tool_runs","logs","app_config"]),label:i(),status:v(["placeholder","available","error"]),summary:i()}),RI=c({id:i().trim().min(1).max(191),agentId:i().trim().min(1).max(191).optional().nullable(),sourcePath:i().trim().min(1).max(2e3).optional().nullable(),sourceActionId:i().trim().min(1).max(191).optional().nullable(),name:i().trim().min(1).max(191).optional().nullable(),label:i().trim().min(1).max(160).optional().nullable(),description:i().trim().max(1e3).optional().nullable(),visibility:i().trim().max(80).optional().nullable(),inputSchema:vt([i().trim().max(191),le(i(),ce())]).optional().nullable(),outputSchema:vt([i().trim().max(191),le(i(),ce())]).optional().nullable(),approvalPolicy:le(i(),ce()).optional().nullable(),artifactPolicy:le(i(),ce()).optional().nullable(),setupRequirements:p(le(i(),ce())).optional(),mcp:le(i(),ce()).optional().nullable(),schedulePolicy:le(i(),ce()).optional().nullable(),trace:le(i(),ce()).optional().nullable(),implementation:le(i(),ce()).optional().nullable(),invokesModel:I().optional()}),rq=c({command:v(["inspect","build","validate","eval","traces","run"]),status:v(["passed","failed"]),checkedAt:i(),exitCode:u().nullable().optional(),sourceHead:i().nullable().optional()}),sq=c({id:i(),name:i(),path:i(),enabled:I()}),lq=c({name:i(),description:i(),path:i(),scope:b("profile"),enabled:I(),sourcePath:i(),charCount:u(),sourceHash:i(),validationStatus:v(["valid","warning","error"]),validationMessages:p(i()),resourceFiles:p(i()).optional().default([])}),cq=c({id:i(),name:i(),path:i(),agentId:i().nullable(),sourcePath:i()}),PI=c({path:i(),originalPath:i().nullable().optional(),indexStatus:i().nullable(),worktreeStatus:i().nullable(),status:i(),category:v(["added","modified","deleted","renamed","untracked","changed"])}),dq=c({isRepo:I(),branch:i().nullable(),head:i().nullable(),shortHead:i().nullable(),dirty:I(),upstream:i().nullable(),ahead:u().nullable(),behind:u().nullable(),remoteUrl:i().nullable(),files:p(PI),fileCount:u().int().nonnegative().optional(),error:i().nullable()}),uq=c({actionCount:u(),generatedAt:i().nullable(),manifestPath:i().nullable(),registryPath:i().nullable(),stale:I(),error:i().nullable()}),mq=c({skillCount:u(),generatedAt:i().nullable(),stale:I(),error:i().nullable()}),xS=c({ref:i(),source:v(["action_catalog","source_upload_metadata"]),actionId:i().nullable(),kind:i().nullable(),label:i(),status:i(),required:I(),blocking:I()}),pq=c({status:v(["ready","setup_required","blocked"]),requirementCount:u(),blockingCount:u(),optionalMissingCount:u(),readyCount:u(),requirements:p(xS),blockingRequirements:p(xS)}),fq=c({changedAgents:p(i()),newAgents:p(i()),deletedAgents:p(i()),changedSkills:p(i()).optional().default([]),changedActions:p(i()),changedExtensions:p(i()),setupChanges:p(i()),envRequirementChanges:p(i()),files:p(PI),fileCount:u().int().nonnegative().optional()}),hq=c({status:i(),agentId:i().nullable().optional(),deployPlanStatus:i().nullable().optional(),canRun:I().nullable().optional(),canDeploy:I().nullable().optional(),sourceRef:i().nullable().optional(),sourceCommitSha:i().nullable().optional(),manifestHash:i().nullable().optional(),manifestPath:i().nullable().optional(),setupCommands:p(i()).optional(),validationCommands:p(i()).optional(),requiredChecks:p(i()).optional(),evalNames:p(i()).optional(),blockedReasons:p(i()).optional(),staleReasons:p(i()).optional(),runtimeId:i().nullable().optional(),sandboxId:i().nullable().optional(),traceArtifactRefs:p(i()).optional(),evalResultArtifactRefs:p(i()).optional(),validatorArtifactRefs:p(i()).optional(),checkedAt:i().nullable().optional(),error:i().nullable().optional()}),gq=c({status:i(),agentId:i().nullable().optional(),runtimeAgentId:i().nullable().optional(),projectId:i().nullable().optional(),sourceRoot:i().nullable().optional(),sourceRef:i().nullable().optional(),sourceCommitSha:i().nullable().optional(),manifestHash:i().nullable().optional(),manifestPath:i().nullable().optional(),manifestSyncedAt:i().nullable().optional(),fileCount:u().nullable().optional(),totalBytes:u().nullable().optional(),generatedManifestPath:i().nullable().optional(),synthesizedOpenPondYaml:I().nullable().optional(),uploadMetadataPath:i().nullable().optional(),setupCommands:p(i()).optional(),validationCommands:p(i()).optional(),materializedAt:i().nullable().optional(),error:i().nullable().optional()}),vq=c({status:i(),agentId:i().nullable().optional(),snapshotId:i().nullable().optional(),sourceRef:i().nullable().optional(),sourceCommitSha:i().nullable().optional(),manifestHash:i().nullable().optional(),manifestPath:i().nullable().optional(),buildStatus:i().nullable().optional(),validationStatus:i().nullable().optional(),evalStatus:i().nullable().optional(),publishedAt:i().nullable().optional(),error:i().nullable().optional()}),bq=c({status:i(),agentId:i().nullable().optional(),runId:i().nullable().optional(),runtimeId:i().nullable().optional(),sandboxId:i().nullable().optional(),sourceRef:i().nullable().optional(),sourceCommitSha:i().nullable().optional(),manifestHash:i().nullable().optional(),setupGateStatus:i().nullable().optional(),setupRequirementRefs:p(i()).optional(),artifactRefs:p(i()).optional(),traceArtifactRefs:p(i()).optional(),evalArtifactRefs:p(i()).optional(),startedAt:i().nullable().optional(),completedAt:i().nullable().optional(),error:i().nullable().optional()}),yq=c({teamId:i().nullable(),projectId:i().nullable(),sourceRef:i().nullable(),sourceCommitSha:i().nullable(),lastPushedAt:i().nullable(),lastPushedLocalHead:i().nullable(),lastPushedHostedHead:i().nullable(),promotionStatus:i().nullable().optional().default(null),hostedRunStatus:i().nullable().optional().default(null),hostedRunAgentId:i().nullable().optional().default(null),hostedRunId:i().nullable().optional().default(null),hostedRunAt:i().nullable().optional().default(null),hostedSourceMaterialization:gq.nullable().optional().default(null),hostedSourceCheck:hq.nullable().optional().default(null),hostedPublish:vq.nullable().optional().default(null),hostedRun:bq.nullable().optional().default(null)}),Sq=c({state:v(["none","ready","dirty","pending_commit","error"]),message:i(),agentCount:u(),actionCount:u(),defaultAction:i().nullable(),checkFresh:I(),checkStaleReason:i().nullable(),localHead:i().nullable(),hostedHead:i().nullable()}),AI=c({mode:v(["none","local"]),repoPath:i().nullable(),activeProfile:i().nullable(),sourcePath:i().nullable(),manifestPath:i().nullable(),agents:p(sq),skills:p(lq).optional().default([]),evals:p(cq).optional().default([]),git:dq.nullable(),catalog:uq,skillCatalog:mq.optional().default({skillCount:0,generatedAt:null,stale:!0,error:null}),actionCatalog:p(RI),sourceSetupRequirements:p(le(i(),ce())),setupGate:pq,diff:fq,hosted:yq.nullable(),summary:Sq,lastCheck:rq.nullable(),error:i().nullable()}),xq=c({ref:Bi,name:i(),repoPath:i(),sourcePath:i().nullable(),state:AI}),kq=c({lastUsed:Bi.nullable(),profiles:p(xq)});function wq(){return{lastUsed:null,profiles:[]}}function Iq(){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 _q=c({name:i(),description:i(),path:i(),sourcePath:i(),enabled:I(),charCount:u().int().nonnegative(),sourceHash:i(),validationStatus:v(["valid","error"]),validationMessages:p(i()),resourceFiles:p(i()),updatedAt:i().nullable()}),Cq=v(["codex","profile","extension"]);c({skillName:i(),scope:Cq,path:i(),byteSize:u().int().nonnegative(),isBinary:I(),content:i().nullable()});const Rq=[{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"]}],Pq=c({name:i(),description:i(),relativePath:i(),sourcePath:i(),charCount:u().int().nonnegative(),sourceHash:i(),resourceFiles:p(i()),validationStatus:v(["valid","error"]),validationMessages:p(i())}),TI=c({id:i(),source:b("github"),owner:i(),repo:i(),repositoryUrl:i().url(),requestedRef:i(),resolvedCommit:i(),sourcePath:i(),readmePath:i().nullable(),installedAt:i(),updatedAt:i(),packageHash:i(),skills:p(Pq),validationStatus:v(["valid","error"]),validationMessages:p(i())});TI.omit({installedAt:!0,updatedAt:!0,sourcePath:!0}).extend({sourcePath:cl()});const Aq=c({rootPath:i(),registryPath:i(),extensions:p(TI),error:i().nullable()});c({source:i().trim().min(1),ref:i().trim().min(1).optional()});const Tq=c({latestSequence:u().int().nonnegative(),oldestSequence:u().int().nonnegative(),totalEvents:u().int().nonnegative(),limit:u().int().nonnegative(),hasMoreBefore:I()});c({server:BD,account:jD,codex:OD,configuration:c({rawRevision:i(),effectiveRevision:i(),sources:p(c({layer:i(),path:i(),revision:i()})),provenance:le(i(),c({layer:i(),path:i(),revision:i()}))}).optional(),preferences:mS.optional().default(()=>mS.parse({})),providers:O0.optional().default(()=>O0.parse({})),personalization:pS.optional().default(()=>pS.parse({soul:Vw[0].content,soulPath:null,updatedAt:null})),apps:p(zN),localProjects:p(WN).optional().default([]),cloudProjects:p(KN).optional().default([]),profile:AI.optional().default(Iq),profileLibrary:kq.optional().default(wq),codexPersonalSkills:p(_q).optional().default([]),extensionCatalog:Aq.optional().default({rootPath:"",registryPath:"",extensions:[],error:null}),codexHistorySessions:p(Cc).optional().default([]),sidebarAppPreferences:CD,sidebarFileBookmarks:p(Bw).optional().default([]),appsError:i().nullable(),appsMeta:uS,accountMeta:uS,sessions:p(Cc),events:p($0),eventWindow:Tq.optional(),approvals:p(iq),placeholders:p(oq),diagnostics:p($0)});const eb=v(["openpond_hosted","local_byok","codex_app_server","unknown"]),EI=v(["provider_usage","codex_context_usage","missing"]),Eq=v(["provider_usage_body","provider_response_headers"]),Mq=v(["chat_turn","tool_loop","slash_command","create_improve_planner","harness_refiner","context_compaction","subagent","codex_context","other"]),jq=v(["foreground","tool_loop","compaction","subagent","refiner","other"]),MI=v(["user_facing","background","system"]),jI=v(["started","completed","failed","interrupted"]),tb=v(["composer_selection","prompt_parse","server_parser","model_tool","api"]),OI=v(["chat","settings","goal","create_improve","compaction","system"]),$I=v(["direct_chat","tool_loop","slash_command","planner","summary","scan","subagent","other"]),Oq=c({surface:OI,workflowKind:$I,sessionId:i().trim().min(1).nullable().default(null),turnId:i().trim().min(1).nullable().default(null),goalId:i().trim().min(1).nullable().default(null),subagentRunId:i().trim().min(1).nullable().default(null),subagentRoleId:i().trim().min(1).nullable().default(null),createImproveRunId:i().trim().min(1).nullable().default(null),commandName:i().trim().min(1).max(160).nullable().default(null),commandSource:tb.nullable().default(null),appId:i().trim().min(1).nullable().default(null),workspaceKind:Yc.nullable().default(null),workspaceId:i().trim().min(1).nullable().default(null),localProjectId:i().trim().min(1).nullable().default(null),cloudProjectId:i().trim().min(1).nullable().default(null),sourceEventSequence:u().int().nonnegative().nullable().default(null)}),$q=c({surface:OI.optional(),workflowKind:$I.optional(),goalId:i().trim().min(1).nullable().optional(),subagentRunId:i().trim().min(1).nullable().optional(),subagentRoleId:i().trim().min(1).nullable().optional(),createImproveRunId:i().trim().min(1).nullable().optional(),commandName:i().trim().min(1).max(160).nullable().optional(),commandSource:tb.nullable().optional()}).strict(),Dr=i().trim().min(1).max(160),Nq=c({id:i().trim().min(1),requestId:i().trim().min(1),requestOrdinal:u().int().nonnegative(),sessionId:i().trim().min(1).nullable(),turnId:i().trim().min(1).nullable(),provider:Dr,model:i().trim().min(1),route:eb,source:EI,requestKind:Mq,visibility:MI,status:jI,startedAt:i().trim().min(1),completedAt:i().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:Eq.nullable(),completionTokens:u().int().nonnegative().nullable(),totalTokens:u().int().nonnegative().nullable(),errorType:i().trim().min(1).max(160).nullable(),errorMessage:i().trim().min(1).max(2e3).nullable(),attribution:Oq}),NI=c({from:i().trim().min(1),to:i().trim().min(1),bucket:v(["day","all_time"])}),nb=vt([b("all"),MI]),ab=v(["all","started","completed","failed","interrupted","missing"]),Dq=c({range:v(["7d","30d","90d","all"]).default("30d"),visibility:nb.default("all"),status:ab.default("all"),provider:Dr.optional(),model:i().trim().min(1).optional()});Dq.extend({sessionId:i().trim().min(1).optional(),turnId:i().trim().min(1).optional(),limit:u().int().positive().max(500).default(100)});c({sessionId:i().trim().min(1)});const Hr=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:i().trim().min(1),lastSeenAt:i().trim().min(1)}),Hq=Hr.extend({provider:Dr,model:i().trim().min(1),route:eb}),Lq=Hr.extend({sessionId:i().trim().min(1),title:i().trim().min(1).nullable(),workspaceKind:Yc.nullable(),workspaceId:i().trim().min(1).nullable()}),qq=Hr.extend({commandName:i().trim().min(1),commandSource:tb.nullable()}),Uq=Hr.extend({route:eb}),zq=Hr.extend({status:jI}),Bq=Hr.extend({source:EI}),Fq=Hr.extend({cohort:jq}),Vq=c({date:i().trim().min(1),totalTokens:u().int().nonnegative(),requests:u().int().nonnegative(),models:p(c({provider:Dr,model:i().trim().min(1),totalTokens:u().int().nonnegative(),requests:u().int().nonnegative()}))}),Kq=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:i().trim().min(1),range:NI,filters:c({visibility:nb,status:ab,provider:Dr.nullable(),model:i().trim().min(1).nullable()}),totals:Kq,daily:p(Vq),models:p(Hq),threads:p(Lq),commands:p(qq),routes:p(Uq),statuses:p(zq),sources:p(Bq),cohorts:p(Fq)});c({generatedAt:i().trim().min(1),range:NI,filters:c({visibility:nb,status:ab,provider:Dr.nullable(),model:i().trim().min(1).nullable(),sessionId:i().trim().min(1).nullable(),turnId:i().trim().min(1).nullable()}),limit:u().int().positive(),hasMore:I(),records:p(Nq)});const Wq=c({turnId:i().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(Dr)});c({generatedAt:i().trim().min(1),sessionId:i().trim().min(1),turns:p(Wq)});const Gq=v(["usage_spike","model_usage_spike","latency_regression","failure_cluster","missing_usage_frames"]);c({type:Gq,title:i().trim().min(1),summary:i().trim().min(1),severity:v(["nit","concern","blocker"]),payload:le(i(),ce()).default({})});const Jq=v(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),Zq=v(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),Yq=v(["native_bot","oauth_connector","wallet_connector","mcp_endpoint"]),Qq=c({kind:b("integration"),provider:Jq,appIds:p(Zq).min(1).max(4),setupSurfaces:p(Yq).min(1).max(4),connectionIds:p(i().trim().min(1)).max(8).optional(),capabilities:p(i().trim().min(1)).max(64).optional()}).strict(),xr={maxAttachments:10,maxAttachmentBytes:12*1024*1024,maxAttachmentBase64Chars:Math.ceil(12*1024*1024*4/3)+16,maxTextChars:2e5},Xq=v(["image","text","file"]),eU=c({sessionId:i().trim().min(1).max(200),turnId:i().trim().min(1).max(200),attachmentId:i().trim().min(1).max(200),storageName:i().trim().min(1).max(240),contentType:i().trim().min(1).max(160)}),tU=c({sessionId:i().trim().min(1).max(200),turnId:i().trim().min(1).max(200),attachmentId:i().trim().min(1).max(200),storageName:i().trim().min(1).max(1024),contentType:i().trim().min(1).max(160)}),DI=c({id:i().trim().min(1),name:i().trim().min(1).max(240),mediaType:i().trim().min(1).max(160),sizeBytes:u().int().nonnegative().max(xr.maxAttachmentBytes),kind:Xq,lineCount:u().int().nonnegative().max(xr.maxAttachmentBytes+1).optional(),relativePath:i().trim().min(1).max(1024).optional(),text:i().max(xr.maxTextChars).optional(),contentsBase64:i().max(xr.maxAttachmentBase64Chars).optional()}),nU=DI.omit({text:!0,contentsBase64:!0}).extend({imagePreview:eU.optional(),filePreview:tU.optional()});c({experience:qv.optional(),provider:ul.default(Tr),modelRef:Sn.optional(),openPondCommandAccessMode:Zc.optional(),systemKind:CI.nullable().optional(),hiddenFromDefaultSidebar:I().optional(),parentSessionId:i().trim().min(1).max(200).nullable().optional(),parentTurnId:i().trim().min(1).max(200).nullable().optional(),subagentRunId:i().trim().min(1).max(200).nullable().optional(),subagentRoleId:dl.nullable().optional(),subagentDelegationMode:Em.nullable().optional(),appId:i().nullable().optional(),appName:i().nullable().optional(),workspaceKind:Yc.optional(),workspaceId:i().nullable().optional(),workspaceName:i().nullable().optional(),localProjectId:i().nullable().optional(),cloudProjectId:i().nullable().optional(),cloudTeamId:i().nullable().optional(),currentProfile:Bi.nullable().optional(),profileWorkflowBinding:Cc.shape.profileWorkflowBinding,profileComponentBinding:Cc.shape.profileComponentBinding,metadata:le(i(),ce()).optional(),cwd:i().nullable().optional(),title:i().optional(),autoTitlePrompt:i().trim().min(1).max(2e4).optional()});c({teamId:i().trim().min(1),projectName:i().trim().min(1).max(120).optional(),branch:i().trim().min(1).max(120).optional(),chatSessionId:i().trim().min(1).max(200).optional(),displayPrompt:i().trim().min(1).max(2e3).optional()});c({branch:i().trim().min(1).max(120).optional()});c({prompt:i().min(1),workflowInput:ce().optional(),metadata:le(i(),ce()).optional(),usageAttribution:$q.optional().nullable(),cwd:i().nullable().optional(),model:i().nullable().optional(),modelRef:Sn.optional(),mentionedAppIds:p(i().trim().min(1)).max(8).optional(),mentionedConnectedApps:p(Qq).max(8).optional(),openPondActionCatalog:p(RI).max(100).optional(),attachments:p(DI).max(xr.maxAttachments).optional(),createImproveRun:Qc.optional().nullable(),approvalPolicy:v(["untrusted","on-failure","on-request","never"]).default("on-request"),sandbox:v(["read-only","workspace-write","danger-full-access"]).default("workspace-write"),codexPermissionMode:Hv.default("default"),codexReasoningEffort:$m.optional()});c({prompt:i().min(1),error:i().min(1),target:v(["cloud_workspace","hybrid_sandbox"])});c({reason:v(["manual"]).default("manual"),model:i().nullable().optional(),modelRef:Sn.optional()});c({experience:qv.optional(),provider:ul.optional(),modelRef:Sn.nullable().optional(),openPondCommandAccessMode:Zc.optional(),pinned:I().optional(),savedForLater:I().optional(),archived:I().optional(),order:u().optional(),title:i().optional(),parentSessionId:i().trim().min(1).max(200).nullable().optional(),parentTurnId:i().trim().min(1).max(200).nullable().optional(),subagentRunId:i().trim().min(1).max(200).nullable().optional(),subagentRoleId:dl.nullable().optional(),subagentDelegationMode:Em.nullable().optional(),appId:i().nullable().optional(),appName:i().nullable().optional(),workspaceKind:Yc.optional(),workspaceId:i().nullable().optional(),workspaceName:i().nullable().optional(),localProjectId:i().nullable().optional(),cloudProjectId:i().nullable().optional(),cloudTeamId:i().nullable().optional(),currentProfile:Bi.nullable().optional(),metadata:le(i(),ce()).optional(),cwd:i().nullable().optional()});c({command:i().trim().min(1),cwd:i().trim().min(1).max(4096).nullable().optional(),timeoutSeconds:u().int().min(1).max(3600).optional()});c({appIds:p(i()).min(1)});c({expectedRevision:i().optional(),defaultChatProvider:ul.optional(),defaultChatModel:i().min(1).optional(),defaultChatModelRef:Sn.nullable().optional(),subagents:xc.optional(),codexPermissionMode:Hv.optional(),codexReasoningEffort:$m.optional(),openPondCommandAccessMode:Zc.optional(),defaultBranchPrefix:i().trim().max(48).optional(),defaultNewProjectDirectory:i().trim().max(4096).optional(),defaultTeamId:i().trim().max(191).nullable().optional(),advancedWorkspaceControls:I().optional(),steerActiveResponses:I().optional(),contextCompaction:fg.optional(),training:hg.optional(),sidebarWidth:u().int().min(244).max(560).optional(),diffPanelWidth:u().int().min(320).max(2400).optional(),sidebarSectionsCollapsed:pg.optional(),editor:Gu.optional()});c({message:i().trim().min(1).max(4e3),surface:i().trim().min(1).max(120).default("app"),stack:i().max(12e3).nullable().optional(),context:le(i(),ce()).optional()}).strict();c({activeTemplateId:Lv,templateName:i().trim().min(1).max(80),soul:i().trim().min(1).max(8e3),saveAsNew:I().optional().default(!1)});c({decision:v(["accept","acceptForSession","decline","cancel"]),answers:le(i().min(1).max(2e3),i().trim().min(1).max(8e3)).optional()});c({branch:i().trim().min(1).max(240).nullable().optional(),surface:v(["desktop","terminal"])});c({handle:i().min(1),baseUrl:i().nullable().optional()});c({handle:i().min(1),baseUrl:i().nullable().optional()});c({handle:i().min(1).optional(),apiKey:i().min(1),baseUrl:i().nullable().optional(),apiBaseUrl:i().nullable().optional(),chatApiBaseUrl:i().nullable().optional(),environment:i().nullable().optional(),setActive:I().optional()});c({handle:i().min(1),currentBaseUrl:i().nullable().optional(),apiKey:i().min(1).optional(),baseUrl:i().nullable().optional(),apiBaseUrl:i().nullable().optional(),chatApiBaseUrl:i().nullable().optional(),environment:i().nullable().optional(),setActive:I().optional()});c({appId:i(),exists:I(),configPath:i().nullable().optional(),envVar:i().nullable(),toolName:i().nullable(),version:vt([i(),u()]).nullable(),source:v(["hosted_env","local_file","defaults","missing"]),currentConfig:le(i(),ce()).nullable(),defaults:le(i(),ce()).nullable(),schema:le(i(),ce()).nullable(),error:i().nullable().optional(),updatedAt:i()}).passthrough();const Xu=v(["create_sandbox_template_scaffold","resource_read","resource_search","list_files","read_files","search_files","preview_write_files","preview_write_file","preview_edit_file","preview_delete_file","write_files","write_file","edit_file","delete_file","workspace_status","validate_sandbox_template","build_sandbox_template","run_sandbox_template","git_init","git_status","git_diff","git_fetch","git_commit","git_push","publish_openpond_repo","sandbox_create","sandbox_templates","sandbox_template_launch","sandbox_status","sandbox_start","sandbox_list_files","sandbox_read_file","sandbox_search_files","sandbox_upload_file","sandbox_write_file","sandbox_edit_file","sandbox_delete_file","sandbox_mkdir","sandbox_move_file","sandbox_exec","sandbox_git_status","sandbox_git_diff","sandbox_git_export_patch","sandbox_git_apply_patch_local","sandbox_git_branch","sandbox_git_commit","sandbox_git_pull","sandbox_git_push","sandbox_preserve_source","sandbox_promote_source","sandbox_run_action","sandbox_open_port","sandbox_snapshot_catalog","sandbox_snapshot_create","sandbox_snapshot_update","sandbox_snapshot_validate","sandbox_snapshot_publish","sandbox_replays","sandbox_replay_start","sandbox_replay_get","sandbox_replay_logs","sandbox_replay_artifacts","sandbox_replay_cancel","sandbox_logs","sandbox_receipts","sandbox_prepare_agent","sandbox_save_agent_package","sandbox_save_output","work_agent_package_install","work_output_delete","work_output_read","sandbox_schedule_create","sandbox_stop"]);c({action:Xu,args:le(i(),ce()).optional().default({}),source:v(["ui_button","chat_action","terminal_command","hook"]).default("chat_action")});c({ok:I(),action:Xu,appId:i().nullable().optional(),output:i(),data:ce().optional()});const nd=c({id:i().trim().min(1).max(200),title:i().trim().min(1).max(240),sourceTaskId:i().trim().min(1).max(200),sourceTurnId:i().trim().min(1).max(200),revision:u().int().positive().default(1),createdAt:i().datetime()}),ad=c({kind:v(["structural","visual","test","user_review"]),status:v(["passed","failed","not_run"]),label:i().trim().min(1).max(240),detail:i().trim().max(4e3).nullable().optional(),ref:i().trim().max(4096).nullable().optional()}),HI=c({kind:b("local"),path:i().trim().min(1).max(4096),deviceId:i().trim().min(1).max(200)}),LI=c({kind:b("managed"),fileId:i().trim().min(1).max(200),downloadPath:i().trim().min(1).max(4096)}),aU=c({kind:b("external"),provider:i().trim().min(1).max(120),resourceId:i().trim().min(1).max(500),url:i().url().nullable()}),qI=nd.extend({kind:b("file"),contentType:i().trim().min(1).max(200),sizeBytes:u().int().nonnegative(),sha256:i().regex(/^[a-f0-9]{64}$/),location:ot("kind",[HI,LI,aU]),validation:p(ad).max(32).default([])}),iU=nd.extend({kind:b("source_change"),projectId:i().trim().min(1).max(200),ref:i().trim().min(1).max(500),url:i().url().nullable(),validation:p(ad).max(32).default([])}),oU=nd.extend({kind:b("deployment"),deploymentId:i().trim().min(1).max(200),url:i().url(),validation:p(ad).max(32).default([])}),rU=nd.extend({kind:b("external_resource"),provider:i().trim().min(1).max(120),resourceId:i().trim().min(1).max(500),url:i().url(),contentType:i().trim().min(1).max(200).nullable(),validation:p(ad).max(32).default([])}),UI=c({id:i().trim().min(1).max(191),label:i().trim().min(1).max(160).nullable(),description:i().trim().max(1e3).nullable(),inputSchema:le(i(),ce()).nullable(),outputSchema:le(i(),ce()).nullable(),schedulePolicy:le(i(),ce()).nullable()}),zI=c({base:i().trim().min(1).max(200),resources:le(i(),ce()),modelPolicy:le(i(),ce()).nullable(),setup:le(i(),ce()).nullable()}),sU=c({id:i().trim().min(1).max(200),kind:v(["sdk_validation","sdk_eval"]),status:v(["passed","failed"]),summary:i().trim().min(1).max(2e3),artifactPath:i().trim().min(1).max(4096),artifactSha256:i().regex(/^[a-f0-9]{64}$/)}),lU=c({path:i().trim().min(1).max(4096),sizeBytes:u().int().nonnegative(),sha256:i().regex(/^[a-f0-9]{64}$/),contentsBase64:i()});c({schema:b("openpond.agent-package.v1"),agentId:i().trim().min(1).max(191),versionId:i().trim().min(1).max(200),digest:i().regex(/^[a-f0-9]{64}$/),title:i().trim().min(1).max(240),source:c({files:p(lU).min(1).max(1e3),totalSizeBytes:u().int().nonnegative()}),manifest:le(i(),ce()),actions:p(UI).min(1).max(256),runtimeRequirements:zI,receipts:p(sU).min(2).max(64)});const cU=nd.extend({kind:b("agent_package"),agentId:i().trim().min(1).max(191),versionId:i().trim().min(1).max(200),digest:i().regex(/^[a-f0-9]{64}$/),packageFileId:i().trim().min(1).max(200),manifestFileId:i().trim().min(1).max(200),actions:p(UI).min(1).max(256),runtimeRequirements:zI,validationReceiptIds:p(i().trim().min(1).max(200)).min(1).max(32),evalReceiptIds:p(i().trim().min(1).max(200)).min(1).max(32),sourceFileCount:u().int().positive(),sourceSizeBytes:u().int().nonnegative(),location:ot("kind",[HI,LI]),validation:p(ad).max(32).default([])}),tie=ot("kind",[qI,iU,oU,rU,cU]);c({outputs:p(qI)});const dU=v(["sandbox_template","sandbox","generic_git","plain_folder"]),uU=v(["sandbox_template"]).nullable();c({productKind:dU,actions:c({files:I(),git:I(),sandboxRuntime:I(),sandboxTemplate:I()}),checks:c({validate:Xu.nullable(),build:Xu.nullable(),postEdit:uU}),ui:c({showSandboxTemplateActions:I(),showSandboxRuntimeActions:I()})});const mU=c({id:i(),name:i(),dnsName:i().nullable(),os:i().nullable(),online:I(),active:I(),isSelf:I(),tailscaleIps:p(i()),lastSeen:i().nullable()}),pU=c({installed:I(),running:I(),version:i().nullable(),backendState:i().nullable(),tailnetName:i().nullable(),magicDnsSuffix:i().nullable(),machineName:i().nullable(),dnsName:i().nullable(),authUrl:i().nullable(),tailscaleIps:p(i()),health:p(i()),error:i().nullable(),peers:p(mU)}),fU=c({enabled:I(),reachable:I(),targetUrl:i().nullable(),httpsUrl:i().nullable(),httpsHost:i().nullable(),httpsPort:u().nullable(),setupUrl:i().nullable(),configText:i().nullable(),error:i().nullable()}),hU=c({localUrl:i(),localWebUrl:i(),remoteUrl:i().nullable(),remoteWebUrl:i().nullable(),tokenHash:i(),tailscaleUpCommand:i(),serveCommand:i(),disableCommand:i(),operatorCommand:i(),webUiAvailable:I(),updatedAt:i(),tailscale:pU,serve:fU});c({message:i(),status:hU});const BI=v(["github","openpond_git"]),FI=v(["private","public"]),gU=v(["actions","workflows","instructions","prompts","goals","evals","examples","tasksets","extensions"]),vU=c({agentIds:p(i().trim().min(1)).max(100),skillNames:p(i().trim().min(1)).max(200),optionalContent:p(gU).max(20).default([])}),VI=c({provider:BI,owner:i().trim().min(1).max(191).nullable().optional(),repository:i().trim().min(1).max(191),visibility:FI.default("private")}),bU=c({ref:Bi,selection:vU,target:VI}),yU=c({path:i(),sizeBytes:u().int().nonnegative(),category:i()});c({sourceHash:i(),sourceRevision:i().nullable(),clean:I(),blockedReasons:p(i()),warnings:p(i()),files:p(yU),excludedFiles:p(i()),target:VI,replacesExisting:I()});bU.extend({expectedSourceHash:i().trim().min(1),confirmed:b(!0)});c({provider:BI,owner:i(),repository:i(),visibility:FI,remoteUrl:i(),webUrl:i(),revision:i()});const SU=v(["cron","rate"]),KI=v(["queued","running","succeeded","failed","skipped"]),ib=c({id:i(),localProjectId:i(),localProjectName:i(),agentRootPath:i(),agentName:i(),scheduleName:i(),scheduleType:SU,scheduleExpression:i(),timezone:i().nullable(),targetAction:i(),input:le(i(),ce()).optional().default({}),enabledByDefault:I(),enabled:I(),sourceHash:i(),manifestHash:i().nullable(),agentVersionId:i().nullable().optional(),agentPackageDigest:i().nullable().optional(),nextRunAt:i().nullable(),lastRunAt:i().nullable(),lastRunStatus:KI.nullable(),lastRunId:i().nullable(),lastError:i().nullable(),createdAt:i(),updatedAt:i()}),WI=c({id:i(),scheduleId:i(),definitionSnapshot:ib.optional(),configurationSnapshot:le(i(),ce()).optional(),inputSnapshot:le(i(),ce()).optional(),localProjectId:i(),scheduleName:i(),scheduledFor:i(),trigger:v(["schedule","manual"]),status:KI,targetAction:i(),agentVersionId:i().nullable().optional(),agentPackageDigest:i().nullable().optional(),startedAt:i().nullable(),completedAt:i().nullable(),exitCode:u().int().nullable(),stdout:i().nullable(),stderr:i().nullable(),result:le(i(),ce()).nullable(),traceArtifactRef:i().nullable(),error:i().nullable(),createdAt:i(),updatedAt:i()});c({schedules:p(ib),scheduler:c({running:I(),nextTickAt:i().nullable(),lastSyncAt:i().nullable(),scanRunning:I()})});c({runs:p(WI)});c({enabled:I().optional()});c({input:le(i(),ce()).optional()});c({schedule:ib,run:WI});const xU=v(["sunday","monday","tuesday","wednesday","thursday","friday","saturday"]),fl=c({version:b(1),kind:v(["once","daily","weekdays","weekly","monthly"]),timeZone:i().trim().min(1).max(100),startDate:i().regex(/^\d{4}-\d{2}-\d{2}$/),localTime:i().regex(/^([01]\d|2[0-3]):([0-5]\d)$/),weekdays:p(xU).min(1).max(7).optional(),dayOfMonth:u().int().min(1).max(31).optional(),end:ot("kind",[c({kind:b("never")}),c({kind:b("on_date"),date:i().regex(/^\d{4}-\d{2}-\d{2}$/)}),c({kind:b("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"]})}),kU=c({id:i(),expression:i().nullable(),timeZone:i(),recurrence:fl.nullable(),configurationVersion:u().int(),enabled:I(),nextRunAt:i().nullable(),lastTriggeredAt:i().nullable(),delivery:le(i(),ce()).default({})}),wU=c({id:i(),definitionKey:i(),version:u().int(),name:i(),prompt:i(),modelId:i(),schedules:p(kU)}),IU=c({id:i(),definitionId:i(),scheduleId:i().nullable(),definitionName:i(),definitionVersion:u().int(),conversationId:i(),triggerKind:v(["manual","schedule","webhook","retry"]),status:i(),notificationStatus:i(),deliveryStatus:i(),deliveryError:i().nullable(),createdAt:i()});c({definitions:p(wU),runs:p(IU),asOf:i(),webBaseUrl:i().url().optional()});c({clientRequestId:i().trim().min(1).max(191),sourceTurnId:i().trim().min(1).max(191).nullable().optional(),targetSessionId:i().trim().min(1).max(191).nullable().optional(),name:i().trim().min(1).max(180),prompt:i().trim().min(1).max(2e4),recurrence:fl,modelId:i().trim().min(1).max(191).default("openpond-chat")});vt([c({enabled:I()}),c({name:i().trim().min(1).max(180),prompt:i().trim().min(1).max(2e4),recurrence:fl})]);const GI=v(["queued","running","succeeded","failed"]),JI=c({id:i(),sessionId:i(),sessionTitle:i(),sourceTurnId:i().nullable(),name:i(),prompt:i(),profileRef:Bi.optional(),profileWorkflowId:i().optional(),profileMigrationError:i().nullable().optional(),recurrence:fl,enabled:I(),nextRunAt:i().nullable(),lastRunAt:i().nullable(),lastRunStatus:GI.nullable(),lastRunId:i().nullable(),lastError:i().nullable(),scheduledRunCount:u().int().nonnegative(),createdAt:i(),updatedAt:i()}),_U=c({definitionSnapshot:JI.optional(),configurationSnapshot:le(i(),ce()).optional(),id:i(),workflowId:i(),sessionId:i(),scheduledFor:i(),trigger:v(["schedule","manual"]),status:GI,turnId:i().nullable(),error:i().nullable(),createdAt:i(),startedAt:i().nullable(),completedAt:i().nullable(),updatedAt:i()});c({sessionId:i().trim().min(1).max(191),sourceTurnId:i().trim().min(1).max(191).nullable().optional(),name:i().trim().min(1).max(180),prompt:i().trim().min(1).max(2e4),recurrence:fl});vt([c({enabled:I()}),c({name:i().trim().min(1).max(180),prompt:i().trim().min(1).max(2e4),recurrence:fl})]);c({workflows:p(JI),runs:p(_U),asOf:i()});const ob=le(i(),ce());c({userId:i(),role:v(["owner","admin","member"]),name:i(),handle:i().nullable(),image:i().nullable()});const CU=c({userId:i(),role:v(["owner","admin","member"]),name:i(),handle:i().nullable(),image:i().nullable(),lastReadSequence:u().int().nonnegative()}),RU=c({id:i(),messageId:i(),refType:v(["hosted_ai_thread","goal","openpond_session","project","agent_run","message_reply"]),refId:i(),preview:ob,createdAt:i()}),ZI=c({id:i(),messageId:i().nullable(),clientAttachmentId:i(),kind:b("image"),name:i(),mediaType:v(["image/png","image/jpeg","image/webp","image/gif"]),sizeBytes:u().int().positive(),status:v(["pending","ready","failed"]),createdAt:i(),readyAt:i().nullable()});c({attachment:ZI,uploadUrl:i().url().nullable(),uploadHeaders:le(i(),i()),expiresAt:i().nullable()});c({url:i().url(),expiresAt:i()});const rb=c({id:i(),threadId:i(),teamId:i(),clientRequestId:i().nullable(),authorType:v(["user","agent","system"]),authorUserId:i().nullable(),authorAgentId:i().nullable(),sequence:u().int().nonnegative(),kind:v(["text","system","command_result"]),body:i(),metadata:ob,editedAt:i().nullable(),deletedAt:i().nullable(),createdAt:i(),refs:p(RU),attachments:p(ZI)}),PU=c({id:i(),teamId:i(),kind:v(["general","dm","group","channel"]),title:i().nullable(),createdByUserId:i(),lastMessageId:i().nullable(),lastMessageSequence:u().int().nonnegative(),lastMessageAt:i(),createdAt:i(),updatedAt:i(),unreadCount:u().int().nonnegative(),pinnedAt:i().nullable(),mutedAt:i().nullable(),archivedAt:i().nullable(),participants:p(CU),lastMessage:rb.nullable()});c({thread:PU,messages:p(rb),hasMoreBefore:I()});c({threadId:i(),mutedAt:i().nullable()});const AU=v(["pending","running","completed","failed","interrupted","cancelled"]),kS=c({id:i(),conversationId:i(),threadId:i(),teamId:i(),requestedByUserId:i(),executorUserId:i().nullable(),providerId:i(),modelId:i(),clientRequestId:i(),baseMessageSequence:u().int().nonnegative(),status:AU,partialBody:i().nullable(),userMessageId:i(),assistantMessageId:i().nullable(),errorCode:i().nullable(),cancelledByUserId:i().nullable(),leaseExpiresAt:i().nullable(),heartbeatAt:i().nullable(),createdAt:i(),updatedAt:i()}),TU=c({id:i(),conversationId:i(),sequence:u().int().nonnegative(),role:v(["user","assistant","system","action"]),body:i(),createdByUserId:i().nullable(),createdAt:i()});c({conversationId:i(),parentThreadId:i(),parentMessageId:i(),teamId:i(),title:i().nullable(),providerId:i().nullable(),modelId:i(),createdByUserId:i(),messages:p(TU),turns:p(kS),activeTurn:kS.nullable(),createdAt:i(),updatedAt:i()});const YI=c({id:u().int().nonnegative(),teamId:i(),threadId:i(),conversationId:i().nullable(),type:v(["thread.created","message.created","message.updated","message.deleted","read.updated","ai_thread.created","ai_turn.updated"]),payload:ob,createdAt:i()});c({events:p(YI),cursor:u().int().nonnegative(),hasMore:I()});c({httpUrl:i().min(1),realtimeUrl:i().min(1),region:i().min(1),token:i().min(1),expiresAt:i().min(1),teamId:i().min(1),userId:i().min(1)});const sb=le(i(),ce()),Va=i().nullable(),EU=v(["draft","published","archived"]),lb=v(["owner","admin","member"]),QI=v(["active","left"]),XI=v(["mentions","all","none"]),e_=v(["public_preview","members"]),MU=v(["members","admins"]),jU=c({canPreview:I(),canJoin:I(),canLeave:I(),canRead:I(),canPost:I(),canUpload:I(),canMention:I(),canManage:I(),requiresRulesAcceptance:I(),currentRulesVersionId:i().nullable()}),t_=c({id:i(),communityId:i(),version:u().int().positive(),title:i(),requiresReacceptance:I(),publishedAt:i()}),OU=t_.extend({bodyMarkdown:i(),contentHash:i()}),$U=c({role:lb,status:QI,notificationMode:XI}),NU=c({id:i(),communityId:i(),userId:i(),role:lb,status:QI,notificationMode:XI,joinedAt:i(),leftAt:Va,createdAt:i(),updatedAt:i()}),n_=c({id:i(),slug:i(),displayName:i(),description:i(),imageUrl:i().nullable(),status:EU,visibility:v(["public","private"]),joinPolicy:v(["open","closed"]),historyVisibility:e_,featuredAt:Va,publishedAt:Va,archivedAt:Va,memberCount:u().int().nonnegative(),membership:$U.nullable(),capabilities:jU,currentRules:t_.nullable()});c({items:p(n_),nextCursor:i().nullable()});const a_=c({lastReadSequence:u().int().nonnegative(),lastReadAt:Va.optional(),mutedAt:Va,pinnedAt:Va}),cb=c({id:i(),communityId:i(),chatThreadId:i().nullable(),slug:i(),displayName:i(),topic:i(),position:u().int().nonnegative(),visibility:e_,postingPolicy:MU,isDefault:I(),archivedAt:Va,lastMessageSequence:u().int().nonnegative(),unreadCount:u().int().nonnegative(),readState:a_.nullable()});n_.omit({currentRules:!0}).extend({currentRules:OU.nullable(),channels:p(cb),previewMessageLimit:u().int().positive()});const DU=c({id:i(),messageId:i(),refType:v(["hosted_ai_thread","goal","openpond_session","project","agent_run","message_reply"]),refId:i(),preview:sb,createdAt:i()}),i_=c({id:i(),messageId:i().nullable(),clientAttachmentId:i(),kind:b("image"),name:i(),mediaType:v(["image/png","image/jpeg","image/webp","image/gif"]),sizeBytes:u().int().positive(),status:v(["pending","ready","failed"]),createdAt:i(),readyAt:Va});c({attachment:i_,uploadUrl:i().url().nullable(),uploadHeaders:le(i(),i()),expiresAt:Va});c({url:i().url(),expiresAt:i()});const o_=c({id:i(),threadId:i(),teamId:cl(),clientRequestId:i().nullable(),authorType:v(["user","agent","system"]),authorUserId:i().nullable(),authorAgentId:i().nullable(),sequence:u().int().nonnegative(),kind:v(["text","system","command_result"]),body:i(),metadata:sb,editedAt:Va,deletedAt:Va,createdAt:i(),refs:p(DU),attachments:p(i_)});c({messages:p(o_),hasMoreBefore:I(),channelId:i(),readState:a_.omit({lastReadAt:!0}).nullable(),preview:I()});const HU=c({userId:i(),handle:i().nullable(),name:i().nullable(),role:lb});c({items:p(HU),nextCursor:i().nullable()});const r_=c({id:u().int().nonnegative(),communityId:i(),channelId:i(),threadId:i(),type:v(["thread.created","message.created","message.updated","message.deleted","read.updated"]),payload:sb,createdAt:i()});c({events:p(r_),cursor:u().int().nonnegative(),hasMore:I()});c({httpUrl:i().min(1),realtimeUrl:i().min(1),region:i().min(1),token:i().min(1),expiresAt:i().min(1),communityId:i().min(1),userId:i().min(1),channel:i().min(1)});c({membership:NU,channels:p(cb)});c({channels:p(cb)});var Rc=i().trim().min(1).max(500),LU=i().regex(/^[a-f0-9]{64}$/),em=c({id:Rc,revision:u().int().positive(),contentHash:LU}).strict(),qU=c({schemaVersion:b("openpond.hostedTasksetSummary.v1"),id:Rc,teamId:Rc,release:em,name:i().min(1).max(500),description:i().max(2e4),taskCount:u().int().nonnegative(),buildIntent:i().min(1).max(100),methodHint:i().min(1).max(100).nullable(),packageBytes:u().int().nonnegative().nullable(),storedBytes:u().int().nonnegative().nullable(),createdAt:i().datetime({offset:!0})}).strict();c({afterId:i().trim().min(1).max(2e3).optional(),limit:u().int().min(1).max(100).default(30),modelProjectId:Rc.optional(),projectId:Rc.optional(),search:i().trim().max(100).optional(),sort:v(["id","name","updated"]).default("id")}).strict();c({items:p(qU).max(100),nextCursor:i().trim().min(1).max(2e3).nullable()}).strict();c({code:i().min(1),message:i().min(1)}).strict();const UU=c({candidateId:i().min(1).max(240),frozenRevision:u().int().positive(),frozenHash:i().regex(/^[a-f0-9]{64}$/),harnessRelease:W,protectedClosureHash:i().regex(/^[a-f0-9]{64}$/)}).strict(),wS=i().trim().min(1).max(240),zU=i().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."),id=c({schemaVersion:b("openpond.tasksetMetricPolicy.v1"),primaryMetric:wS,aggregation:v(["mean_score","pass_rate","weighted_mean","custom"]),missingReward:v(["zero","exclude"]),taskWeights:le(wS,u().positive().max(1e6)).optional(),customAggregator:c({module:zU,exportName:i().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),contentHash:H,timeoutMs:u().int().positive().max(3e5),networkPolicy:b("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."})}),BU=c({schemaVersion:b("openpond.tasksetMetricResult.v1"),runManifest:W,tasksetRelease:W,policy:id,policyHash:H,receiptRefs:p(W).min(1).max(1e6),includedCount:u().int().nonnegative(),missingRewardCount:u().int().nonnegative(),excludedCount:u().int().nonnegative(),value:u().min(0).max(1).nullable()}).strict(),db=BU.extend({contentHash:H}).strict(),en=T,Do=H,s_=c({id:en,revision:u().int().positive(),contentHash:Do}).strict(),ub=c({kind:b("owner_attested_local"),ownerActorId:en,teamId:en,executionHash:Do,configurationHash:Do,retainedAttemptHash:Do,traceHash:Do,publicationCutoffHash:Do}).strict(),FU=ub.omit({publicationCutoffHash:!0,kind:!0}).extend({kind:b("native_local")}).strict(),VU=c({origin:ub,executionId:en,receiptId:en,taskId:en,targetId:en,familyKey:en,split:v(["train","validation","test","frozen_eval"]),input:le(i(),ce()),policyVisibleContext:le(i(),ce()),output:i().nullable(),error:i().nullable(),events:p(le(i(),ce())).max(1e3),coverage:c({sourceEventCount:u().int().nonnegative().max(2e4),publishedEventCount:u().int().nonnegative().max(1e3),traceLimited:I(),artifactsIncluded:b(!1)}).strict()}).strict().superRefine((e,t)=>{(e.events.length!==e.coverage.publishedEventCount||e.coverage.sourceEventCount<e.events.length||e.coverage.traceLimited!==e.coverage.sourceEventCount>e.events.length)&&t.addIssue({code:"custom",message:"Publication coverage must describe its actual retained event population."}),ct(e.events)!==e.origin.publicationCutoffHash&&t.addIssue({code:"custom",message:"Published trace cutoff changed."})}),KU=c({schemaVersion:b("openpond.humanLocalEvidenceExport.v1"),actorId:en,scope:en,projectId:en,dataset:s_,graderId:en,compiledGraderHash:Do,attempts:p(VU).min(1).max(2),sealedAt:ye}).strict().superRefine((e,t)=>{e.attempts.some(n=>n.origin.ownerActorId!==e.actorId||n.origin.teamId!==e.scope)&&t.addIssue({code:"custom",message:"Local publication belongs to another actor/workspace."})}),WU=KU.safeExtend({contentHash:Do}).strict().superRefine((e,t)=>{const{contentHash:n,...a}=e;ct(a)!==n&&t.addIssue({code:"custom",message:"Local evidence export bytes changed."})}),l_=c({endpoint:b("export_local"),scope:en,projectId:en,graderId:en,selections:p(c({executionId:en,receiptId:en}).strict()).min(1).max(2)}).strict(),GU=c({endpoint:b("publish_local"),scope:en,projectId:en,operationId:en,audience:p(en).max(100),workspaceVisible:I(),evidence:WU}).strict(),JU=l_.omit({endpoint:!0}).extend({endpoint:b("share_local"),operationId:en,audience:p(en).max(100),workspaceVisible:I()}).strict(),ZU=c({endpoint:b("local_publications"),scope:en,executionId:en}).strict(),YU=c({endpoint:b("revoke_local"),scope:en,publication:s_}).strict();var c_=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},QU=c_((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 r,s,l;if(Array.isArray(a)){if(r=a.length,r!=o.length)return!1;for(s=r;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),r=l.length,r!==Object.keys(o).length)return!1;for(s=r;s--!==0;)if(!Object.prototype.hasOwnProperty.call(o,l[s]))return!1;for(s=r;s--!==0;){var m=l[s];if(!n(a[m],o[m]))return!1}return!0}return a!==a&&o!==o}}),XU=c_(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var t=QU();t.code='require("ajv/dist/runtime/equal").default',e.default=t}),IS=zt,_S={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"}}},ez=Object.prototype.hasOwnProperty,tz=XU().default,Pt={validate:zt};function Pa(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:r={}}={}){let s=null,l=0,m=Pa.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 f in e){let g=l;Pt.validate(e[f],{instancePath:t+"/"+f.replace(/~/g,"~0").replace(/\//g,"~1"),parentData:e,parentDataProperty:f,rootData:o,dynamicAnchors:r})||(s=s===null?Pt.validate.errors:s.concat(Pt.validate.errors),l=s.length);var d=g===l;if(!d)break}else return Pa.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"object"}}],!1;return Pa.errors=s,l===0}Pa.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};function qn(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:r={}}={}){let s=null,l=0,m=qn.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 qn.errors=[{instancePath:t,schemaPath:"#/maxItems",keyword:"maxItems",params:{limit:32}}],!1;if(e.length<1)return qn.errors=[{instancePath:t,schemaPath:"#/minItems",keyword:"minItems",params:{limit:1}}],!1;{var d=!0;let f=e.length;for(let g=0;g<f;g++){let x=l;Pt.validate(e[g],{instancePath:t+"/"+g,parentData:e,parentDataProperty:g,rootData:o,dynamicAnchors:r})||(s=s===null?Pt.validate.errors:s.concat(Pt.validate.errors),l=s.length);var d=x===l;if(!d)break}}}else return qn.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"array"}}],!1;return qn.errors=s,l===0}qn.evaluated={items:!0,dynamicProps:!1,dynamicItems:!1};var nz={enum:["array","boolean","integer","null","number","object","string"]};function Mi(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:r={}}={}){let s=null,l=0,m=Mi.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"?(Mi.errors=s,l===0):(Mi.errors=[{instancePath:t,schemaPath:"#/enum",keyword:"enum",params:{allowedValues:nz.enum}}],!1)}Mi.evaluated={dynamicProps:!1,dynamicItems:!1};function Bt(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:r={}}={}){let s=null,l=0,m=Bt.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))?(Bt.errors=[{instancePath:t,schemaPath:"#/minimum",keyword:"minimum",params:{comparison:">=",limit:0}}],!1):(Bt.errors=s,l===0):(Bt.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"integer"}}],!1)}Bt.evaluated={dynamicProps:!1,dynamicItems:!1};function qa(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:r={}}={}){let s=null,l=0,m=qa.evaluated;if(m.dynamicProps&&(m.props=void 0),m.dynamicItems&&(m.items=void 0),l===0)if(Array.isArray(e)){var d=!0;let f=e.length;for(let g=0;g<f;g++){let x=l;if(typeof e[g]!="string")return qa.errors=[{instancePath:t+"/"+g,schemaPath:"#/items/type",keyword:"type",params:{type:"string"}}],!1;var d=x===l;if(!d)break}if(d){let g=e.length,x;if(g>1){let k={};for(;g--;){let C=e[g];if(typeof C=="string"){if(typeof k[C]=="number")return x=k[C],qa.errors=[{instancePath:t,schemaPath:"#/uniqueItems",keyword:"uniqueItems",params:{i:g,j:x}}],!1;k[C]=g}}}}}else return qa.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"array"}}],!1;return qa.errors=s,l===0}qa.evaluated={items:!0,dynamicProps:!1,dynamicItems:!1};function zt(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:r={}}={}){let s=null,l=0,m=zt.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 zt.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:_S.type}}],!1;if(l===0&&e&&typeof e=="object"&&!Array.isArray(e)){let k=l;for(let C in e)if(!ez.call(_S.properties,C))return zt.errors=[{instancePath:t,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:C}}],!1;if(k===l){if(e.$schema!==void 0){let C=l;if(e.$schema!=="https://json-schema.org/draft/2020-12/schema")return zt.errors=[{instancePath:t+"/$schema",schemaPath:"#/properties/%24schema/const",keyword:"const",params:{allowedValue:"https://json-schema.org/draft/2020-12/schema"}}],!1;var d=C===l}else var d=!0;if(d){if(e.$ref!==void 0){let R=l;if(typeof e.$ref!="string")return zt.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 E=l;if(typeof e.$comment!="string")return zt.errors=[{instancePath:t+"/$comment",schemaPath:"#/properties/%24comment/type",keyword:"type",params:{type:"string"}}],!1;var d=E===l}else var d=!0;if(d){if(e.$defs!==void 0){let A=l;Pa(e.$defs,{instancePath:t+"/$defs",parentData:e,parentDataProperty:"$defs",rootData:o,dynamicAnchors:r})||(s=s===null?Pa.errors:s.concat(Pa.errors),l=s.length);var d=A===l}else var d=!0;if(d){if(e.properties!==void 0){let O=l;Pa(e.properties,{instancePath:t+"/properties",parentData:e,parentDataProperty:"properties",rootData:o,dynamicAnchors:r})||(s=s===null?Pa.errors:s.concat(Pa.errors),l=s.length);var d=O===l}else var d=!0;if(d){if(e.dependentSchemas!==void 0){let $=l;Pa(e.dependentSchemas,{instancePath:t+"/dependentSchemas",parentData:e,parentDataProperty:"dependentSchemas",rootData:o,dynamicAnchors:r})||(s=s===null?Pa.errors:s.concat(Pa.errors),l=s.length);var d=$===l}else var d=!0;if(d){if(e.allOf!==void 0){let M=l;qn(e.allOf,{instancePath:t+"/allOf",parentData:e,parentDataProperty:"allOf",rootData:o,dynamicAnchors:r})||(s=s===null?qn.errors:s.concat(qn.errors),l=s.length);var d=M===l}else var d=!0;if(d){if(e.anyOf!==void 0){let w=l;qn(e.anyOf,{instancePath:t+"/anyOf",parentData:e,parentDataProperty:"anyOf",rootData:o,dynamicAnchors:r})||(s=s===null?qn.errors:s.concat(qn.errors),l=s.length);var d=w===l}else var d=!0;if(d){if(e.oneOf!==void 0){let P=l;qn(e.oneOf,{instancePath:t+"/oneOf",parentData:e,parentDataProperty:"oneOf",rootData:o,dynamicAnchors:r})||(s=s===null?qn.errors:s.concat(qn.errors),l=s.length);var d=P===l}else var d=!0;if(d){if(e.prefixItems!==void 0){let j=l;qn(e.prefixItems,{instancePath:t+"/prefixItems",parentData:e,parentDataProperty:"prefixItems",rootData:o,dynamicAnchors:r})||(s=s===null?qn.errors:s.concat(qn.errors),l=s.length);var d=j===l}else var d=!0;if(d){if(e.items!==void 0){let N=l;Pt.validate(e.items,{instancePath:t+"/items",parentData:e,parentDataProperty:"items",rootData:o,dynamicAnchors:r})||(s=s===null?Pt.validate.errors:s.concat(Pt.validate.errors),l=s.length);var d=N===l}else var d=!0;if(d){if(e.additionalProperties!==void 0){let z=l;Pt.validate(e.additionalProperties,{instancePath:t+"/additionalProperties",parentData:e,parentDataProperty:"additionalProperties",rootData:o,dynamicAnchors:r})||(s=s===null?Pt.validate.errors:s.concat(Pt.validate.errors),l=s.length);var d=z===l}else var d=!0;if(d){if(e.not!==void 0){let D=l;Pt.validate(e.not,{instancePath:t+"/not",parentData:e,parentDataProperty:"not",rootData:o,dynamicAnchors:r})||(s=s===null?Pt.validate.errors:s.concat(Pt.validate.errors),l=s.length);var d=D===l}else var d=!0;if(d){if(e.if!==void 0){let F=l;Pt.validate(e.if,{instancePath:t+"/if",parentData:e,parentDataProperty:"if",rootData:o,dynamicAnchors:r})||(s=s===null?Pt.validate.errors:s.concat(Pt.validate.errors),l=s.length);var d=F===l}else var d=!0;if(d){if(e.then!==void 0){let te=l;Pt.validate(e.then,{instancePath:t+"/then",parentData:e,parentDataProperty:"then",rootData:o,dynamicAnchors:r})||(s=s===null?Pt.validate.errors:s.concat(Pt.validate.errors),l=s.length);var d=te===l}else var d=!0;if(d){if(e.else!==void 0){let ve=l;Pt.validate(e.else,{instancePath:t+"/else",parentData:e,parentDataProperty:"else",rootData:o,dynamicAnchors:r})||(s=s===null?Pt.validate.errors:s.concat(Pt.validate.errors),l=s.length);var d=ve===l}else var d=!0;if(d){if(e.contains!==void 0){let re=l;Pt.validate(e.contains,{instancePath:t+"/contains",parentData:e,parentDataProperty:"contains",rootData:o,dynamicAnchors:r})||(s=s===null?Pt.validate.errors:s.concat(Pt.validate.errors),l=s.length);var d=re===l}else var d=!0;if(d){if(e.unevaluatedProperties!==void 0){let K=l;Pt.validate(e.unevaluatedProperties,{instancePath:t+"/unevaluatedProperties",parentData:e,parentDataProperty:"unevaluatedProperties",rootData:o,dynamicAnchors:r})||(s=s===null?Pt.validate.errors:s.concat(Pt.validate.errors),l=s.length);var d=K===l}else var d=!0;if(d){if(e.unevaluatedItems!==void 0){let L=l;Pt.validate(e.unevaluatedItems,{instancePath:t+"/unevaluatedItems",parentData:e,parentDataProperty:"unevaluatedItems",rootData:o,dynamicAnchors:r})||(s=s===null?Pt.validate.errors:s.concat(Pt.validate.errors),l=s.length);var d=L===l}else var d=!0;if(d){if(e.propertyNames!==void 0){let de=l;Pt.validate(e.propertyNames,{instancePath:t+"/propertyNames",parentData:e,parentDataProperty:"propertyNames",rootData:o,dynamicAnchors:r})||(s=s===null?Pt.validate.errors:s.concat(Pt.validate.errors),l=s.length);var d=de===l}else var d=!0;if(d){if(e.type!==void 0){let X=e.type,Z=l,pe=l,ee=!1,me=l;Mi(X,{instancePath:t+"/type",parentData:e,parentDataProperty:"type",rootData:o,dynamicAnchors:r})||(s=s===null?Mi.errors:s.concat(Mi.errors),l=s.length);var g=me===l;ee=ee||g;let be=l;if(l===be)if(Array.isArray(X))if(X.length<1){let ke={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf/1/minItems",keyword:"minItems",params:{limit:1}};s===null?s=[ke]:s.push(ke),l++}else{var f=!0;let ke=X.length;for(let ue=0;ue<ke;ue++){let Ie=l;Mi(X[ue],{instancePath:t+"/type/"+ue,parentData:X,parentDataProperty:ue,rootData:o,dynamicAnchors:r})||(s=s===null?Mi.errors:s.concat(Mi.errors),l=s.length);var f=Ie===l;if(!f)break}if(f){let ue=X.length,Ie;if(ue>1){e:for(;ue--;)for(Ie=ue;Ie--;)if(tz(X[ue],X[Ie])){let Le={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf/1/uniqueItems",keyword:"uniqueItems",params:{i:ue,j:Ie}};s===null?s=[Le]:s.push(Le),l++;break e}}}}else{let ke={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf/1/type",keyword:"type",params:{type:"array"}};s===null?s=[ke]:s.push(ke),l++}var g=be===l;if(ee=ee||g,ee)l=pe,s!==null&&(pe?s.length=pe:s=null);else{let ke={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf",keyword:"anyOf",params:{}};return s===null?s=[ke]:s.push(ke),l++,zt.errors=s,!1}var d=Z===l}else var d=!0;if(d){if(e.enum!==void 0){let Z=e.enum,pe=l;if(l===pe)if(Array.isArray(Z)){if(Z.length<1)return zt.errors=[{instancePath:t+"/enum",schemaPath:"#/properties/enum/minItems",keyword:"minItems",params:{limit:1}}],!1}else return zt.errors=[{instancePath:t+"/enum",schemaPath:"#/properties/enum/type",keyword:"type",params:{type:"array"}}],!1;var d=pe===l}else var d=!0;if(d){if(e.title!==void 0){let pe=l;if(typeof e.title!="string")return zt.errors=[{instancePath:t+"/title",schemaPath:"#/properties/title/type",keyword:"type",params:{type:"string"}}],!1;var d=pe===l}else var d=!0;if(d){if(e.description!==void 0){let ee=l;if(typeof e.description!="string")return zt.errors=[{instancePath:t+"/description",schemaPath:"#/properties/description/type",keyword:"type",params:{type:"string"}}],!1;var d=ee===l}else var d=!0;if(d){if(e.examples!==void 0){let me=l;if(!Array.isArray(e.examples))return zt.errors=[{instancePath:t+"/examples",schemaPath:"#/properties/examples/type",keyword:"type",params:{type:"array"}}],!1;var d=me===l}else var d=!0;if(d){if(e.readOnly!==void 0){let be=l;if(typeof e.readOnly!="boolean")return zt.errors=[{instancePath:t+"/readOnly",schemaPath:"#/properties/readOnly/type",keyword:"type",params:{type:"boolean"}}],!1;var d=be===l}else var d=!0;if(d){if(e.writeOnly!==void 0){let je=l;if(typeof e.writeOnly!="boolean")return zt.errors=[{instancePath:t+"/writeOnly",schemaPath:"#/properties/writeOnly/type",keyword:"type",params:{type:"boolean"}}],!1;var d=je===l}else var d=!0;if(d){if(e.deprecated!==void 0){let ke=l;if(typeof e.deprecated!="boolean")return zt.errors=[{instancePath:t+"/deprecated",schemaPath:"#/properties/deprecated/type",keyword:"type",params:{type:"boolean"}}],!1;var d=ke===l}else var d=!0;if(d){if(e.multipleOf!==void 0){let ue=e.multipleOf,Ie=l;if(l===Ie)if(typeof ue=="number"&&isFinite(ue)){if(ue<=0||isNaN(ue))return zt.errors=[{instancePath:t+"/multipleOf",schemaPath:"#/properties/multipleOf/exclusiveMinimum",keyword:"exclusiveMinimum",params:{comparison:">",limit:0}}],!1}else return zt.errors=[{instancePath:t+"/multipleOf",schemaPath:"#/properties/multipleOf/type",keyword:"type",params:{type:"number"}}],!1;var d=Ie===l}else var d=!0;if(d){if(e.maximum!==void 0){let Ie=e.maximum,Le=l;if(!(typeof Ie=="number"&&isFinite(Ie)))return zt.errors=[{instancePath:t+"/maximum",schemaPath:"#/properties/maximum/type",keyword:"type",params:{type:"number"}}],!1;var d=Le===l}else var d=!0;if(d){if(e.exclusiveMaximum!==void 0){let Le=e.exclusiveMaximum,Fe=l;if(!(typeof Le=="number"&&isFinite(Le)))return zt.errors=[{instancePath:t+"/exclusiveMaximum",schemaPath:"#/properties/exclusiveMaximum/type",keyword:"type",params:{type:"number"}}],!1;var d=Fe===l}else var d=!0;if(d){if(e.minimum!==void 0){let Fe=e.minimum,Xe=l;if(!(typeof Fe=="number"&&isFinite(Fe)))return zt.errors=[{instancePath:t+"/minimum",schemaPath:"#/properties/minimum/type",keyword:"type",params:{type:"number"}}],!1;var d=Xe===l}else var d=!0;if(d){if(e.exclusiveMinimum!==void 0){let Xe=e.exclusiveMinimum,Ze=l;if(!(typeof Xe=="number"&&isFinite(Xe)))return zt.errors=[{instancePath:t+"/exclusiveMinimum",schemaPath:"#/properties/exclusiveMinimum/type",keyword:"type",params:{type:"number"}}],!1;var d=Ze===l}else var d=!0;if(d){if(e.maxLength!==void 0){let Ze=l;Bt(e.maxLength,{instancePath:t+"/maxLength",parentData:e,parentDataProperty:"maxLength",rootData:o,dynamicAnchors:r})||(s=s===null?Bt.errors:s.concat(Bt.errors),l=s.length);var d=Ze===l}else var d=!0;if(d){if(e.minLength!==void 0){let Be=l;Bt(e.minLength,{instancePath:t+"/minLength",parentData:e,parentDataProperty:"minLength",rootData:o,dynamicAnchors:r})||(s=s===null?Bt.errors:s.concat(Bt.errors),l=s.length);var d=Be===l}else var d=!0;if(d){if(e.maxItems!==void 0){let Ge=l;Bt(e.maxItems,{instancePath:t+"/maxItems",parentData:e,parentDataProperty:"maxItems",rootData:o,dynamicAnchors:r})||(s=s===null?Bt.errors:s.concat(Bt.errors),l=s.length);var d=Ge===l}else var d=!0;if(d){if(e.minItems!==void 0){let Ve=l;Bt(e.minItems,{instancePath:t+"/minItems",parentData:e,parentDataProperty:"minItems",rootData:o,dynamicAnchors:r})||(s=s===null?Bt.errors:s.concat(Bt.errors),l=s.length);var d=Ve===l}else var d=!0;if(d){if(e.maxContains!==void 0){let U=l;Bt(e.maxContains,{instancePath:t+"/maxContains",parentData:e,parentDataProperty:"maxContains",rootData:o,dynamicAnchors:r})||(s=s===null?Bt.errors:s.concat(Bt.errors),l=s.length);var d=U===l}else var d=!0;if(d){if(e.minContains!==void 0){let J=l;Bt(e.minContains,{instancePath:t+"/minContains",parentData:e,parentDataProperty:"minContains",rootData:o,dynamicAnchors:r})||(s=s===null?Bt.errors:s.concat(Bt.errors),l=s.length);var d=J===l}else var d=!0;if(d){if(e.maxProperties!==void 0){let q=l;Bt(e.maxProperties,{instancePath:t+"/maxProperties",parentData:e,parentDataProperty:"maxProperties",rootData:o,dynamicAnchors:r})||(s=s===null?Bt.errors:s.concat(Bt.errors),l=s.length);var d=q===l}else var d=!0;if(d){if(e.minProperties!==void 0){let oe=l;Bt(e.minProperties,{instancePath:t+"/minProperties",parentData:e,parentDataProperty:"minProperties",rootData:o,dynamicAnchors:r})||(s=s===null?Bt.errors:s.concat(Bt.errors),l=s.length);var d=oe===l}else var d=!0;if(d){if(e.uniqueItems!==void 0){let he=l;if(typeof e.uniqueItems!="boolean")return zt.errors=[{instancePath:t+"/uniqueItems",schemaPath:"#/properties/uniqueItems/type",keyword:"type",params:{type:"boolean"}}],!1;var d=he===l}else var d=!0;if(d){if(e.required!==void 0){let Re=l;qa(e.required,{instancePath:t+"/required",parentData:e,parentDataProperty:"required",rootData:o,dynamicAnchors:r})||(s=s===null?qa.errors:s.concat(qa.errors),l=s.length);var d=Re===l}else var d=!0;if(d){if(e.dependentRequired!==void 0){let qe=e.dependentRequired,Je=l;if(l===Je)if(qe&&typeof qe=="object"&&!Array.isArray(qe))for(let dt in qe){let _t=l;qa(qe[dt],{instancePath:t+"/dependentRequired/"+dt.replace(/~/g,"~0").replace(/\//g,"~1"),parentData:qe,parentDataProperty:dt,rootData:o,dynamicAnchors:r})||(s=s===null?qa.errors:s.concat(qa.errors),l=s.length);var x=_t===l;if(!x)break}else return zt.errors=[{instancePath:t+"/dependentRequired",schemaPath:"#/properties/dependentRequired/type",keyword:"type",params:{type:"object"}}],!1;var d=Je===l}else var d=!0;if(d){if(e.contentEncoding!==void 0){let Je=l;if(typeof e.contentEncoding!="string")return zt.errors=[{instancePath:t+"/contentEncoding",schemaPath:"#/properties/contentEncoding/type",keyword:"type",params:{type:"string"}}],!1;var d=Je===l}else var d=!0;if(d)if(e.contentMediaType!==void 0){let Je=l;if(typeof e.contentMediaType!="string")return zt.errors=[{instancePath:t+"/contentMediaType",schemaPath:"#/properties/contentMediaType/type",keyword:"type",params:{type:"string"}}],!1;var d=Je===l}else var d=!0}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}return zt.errors=s,l===0}zt.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};const CS="https://json-schema.org/draft/2020-12/schema",az=1048576,iz=32768,oz=new Set(["properties","$defs","dependentSchemas"]),rz=new Set(["allOf","anyOf","oneOf","prefixItems"]),sz=new Set(["items","additionalProperties","not","if","then","else","contains","unevaluatedProperties","unevaluatedItems","propertyNames"]);function Qa(e,t=az){const n=[{value:e,depth:0}],a=new Set;let o=0;for(;n.length;){const r=n.pop();if(r.exit){a.delete(r.value);continue}if(++o>1e5||r.depth>48)throw new Error("task_json_complexity_exceeded");if(r.value===null||typeof r.value=="string"||typeof r.value=="boolean"||typeof r.value=="number"&&Number.isFinite(r.value))continue;if(typeof r.value!="object")throw new Error("task_json_value_invalid");if(a.has(r.value))throw new Error("task_json_cycle");a.add(r.value),n.push({...r,exit:!0});const s=Object.getPrototypeOf(r.value);if(!Array.isArray(r.value)&&s!==Object.prototype&&s!==null)throw new Error("task_json_object_invalid");if(Object.getOwnPropertySymbols(r.value).length)throw new Error("task_json_symbol_invalid");if(Object.hasOwn(r.value,"toJSON"))throw new Error("task_json_serializer_invalid");if(Array.isArray(r.value)&&(r.value.length>1e4||Object.keys(r.value).length!==r.value.length))throw new Error("task_json_array_invalid");for(const[l,m]of Object.entries(Object.getOwnPropertyDescriptors(r.value))){if(m.get||m.set)throw new Error("task_json_accessor_invalid");if(Array.isArray(r.value)&&l!=="length"&&(!/^(0|[1-9]\d*)$/u.test(l)||Number(l)>=r.value.length))throw new Error("task_json_array_invalid");m.enumerable&&n.push({value:m.value,depth:r.depth+1})}}if(new TextEncoder().encode(JSON.stringify(e)).byteLength>t)throw new Error("task_json_size_exceeded")}function mb(e){try{return lz(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 lz(e){if(Qa(e,iz),nc(e,e,new Set,0,{remaining:2048}),!IS(e)){const t=IS.errors?.[0];throw new Error(`Task schema ${t?.instancePath||"/"} violates ${t?.keyword??"schema"}.`)}}function nc(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 r=new Set(n).add(e),s=e;if(s.$schema!==void 0&&s.$schema!==CS)throw new Error(`Task schemas must use ${CS}.`);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 f of m.slice(2).split("/")){if(/~(?![01])/u.test(f))throw new Error("Invalid task schema JSON pointer.");const g=f.replaceAll("~1","/").replaceAll("~0","~");if(!d||typeof d!="object"||!Object.hasOwn(d,g))throw new Error(`Task schema reference ${m} is missing.`);d=d[g]}nc(d,t,r,a+1,o)}else if(oz.has(l)){if(!m||typeof m!="object"||Array.isArray(m))throw new Error(`Invalid schema map ${l}.`);for(const d of Object.values(m))nc(d,t,r,a+1,o)}else if(rz.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)nc(d,t,r,a+1,o)}else sz.has(l)&&nc(m,t,r,a+1,o)}const d_=c({taskId:T,input:le(i(),ce()),policyVisibleContext:le(i(),ce()),expectedOutput:le(i(),ce()).nullable().optional(),tags:p(T).max(100).optional()}).strict(),Js=c({schemaVersion:b("openpond.humanTaskProposal.v1"),tasks:p(d_).min(1).max(1e3),contentHash:H}).strict().superRefine((e,t)=>{const{contentHash:n,...a}=e;n!==ct(a)&&t.addIssue({code:"custom",message:"Task proposal content hash differs."}),new Set(e.tasks.map(o=>o.taskId)).size!==e.tasks.length&&t.addIssue({code:"custom",message:"Each task may be proposed once."});try{Qa(e,1048576)}catch{t.addIssue({code:"custom",message:"Task proposal exceeds retained data bounds."})}}),RS=c({schemaVersion:b("openpond.humanTaskProposal.v1"),tasks:p(d_).min(1).max(1e3),contentHash:H,referenceRedacted:b(!0).optional()}).strict().superRefine((e,t)=>{e.referenceRedacted?e.tasks.some(n=>n.expectedOutput!==void 0)&&t.addIssue({code:"custom",message:"Redacted proposals cannot include reference outputs."}):Js.safeParse(e).success||t.addIssue({code:"custom",message:"Task proposal integrity differs."})});function nie(e){const t={schemaVersion:"openpond.humanTaskProposal.v1",tasks:e};return Js.parse({...t,contentHash:ct(t)})}const ze=T,Cn=c({id:ze,revision:u().int().positive(),contentHash:H}).strict(),cz=ot("kind",[c({id:ze,label:i().trim().min(1).max(500),instructions:i().max(2e4),required:I(),allowAbstain:I(),requireRationale:I().optional(),anchors:p(c({value:vt([u(),i(),I()]),description:i().min(1).max(2e3)}).strict()).max(100).optional(),kind:b("score"),minimum:u().finite(),maximum:u().finite(),step:u().positive().finite()}).strict().refine(e=>e.minimum<e.maximum&&e.step<=e.maximum-e.minimum,"Use an increasing raw score range and a step within that range."),c({id:ze,label:i().trim().min(1).max(500),instructions:i().max(2e4),required:I(),allowAbstain:I(),requireRationale:I().optional(),anchors:p(c({value:vt([u(),i(),I()]),description:i().min(1).max(2e3)}).strict()).max(100).optional(),kind:b("category"),options:p(i().trim().min(1).max(500)).min(2).max(100)}).strict().refine(e=>new Set(e.options).size===e.options.length,"Category options must be unique."),c({id:ze,label:i().trim().min(1).max(500),instructions:i().max(2e4),required:I(),allowAbstain:I(),requireRationale:I().optional(),anchors:p(c({value:vt([u(),i(),I()]),description:i().min(1).max(2e3)}).strict()).max(100).optional(),kind:b("boolean")}).strict(),c({id:ze,label:i().trim().min(1).max(500),instructions:i().max(2e4),required:I(),allowAbstain:I(),requireRationale:I().optional(),anchors:p(c({value:vt([u(),i(),I()]),description:i().min(1).max(2e3)}).strict()).max(100).optional(),kind:b("text"),minimumLength:u().int().nonnegative().max(2e4).optional(),maximumLength:u().int().positive().max(2e4)}).strict(),c({id:ze,label:i().trim().min(1).max(500),instructions:i().max(2e4),required:I(),allowAbstain:I(),requireRationale:I().optional(),anchors:p(c({value:vt([u(),i(),I()]),description:i().min(1).max(2e3)}).strict()).max(100).optional(),kind:b("preference"),requireStrength:I().optional(),allowTie:I()}).strict()]),od=c({schemaVersion:b("openpond.humanForm.v1"),mode:v(["individual","pairwise"]),instructions:i().max(2e4),criteria:p(cz).min(1).max(100)}).strict().superRefine((e,t)=>{e.criteria.forEach((n,a)=>{n.kind==="text"&&(n.minimumLength??0)>n.maximumLength&&t.addIssue({code:"custom",path:["criteria",a,"minimumLength"],message:"Minimum text length must not exceed maximum length."});const o=new Set;n.anchors?.forEach((r,s)=>{const l=r.value,m=n.kind==="score"?typeof l=="number"&&Number.isFinite(l)&&l>=n.minimum&&l<=n.maximum&&Math.abs((l-n.minimum)/n.step-Math.round((l-n.minimum)/n.step))<1e-8:n.kind==="category"?typeof l=="string"&&n.options.includes(l):n.kind==="boolean"?typeof l=="boolean":n.kind==="preference"?["A","B",...n.allowTie?["tie"]:[]].includes(String(l)):typeof l=="string",d=JSON.stringify(l);(!m||o.has(d))&&t.addIssue({code:"custom",path:["criteria",a,"anchors",s,"value"],message:"Each anchor must describe a unique valid raw value."}),o.add(d)})}),new Set(e.criteria.map(n=>n.id)).size!==e.criteria.length&&t.addIssue({code:"custom",path:["criteria"],message:"Criterion IDs must be unique."}),e.mode==="individual"&&e.criteria.some(n=>n.kind==="preference")&&t.addIssue({code:"custom",path:["criteria"],message:"Preferences require an explicit pair."})}),dz=c({localSource:vt([ub,FU]).optional(),recordedSource:c({id:ze,snapshotHash:H,boundaryId:ze,boundaryRevisionHash:H}).strict().optional(),experimentId:ze,attemptId:ze,taskId:ze,targetId:ze,output:Cn,trace:Cn.nullable(),familyKey:ze,split:v(["train","validation","test","frozen_eval"])}).strict(),pb=c({publication:Cn.optional(),dataset:Cn,grader:Cn,graderBinding:c({id:ze,version:i().min(1).max(100),contentHash:H}).strict(),rubric:Cn,attempts:p(dz).max(2),taskIds:p(ze).min(1).max(1e3).optional()}).strict().superRefine((e,t)=>{!e.attempts.length&&!e.taskIds?.length&&t.addIssue({code:"custom",message:"Select retained attempts or exact tasks."}),e.taskIds&&new Set(e.taskIds).size!==e.taskIds.length&&t.addIssue({code:"custom",path:["taskIds"],message:"Select each task once."}),e.attempts.length===2&&(e.attempts[0].attemptId===e.attempts[1].attemptId||e.attempts[0].taskId!==e.attempts[1].taskId||e.attempts[0].familyKey!==e.attempts[1].familyKey||e.attempts[0].split!==e.attempts[1].split)&&t.addIssue({code:"custom",path:["attempts"],message:"A/B review requires distinct attempts of the same task, family and split."})}),Zs=c({criterionId:ze,value:vt([u().finite(),I(),i().max(2e4),cl()]),abstain:I(),note:i().max(2e4),strength:v(["slight","moderate","strong"]).optional()}).strict(),u_=c({approval:v(["none","manager"]),minimumRaters:u().int().min(1).max(100),managerIds:p(ze).max(100),reviewerIds:p(ze).max(100),queueClaim:I(),teamVisible:I(),distinctManager:I().optional(),independentRaters:I().optional(),blindPair:I().optional()}).strict().superRefine((e,t)=>{e.approval==="none"&&e.minimumRaters!==1&&t.addIssue({code:"custom",path:["minimumRaters"],message:"Multi-rater review requires explicit adjudication."})}),m_=c({taskProposal:Js.optional(),id:ze,revision:u().int().positive(),actorId:ze,generation:u().int().positive(),evidenceHash:H,formHash:H,answers:p(Zs).max(100),note:i().max(2e4),submittedAt:ye,supersedes:ze.nullable(),contentHash:H}).strict(),ac=c({taskProposalHash:H.optional(),id:ze,revision:u().int().positive(),actorId:ze,outcome:v(["accept","reject","request_changes"]),submissions:p(c({id:ze,contentHash:H}).strict()).min(1).max(100),answers:p(Zs).max(100),note:i().max(2e4),decidedAt:ye,contentHash:H}).strict(),tm=c({schemaVersion:b("openpond.humanReview.v1"),id:ze,revision:u().int().positive(),scope:ze,projectId:ze,createdBy:ze,kind:v(["author","execute","grade"]),dueAt:ye.optional(),title:i().trim().min(1).max(500),authorPublication:c({proposalHash:H,dataset:Cn,operationId:ze,publishedBy:ze,publishedAt:ye}).strict().nullable(),evidence:pb,form:od,policy:u_,status:v(["queued","assigned","in_progress","submitted","returned","accepted","rejected","cancelled"]),assigneeId:ze.nullable(),generation:u().int().positive(),drafts:p(c({taskProposal:Js.optional(),actorId:ze,generation:u().int().positive(),answers:p(Zs).max(100),note:i().max(2e4),updatedAt:ye}).strict()).max(100),submissions:p(m_).max(1e3),decisions:p(ac).max(1e3),audit:p(c({actorId:ze,action:v(["claim","reassign","cancel"]),priorAssigneeId:ze.nullable(),assigneeId:ze.nullable(),generation:u().int().positive(),note:i().max(2e4),occurredAt:ye}).strict()).max(1e3),execution:c({executionId:ze.nullable(),operationId:ze,boundBy:ze,configurationHash:H,generation:u().int().positive(),result:Cn.nullable()}).strict().nullable(),createdAt:ye,updatedAt:ye,contentHash:H}).strict(),Ci={operationId:ze,id:ze,expectedRevision:u().int().nonnegative()},uz=ot("action",[c({...Ci,action:b("create"),projectId:ze,kind:tm.shape.kind,title:tm.shape.title,dueAt:ye.optional(),evidence:pb,form:od,policy:u_,assigneeId:ze.nullable()}).strict(),c({...Ci,action:b("claim")}).strict(),c({...Ci,action:b("bind_author_publication"),proposalHash:H,dataset:Cn}).strict(),c({...Ci,action:b("reserve_execution"),generation:u().int().positive(),runOperationId:ze,configurationHash:H}).strict(),c({...Ci,action:b("bind_execution"),generation:u().int().positive(),executionId:ze,runOperationId:ze,configurationHash:H}).strict(),c({...Ci,action:b("reassign"),assigneeId:ze.nullable(),note:i().trim().min(1).max(2e4)}).strict(),c({...Ci,action:b("cancel"),note:i().max(2e4)}).strict(),c({...Ci,action:b("save_draft"),taskProposal:Js.optional(),generation:u().int().positive(),answers:p(Zs).max(100),note:i().max(2e4)}).strict(),c({...Ci,action:b("submit"),taskProposal:Js.optional(),generation:u().int().positive(),evidenceHash:H,formHash:H,executionResult:Cn.optional(),answers:p(Zs).max(100),note:i().max(2e4)}).strict(),c({...Ci,action:b("decide"),taskProposalHash:H.optional(),outcome:ac.shape.outcome,submissions:ac.shape.submissions,answers:ac.shape.answers,note:ac.shape.note}).strict()]),mz=ot("endpoint",[c({endpoint:b("command"),scope:ze,command:uz}).strict(),c({endpoint:b("get"),scope:ze,id:ze,revision:u().int().positive().optional()}).strict(),c({endpoint:b("inbox"),scope:ze,projectId:ze.optional(),view:v(["mine","team","approval"]),status:v(["active","history"]),afterId:ze.optional(),limit:u().int().min(1).max(100)}).strict()]),p_=tm.omit({evidence:!0,drafts:!0,submissions:!0}).extend({drafts:p(tm.shape.drafts.element.omit({taskProposal:!0}).extend({taskProposal:RS.optional()})).max(100),submissions:p(m_.omit({taskProposal:!0}).extend({taskProposal:RS.optional()})).max(1e3),evidence:pb.nullable(),evidenceHash:H,formHash:H,permissions:c({owner:I(),manager:I(),reviewer:I(),claim:I()}).strict()}).strict(),pz=c({items:p(p_).max(100),nextCursor:ze.nullable(),actionCount:u().int().nonnegative(),approvalAvailable:I()}).strict(),f_=c({endpoint:b("snapshot"),scope:ze,projectId:ze,graderId:ze,selections:p(c({executionId:ze,receiptId:ze}).strict()).min(1).max(2)}).strict(),fz=c({endpoint:b("snapshot_tasks"),scope:ze,projectId:ze,graderId:ze,dataset:Cn,taskIds:p(ze).min(1).max(1e3).optional(),all:b(!0).optional()}).strict().refine(e=>!!e.all!=!!e.taskIds,"Choose an exact selected task list or the server-frozen full Dataset."),hz=c({endpoint:b("inspect"),scope:ze,id:ze,slot:u().int().min(0).max(1).optional(),afterId:i().min(1).max(500).optional()}).strict(),gz=c({endpoint:b("results"),scope:ze,executionId:ze,selection:p(Cn).max(1e4).optional()}).strict(),vz=c({endpoint:b("members"),scope:ze}).strict(),bz=c({endpoint:b("execute"),scope:ze,id:ze,expectedRevision:u().int().positive(),generation:u().int().positive(),operationId:ze,configuration:ce()}).strict(),yz=c({endpoint:b("execution"),scope:ze,id:ze,action:v(["status","result","cancel"])}).strict(),Sz=f_.omit({endpoint:!0}).extend({endpoint:b("publish_evidence"),operationId:ze,audience:p(ze).max(100),workspaceVisible:I()}).strict(),xz=c({endpoint:b("publication_access"),scope:ze,projectId:ze}).strict(),kz=c({endpoint:b("revoke_publication"),scope:ze,publication:Cn}).strict(),wz=c({endpoint:b("publish_author"),scope:ze,id:ze,expectedRevision:u().int().positive(),operationId:ze,proposalHash:H,workspaceId:ze.optional(),expectedWorkspaceRevision:u().int().positive().optional()}).strict(),Iz=c({endpoint:b("author_tasks"),scope:ze,id:ze,includeReference:b(!0).optional()}).strict(),_z=c({endpoint:b("graders"),scope:ze,projectId:ze,dataset:Cn}).strict(),aie=p(c({id:ze,name:i(),version:i(),contentHash:H,mode:v(["individual","pairwise"])}).strict()).max(1e3),Cz=vt([YU,ZU,l_,GU,JU,xz,wz,Iz,_z,Sz,kz,bz,yz,mz,f_,fz,hz,gz,vz]),Rz=p(c({origin:b("owner_attested_local").optional(),coverage:c({sourceEventCount:u().int().nonnegative(),publishedEventCount:u().int().nonnegative(),traceLimited:I(),artifactsIncluded:b(!1)}).strict().optional(),reviewId:ze,reviewRevision:u().int().positive(),evidenceHash:H,slot:i(),input:ce(),output:ce(),error:i().nullable(),events:p(le(i(),ce())),eventCount:u().int().nonnegative(),evidenceLimited:I(),nextEventCursor:i().nullable(),slotIndex:u().int().nonnegative(),executionId:ze.optional(),receiptId:ze.optional()}).strict()).max(1e3),Xa=v(["train","validation","test","frozen_eval"]),Pz=c({path:i().trim().min(1).max(2e3).refine(Tz),mediaType:i().trim().min(1).max(200),schemaRef:bn.nullable().default(null),maxBytes:u().int().positive().max(25e7).nullable().default(null),metadata:Nn}).strict(),Az=c({policyVisibleFields:p(T).max(1e3).default([]),privilegedFields:p(T).max(1e3).default([]),hiddenGraderRefs:p(T).max(1e3).default([]),connectedAppScopes:p(T).max(100).default([])}).strict(),h_=c({protocolVersion:b("openpond.environment.v1"),kind:v(["text","agent","work","custom_program"]),entrypoint:i().trim().min(1).max(1e3),stateful:I(),deterministicSeeds:I(),lifecycle:p(v(["create","reset","step","collect","destroy"])).min(5).max(5),networkPolicy:v(["none","declared_read_only","declared_scoped"]),defaultTimeoutMs:u().int().positive().max(36e5)}).strict(),Bm=c({id:T,version:i().trim().min(1).max(100),weight:u().nonnegative().max(1e3).default(1),hardGate:I().default(!1),rewardEligible:I().default(!1),privileged:I().default(!1)}),g_=Bm.extend({kind:v(["content","schema","artifact","runtime_event","state"]),config:le(i(),ce())}).strict(),v_=Bm.extend({kind:b("model_judge"),rubricRef:bn,calibrationStatus:v(["pending","passed","failed"]),model:c({providerId:T,modelId:T,revision:i().trim().min(1).max(500).nullable()}).strict().optional(),temperature:u().min(0).max(2).optional()}).strict(),b_=v(["isolated_javascript","sandbox_process"]),y_=Bm.extend({kind:b("custom_verifier"),runtime:b_.optional(),verifierRef:bn,exportName:i().trim().min(1).max(240).optional(),timeoutMs:u().int().positive().max(3e5),networkPolicy:b("none")}).strict(),S_=Bm.extend({kind:b("human"),rubricRef:bn,reviewerRole:i().trim().min(1).max(500),form:od.optional()}).strict(),x_=vt([g_,v_,y_,S_]),fb=c({id:T,clusterKey:T,split:Xa,input:le(i(),ce()),expectedOutput:le(i(),ce()).nullable(),policyVisibleContext:le(i(),ce()).default({}),privilegedContextRef:T.nullable(),artifactRefs:p(bn).max(1e3).default([]),requiredOutputs:p(Pz).max(1e3).optional(),tags:p(T).max(100).default([])}).strict(),k_=c({schemaVersion:b("openpond.tasksetRelease.v2"),id:T,revision:u().int().positive(),policy:Az,environment:h_,environmentRelease:c({id:T,contentHash:H}).strict().optional(),tools:p(Xc).max(200),capabilities:p(Bv).max(200),tasks:p(fb).min(1).max(1e6),graders:p(x_).min(1).max(1e3),verifierSetRelease:c({id:T,contentHash:H}).strict().optional(),metrics:id.optional(),metadata:Nn}).strict(),w_=k_.extend({contentHash:H}).strict();function Tz(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}const Ez=i().min(1).max(2e3).refine(e=>!e.includes("\\")&&!e.includes(":")&&!e.startsWith("/")&&e.split("/").every(t=>t!==""&&t!=="."&&t!==".."),"Evaluation paths must be portable and relative."),hb=ot("kind",[c({kind:b("profile")}).strict(),c({kind:b("workflow"),workflowId:T}).strict(),c({kind:b("skill"),skillPath:Ez}).strict(),c({kind:b("agent_action"),actionId:T}).strict()]),Mz=c({taskId:T,seed:i().min(1).max(500),fixtureId:T.nullable()}).strict(),PS=i().min(1).max(200).refine(e=>!["__proto__","prototype","constructor"].includes(e),"Use an ordinary field name."),AS=v(["input","output","expectedOutput","evaluatorContext"]),jz=p(c({graderId:T,fields:p(c({destination:AS,path:p(PS).min(1).max(20),source:AS,sourcePath:p(PS).max(20)}).strict()).max(100)}).strict()).max(100),Oz=c({execution:W,originalEvidence:W,members:p(c({caseId:T,seed:i().min(1).max(500),fixtureId:H,sourceId:T,snapshotHash:H,boundaryRevisionHash:H}).strict()).min(1).max(500)}).strict(),$z=c({release:W.extend({revision:vt([u().int().positive(),i().min(1).max(200)])}).strict(),feedbackKey:i().min(1).max(240),configurationHash:H,output:v(["boolean","score","category"]),categories:p(i().min(1).max(120)).max(50)}).strict(),Nz=c({schemaVersion:b("openpond.profileExternalDatasetBinding.v1"),dataset:W.extend({revision:u().int().positive()}).strict(),packageHash:H,profileId:T,target:hb,declaredProfileCatalogHash:H.nullable(),protectedProfileClosureHash:H,recordedOrigin:Oz.optional(),gradingSource:c({pass:W,evidence:W}).strict().optional(),split:Xa,population:p(Mz).min(1).max(1e4),evaluators:p($z).min(1).max(100),fieldMappingsHash:H,fieldMappings:jz,environmentHash:H,privateDatasetClosureHash:H,criterion:c({minimumPassRate:u().min(0).max(1),requireComplete:I()}).strict()}).strict().superRefine((e,t)=>{e.recordedOrigin&&(e.recordedOrigin.members.length!==e.population.length||e.recordedOrigin.members.some((n,a)=>n.caseId!==e.population[a].taskId||n.seed!==e.population[a].seed||n.fixtureId!==n.snapshotHash||e.population[a].fixtureId!==null))&&t.addIssue({code:"custom",message:"Recorded-to-rerun mapping must preserve every exact ordered cutoff and seed while admitting new target attempts."}),ct(e.fieldMappings)!==e.fieldMappingsHash&&t.addIssue({code:"custom",message:"Field mappings differ from their sealed hash."}),new Set(e.fieldMappings.map(n=>n.graderId)).size!==e.fieldMappings.length&&t.addIssue({code:"custom",message:"Field mappings must name each grader once."}),new Set(e.population.map(n=>JSON.stringify([n.taskId,n.seed,n.fixtureId]))).size!==e.population.length&&t.addIssue({code:"custom",message:"External Dataset population must be unique."}),new Set(e.evaluators.map(n=>n.feedbackKey)).size!==e.evaluators.length&&t.addIssue({code:"custom",message:"External Dataset feedback keys must be unique."});for(const n of e.evaluators)n.output==="category"!=n.categories.length>0&&t.addIssue({code:"custom",message:"Only category grading declares categories."})}),Wo=Nz.safeExtend({contentHash:H}).strict();function xg(e){const t=Wo.parse(e),{contentHash:n,...a}=t;if(ct(a)!==n)throw new Error("External Dataset binding integrity failed.");return t}const I_=c({id:T,label:i().trim().min(1).max(240),description:i().max(4e3),target:hb,tasksetRelease:W,split:Xa,taskIds:p(T).min(1).max(1e5),seeds:p(i().trim().min(1).max(500)).min(1).max(100),criterion:c({minimumPassRate:u().min(0).max(1),requireComplete:I()}).strict()}).strict().superRefine((e,t)=>{new Set(e.taskIds).size!==e.taskIds.length&&t.addIssue({code:"custom",path:["taskIds"],message:"Evaluation task identities must be unique."}),new Set(e.seeds).size!==e.seeds.length&&t.addIssue({code:"custom",path:["seeds"],message:"Evaluation seeds must be unique."})}),__=c({id:T,label:i().trim().min(1).max(240),scope:v(["component","profile"]),definitionIds:p(T).min(1).max(1e3)}).strict();c({schemaVersion:b("openpond.profileEvaluations.v1"),definitions:p(I_).max(1e3),suites:p(__).max(100)}).strict();const Ys=c({profileId:T,sourceRevision:i().trim().min(1).max(240),harnessRelease:W,catalogHash:H,definitionId:T,definitionHash:H,target:hb,environmentHash:H,externalDatasetBinding:Wo.optional(),sourceCandidate:UU.optional()}).strict();class pi extends Error{code;status;constructor(t,n=422,a){super(a?`${t}: ${a}`:t),this.code=t,this.status=n,this.name="LearningDomainError"}}const Dz=c({schemaVersion:b("openpond.modelJudgeTransportPolicy.v1"),responseFormat:b("judgment_json_schema"),reasoningEffort:v(["off","low","medium","high","xhigh","max"]),maximumOutputTokens:u().int().positive().max(1e6)}).strict(),Hz=c({schemaVersion:b("openpond.modelJudgeReceipt.v1"),providerId:i().trim().min(1).max(200),modelId:i().trim().min(1).max(500),modelRevision:i().trim().min(1).max(500).nullable(),responseId:i().trim().min(1).max(500).nullable(),requestHash:H,responseHash:H,inputTokens:u().int().nonnegative().nullable(),outputTokens:u().int().nonnegative().nullable(),costUsd:u().finite().nonnegative().nullable(),transportPolicy:Dz.optional(),effectiveRequestHash:H.optional(),finishReason:i().trim().min(1).max(200).nullable().optional(),reasoningTokens:u().int().nonnegative().nullable().optional()}).strict(),Lz=c({schemaVersion:b("openpond.graderEvidence.v1"),graderId:T,graderVersion:i().trim().min(1).max(100),status:v(["scored","pending","unavailable","failed"]).optional(),score:u().min(0).max(1).nullable(),passed:I(),rewardEligible:I(),failureClass:Wc.nullable(),feedback:p(i().max(2e4)).max(1e3),visibleEvidenceRefs:p(T).max(1e4),privilegedEvidenceRefs:p(T).max(1e4),modelJudgeReceipt:Hz.optional()}).strict(),C_=Lz.extend({contentHash:H}).strict(),qz=c({score:u().min(0).max(1).nullable(),passed:I(),rewardEligible:I(),failureClass:Wc.nullable(),gradingStatus:v(["scored","pending","unscorable","not_configured"])}).strict(),R_=qz.extend({schemaVersion:b("openpond.taskGrade.v1"),taskHash:H,evidenceHash:H,graderSetHash:H,components:p(C_).max(1e3),contentHash:H}).strict(),Qd={id:!0,version:!0,weight:!0,hardGate:!0,rewardEligible:!0,privileged:!0},rd=i().regex(/^[a-z][a-z0-9_]{0,79}$/);function Uz(e){return e.feedbackKey??`reward_${ct(e.id).slice(0,24)}`}const zz=vt([g_.omit(Qd),v_.omit(Qd),y_.omit(Qd),S_.omit(Qd),c({kind:b("learned_model"),modelVersion:W,inputContract:bn}).strict()]),P_=c({schemaVersion:b("openpond.rewardRelease.v1"),id:T,revision:u().int().positive(),name:i().trim().min(1).max(500),description:i().max(1e4),feedbackKey:rd.optional(),implementation:zz,rawScore:c({minimum:u().finite(),maximum:u().finite()}).strict(),assets:p(bn).max(1e3),fixtureSetRef:bn.optional(),calibrationCheckRef:W.extend({revision:u().int().positive()}).optional()}).strict().superRefine((e,t)=>{if(e.fixtureSetRef&&(e.fixtureSetRef.visibility!=="verifier"||!e.assets.some(n=>ct(n)===ct(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=mb(e.implementation.config.jsonSchema);n.valid||t.addIssue({code:"custom",path:["implementation","config","jsonSchema"],message:n.issues[0].message})}}),sd=P_.safeExtend({contentHash:H}).strict(),Xo=W.extend({revision:u().int().positive()}).strict(),Bz=ot("kind",[c({kind:b("identity")}).strict(),c({kind:b("linear"),minimum:u().finite(),maximum:u().finite(),direction:v(["higher","lower"])}).strict()]),gb=c({graderId:T,reward:Xo,role:v(["training","evaluation"]),normalization:Bz,weight:u().nonnegative().max(1e3),required:I(),hardGate:I(),privileged:I(),fixtureRefs:p(W).max(1e3)}).strict(),Fz=c({schemaVersion:b("openpond.rewardBinding.v1"),id:T,revision:u().int().positive(),name:i().trim().min(1).max(500).optional(),description:i().max(1e4).optional(),recipeRef:Xo.optional(),sources:p(gb).max(100),aggregation:b("weighted_mean"),unscorable:b("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."})}),Fm=Fz.safeExtend({contentHash:H}).strict(),A_=c({graderId:T,reward:Xo,role:v(["training","evaluation"]),status:v(["scored","pending","unavailable","failed"]),rawScore:u().finite().nullable(),normalizedScore:u().min(0).max(1).nullable(),passed:I().nullable(),evidenceHashes:p(H).max(1e3),graderEvidence:C_.optional(),message:i().max(2e4).nullable()}).strict(),Vz=c({schemaVersion:b("openpond.rewardComposition.v1"),binding:Xo,taskHash:H,outputHash:H,results:p(A_).max(100),training:c({status:v(["scored","pending","unscorable","not_configured"]),score:u().min(0).max(1).nullable(),passed:I().nullable()}).strict(),evaluation:c({status:v(["scored","pending","unscorable","not_configured"]),score:u().min(0).max(1).nullable(),passed:I().nullable()}).strict()}).strict(),Pc=Vz.extend({contentHash:H}).strict();function Kz(e){Qa(e);const t=P_.parse(e);return sd.parse({...t,contentHash:ct(t)})}const ld=c({harnessRelease:W,agentSnapshot:W,sourcePackageHash:H}).strict(),mh=i().trim().min(1).max(200),vb=c({sessionId:mh,turnId:mh,source:ld,admissionHash:H,modelConfigurationHash:H,traceHash:H,runtimeEventRefs:p(mh).max(1e4),startedAt:ye,completedAt:ye,outputHash:H,partialOutputAvailable:I()}).strict().superRefine((e,t)=>{new Set(e.runtimeEventRefs).size!==e.runtimeEventRefs.length&&t.addIssue({code:"custom",path:["runtimeEventRefs"],message:"Native event references must be unique."}),Date.parse(e.completedAt)<Date.parse(e.startedAt)&&t.addIssue({code:"custom",path:["completedAt"],message:"Native completion precedes its start."})}),Wz=c({schemaVersion:b("openpond.nativeHarnessExperimentAttempt.v1"),taskId:i().min(1).max(500),status:v(["completed","cancelled","timed_out","policy_failure"]),output:i().max(8388608).nullable(),error:i().max(2e3).nullable(),messages:p(ce()).max(4002),collected:I(),environmentCleanupComplete:b(!0),snapshot:cl(),native:vb}).strict().superRefine((e,t)=>{const n=e.status==="completed";(n!==e.collected||n!==(e.output!==null)||n!==(e.error===null))&&t.addIssue({code:"custom",message:"Native status, output, collection and error must agree."}),n&&(e.native.partialOutputAvailable||e.native.outputHash!==ct(e.output))&&t.addIssue({code:"custom",path:["native","outputHash"],message:"Native output differs from its retained evidence."})});Wz.extend({contentHash:H}).strict();const T_=u().finite().nonnegative(),E_=ot("kind",[c({kind:b("model"),modelId:T,configurationHash:H}).strict(),c({kind:b("harness"),source:Ys,model:c({modelId:T,configurationHash:H}).strict()}).strict(),c({kind:b("agent"),source:ld,model:c({modelId:T,configurationHash:H}).strict()}).strict(),c({kind:b("fixture"),configurationHash:H}).strict()]),M_=c({release:W.extend({revision:vt([u().int().positive(),i().trim().min(1).max(200)])}).strict(),feedbackKey:rd,configurationHash:H.optional(),output:v(["boolean","score","category"]),categories:p(i().trim().min(1).max(500)).max(100)}).strict().superRefine((e,t)=>{e.output==="category"!=e.categories.length>0&&t.addIssue({code:"custom",path:["categories"],message:"Only category feedback declares categories."}),new Set(e.categories).size!==e.categories.length&&t.addIssue({code:"custom",path:["categories"],message:"Feedback categories must be unique."})}),bb=c({caseId:T,seed:i().trim().min(1).max(500),fixtureId:T.nullable()}).strict();function Ac(e){const t=bb.parse(e);return JSON.stringify([t.caseId,t.seed,t.fixtureId])}function Gz(e,t,n){return`human-projection-${ct({originalManifest:e,selectionHash:t,rulesHash:n}).slice(0,48)}`}const Jz=c({schemaVersion:b("openpond.experimentManifest.v1"),id:T,name:i().trim().min(1).max(500),teamId:T,operationId:T,maximumCostUsd:T_.nullable(),dataset:W.extend({revision:u().int().positive()}).strict(),target:E_,execution:c({packageHash:H,runtimeTargetHash:H,metricPolicyHash:H,compatibility:c({protocol:b("openpond.evaluation-execution.v1"),targetKind:v(["model","agent","harness","fixture"])}).strict().optional()}).strict().optional(),lineage:c({definition:W.extend({revision:u().int().positive()}).strict().nullable(),execution:W,scoringPassId:T.nullable(),humanProjection:c({originalManifest:W,selectionHash:H,rulesHash:H}).strict().optional()}).strict().optional(),evaluators:p(M_).max(100),population:p(bb).min(1).max(1e4),createdAt:ye}).strict().superRefine((e,t)=>{if(e.execution?.compatibility&&e.execution.compatibility.targetKind!==e.target.kind&&t.addIssue({code:"custom",path:["execution","compatibility"],message:"Execution compatibility differs from its admitted target kind."}),e.lineage){const n=e.lineage.scoringPassId??e.lineage.execution.id,a=e.lineage.humanProjection;a?(a.originalManifest.id!==n||a.originalManifest.id.startsWith("human-projection-")||e.id!==Gz(a.originalManifest,a.selectionHash,a.rulesHash))&&t.addIssue({code:"custom",path:["lineage","humanProjection"],message:"Human view must bind its original execution or scoring pass and deterministic selection identity."}):e.id!==n&&t.addIssue({code:"custom",path:["lineage"],message:"Experiment identity must match its execution or independent scoring pass."})}new Set(e.population.map(Ac)).size!==e.population.length&&t.addIssue({code:"custom",path:["population"],message:"Experiment cases must be unique."}),new Set(e.evaluators.map(n=>n.feedbackKey)).size!==e.evaluators.length&&t.addIssue({code:"custom",path:["evaluators"],message:"Experiment feedback keys must be unique."})}),uo=Jz.extend({contentHash:H}).strict(),Zz=c({feedbackKey:rd,evaluator:M_.shape.release,status:v(["scored","unavailable","failed","pending"]),value:vt([I(),u().finite(),i().max(500)]).nullable(),passed:I().nullable().optional(),reasoning:i().max(2e4).nullable(),evidenceRefs:p(Ma).max(1e3)}).strict(),Yz=c({inputTokens:u().int().nonnegative().nullable(),outputTokens:u().int().nonnegative().nullable(),totalTokens:u().int().nonnegative().nullable(),costUsd:T_.nullable(),latencyMs:u().finite().nonnegative().nullable()}).strict().superRefine((e,t)=>{e.inputTokens!==null&&e.outputTokens!==null&&e.totalTokens!==null&&e.totalTokens<e.inputTokens+e.outputTokens&&t.addIssue({code:"custom",path:["totalTokens"],message:"Total tokens cannot be less than input plus output."})}),Qz=c({identity:bb,status:v(["completed","failed","cancelled","unavailable"]),output:ce().nullable(),error:c({code:T,message:i().max(2e3)}).strict().nullable(),feedback:p(Zz).max(100),usage:Yz,traceRef:Ma.nullable(),startedAt:ye.nullable(),completedAt:ye.nullable()}).strict(),j_=c({schemaVersion:b("openpond.experimentResult.v1"),manifest:W,status:v(["completed","failed","cancelled"]),cases:p(Qz).min(1).max(1e4),completedAt:ye}).strict(),mo=j_.extend({contentHash:H}).strict();function Xz(e,t){uo.parse(t),j$(t,"Experiment manifest");const n=j_.parse(e);if(n.manifest.id!==t.id||n.manifest.contentHash!==t.contentHash)throw new Error("Experiment result differs from its manifest.");const a=new Set(t.population.map(Ac)),o=new Set,r=new Map(t.evaluators.map(s=>[s.feedbackKey,s]));for(const s of n.cases){const l=Ac(s.identity);if(!a.has(l)||o.has(l))throw new Error("Experiment result has an unexpected or repeated case.");o.add(l);const m=new Set;for(const d of s.feedback){const f=r.get(d.feedbackKey);if(!f||m.has(d.feedbackKey)||d.evaluator.id!==f.release.id||d.evaluator.contentHash!==f.release.contentHash||d.evaluator.revision!==f.release.revision)throw new Error("Experiment feedback differs from its pinned evaluator.");if(m.add(d.feedbackKey),d.status==="scored"){if(d.value===null||typeof d.value!=={boolean:"boolean",score:"number",category:"string"}[f.output]||f.output==="category"&&!f.categories.includes(d.value)||f.output==="score"&&(d.value<0||d.value>1))throw new Error("Experiment feedback value violates its output contract.")}else if(d.value!==null||d.passed!==null&&d.passed!==void 0)throw new Error("Unscored experiment feedback cannot claim a value or pass decision.")}}if(o.size!==a.size)throw new Error("Experiment result omits admitted cases.");return mo.parse({...n,contentHash:ct(n)})}function Pr(e){const t=uo.parse(e.manifest),n=mo.parse(e.result),{contentHash:a,...o}=n;if(ct(o)!==a)throw new Error("Experiment result integrity failed.");return Xz(o,t),{manifest:t,result:n}}function e4(e,t){for(const g of[e,t])Pr(g);const n=[];e.manifest.teamId!==t.manifest.teamId&&n.push("different_workspace"),(e.manifest.dataset.id!==t.manifest.dataset.id||e.manifest.dataset.contentHash!==t.manifest.dataset.contentHash||e.manifest.dataset.revision!==t.manifest.dataset.revision)&&n.push("different_dataset_version"),e.manifest.target.kind!==t.manifest.target.kind&&n.push("different_target_kind");const a=g=>{const x=g.execution;if(!x?.compatibility)return x??null;const{runtimeTargetHash:k,...C}=x;return C};if(ct(a(e.manifest))!==ct(a(t.manifest))&&n.push("different_execution_contract"),e.manifest.target.kind==="harness"&&t.manifest.target.kind==="harness"){const g=e.manifest.target.source,x=t.manifest.target.source;(g.profileId!==x.profileId||ct(g.target)!==ct(x.target))&&n.push("different_component");const k=e.manifest.execution?.compatibility&&t.manifest.execution?.compatibility&&e.manifest.execution.packageHash===t.manifest.execution.packageHash;g.environmentHash!==x.environmentHash&&!k&&n.push("different_environment"),(g.definitionId!==x.definitionId||g.definitionHash!==x.definitionHash)&&n.push("different_evaluation_definition")}const o=g=>[...g.evaluators].sort((x,k)=>x.feedbackKey.localeCompare(k.feedbackKey));ct(o(e.manifest))!==ct(o(t.manifest))&&n.push("different_evaluators");const r=new Map(e.result.cases.map(g=>[Ac(g.identity),g])),s=new Map(t.result.cases.map(g=>[Ac(g.identity),g])),l=[...new Set([...r.keys(),...s.keys()])].sort();(r.size!==s.size||l.some(g=>!r.has(g)||!s.has(g)))&&n.push("different_population");const m=n.length===0,d=l.map(g=>{const x=r.get(g)??null,k=s.get(g)??null,C=new Map(x?.feedback.map(E=>[E.feedbackKey,E])??[]),R=new Map(k?.feedback.map(E=>[E.feedbackKey,E])??[]);return{identity:(x??k).identity,baseline:x,candidate:k,feedback:e.manifest.evaluators.map(E=>{const A=C.get(E.feedbackKey),O=R.get(E.feedbackKey),$=m?!x||!k?"missing_case":x.status!=="completed"||k.status!=="completed"||x.error||k.error?"case_not_completed":!A||!O||A.status!=="scored"||O.status!=="scored"?"feedback_unavailable":E.output==="category"?"categorical_feedback":null:"incompatible_experiments",M=N=>typeof N?.value=="boolean"?Number(N.value):typeof N?.value=="number"?N.value:null,w=$?null:M(A),P=$?null:M(O),j=N=>$?null:typeof N?.value=="boolean"?N.value:N?.passed??null;return{feedbackKey:E.feedbackKey,eligible:$===null,reason:$,baseline:w,candidate:P,delta:w===null||P===null?null:P-w,baselinePassed:j(A),candidatePassed:j(O)}})}}),f=e.manifest.evaluators.map((g,x)=>{const k=d.map(M=>M.feedback[x]).filter(M=>M.eligible),C=M=>k.length?k.reduce((w,P)=>w+P[M],0)/k.length:null,R=C("baseline"),E=C("candidate"),A=M=>k.length&&k.every(w=>w[M]!==null)?k.reduce((w,P)=>w+Number(P[M]),0)/k.length:null,O=A("baselinePassed"),$=A("candidatePassed");return{feedbackKey:g.feedbackKey,eligibleCount:k.length,excludedCount:d.length-k.length,baseline:R,candidate:E,delta:R===null||E===null?null:E-R,baselinePassRate:O,candidatePassRate:$,passRateDelta:O===null||$===null?null:$-O}});return{comparable:m,reasons:n,cases:d,metrics:f}}const $o=i().trim().min(1).max(200),ic=i().regex(/^[a-f0-9]{64}$/),t4=c({id:$o,contentHash:ic}).strict(),Vm=c({schemaVersion:b("openpond.trainingHandoffOrigin.v1"),teamId:$o,projectId:$o.nullable(),configurationId:$o,source:c({executionId:$o,passId:$o.nullable(),manifestHash:ic,resultHash:ic}).strict(),dataset:c({id:$o,revision:u().int().positive(),contentHash:ic}).strict(),target:E_,graders:p(c({feedbackKey:$o,evaluator:t4,expectedCount:u().int().positive(),scoredCount:u().int().nonnegative(),score:u().finite().nullable()}).strict()).max(100),contentHash:ic}).strict(),n4=c({text:i().max(1e5),modelId:i().trim().min(1).max(500),modelRevision:i().trim().min(1).max(500).nullable(),responseId:i().trim().min(1).max(500).nullable(),inputTokens:u().int().nonnegative().nullable(),outputTokens:u().int().nonnegative().nullable(),costUsd:u().finite().nonnegative().nullable(),effectiveRequestHash:i().regex(/^[a-f0-9]{64}$/).optional(),finishReason:i().trim().min(1).max(200).nullable().optional(),reasoningTokens:u().int().nonnegative().nullable().optional()}).strict(),O_=c({id:T,requestHash:H,reservedUsd:u().finite().positive(),status:v(["reserved","settled","not_dispatched"]),response:n4.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."})}),$_=c({localTime:i().regex(/^(?:[01]\d|2[0-3]):[0-5]\d$/),timeZone:i().min(1).max(200).refine(e=>{try{return new Intl.DateTimeFormat("en",{timeZone:e}),!0}catch{return!1}},"Choose a valid IANA timezone.")}).strict(),Lt=le(i(),Ko()),lt=Xo,jo=i().max(2e3).refine(e=>e===""||e.startsWith("/")&&!/~(?![01])/u.test(e),"Use an RFC 6901 JSON pointer."),a4=c({schemaVersion:b("openpond.taskDefinition.v1"),id:T,revision:u().int().positive(),name:i().trim().min(1).max(500),description:i().max(1e4),instructions:i().trim().min(1).max(2e4),category:v(["structured","question_answering","coding","tool_workflow","custom"]),familyNamespace:T,inputSchema:le(i(),ce()),outputSchema:le(i(),ce()),requiredOutputs:fb.shape.requiredOutputs,contextRequirements:p(i().trim().min(1).max(2e3)).max(100).optional(),rewardBinding:lt,harness:W.nullable(),execution:k_.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=mb(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."})}),cd=a4.safeExtend({contentHash:H}).strict(),i4=c({schemaVersion:b("openpond.taskSourceMapping.v1"),exampleId:jo,attemptId:jo,occurredAt:jo,input:jo,observedOutput:jo.nullable(),expected:jo.nullable(),evaluatorContext:jo.nullable(),familyKey:jo,split:Xa}).strict(),o4=c({modelId:T,packageHash:H,taskset:lt,batch:lt,rewardBinding:lt}).strict(),r4=c({schemaVersion:b("openpond.learningSource.v1"),id:T,revision:u().int().positive(),name:i().trim().min(1).max(500),kind:v(["direct","benchmark","work","opentelemetry","provider"]),taskDefinition:lt,enabled:I(),allowedSplits:p(Xa).min(1).max(4),mapping:i4.nullable(),adapterVersion:i().trim().min(1).max(200).nullable(),reviewOrigin:o4.optional(),capturedOrigin:c({receiptId:T,ownerUserId:T,modelId:T,packageHash:H,taskset:lt}).strict().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."})}),Km=r4.safeExtend({contentHash:H}).strict(),s4=c({schemaVersion:b("openpond.taskExample.v1"),sourceId:T,idempotencyKey:T,taskDefinition:lt,exampleId:T,attemptId:T,occurredAt:ye,familyKey:T.nullable(),split:Xa,input:Lt,observedOutput:Lt.nullable(),expected:Lt.nullable(),evaluatorContext:Lt.nullable(),assets:p(bn).max(1e3),requiredOutputs:fb.shape.requiredOutputs,provenance:c({sourceRecordRef:i().max(2e3).nullable(),mappingHash:H.nullable()}).strict()}).strict(),l4=c({schemaVersion:b("openpond.taskEvidence.v1"),id:T,revision:u().int().positive(),source:lt,submission:s4,supersedes:lt.nullable(),correctionFeedbackId:T.nullable(),receivedAt:ye}).strict(),Wm=l4.extend({contentHash:H}).strict(),c4=c({schemaVersion:b("openpond.taskRating.v1"),criteria:i().trim().min(1).max(2e4),scale:c({minimum:u().finite(),maximum:u().finite()}).strict(),score:u().finite(),evidence:i().max(2e4),explanation:i().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."})}),d4=c({schemaVersion:b("openpond.taskFeedback.v1"),sourceId:T,idempotencyKey:T,exampleId:T,attemptId:T,expectedEvidenceHash:H.nullable(),occurredAt:ye,kind:v(["outcome","target_correction","ground_truth_correction","input_correction","family_resolution"]),value:Lt,note:i().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=c4.safeParse(e.value);if(!n.success)for(const a of n.error.issues)t.addIssue({code:"custom",path:["value",...a.path],message:a.message})}),N_=c({schemaVersion:b("openpond.taskFeedbackRecord.v1"),id:T,submission:d4,status:v(["pending_example","pending_review","applied","superseded","rejected"]),evidence:lt.nullable(),createdAt:ye,revision:u().int().positive(),submittedBy:c({id:T,role:v(["editor","reviewer","source"]),sourceId:T.nullable()}).strict().nullable().default(null),review:c({actorId:T,decision:lt.nullable(),note:i().max(2e4),resolvedAt:ye}).strict().nullable().default(null)}).strict(),u4=c({schemaVersion:b("openpond.taskAdmissionDecision.v1"),id:T,revision:u().int().positive(),evidence:lt,supersedes:lt.nullable(),actor:c({kind:v(["human","qualified_policy"]),id:T,policy:lt.nullable()}).strict(),evidenceValidity:v(["valid","invalid","pending"]),taskAdmissibility:v(["approved","rejected","pending"]),observedQuality:v(["passed","failed","unscored","unavailable"]),targetApproval:v(["approved","rejected","pending","not_required"]),approvedTarget:Lt.nullable(),grade:Pc.nullable(),targetGrade:Pc.nullable(),note:i().max(2e4),decidedAt:ye}).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."})}),yb=u4.safeExtend({contentHash:H}).strict(),m4=c({schemaVersion:b("openpond.taskBatch.v1"),id:T,revision:b(1),taskDefinition:lt,rewardBinding:lt,purpose:v(["supervised_training","reward_training","evaluation"]),examples:p(c({evidence:lt,decision:lt,familyKey:T,inputHash:H,split:Xa}).strict()).min(1).max(1e4),sealedAt:ye,sealedBy:T}).strict().superRefine((e,t)=>{new Set(e.examples.map(a=>a.evidence.id)).size!==e.examples.length&&t.addIssue({code:"custom",path:["examples"],message:"Each evidence identity can occur only once in a batch."});const n=new Map;for(const[a,o]of e.examples.entries()){e.purpose==="evaluation"==(o.split==="train")&&t.addIssue({code:"custom",path:["examples",a,"split"],message:"Training uses train examples; evaluation uses held-out examples."});for(const r of[`family:${o.familyKey}`,`input:${o.inputHash}`])n.has(r)&&n.get(r)!==o.split&&t.addIssue({code:"custom",path:["examples",a],message:"A task family or identical input cannot cross splits."}),n.set(r,o.split)}}),Sb=m4.safeExtend({contentHash:H}).strict(),p4=c({origin:Vm.optional(),schemaVersion:b("openpond.learningPolicy.v1"),id:T,revision:u().int().positive(),modelProjectId:T,executionOwner:v(["local","hosted"]),enabled:I(),sources:p(lt).min(1).max(100),taskDefinition:lt,rewardBinding:lt,admission:c({mode:v(["human","qualified_automatic"]),qualification:W.nullable(),minimumApprovedExamples:u().int().positive().max(1e5)}).strict(),trigger:ot("kind",[c({kind:b("manual")}).strict(),c({kind:b("approved_count")}).strict(),c({kind:b("schedule"),intervalSeconds:u().int().min(60).max(31536e3)}).strict(),$_.extend({kind:b("nightly")}).strict(),c({kind:b("upstream_accepted"),modelProjectId:T}).strict()]),trainingParent:W,teacher:W.nullable(),training:c({method:v(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),recipe:W,retentionEvaluation:W,replayBatches:p(W).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:I(),train:I(),accept:I(),serve:I()}).strict(),acceptance:c({minimumScore:u().min(0).max(1),maximumRetentionRegression:u().min(0).max(1),requireImprovement:I(),rollbackVersion:W.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."})}),D_=p4.safeExtend({contentHash:H}).strict(),xb=c({iterationId:T,iterationRevision:u().int().positive(),candidate:W,decision:lt,decidedAt:ye}).strict(),f4=v(["waiting_for_data","waiting_for_review","ready","dispatching","training","evaluating","candidate_ready","accepted","rejected","paused","failed","cancelling","cancelled","completed_without_candidate"]),H_=c({schemaVersion:b("openpond.learningIteration.v1"),id:T,revision:u().int().positive(),policy:lt,status:f4,triggerIdentity:T,batch:lt.nullable(),sourceWatermarks:le(T,u().int().nonnegative()),trainingParent:W,trainingParentSelection:xb.nullable().optional(),teacher:W.nullable(),upstreamEvent:W.nullable(),trainingJob:W.nullable(),evaluationJob:W.nullable(),candidateVersion:W.nullable(),candidateDecision:lt.nullable().default(null),candidateDecisionAt:ye.nullable().optional(),dispatchId:T,retryCount:u().int().nonnegative(),spendUsd:u().nonnegative(),failure:c({code:T,message:i().max(2e4)}).strict().nullable(),createdAt:ye,updatedAt:ye}).strict(),h4=c({schemaVersion:b("openpond.taskGradeRun.v1"),id:T,revision:u().int().positive(),evidence:lt,binding:lt,target:v(["observed","proposed_target"]),output:Lt,status:v(["queued","running","completed","failed","cancelling","cancelled"]),composition:Pc.nullable(),leaseOwner:T.nullable(),leaseExpiresAt:ye.nullable(),attemptCount:u().int().nonnegative(),timeoutMs:u().int().min(100).max(3e5),maximumSpendUsd:u().nonnegative().max(1e3),judgeCalls:p(O_).max(1e4).optional(),requestedBy:T.optional(),failure:i().max(2e4).nullable(),createdAt:ye,updatedAt:ye}).strict();vt([cd,sd,Fm,Km,Wm,N_,yb,Sb,D_,H_,h4]);function g4(e){return lt.parse({id:e.id,revision:e.revision,contentHash:e.contentHash})}function iie(e,t){return e.id===t.id&&e.revision===t.revision&&e.contentHash===t.contentHash}function oie(e){return Qa(e,16777216),{...e,contentHash:ct(e)}}function rie(e){const{contentHash:t,...n}=e;if(Qa(n,16777216),ct(n)!==t)throw new pi("learning_content_hash_mismatch",422)}const L_=c({schemaVersion:b("openpond.learningTextAsset.v1"),id:T,revision:b(1),asset:bn,text:i().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!==wv(e.text)&&t.addIssue({code:"custom",path:["asset","contentHash"],message:"Asset source does not match its SHA-256."})}),Gm=L_.safeExtend({contentHash:H}).strict();function Xd(e){Qa(e);const{text:t,...n}=e,a=wv(t),o=`asset-${a}-${ct(n).slice(0,16)}`,r=L_.parse({schemaVersion:"openpond.learningTextAsset.v1",id:o,revision:1,asset:{...n,id:o,contentHash:a,sizeBytes:new TextEncoder().encode(t).byteLength},text:t});return Gm.parse({...r,contentHash:ct(r)})}function TS(e,t){const{contentHash:n,...a}=Gm.parse(e);if(ct(a)!==n||ct(a.asset)!==ct(t))throw new pi("learning_asset_reference_mismatch",409);return a.text}const v4=ot("kind",[c({kind:b("manual"),identity:T}).strict(),c({kind:b("schedule"),scheduledAt:ye}).strict(),c({kind:b("approved_count"),checkedAt:ye}).strict()]),b4=c({schemaVersion:b("openpond.learningChain.v1"),id:T,revision:u().int().positive(),modelProjectId:T,activeIterationId:T.nullable(),acceptedParent:xb.nullable().optional(),latestIterationId:T,lastReservedAt:ye.nullable(),updatedAt:ye}).strict(),q_=c({eligible:u().int().nonnegative(),awaitingReview:u().int().nonnegative(),excluded:u().int().nonnegative(),consumed:u().int().nonnegative()}).strict(),sie=c({schemaVersion:b("openpond.learningConsumption.v1"),id:T,revision:b(1),chainId:T,iterationId:T,evidence:lt,decision:lt,reservedAt:ye}).strict(),lie=c({schemaVersion:b("openpond.learningIterationReservation.v1"),id:T,revision:u().int().positive(),chainId:T,iterationId:T,policy:lt,trigger:v4,requestHash:H,outcome:v(["reserved","waiting_for_data","waiting_for_review"]),counts:q_,budget:c({maximumSpendUsd:u().nonnegative(),reservedSpendUsd:u().nonnegative(),settledSpendUsd:u().nonnegative(),settledAt:ye.nullable()}).strict(),createdAt:ye,updatedAt:ye}).strict(),U_=c({id:T,name:i().max(500),input:i(),output:i(),expectedOutput:i(),evaluatorContext:i(),artifactRefs:p(i().max(500)).max(100),runtimeEventRefs:p(i().max(500)).max(100),infrastructureError:i().max(2e4),expectedStatus:v(["scored","pending","unavailable","failed"]),minimumScore:i(),maximumScore:i(),expectedPassed:v(["true","false","any"]),sourceLabel:c({evidence:lt,feedback:c({id:T,revision:u().int().positive()}).strict()}).strict().optional()}).strict(),z_=c({name:i().max(500),description:i().max(1e4),feedbackKey:rd.optional(),kind:v(["custom_verifier","state","content","schema","artifact","runtime_event","model_judge","learned_model","human"]),fields:i(),outputField:i(),expectedField:i(),expectedValue:i(),schema:i(),reference:i(),events:i(),code:i(),exportName:i(),timeout:i(),verifierRuntime:v(["isolated_javascript","sandbox_process"]).optional(),rubric:i(),providerId:i(),modelId:i(),modelRevision:i(),temperature:i(),reviewerRole:i(),humanForm:i().max(131072).optional(),learnedId:i(),learnedHash:i(),inputContract:i(),minimum:i(),maximum:i(),fixtures:p(U_).max(50).optional()}).strict(),y4=c({name:i().max(500),description:i().max(1e4),instructions:i().max(2e4),input:i(),output:i(),familyNamespace:i(),sources:p(gb).max(100),recipeRef:Xo.optional()}).strict(),S4=c({name:i().max(500),description:i().max(1e4),sources:p(gb).max(100)}).strict(),x4=v(["definition","reward","binding"]),ph=c({id:T,targetId:T,baseRelease:lt.nullable(),editorVersion:b("openpond.modelsEditor.v1")}),fh=ot("targetKind",[ph.extend({targetKind:b("definition"),fields:y4}).strict(),ph.extend({targetKind:b("reward"),fields:z_}).strict(),ph.extend({targetKind:b("binding"),fields:S4}).strict()]),hh={schemaVersion:b("openpond.authoringDraft.v1"),revision:u().int().positive(),status:v(["draft","archived","published"]),publishedRelease:lt.nullable(),createdAt:ye,updatedAt:ye},gh=ot("targetKind",[fh.options[0].extend(hh).strict(),fh.options[1].extend(hh).strict(),fh.options[2].extend(hh).strict()]),cie=ot("targetKind",[gh.options[0].extend({contentHash:H}).strict(),gh.options[1].extend({contentHash:H}).strict(),gh.options[2].extend({contentHash:H}).strict()]),die=c({draft:lt,targetKind:x4,release:lt}).strict(),si={bytes:5*1024*1024,records:1e3,files:100,messages:2e3},B_=v(["json","jsonl","csv","hermes","openclaw"]),k4=c({path:i().min(1).max(500),text:i()}).strict(),kb=c({id:i().min(1).max(200),familyKey:i().min(1).max(200),split:Xa,kind:v(["task","attempt"]),input:Lt,observedOutput:Lt.nullable(),expected:Lt.nullable(),sourceId:i().min(1).max(2e3),sourceHash:i().length(64),occurredAt:i().datetime().nullable(),metadata:Lt,warnings:p(i().max(2e3)).max(100),needsContext:I()}).strict(),F_=c({schemaVersion:b("openpond.taskIntakePreview.v1"),format:B_,contentHash:i().length(64),records:p(kb).max(si.records),issues:p(c({file:i(),row:u().int().positive().nullable(),message:i()}).strict()).max(1e3)}).strict();function nm(e,t){return`${e}-${ct(t)}`}function V_(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}const w4=`export function verify({ output, expectedOutput }) {
|
|
181
|
-
if (!expectedOutput || !Object.hasOwn(expectedOutput, "answer")) {
|
|
182
|
-
throw new Error("An expected answer is required.");
|
|
183
|
-
}
|
|
184
|
-
const passed = output.answer === expectedOutput.answer;
|
|
185
|
-
return { score: passed ? 1 : 0, passed, feedback: passed ? "Answer matched" : "Answer differed" };
|
|
186
|
-
}`;function uie(e){Qa(e,262144);const t=z_.parse(e.fields),n=e.base?sd.parse(e.base):null;if(n&&n.id!==e.id)throw new pi("reward_authoring_base_mismatch",422);const a=t.fixtures?.length?Xd({text:JSON.stringify(t.fixtures),path:"reward-fixtures.json",mediaType:"application/json",visibility:"verifier"}):null;let o=null,r,s;if(t.kind==="custom_verifier")o=Xd({text:t.code,path:"verifier.mjs",mediaType:"application/javascript",visibility:"verifier"}),r={kind:t.kind,verifierRef:o.asset,exportName:t.exportName,timeoutMs:As(t.timeout,"Time limit"),networkPolicy:"none",...t.verifierRuntime??(n?.implementation.kind==="custom_verifier"?n.implementation.runtime:void 0)?{runtime:t.verifierRuntime??(n?.implementation.kind==="custom_verifier"?n.implementation.runtime:void 0)}:{}};else if(t.kind==="model_judge"||t.kind==="human"){if(!t.rubric.trim())throw new pi("reward_rubric_required",422,"Write the rubric before checking or publishing this Reward.");if(o=Xd({text:t.rubric,path:"rubric.md",mediaType:"text/markdown",visibility:"verifier"}),t.kind==="human")r={kind:t.kind,rubricRef:o.asset,reviewerRole:t.reviewerRole,form:od.parse(JSON.parse(t.humanForm||JSON.stringify({schemaVersion:"openpond.humanForm.v1",mode:"individual",instructions:t.rubric,criteria:[{id:"quality",label:"Quality",instructions:t.rubric,required:!0,allowAbstain:!0,kind:"score",minimum:0,maximum:1,step:.1}]})))};else{const d={providerId:t.providerId,modelId:t.modelId,revision:t.modelRevision.trim()||null},f=As(t.temperature,"Temperature"),g=n?.implementation,x=g?.kind==="model_judge"&&g.rubricRef.contentHash===o.asset.contentHash&&g.model?.providerId===d.providerId&&g.model?.modelId===d.modelId&&g.model?.revision===d.revision&&(g.temperature??0)===f&&n?.fixtureSetRef?.contentHash===a?.asset.contentHash;r={kind:t.kind,rubricRef:o.asset,model:d,temperature:f,calibrationStatus:x?g.calibrationStatus:"pending"},x&&(s=n?.calibrationCheckRef)}}else t.kind==="learned_model"?(Ps(t.inputContract,"Model input contract"),o=Xd({text:t.inputContract,path:"input-contract.json",mediaType:"application/json",visibility:"verifier"}),r={kind:t.kind,modelVersion:{id:t.learnedId,contentHash:t.learnedHash},inputContract:o.asset}):t.kind==="state"?r={kind:t.kind,config:{fields:MS(t.fields)}}:t.kind==="content"?r={kind:t.kind,config:{outputField:t.outputField,expectedField:t.expectedField,...t.expectedValue?{expectedValue:t.expectedValue}:{}}}:t.kind==="schema"?r={kind:t.kind,config:{jsonSchema:Ps(t.schema,"Output schema")}}:t.kind==="artifact"?r={kind:t.kind,config:{refIncludes:t.reference}}:r={kind:t.kind,config:{requiredEvents:MS(t.events)}};const l=[...o?[o]:[],...a?[a]:[]];return{reward:Kz({schemaVersion:"openpond.rewardRelease.v1",id:e.id,revision:(n?.revision??0)+1,name:t.name,description:t.description,feedbackKey:t.feedbackKey??Uz({id:e.id}),implementation:r,rawScore:t.kind==="learned_model"?{minimum:As(t.minimum,"Minimum score"),maximum:As(t.maximum,"Maximum score")}:{minimum:0,maximum:1},assets:l.map(d=>d.asset),...a?{fixtureSetRef:a.asset}:{},...s?{calibrationCheckRef:s}:{}}),assets:l}}function mie(e,t,n=null){const a=e?.implementation,o=a&&"verifierRef"in a?a.verifierRef:a&&"rubricRef"in a?a.rubricRef:a&&"inputContract"in a?a.inputContract:null;if(o&&!t)throw new pi("reward_source_required",422);const r=o&&t?TS(t,o):"";if(e?.fixtureSetRef&&!n)throw new pi("reward_fixtures_required",422);const s=e?.fixtureSetRef&&n?U_.array().max(50).parse(JSON.parse(TS(n,e.fixtureSetRef))):[],l=a&&"config"in a?a.config:{};return{name:e?.name??"",description:e?.description??"",...e?.feedbackKey?{feedbackKey:e.feedbackKey}:{},kind:a?.kind??"state",fields:ES(l.fields).join(", ")||"answer",outputField:eu(l.outputField)||"text",expectedField:eu(l.expectedField)||"text",expectedValue:eu(l.expectedValue),schema:JSON.stringify(l.jsonSchema??{type:"object",properties:{answer:{type:"string"}},required:["answer"]},null,2),reference:eu(l.refIncludes),events:ES(l.requiredEvents).join(", "),code:a?.kind==="custom_verifier"?r:w4,verifierRuntime:a?.kind==="custom_verifier"?a.runtime??"isolated_javascript":"isolated_javascript",exportName:a?.kind==="custom_verifier"?a.exportName??"verify":"verify",timeout:String(a?.kind==="custom_verifier"?a.timeoutMs:5e3),rubric:a?.kind==="model_judge"||a?.kind==="human"?r:"",providerId:a?.kind==="model_judge"?a.model?.providerId??"":"",modelId:a?.kind==="model_judge"?a.model?.modelId??"":"",modelRevision:a?.kind==="model_judge"?a.model?.revision??"":"",temperature:String(a?.kind==="model_judge"?a.temperature??0:0),reviewerRole:a?.kind==="human"?a.reviewerRole:"Subject matter reviewer",humanForm:a?.kind==="human"&&a.form?JSON.stringify(a.form,null,2):"",learnedId:a?.kind==="learned_model"?a.modelVersion.id:"",learnedHash:a?.kind==="learned_model"?a.modelVersion.contentHash:"",inputContract:a?.kind==="learned_model"?r:"{}",minimum:String(e?.rawScore.minimum??0),maximum:String(e?.rawScore.maximum??1),...s.length?{fixtures:s}:{}}}function Ps(e,t){try{const n=JSON.parse(e);return Qa(n,131072),Lt.parse(n)}catch{throw new pi("reward_authoring_json_invalid",422,`${t} must be a JSON object.`)}}function As(e,t){const n=Number(e);if(!e.trim()||!Number.isFinite(n))throw new pi("reward_authoring_number_invalid",422,`${t} must be a finite number.`);return n}function eu(e){return typeof e=="string"?e:""}function ES(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function MS(e){return e.split(",").map(t=>t.trim()).filter(Boolean)}const K_=c({id:T,name:i().trim().min(1).max(500),input:Lt,output:Lt,expectedOutput:Lt.nullable(),evaluatorContext:Lt.nullable(),artifactRefs:p(T).max(100),runtimeEventRefs:p(T).max(100),infrastructureError:i().max(2e4).nullable(),expected:ot("status",[c({status:b("scored"),minimum:u().finite(),maximum:u().finite(),passed:I().nullable()}).strict(),c({status:v(["pending","unavailable","failed"])}).strict()])}).strict().superRefine((e,t)=>{e.expected.status==="scored"&&e.expected.minimum>e.expected.maximum&&t.addIssue({code:"custom",path:["expected"],message:"Expected score minimum must not exceed maximum."})}),I4=c({id:T,packageVersion:i().min(1).max(100),engine:i().min(1).max(200)}).strict(),_4=c({fixture:c({id:T,contentHash:H}).strict(),result:A_,matchesExpectation:I()}).strict(),pie=c({schemaVersion:b("openpond.rewardCheckRun.v1"),id:T,revision:u().int().positive(),draft:lt,reward:lt,snapshotHash:H,fixtureRefs:p(c({id:T,contentHash:H}).strict()).min(1).max(50),status:v(["queued","running","completed","failed","cancelling","cancelled"]),runtime:I4.nullable(),results:p(_4).max(50),matchesExpectations:I().nullable(),failure:i().max(2e4).nullable(),timeoutMs:u().int().min(100).max(3e5),maximumSpendUsd:u().nonnegative().max(1e3),judgeCalls:p(O_).max(1e3).optional(),requestedBy:T.optional(),leaseOwner:T.nullable(),leaseExpiresAt:ye.nullable(),attemptCount:u().int().nonnegative(),createdAt:ye,updatedAt:ye}).strict();function fie(e){if(!e.length||e.length>50)throw new pi("reward_check_fixtures_required",422,"Add between one and 50 fixtures before checking this Reward.");if(new Set(e.map(t=>t.id)).size!==e.length)throw new pi("reward_fixture_id_duplicate",422);return e.map(t=>K_.parse({id:t.id,name:t.name,input:Ps(t.input,`${t.name}: input`),output:Ps(t.output,`${t.name}: output`),expectedOutput:t.expectedOutput.trim()?Ps(t.expectedOutput,`${t.name}: expected answer`):null,evaluatorContext:t.evaluatorContext.trim()?Ps(t.evaluatorContext,`${t.name}: evaluator context`):null,artifactRefs:t.artifactRefs.map(n=>n.trim()).filter(Boolean),runtimeEventRefs:t.runtimeEventRefs.map(n=>n.trim()).filter(Boolean),infrastructureError:t.infrastructureError||null,expected:t.expectedStatus==="scored"?{status:t.expectedStatus,minimum:As(t.minimumScore,`${t.name}: minimum score`),maximum:As(t.maximumScore,`${t.name}: maximum score`),passed:t.expectedPassed==="any"?null:t.expectedPassed==="true"}:{status:t.expectedStatus}}))}const C4=c({policy:lt,modelProjectId:T,inspectedAt:ye,chain:b4.nullable(),trainingParent:c({reference:W,selection:xb.nullable()}).strict().nullable().default(null),counts:q_.nullable(),minimumApprovedExamples:u().int().positive(),canReserve:I(),blockers:p(c({code:i().min(1).max(200),message:i().min(1).max(2e4)}).strict()).max(20),cooldownUntil:ye.nullable(),budget:c({reservedSpendUsd:u().nonnegative(),settledSpendUsd:u().nonnegative(),committedSpendUsd:u().nonnegative(),maximumIterationSpendUsd:u().nonnegative(),maximumDailySpendUsd:u().nonnegative()}).strict()}).strict();function R4(e){const t=[];let n=[],a="",o=!1,r=!1;const s=()=>{n.push(a),a="",r=!1},l=()=>{if(s(),n.some(f=>f.length)&&t.push(n),n=[],t.length>si.records+1)throw new Error("CSV exceeds the 1,000-record limit.")};for(let f=0;f<e.length;f++){const g=e[f];if(o)g==='"'&&e[f+1]==='"'?(a+='"',f++):g==='"'?(o=!1,r=!0):a+=g;else if(g===",")s();else if(g===`
|
|
187
|
-
`||g==="\r")g==="\r"&&e[f+1]===`
|
|
188
|
-
`&&f++,l();else if(g==='"'&&!a&&!r)o=!0;else{if(r||g==='"')throw new Error("CSV has an invalid quoted field.");a+=g}}if(o)throw new Error("CSV has an unterminated quoted field.");(a||n.length||r)&&l();const m=t.shift()?.map(f=>f.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(f=>!d.has(f))||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((f,g)=>{if(f.length!==m.length)throw new Error(`CSV record ${g+2} has a different number of columns from its header.`);return Object.fromEntries(m.map((x,k)=>[x,f[k]]).filter(([,x])=>x!==""))})}function hie(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 W_(e){return e.startsWith("\uFEFF")?e.slice(1):e}const G_=c({role:i().min(1),content:Ko().nullable().optional()}).catchall(Ko()),P4=c({id:i().min(1),messages:p(G_).min(1).max(si.messages),lineage_session_ids:p(i()).optional(),parent_session_id:i().nullable().optional()}).catchall(Ko());function A4(e){const t=P4.parse(e),n=t.lineage_session_ids?.[0]??t.parent_session_id??t.id,{messages:a,segments:o,...r}=t;return J_("hermes",t.id,n,t.messages,{sourceHash:ct(e),metadata:{session:r},warnings:["Imported session context and tools need review before this can become an executable task."]})}const T4=c({traceSchema:b("openclaw-trajectory"),schemaVersion:b(1),traceId:i().min(1),sessionId:i().min(1),leafId:i().nullable(),eventCount:u().int().nonnegative(),warnings:p(Lt).optional()}).catchall(Ko()),E4=c({traceSchema:b("openclaw-trajectory"),schemaVersion:b(1),traceId:i(),sessionId:i(),seq:u().int().nonnegative(),type:i(),ts:i()}).catchall(Ko()),M4=c({header:Lt.nullable(),leafId:i().nullable(),entries:p(c({id:i().min(1),type:i().min(1),parentId:i().nullable().optional(),message:G_.optional()}).catchall(Ko())).max(si.messages)}).strict();function j4(e){const t=l=>{const m=e.find(d=>d.path===l);if(!m)throw new Error(`OpenClaw bundle is missing ${l}.`);return W_(m.text)},n=T4.parse(JSON.parse(t("manifest.json"))),a=M4.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=>E4.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 r=new Set;for(const[l,m]of a.entries.entries()){if(r.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.");r.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 J_("openclaw",n.sessionId,n.sessionId,s,{sourceHash:ct(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 J_(e,t,n,a,o){const r=a.flatMap((l,m)=>l.role==="user"?[m]:[]);if(!r.length)throw new Error("This history contains no user request. Supply a session with its request context.");let s=0;return r.map((l,m)=>{const d=r[m+1]??a.length,f=a.slice(l+1,d),g=f.filter(R=>R.role==="assistant").at(-1),x=a[l],k=x.entryId??x.message_id??x.id??ct({start:l,request:x}),C={id:nm(e,[t,k]),familyKey:nm(e,n),split:"train",kind:"attempt",input:{request:x.content??null,messages:a.slice(0,l+1)},observedOutput:g?{response:g.content??null,messages:f}:null,expected:null,sourceId:`${e}:${t}:${String(k)}`,sourceHash:o.sourceHash,occurredAt:V_(g?.timestamp??x.timestamp),metadata:o.metadata,warnings:[...o.warnings,...g?[]:["No assistant response was recorded for this request."]],needsContext:!0};if(Qa(C),s+=new TextEncoder().encode(JSON.stringify(C)).length,s>si.bytes)throw new Error("Expanded history exceeds the 5 MiB preview limit. Export a smaller session selection.");return kb.parse(C)})}const O4=c({instruction:i().trim().min(1).max(1e5),context:vt([i(),Lt]).optional(),reference:vt([i(),Lt]).optional(),labels:vt([i(),p(i()),Lt]).optional(),id:i().min(1).max(200).optional(),familyKey:i().min(1).max(200).optional(),split:Xa.optional()}).strict(),$4=c({input:Lt,observedOutput:Lt.nullable().optional(),expectedOutput:Lt.nullable().optional(),id:i().min(1).max(200).optional(),familyKey:i().min(1).max(200).optional(),split:Xa.optional(),occurredAt:i().datetime().optional(),labels:Lt.optional()}).strict();function N4(e){const t=B_.parse(e.format),n=p(k4).min(1).max(si.files).parse(e.files);if(n.reduce((d,f)=>d+new TextEncoder().encode(f.text).length,0)>si.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(f=>!f||f==="."||f===".."))||new Set(n.map(d=>d.path)).size!==n.length)throw new Error("Import contains an unsafe or duplicate file path.");const a=[],o=[],r=new Map,s=new Map;let l=0;function m(d,f,g){try{const x=g();if(a.length+x.length>si.records)throw new Error("Import exceeds the 1,000-record limit.");const k=new Map(r),C=new Map(s);let R=0;for(const E of x){Qa(E);const A=ct(E),O=k.get(E.id);if(O&&O!==A)throw new Error("The same record identity has different content in this upload.");O||(R+=new TextEncoder().encode(JSON.stringify(E)).length),k.set(E.id,A);for(const $ of[`family:${E.familyKey}`,`input:${ct(E.input)}`]){if(C.has($)&&C.get($)!==E.split)throw new Error("The same task family or request occurs in different splits.");C.set($,E.split)}}if(l+R>si.bytes*2)throw new Error("Expanded import exceeds the 10 MiB preview limit. Select fewer source files.");for(const E of x)r.has(E.id)||a.push(E),r.set(E.id,ct(E));for(const[E,A]of C)s.set(E,A);l+=R}catch(x){o.push({file:d,row:f,message:x instanceof k2?`Unsupported record fields or values (${x.issues.slice(0,3).map(k=>k.path.join(".")||"record").join(", ")}).`:x instanceof SyntaxError?"Invalid JSON.":x instanceof Error?x.message:"Invalid import record."})}}if(t==="openclaw")m("manifest.json",null,()=>j4(n));else for(const d of n){const f=W_(d.text);if(t==="jsonl"||t==="hermes"){for(const[g,x]of f.split(/\r?\n/u).entries())if(x.trim()){if(o.length>=si.records)break;m(d.path,g+1,()=>t==="hermes"?A4(JSON.parse(x)):[jS(JSON.parse(x))])}}else{let g;try{const x=t==="csv"?R4(f):JSON.parse(f);g=Array.isArray(x)?x:[x]}catch(x){m(d.path,null,()=>{throw x});continue}if(g.length>si.records){m(d.path,null,()=>{throw new Error("Import exceeds the 1,000-record limit.")});continue}g.forEach((x,k)=>m(d.path,k+(t==="csv"?2:1),()=>[jS(x)]))}}return F_.parse({schemaVersion:"openpond.taskIntakePreview.v1",format:t,contentHash:ct({format:t,files:n}),records:a,issues:o.slice(0,1e3)})}function jS(e){const t=vt([O4,$4]).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,r=n?null:t.observedOutput??null,s=t.familyKey??nm("family",a),l=t.id??nm("task",{input:a,expected:o,observedOutput:r});return kb.parse({id:l,familyKey:s,split:t.split??"train",kind:r?"attempt":"task",input:a,expected:o,observedOutput:r,sourceId:l,sourceHash:ct(e),occurredAt:n?null:V_(t.occurredAt),metadata:t.labels===void 0?{}:{importedLabels:t.labels,labelOrigin:"unverified_import"},warnings:[],needsContext:!1})}const Tc=i().trim().min(1).max(240),Ho=i().regex(/^[a-f0-9]{64}$/),D4=c({id:Tc,name:i().trim().min(1).max(200),required:I(),role:v(["quality","retention","diagnostic"]).optional(),unit:i().trim().min(1).max(80).optional(),baselineReuse:c({maximumAgeSeconds:u().int().positive().max(31536e3),qualification:W}).strict().optional(),dataset:W,evaluator:W,executionHash:Ho,populationHash:Ho,metric:Tc,direction:v(["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."})}),Z_=c({schemaVersion:b("openpond.acceptancePlan.v1"),id:Tc,revision:u().int().positive(),checks:p(D4).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."})}),Y_=Z_.safeExtend({contentHash:Ho});function gie(e){const t=Z_.parse(e);return{...t,contentHash:ct(t)}}const H4=c({runId:Tc,artifact:W,checkHash:Ho,populationHash:Ho,scoredPopulationHash:Ho,executionHash:Ho,evaluator:W,metric:Tc,expectedCount:u().int().positive(),scoredCount:u().int().nonnegative(),score:u().finite().nullable(),status:v(["pending","running","completed","failed","cancelled"]),evidenceHash:Ho}).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."})}),Lo=i().trim().min(1).max(240),wb=i().regex(/^[a-f0-9]{64}$/),am=on(),OS=u().finite().nonnegative(),L4=new Set(["completed","failed","cancelled","budget_exhausted"]),q4=c({schemaVersion:b("openpond.acceptanceGroupManifest.v1"),id:Lo,teamId:Lo,trainingJob:W,baseline:W,candidate:W,plan:Y_,maximumParallelAttempts:u().int().min(1).max(8),createdAt:am}).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."})}),U4=q4.safeExtend({contentHash:wb}),z4=c({id:Lo,checkId:Lo,subject:v(["baseline","candidate"]),ordinal:u().int().positive(),dispatchId:Lo,state:v(["queued","dispatching","running","grading","cleaning","completed","failed","cancelled","budget_exhausted"]),artifact:W,checkHash:wb,measurement:H4.nullable(),executionReceipt:W.nullable(),reusedFrom:c({group:W,attemptId:Lo}).strict().nullable(),spendUsd:OS,reservedUsd:OS,cleanupComplete:I(),accountingComplete:I(),failureCode:Lo.nullable(),createdAt:am,updatedAt:am}).strict().superRefine((e,t)=>{Date.parse(e.updatedAt)<Date.parse(e.createdAt)&&t.addIssue({code:"custom",message:"Attempt timestamps are reversed."}),L4.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."})}),B4=c({schemaVersion:b("openpond.acceptanceGroupSnapshot.v1"),manifest:U4,revision:u().int().positive(),state:v(["queued","running","blocked","cancelling","cleaning","completed","failed","cancelled","budget_exhausted"]),attempts:p(z4).max(2e3),failureCode:Lo.nullable(),updatedAt:am}).strict(),F4=B4.extend({contentHash:wb});var Er=lt.shape.id,Ec=i().regex(/^[a-f0-9]{64}$/),V4=c({scopeId:Er,modelId:Er}).strict(),K4=c({schemaVersion:b("openpond.modelTasksetAuthoring.v1"),owner:V4,root:lt,parent:lt}).strict(),vie=c({schemaVersion:b("openpond.modelTasksetDraftRequest.v1"),operationId:Er,modelId:Er,expectedModelRevision:u().int().positive(),sourcePackageHash:Ec}).strict(),W4=c({schemaVersion:b("openpond.modelTasksetDraftPreparation.v1"),draftId:Er,requestHash:Ec,sourcePackageHash:Ec,sourceTasksetRef:lt,tasksetId:Er,tasksetRevision:u().int().positive(),lineage:K4,authoringGraph:b("bound").optional()}).strict(),dd=i().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."),Q_=c({path:dd,sizeBytes:u().int().nonnegative(),writable:I()}).strict(),X_=c({encoding:v(["utf8","base64"]),data:i().max(8e6)}).strict(),G4=Q_.extend({contentHash:Ec,content:X_}).strict();c({draftId:Er,expectedDraftRevision:u().int().positive(),path:dd,expectedFileHash:Ec.nullable(),content:X_.nullable()}).strict();var J4=$_.extend({mode:v(["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."})}),Z4=67108864,kg=524288,oc=class extends Error{code;constructor(e,t){super(t),this.name="OpenPondProtocolError",this.code=e}};function Ib(e){return JSON.stringify(wg(e))}function Y4(e){return new TextEncoder().encode(Ib(e)).byteLength}async function Q4(e){const t=new TextEncoder().encode(Ib(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 X4(e,t,n){const a=Y4(e);if(a>t)throw new oc("payload_too_large",`${n} is ${a} bytes; the maximum is ${t} bytes.`)}function wg(e){if(e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number"){if(!Number.isFinite(e))throw new oc("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=>wg(t));if(typeof e=="object"){const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)throw new oc("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 oc("non_json_value",`Canonical JSON cannot contain ${typeof o} at ${a}.`);n[a]=wg(o)}return n}throw new oc("non_json_value",`Canonical JSON cannot contain ${typeof e}.`)}var qt=i().trim().min(1).max(500),Oi=i().regex(/^[a-f0-9]{64}$/),Ka=i().datetime({offset:!0}),Mt=c({id:qt,contentHash:Oi}).strict(),la=Mt.extend({revision:u().int().positive()}).strict(),Lr=c({schemaVersion:b("openpond.baseModelPreference.v1"),modelId:qt,revision:i().trim().min(1).max(256).nullable(),tokenizerRevision:i().trim().min(1).max(256).nullable(),chatTemplateHash:i().trim().min(8).max(256).nullable(),modelAssetId:qt.nullable(),source:v(["managed","local","builtin"])}).strict(),eC=v(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),tC=c({schemaVersion:i().regex(/^openpond\.[A-Za-z0-9]+Recipe\.v\d+$/),method:eC,parameterization:v(["lora","full"])}).catchall(ce()),eB=c({profileProjectId:qt,sourceRevision:i().regex(/^[a-f0-9]{40,64}$/),harnessRelease:Mt}).strict(),tB=c({profileProjectId:qt,sourceRevision:i().regex(/^[a-f0-9]{40,64}$/),catalogHash:Oi,definitionId:qt,harnessRelease:Mt,tasksetRelease:Mt}).strict(),nC=c({tasksetRef:la.nullable().default(null),evaluationTasksetRef:la.nullable().optional(),profileSource:eB.nullable().optional(),profileEvaluation:tB.nullable().optional(),rewardBindingRef:la.nullable().optional(),tasksetRelease:Mt.nullable().default(null),harnessRelease:Mt.nullable().default(null),baseModel:Lr.nullable().default(null),method:eC.nullable().default(null),destinationId:qt.nullable().default(null),managedRolloutPlacement:v(["local","remote"]).default("remote"),managedGpuPlacementObjective:v(["fast","balanced","economical"]).default("balanced"),managedGpuRequirement:v(["any","h100_hbm3"]).default("any"),runPreset:v(["small","standard","custom","small_experiment"]).nullable().default(null),recipe:tC.nullable().default(null),preferredMaximumSpendUsd:u().nonnegative().nullable().default(null),preferredRetentionDays:u().int().nonnegative().nullable().default(null)}).strict(),_b=nC.omit({managedGpuRequirement:!0}),nB=c({schemaVersion:b("openpond.hostedModelProjectLink.v1"),apiOrigin:i().url().refine(e=>new URL(e).origin===e,"Use a canonical API origin.").nullable().default(null),teamId:qt,projectId:qt,portableProjectId:qt,revision:u().int().positive(),etag:Oi,syncedSourceRevision:u().int().positive(),syncedAt:Ka,tasksets:p(c({localTasksetId:qt,localTasksetHash:Oi.nullable().default(null),releaseId:qt,releaseRevision:u().int().positive(),releaseHash:Oi,packageHash:Oi.nullable().default(null),hostedTasksetId:qt,syncedAt:Ka}).strict()).max(1e4).default([])}).strict(),aB=c({localTasksetId:qt,releaseId:qt,releaseRevision:u().int().positive(),releaseHash:Oi,state:v(["syncing","synced","sync_failed"]),hostedTasksetId:qt.nullable().default(null),lastAttemptAt:Ka,syncedAt:Ka.nullable().default(null),lastError:i().trim().min(1).max(5e3).nullable().default(null)}).strict(),aC=c({schemaVersion:b("openpond.modelProject.v2"),id:qt,profileId:qt,revision:u().int().positive().default(1),name:i().trim().min(1).max(200),objective:i().trim().max(5e3).nullable(),defaultBaseModel:Lr.nullable(),defaultDestinationId:qt.nullable(),trainingSetup:nC,hosted:nB.nullable().default(null),tasksetSyncs:p(aB).max(1e4).default([]),createdAt:Ka,updatedAt:Ka}).strict(),iC=aC.pick({id:!0,profileId:!0,name:!0,objective:!0,defaultBaseModel:!0,defaultDestinationId:!0,trainingSetup:!0}),iB=c({schemaVersion:b("openpond.modelProjectSave.v1"),operationId:qt,expectedRevision:u().int().nonnegative(),project:iC,learning:J4.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."})}),oC=c({schemaVersion:b("openpond.modelProjectConfigurationCheck.v1"),configurationHash:Oi,projectId:qt,expectedRevision:u().int().nonnegative(),checkedAt:Ka,canSave:I(),deferred:p(v(["base_model","taskset"])).max(2),findings:p(c({code:qt,severity:v(["error","warning"]),message:i().min(1).max(5e3),field:i().min(1).max(500).nullable()}).strict()).max(100)}).strict();c({id:qt,name:i().min(1).max(500),available:I(),preference:Lr}).strict();function oB(e){try{Qa(e,kg)}catch{throw new cB(400,{schemaVersion:"openpond.modelProjectApiError.v2",code:"model_configuration_json_invalid",message:"Model configuration must be bounded JSON data.",retryable:!1,requestId:null,details:{}})}return iB.parse(e)}async function rB(e,t,n){Qa(e,kg);const a=iC.parse(e);X4(a,kg,"Model configuration");const o=await Q4({project:a,expectedRevision:t});return oB({schemaVersion:"openpond.modelProjectSave.v1",operationId:`model-save:${o}`,expectedRevision:t,project:a})}var sB=c({schemaVersion:b("openpond.hostedModelProjectSync.v2"),portableProjectId:qt,name:i().trim().min(1).max(200),objective:i().trim().max(5e3).nullable(),defaultBaseModel:Lr.nullable(),defaultDestinationId:qt.nullable(),trainingSetup:_b,sourceRevision:u().int().positive(),sourceUpdatedAt:Ka,expectedEtag:Oi.nullable().default(null)}).strict(),Jm=c({id:qt,teamId:qt,portableProjectId:qt,name:i().trim().min(1).max(200),objective:i().trim().max(5e3).nullable(),defaultBaseModel:Lr.nullable(),defaultDestinationId:qt.nullable(),trainingSetup:_b,sourceRevision:u().int().positive(),sourceUpdatedAt:Ka,revision:u().int().positive(),etag:Oi,createdAt:Ka,updatedAt:Ka}).strict(),lB=c({kind:v(["taskset_release","harness_release","dataset_release","evidence_set","model_version","reward_model_version","evaluation_receipt"]),ref:Mt,role:i().trim().min(1).max(200).nullable().default(null),updatedAt:Ka}).strict();c({project:Jm,resources:p(lB).max(1e4),jobCount:u().int().nonnegative(),latestJobIds:p(qt).max(100)}).strict();c({schemaVersion:b("openpond.modelProjectApiError.v2"),code:i().trim().min(1).max(200),message:i().trim().min(1).max(5e3),retryable:I().default(!1),requestId:i().trim().min(1).max(500).nullable().default(null),details:le(i(),ce()).default({})}).strict();var cB=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}},dB=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),uB=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]),mB=class rC{state=new Uint32Array(dB);pending=new Uint8Array(64);pendingLength=0;byteLength=0;words=new Uint32Array(64);update(t){const n=typeof t=="string"?new TextEncoder().encode(t):t;if(!Number.isSafeInteger(this.byteLength+n.length))throw new RangeError("SHA-256 input is too large");this.byteLength+=n.length;let a=0;if(this.pendingLength){const o=Math.min(64-this.pendingLength,n.length);this.pending.set(n.subarray(0,o),this.pendingLength),this.pendingLength+=o,a+=o,this.pendingLength===64&&(this.compress(this.pending),this.pendingLength=0)}for(;a+64<=n.length;)this.compress(n.subarray(a,a+64)),a+=64;return a<n.length&&(this.pending.set(n.subarray(a)),this.pendingLength=n.length-a),this}clone(){const t=new rC;return t.state.set(this.state),t.pending.set(this.pending),t.pendingLength=this.pendingLength,t.byteLength=this.byteLength,t}digestHex(){const t=this.clone(),n=new Uint8Array(t.pendingLength<56?64:128);n.set(t.pending.subarray(0,t.pendingLength)),n[t.pendingLength]=128;const a=t.byteLength*8,o=new DataView(n.buffer);return o.setUint32(n.length-8,Math.floor(a/4294967296),!1),o.setUint32(n.length-4,a>>>0,!1),t.compress(n.subarray(0,64)),n.length===128&&t.compress(n.subarray(64)),Array.from(t.state,r=>r.toString(16).padStart(8,"0")).join("")}compress(t){const n=new DataView(t.buffer,t.byteOffset,64),a=this.state,o=this.words;for(let k=0;k<16;k+=1)o[k]=n.getUint32(k*4,!1);for(let k=16;k<64;k+=1){const C=o[k-15],R=o[k-2],E=Ri(C,7)^Ri(C,18)^C>>>3,A=Ri(R,17)^Ri(R,19)^R>>>10;o[k]=o[k-16]+E+o[k-7]+A>>>0}let r=a[0],s=a[1],l=a[2],m=a[3],d=a[4],f=a[5],g=a[6],x=a[7];for(let k=0;k<64;k+=1){const C=d&f^~d&g,R=r&s^r&l^s&l,E=Ri(r,2)^Ri(r,13)^Ri(r,22),A=Ri(d,6)^Ri(d,11)^Ri(d,25),O=x+A+C+uB[k]+o[k]>>>0,$=E+R>>>0;x=g,g=f,f=d,d=m+O>>>0,m=l,l=s,s=r,r=O+$>>>0}a[0]=a[0]+r>>>0,a[1]=a[1]+s>>>0,a[2]=a[2]+l>>>0,a[3]=a[3]+m>>>0,a[4]=a[4]+d>>>0,a[5]=a[5]+f>>>0,a[6]=a[6]+g>>>0,a[7]=a[7]+x>>>0}};function pB(e){return new mB().update(e).digestHex()}function Ri(e,t){return e>>>t|e<<32-t}var fB=2e3,sC=25e7,Ke=i().trim().min(1).max(240),Qe=i().regex(/^[a-f0-9]{64}$/),At=i().datetime({offset:!0}),Zm=le(i(),ce()).default({}),He=c({id:Ke,contentHash:Qe}).strict(),hB=He.extend({revision:u().int().positive()}).strict(),di=c({id:Ke,path:i().trim().min(1).max(fB).refine(bB),contentHash:Qe,sizeBytes:u().int().nonnegative().max(sC),mediaType:i().trim().min(1).max(200),visibility:v(["policy","verifier","host_private"])}).strict(),gB=c({id:Ke,contentHash:Qe,mediaType:i().trim().min(1).max(200).nullable().default(null),sizeBytes:u().int().nonnegative().max(sC).nullable().default(null)}).strict(),lC=v(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]);function vB(e){return`${JSON.stringify(Ig(e),null,2)}
|
|
189
|
-
`}function cC(e){return pB(e)}function Tt(e){return cC(vB(e))}function bie(e,t){const{contentHash:n,...a}=e,o=Tt(a);if(n!==o)throw new Error(`${t} contentHash is ${n}; expected ${o}.`)}function bB(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function Ig(e){return Array.isArray(e)?e.map(Ig):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,Ig(n)]))}var yB=v(["memory","prompt","skill","agent"]),SB=v(["runtime","product","taskset","training"]),xB=c({id:i().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),text:i().trim().min(1).max(1e4)}).strict(),kB=c({schemaVersion:b("openpond.refinerReviewProfile.v1"),id:i().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),version:i().trim().min(1).max(120),name:i().trim().min(1).max(200),objective:i().trim().min(1).max(1e4),instructions:p(xB).max(100),allowedProposalRoutes:p(yB).max(4),allowedExternalRoutes:p(SB).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:b("openpond.refinerRelease.v1"),id:i().trim().min(1).max(240),coreVersion:i().trim().min(1).max(120),coreHash:Qe,profile:kB,profileHash:Qe,composedPromptHash:Qe,createdAt:At,contentHash:Qe}).strict();c({schemaVersion:b("openpond.refinerBinding.v1"),channel:b("active"),revision:u().int().nonnegative(),release:He,updatedAt:At}).strict();c({schemaVersion:b("openpond.refinerTransitionReceipt.v1"),id:i().trim().min(1).max(240),operation:v(["initialize","update","activate","rollback"]),bindingChanged:I(),previousRelease:He.nullable(),nextRelease:He,actor:i().trim().min(1).max(240),reason:i().trim().min(1).max(1e4),authoringSkillHash:Qe.nullable(),validation:c({valid:I(),messages:p(i().max(2e3)).max(100)}).strict(),createdAt:At,contentHash:Qe}).strict();var wB=c({schemaVersion:b("openpond.localHarnessRefinerDecision.v1"),decision:b("no_action"),reason:i().trim().min(1).max(1e4)}).strip(),IB=c({schemaVersion:b("openpond.localHarnessRefinerDecision.v1"),decision:b("route"),route:v(["runtime","product","taskset","training"]),summary:i().trim().min(1).max(2e3),expectedOutcome:i().trim().min(1).max(1e4),reason:i().trim().min(1).max(1e4)}).strip(),_B=c({schemaVersion:b("openpond.localHarnessRefinerDecision.v1"),decision:b("propose"),route:v(["memory","prompt","skill","agent"]),operation:v(["create","update","delete"]),target:i().trim().min(1).max(2e3),summary:i().trim().min(1).max(2e3),createContent:i().min(1).max(2e4).nullable(),find:i().min(1).max(8e3).nullable(),replace:i().max(8e3).nullable(),expectedOutcome:i().trim().min(1).max(1e4),reason:i().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"]})}),CB=ot("decision",[wB,IB,_B]),RB=CB,Cb=c({kind:v(["single_deterministic","recurrent_independent"]),supportingEvidenceIds:p(i().trim().min(1).max(2e3)).min(1).max(100),counterevidence:p(i().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"]})}),PB=c({schemaVersion:b("openpond.localHarnessRefinerDecision.v2"),decision:b("no_action"),reason:i().trim().min(1).max(1e4)}).strict(),AB=c({schemaVersion:b("openpond.localHarnessRefinerDecision.v2"),decision:b("route"),route:v(["runtime","product","taskset","training"]),summary:i().trim().min(1).max(2e3),evidenceBasis:Cb,expectedOutcome:i().trim().min(1).max(1e4),reason:i().trim().min(1).max(1e4)}).strict(),TB=c({schemaVersion:b("openpond.localHarnessRefinerDecision.v2"),decision:b("propose"),route:v(["memory","prompt","skill","agent"]),operation:v(["create","update","delete"]),target:i().trim().min(1).max(2e3),summary:i().trim().min(1).max(2e3),evidenceBasis:Cb,createContent:i().min(1).max(2e4).nullable(),find:i().min(1).max(8e3).nullable(),replace:i().max(8e3).nullable(),expectedOutcome:i().trim().min(1).max(1e4),reason:i().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"]})}),dC=ot("decision",[PB,AB,TB]);vt([RB,dC]);var Rb=c({memory:I(),prompt:I(),skill:I(),agent:I()}).strict(),uC=v(["memory","instruction","skill","agent"]),$S=c({path:i().trim().min(1).max(2e3),kind:uC,content:i().max(6e4),loaded:I()}).strict(),NS=c({path:i().trim().min(1).max(2e3),kind:uC,loaded:I()}).strict(),EB=c({capabilities:Rb,trigger:le(i(),ce()),observations:p(le(i(),ce())).max(20),admissibleEvidenceIds:p(i().trim().min(1).max(2e3)).max(1e4),reviewPacket:c({currentTurn:c({id:i().trim().min(1).max(2e3),status:i().trim().min(1).max(100).nullable(),error:i().max(2100).nullable(),prompt:i().max(8100).nullable(),assistantOutput:i().max(8100).nullable(),assistantOutputLinkCount:u().int().nonnegative()}).strict(),priorConversation:p(c({turnId:i().trim().min(1).max(2e3),status:i().trim().min(1).max(100).nullable(),prompt:i().max(3100).nullable(),assistantOutput:i().max(3100).nullable()}).strict()).max(3),timeline:p(le(i(),ce())).max(60),artifacts:p(le(i(),ce())).max(30),artifactDiagnostics:p(le(i(),ce())).max(20),executionProfile:c({modelRequestCount:u().int().nonnegative(),failedModelRequestCount:u().int().nonnegative(),promptTokens:u().int().nonnegative(),completionTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative(),toolFailureCount:u().int().nonnegative(),retryCount:u().int().nonnegative(),recoveryCount:u().int().nonnegative()}).strict(),priorIncidents:p(le(i(),ce())).max(3),truncation:c({timelineEventCount:u().int().nonnegative(),includedTimelineEventCount:u().int().nonnegative(),timelineTruncated:I()}).strict()}).strict(),runtimeActivation:c({admittedRelease:He,currentRelease:He,rebasedOntoCurrent:I(),admittedSourceFiles:p($S).max(100),admittedSourceCatalog:p(NS).max(1e3)}).strict(),sourceFiles:p($S).max(100),sourceCatalog:p(NS).max(1e3),additionalEvidence:ce().nullable().optional()}).strict(),MB=c({id:i().trim().min(1).max(240),revision:u().int().nonnegative(),contentHash:Qe}).strict();c({schemaVersion:b("openpond.hostedHarnessRefinerRequest.v2"),requestId:i().trim().min(1).max(240),idempotencyKey:i().trim().min(1).max(240),evidenceHash:Qe,harness:c({admittedRelease:He,currentRelease:He,overlay:MB,workspace:c({id:i().trim().min(1).max(240),revision:u().int().nonnegative(),sourceRevision:Qe,channelRevision:u().int().nonnegative()}).strict(),capabilities:Rb}).strict(),evidence:EB}).strict();var jB=c({promptTokens:u().int().nonnegative(),completionTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative()}).strict();c({schemaVersion:b("openpond.hostedHarnessRefinerResponse.v2"),requestId:i().trim().min(1).max(240),evidenceHash:Qe,admittedRelease:He,currentRelease:He,decision:dC,serviceRevision:i().trim().min(1).max(240),usage:jB}).strict();c({provider:Ke,model:Ke,revision:i().trim().min(1).max(500).nullable().default(null),artifactHash:Qe.nullable().default(null),tokenizerRevision:i().trim().min(1).max(500).nullable().default(null),chatTemplateHash:Qe.nullable().default(null)}).strict();var OB=["openpond","codex","claude-code","grok-build","opencode","anthropic","openai","xai","google","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],$B=v(OB),Pb=c({providerId:$B,modelId:i().trim().min(1).max(300)}),mC=c({name:i().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:i().trim().min(1).max(2e3),inputSchema:le(i(),ce()),inputSchemaHash:Qe,sideEffect:v(["read","write"]),timeoutMs:u().int().positive().max(36e5)}).strict(),NB=c({id:Ke,required:I(),scopes:p(i().trim().min(1).max(500)).max(100).default([]),portability:v(["portable","host_adapter","local_only","hosted_only"])}).strict(),DB=c({portable:I(),blockers:p(i().trim().min(1).max(2e3)).max(1e3),localOnlyAssetRefs:p(Ke).max(1e4),hostPrivateAssetRefs:p(Ke).max(1e4)}).strict(),HB=c({schemaVersion:b("openpond.agentSnapshot.v2"),id:Ke,sourceRelease:He.nullable(),instructions:p(di).max(1e4),skills:p(di).max(1e4),agents:p(di).max(1e4),toolDeclarations:p(mC).max(200),capabilityRequirements:p(NB).max(200),dependencyLock:di,portability:DB,metadata:Zm}).strict(),LB=HB.extend({contentHash:Qe}).strict(),qB=c({create:b(!0),reset:b(!0),step:b(!0),collect:b(!0),destroy:b(!0),resetScope:v(["task","attempt"])}).strict(),UB=c({visibleEvidence:p(Ke).max(1e3),privilegedEvidence:p(Ke).max(1e3),privateVerifierIsolation:I()}).strict(),zB=c({schemaVersion:b("openpond.harnessRelease.v2"),id:Ke,agentSnapshot:He,program:di,tools:p(mC).max(200),lifecycle:qB,graderInterface:UB,files:p(di).max(1e5),metadata:Zm}).strict(),BB=zB.extend({contentHash:Qe}).strict(),FB=c({id:Ke,turn:u().int().nonnegative(),kind:v(["message","tool_call","terminal"]),name:Ke.nullable(),arguments:le(i(),ce()),content:i().max(1e6).nullable()}).strict(),VB=c({actionId:Ke,turn:u().int().nonnegative(),terminal:I(),output:le(i(),ce()),artifactRefs:p(gB).max(1e5)}).strict(),KB=c({sequence:u().int().nonnegative(),type:v(["created","reset","action","observation","terminal","failure","collected","destroyed"]),payloadHash:Qe,metadata:Zm}).strict();c({schemaVersion:b("openpond.harnessTrace.v1"),manifest:He,taskId:Ke,seed:i().trim().min(1).max(500),events:p(KB).max(1e6),actions:p(FB).max(1e5),observations:p(VB).max(1e5),terminal:I(),failureClass:lC.nullable(),output:le(i(),ce()),contentHash:Qe}).strict();var WB=25*1024*1024,GB=c({path:di.shape.path,base64:i().max(Math.ceil(WB/3)*4)}).strict(),pC=c({schemaVersion:b("openpond.harnessSourcePackage.v1"),agentSnapshot:LB,harnessRelease:BB,files:p(GB).max(1e4)}).strict();pC.extend({contentHash:Qe}).strict();var yie=pC.extend({schemaVersion:b("openpond.harnessPolicySourcePackage.v1"),contentHash:Qe}).strict();c({schemaVersion:b("openpond.harnessSourceSelection.v1"),mode:v(["taskset_owned","selected_release"]),harnessRelease:He,sourcePackageHash:Qe.nullable()}).strict().superRefine((e,t)=>{e.mode==="selected_release"!=(e.sourcePackageHash!==null)&&t.addIssue({code:"custom",path:["sourcePackageHash"],message:"Only a selected release binds a source package."})});var po=i().trim().min(1).max(1e5),JB=v(["no_action","harness_maintenance","runtime","product","taskset","model_improvement"]),ZB=v(["none","runtime_service","product_team","human_review","evaluation_system","training_system"]),fC=v(["observation","trigger","route_decision","refiner_outcome","proposal","validation","apply_receipt","harness_advance","rollback","work_outcome","taskset","evaluation","training_qualification","model_candidate"]),Ab=c({kind:v(["personal","team"]),id:Ke}).strict(),hC=c({policy:He,state:v(["authorized","revoked","deleted","expired"]),checkedAt:At}).strict(),Mc=c({evidence:He,kind:fC,sourceRef:Ke,sourcePolicy:hC,occurrenceKey:Qe,occurredAt:At}).strict(),YB=c({evidence:He,sourcePolicy:hC.nullable(),reason:v(["outside_scope","before_watermark","duplicate","resolved","revoked","deleted","expired","sensitive","unverified","budget"])}).strict(),DS=c({cursor:Qe,throughCreatedAt:At}).strict(),QB=c({fingerprint:Qe,recurrenceFamily:i().trim().min(1).max(1e3),statement:po,candidateDisposition:v(["observe","confirm"]).optional(),independentOccurrences:u().int().positive().max(1e6),unresolvedOccurrences:u().int().positive().max(1e6)}).strict().refine(e=>e.unresolvedOccurrences<=e.independentOccurrences,"unresolved occurrences cannot exceed independent occurrences"),gC=v(["harness","runtime","product","retrieval","tools","evaluation","model"]),XB=c({layer:gC,status:v(["not_applicable","unresolved","resolved","blocked"]),reason:po,evidenceRefs:p(He).max(1e3)}).strict(),eF=c({schemaVersion:b("openpond.harnessEvaluationReviewReceipt.v1"),id:Ke,ownerScope:Ab,workspaceRef:Ke,harnessRelease:He,previousWatermark:DS.nullable(),nextWatermark:DS,selectedEvidence:p(Mc).max(1e4),excludedEvidence:p(YB).max(1e4),claim:QB.nullable(),classification:JB,triage:p(XB).max(16),reason:po,nextAuthority:ZB,maxEstimatedCostUsd:u().finite().nonnegative(),tasksetProposal:He.nullable(),evaluation:He.nullable(),trainingQualification:He.nullable(),policyVersion:Ke,createdAt:At,metadata:Zm}).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"})});eF.extend({contentHash:Qe}).strict();c({id:Ke,evidence:He,kind:fC,sourceRef:Ke,occurredAt:At,payload:le(i(),ce())}).strict();var tF=c({schemaVersion:b("openpond.harnessEvaluationReviewModelDecision.v2"),decision:b("no_action"),reason:po,ignoredEvidence:p(c({id:Ke,reason:i().trim().min(1).max(2e3)}).strict()).max(1e3)}).strict(),nF=c({schemaVersion:b("openpond.harnessEvaluationReviewModelDecision.v2"),decision:b("review"),classification:v(["harness_maintenance","runtime","product","taskset"]),selectedEvidenceIds:p(Ke).min(1).max(1e3),ignoredEvidence:p(c({id:Ke,reason:i().trim().min(1).max(2e3)}).strict()).max(1e3),recurrenceFamily:i().trim().min(1).max(1e3),statement:po,triageLayer:gC,expectedOutcome:po,counterevidence:i().trim().max(1e4),confidence:u().min(0).max(1),candidateDisposition:v(["observe","confirm"]).nullable(),reason:po}).strict().superRefine((e,t)=>{e.classification==="harness_maintenance"!==(e.candidateDisposition!==null)&&t.addIssue({code:"custom",message:"Harness maintenance requires a candidate disposition; external routes require null",path:["candidateDisposition"]})}),aF=c({schemaVersion:b("openpond.harnessEvaluationReviewModelDecision.v2"),decision:b("resolve_candidate"),candidateId:Ke,candidateFingerprint:Qe,selectedEvidenceIds:p(Ke).min(1).max(1e3),ignoredEvidence:p(c({id:Ke,reason:i().trim().min(1).max(2e3)}).strict()).max(1e3),confidence:u().min(0).max(1),reason:po}).strict();ot("decision",[tF,nF,aF]);c({schemaVersion:b("openpond.harnessEvaluationReviewNavigationDecision.v1"),selectedEvidenceIds:p(Ke).min(1).max(50),reason:po}).strict();var hl=le(i(),ce()).default({}),za=u().int().nonnegative(),Ym=i().trim().min(1).max(1e5),vC=c({kind:v(["personal","team"]),id:Ke}).strict(),iF=c({name:Ke,release:He.nullable(),revision:za}).strict();c({schemaVersion:b("openpond.harnessWorkspace.v1"),id:Ke,ownerScope:vC,name:i().trim().min(1).max(240),location:v(["local","hosted"]),sourceRevision:i().trim().min(1).max(500),revision:za,dirty:I(),currentChannel:iF,createdAt:At,updatedAt:At,metadata:hl}).strict();var Qs=v(["runtime","memory","prompt","skill","agent","product","taskset","training"]),bC=v(["text_instruction","memory","dependency_selection","executable_code","business_logic","financial_logic","permission","connected_app","publication","deployment","training","model_binding","team_or_global"]),yC=c({id:Ke,route:Qs,operation:v(["create","update","delete"]),target:i().trim().min(1).max(2e3),summary:i().trim().min(1).max(2e3),content:i().max(1e6).nullable(),contentHash:Qe.nullable(),effects:p(bC).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=Tt(e.content);e.contentHash!==n&&t.addIssue({code:"custom",message:`edit contentHash is ${e.contentHash}; expected ${n}`,path:["contentHash"]})}),SC=c({workspaceId:Ke,revision:za,sourceRevision:i().trim().min(1).max(500),channelRevision:za}).strict(),fo=c({id:Ke,revision:za,contentHash:Qe}).strict();c({schemaVersion:b("openpond.harnessTurnSnapshot.v1"),workspaceId:Ke,workspaceRevision:za,sourceRevision:i().trim().min(1).max(500),channelName:Ke,channelRevision:za,harnessRelease:He,toolCatalogHash:Qe.nullable().optional(),overlay:fo.nullable().optional().default(null)}).strict();var oF=c({schemaVersion:b("openpond.harnessRunOverlay.v1"),id:Ke,runId:Ke,baseHarnessRelease:He,workspace:SC,revision:za,status:v(["active","frozen","abandoned"]),edits:p(yC).max(1e3),createdAt:At,updatedAt:At,metadata:hl}).strict();oF.extend({contentHash:Qe}).strict();var xC=c({kind:v(["tool_event","recovery","validation","user_turn","work_output","work_receipt"]),id:Ke,contentHash:Qe.nullable()}).strict(),kC=c({id:Ke,kind:v(["dependency","schema","package","file_render","skill","prompt","business_formula","targeted_evaluation","observed_recovery","memory","component_activation"]),description:Ym,required:I()}).strict(),rF=c({schemaVersion:b("openpond.harnessImprovementProposal.v1"),id:Ke,overlay:fo,baseHarnessRelease:He,expectedWorkspace:SC,requestedScope:v(["personal","team","global"]),route:Qs,risk:v(["low","review","restricted"]),effects:p(bC).min(1).max(20),evidence:p(xC).min(1).max(1e3),edits:p(yC).min(1).max(1e3),validationPlan:p(kC).min(1).max(100),expectedOutcome:Ym,createdAt:At,metadata:hl}).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 r of o.effects)n.has(r)||t.addIssue({code:"custom",message:`edit effect ${r} is missing from proposal effects`,path:["edits",a,"effects"]})}new Set(e.validationPlan.map(a=>a.id)).size!==e.validationPlan.length&&t.addIssue({code:"custom",message:"validation plan ids must be unique",path:["validationPlan"]})});rF.extend({contentHash:Qe}).strict();var sF=c({schemaVersion:b("openpond.harnessTargetedValidationReceipt.v1"),id:Ke,proposal:He,validationId:Ke,kind:kC.shape.kind,status:v(["passed","failed","blocked","skipped"]),summary:Ym,evidenceRefs:p(xC).max(1e3),createdAt:At,metadata:hl}).strict();sF.extend({contentHash:Qe}).strict();var lF=v(["advanced","retained","conflict","rolled_back"]),cF=c({schemaVersion:b("openpond.harnessAdvanceReceipt.v1"),id:Ke,workspaceId:Ke,ownerScope:vC,proposal:He.nullable(),expectedWorkspaceRevision:za,observedWorkspaceRevision:za,previousChannelRevision:za,nextChannelRevision:za,previousRelease:He.nullable(),nextRelease:He.nullable(),validationReceipts:p(He).max(100),decision:lF,reason:Ym,rollbackOf:He.nullable(),createdAt:At,metadata:hl}).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"]})});cF.extend({contentHash:Qe}).strict();var dF=c({schemaVersion:b("openpond.harnessOverlayMergeReceipt.v1"),id:Ke,workspaceId:Ke,baseHarnessRelease:He,leftOverlay:fo,rightOverlay:fo,decision:v(["merged","conflict"]),mergedOverlay:fo.nullable(),conflictTargets:p(i().trim().min(1).max(2e3)).max(1e3),requiresRevalidation:b(!0),createdAt:At,metadata:hl}).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"]})});dF.extend({contentHash:Qe}).strict();var Qm=i().trim().min(1).max(1e5),ud=le(i(),ce()).default({}),uF=v(["completed_tool_batch","before_model_step","turn_completed","turn_paused"]),wC=c({kind:uF,eventSequence:u().int().nonnegative(),occurredAt:At}).strict(),IC=c({id:Ke,sequence:u().int().nonnegative().nullable(),contentHash:Qe}).strict(),mF=v(["tool_failure","retry","recovery","validation","user_turn","reusable_success","completion_detour"]),pF=v(["open","recovered","terminal"]),fF=c({name:i().trim().min(1).max(500),invocationKey:Qe}).strict(),hF=c({schemaVersion:b("openpond.improvementObservation.v1"),id:Ke,runRef:Ke,turnId:Ke,harnessRelease:He,overlay:fo.nullable(),eventRefs:p(IC).min(1).max(100),kind:mF,state:pF,tool:fF.nullable(),deterministicClass:i().trim().min(1).max(500).nullable(),summary:Qm,createdAt:At,metadata:ud}).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"]})});hF.extend({contentHash:Qe}).strict();var gF=c({schemaVersion:b("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(),vF=v(["no_action","route_deterministically","queue_refiner"]),bF=c({schemaVersion:b("openpond.refinementTriggerDecision.v1"),id:Ke,runRef:Ke,turnId:Ke,harnessRelease:He,overlay:fo.nullable(),observations:p(He).max(100),decision:vF,deterministicRoute:Qs.nullable(),suggestedRoutes:p(Qs).max(8),reason:Qm,deduplicationKey:Qe,policy:gF,estimatedMaxCostUsd:u().finite().nonnegative(),pendingPlanCount:u().int().nonnegative(),boundary:wC,cooldownUntil:At.nullable(),createdAt:At,metadata:ud}).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"]})});bF.extend({contentHash:Qe}).strict();var yF=v(["runtime_service","refiner_model","human_review","evaluation_system","training_system"]),SF=c({schemaVersion:b("openpond.improvementRouteDecision.v1"),id:Ke,trigger:He,route:Qs,authority:yF,automatic:I(),reason:Qm,createdAt:At,metadata:ud}).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"]})});SF.extend({contentHash:Qe}).strict();var xF=c({schemaVersion:b("openpond.harnessRefinerOutcome.v1"),id:Ke,trigger:He,decision:v(["no_action","proposed"]),proposal:He.nullable(),reason:Qm,evidenceRefs:p(He).max(100),estimatedCostUsd:u().finite().nonnegative(),createdAt:At,metadata:ud}).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"]})});xF.extend({contentHash:Qe}).strict();var kF=v(["applied","retained","declined","conflict","rolled_back"]),wF=c({schemaVersion:b("openpond.improvementApplyReceipt.v1"),id:Ke,proposal:He,beforeOverlay:fo,afterOverlay:fo.nullable(),decision:kF,boundary:wC,validationRefs:p(He).max(100),outcomeEvidenceRefs:p(IC).max(1e3),rollbackOf:He.nullable(),createdAt:At,metadata:ud}).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"]})});wF.extend({contentHash:Qe}).strict();var IF=i().trim().min(1).max(2e3),Tb=i().trim().min(1).max(1e5),_F=v(["create","update","delete"]),CF=v(["memory","prompt","skill","agent"]),RF=v(["runtime","product","taskset","training"]),PF=v(["no_action","routed","applied","retained","failed"]),AF=v(["not_applicable","pending","passed","rejected","failed"]),TF=v(["not_applicable","pending","passed","failed"]),EF=c({schemaVersion:b("openpond.harnessRefinerActivityReceipt.v1"),id:Ke,runRef:Ke,turnId:Ke,result:PF,decision:v(["no_action","route","propose"]).nullable(),route:Qs.nullable(),operation:_F.nullable(),target:i().trim().min(1).max(2e3).nullable(),summary:IF,evidenceBasis:Cb.nullable(),critiqueStatus:AF,validationStatus:TF,trigger:He,outcome:He.nullable(),proposal:He.nullable(),applyReceipt:He.nullable(),inputHarness:He,outputHarness:He.nullable(),createdAt:At}).strict().superRefine((e,t)=>{const n=e.result==="applied"||e.result==="retained";e.result==="no_action"?HS(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"||!RF.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"}),HS(t,e,{critiqueStatus:"not_applicable",validationStatus:"not_applicable"})):n?((e.decision!=="propose"||!CF.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"]})});EF.extend({contentHash:Qe}).strict();var MF=v(["unresolved","confirmed","resolved","rejected","expired"]),jF=c({kind:v(["applied_change","later_success","manual_rejection","source_revoked","expired"]),reason:Tb,evidenceRefs:p(He).max(1e3),resolvedAt:At}).strict(),OF=c({schemaVersion:b("openpond.harnessRefinementCandidate.v1"),id:Ke,ownerScope:Ab,workspaceRef:Ke,fingerprint:Qe,recurrenceFamily:i().trim().min(1).max(1e3),statement:Tb,status:MF,occurrences:p(Mc).max(1e3),counterevidence:p(Mc).max(1e3),sourceReviews:p(He).min(1).max(100),relatedHarnessReleases:p(He).max(100),firstSeenAt:At,lastSeenAt:At,lastReviewedAt:At,expiresAt:At,resolution:jF.nullable(),createdAt:At,updatedAt:At}).strict().superRefine((e,t)=>{kr(t,e.occurrences,"occurrences"),kr(t,e.counterevidence,"counterevidence"),kr(t,e.sourceReviews,"sourceReviews"),kr(t,e.relatedHarnessReleases,"relatedHarnessReleases");const n=new Set(e.occurrences.map(o=>o.occurrenceKey));e.counterevidence.some(o=>n.has(o.occurrenceKey))&&t.addIssue({code:"custom",message:"supporting occurrences and counterevidence must be disjoint",path:["counterevidence"]});const a=e.status==="unresolved"||e.status==="confirmed";a&&e.occurrences.length===0&&t.addIssue({code:"custom",message:"actionable candidates require at least one supporting occurrence",path:["occurrences"]}),a&&[...e.occurrences,...e.counterevidence].some(o=>o.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"actionable candidates may contain only currently authorized evidence",path:["occurrences"]}),a!==(e.resolution===null)&&t.addIssue({code:"custom",message:"only resolved, rejected, or expired candidates require a resolution",path:["resolution"]}),e.status==="expired"&&e.resolution?.kind!=="expired"&&t.addIssue({code:"custom",message:"expired candidates require an expired resolution",path:["resolution","kind"]}),e.status==="rejected"&&e.resolution&&!["manual_rejection","source_revoked"].includes(e.resolution.kind)&&t.addIssue({code:"custom",message:"rejected candidates require a rejection or revocation resolution",path:["resolution","kind"]}),e.status==="resolved"&&e.resolution&&!["applied_change","later_success"].includes(e.resolution.kind)&&t.addIssue({code:"custom",message:"resolved candidates require applied-change or later-success evidence",path:["resolution","kind"]}),LF(t,e)});OF.extend({contentHash:Qe}).strict();var $F=v(["created","merged","rejected","expired","reopened","resolved"]),NF=c({schemaVersion:b("openpond.harnessRefinementCandidateLifecycleReceipt.v1"),id:Ke,candidateId:Ke,decision:$F,beforeCandidate:He.nullable(),afterCandidate:He,review:He,addedEvidence:p(Mc).max(1e3),removedEvidence:p(He).max(1e3),reason:Tb,createdAt:At}).strict().superRefine((e,t)=>{e.decision==="created"!=(e.beforeCandidate===null)&&t.addIssue({code:"custom",message:"only candidate creation omits the previous candidate reference",path:["beforeCandidate"]}),e.beforeCandidate&&e.beforeCandidate.contentHash===e.afterCandidate.contentHash&&t.addIssue({code:"custom",message:"candidate lifecycle transitions must change candidate content",path:["afterCandidate"]}),["created","reopened"].includes(e.decision)&&e.addedEvidence.length===0&&t.addIssue({code:"custom",message:`${e.decision} candidate transitions require added evidence`,path:["addedEvidence"]}),e.addedEvidence.some(a=>a.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"candidate transitions may add only authorized evidence",path:["addedEvidence"]}),kr(t,e.addedEvidence,"addedEvidence"),kr(t,e.removedEvidence,"removedEvidence");const n=new Set(e.removedEvidence.map(a=>_g(a)));e.addedEvidence.some(a=>n.has(_g(a.evidence)))&&t.addIssue({code:"custom",message:"candidate lifecycle evidence cannot be added and removed together",path:["removedEvidence"]})});NF.extend({contentHash:Qe}).strict();var DF=c({schemaVersion:b("openpond.harnessCrossRunRefinementRequest.v1"),id:Ke,ownerScope:Ab,workspaceRef:Ke,candidate:He,candidateFingerprint:Qe,review:He,admittedHarness:He,evidence:p(Mc).min(1).max(1e3),capabilities:Rb,deduplicationKey:Qe,createdAt:At}).strict().superRefine((e,t)=>{e.evidence.some(a=>a.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"cross-run refinement requires currently authorized evidence",path:["evidence"]}),kr(t,e.evidence,"evidence"),Object.values(e.capabilities).some(Boolean)||t.addIssue({code:"custom",message:"cross-run refinement requires at least one available Harness capability",path:["capabilities"]});const n=HF(e);e.deduplicationKey!==n&&t.addIssue({code:"custom",message:`cross-run refinement deduplicationKey is ${e.deduplicationKey}; expected ${n}`,path:["deduplicationKey"]})});DF.extend({contentHash:Qe}).strict();function HF(e){return Tt({schemaVersion:"openpond.harnessCrossRunRefinementIdentity.v1",workspaceRef:e.workspaceRef,candidateFingerprint:e.candidateFingerprint,admittedHarness:e.admittedHarness})}function HS(e,t,n){for(const[a,o]of Object.entries(n))t[a]!==o&&e.addIssue({code:"custom",message:`${a} must be ${String(o)}`,path:[a]})}function kr(e,t,n){const a=t.map(o=>_g(o));new Set(a).size!==a.length&&e.addIssue({code:"custom",message:`${n} references must be unique`,path:[n]})}function _g(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 LF(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],r=n[a];Date.parse(o[1])<=Date.parse(r[1])||e.addIssue({code:"custom",message:`${r[0]} must not precede ${o[0]}`,path:[r[0]]})}Date.parse(t.createdAt)>Date.parse(t.updatedAt)&&e.addIssue({code:"custom",message:"updatedAt must not precede createdAt",path:["updatedAt"]})}c({path:i().min(1).max(2e3),offset:u().int().nonnegative().default(0),length:u().int().positive().max(65536).default(16384)}).strict();var _C=i().regex(/^[a-z][a-z0-9_-]{0,119}$/),CC=i().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"),qF=c({id:_C,label:i().trim().min(1).max(240),description:i().max(4e3),inputSchema:le(i(),ce()),invocation:ot("kind",[c({kind:b("instructions"),instructions:i().min(1).max(1e5).refine(e=>!!e.trim())}).strict(),c({kind:b("agent_action"),actionId:i().trim().min(1).max(240)}).strict()]),skillPaths:p(CC).max(100)}).strict();c({schemaVersion:b("openpond.profileWorkflows.v1"),workflows:p(qF).max(1e3)}).strict();var UF=c({id:i().trim().min(1).max(240),agentId:i().regex(/^[a-zA-Z0-9_-]{1,240}$/),sourceActionId:i().trim().min(1).max(240),inputSchema:le(i(),ce())}).strict();c({schemaVersion:b("openpond.profileWorkflowActions.v1"),actions:p(UF).max(200)}).strict();c({schemaVersion:b("openpond.profileWorkflowBinding.v1"),profileId:i().trim().min(1).max(240),sourceRevision:i().trim().min(1).max(240),harnessRelease:He,catalogHash:Qe,workflowId:_C}).strict();c({schemaVersion:b("openpond.profileComponentBinding.v1"),profileId:i().trim().min(1).max(240),sourceRevision:i().trim().min(1).max(240),harnessRelease:He,target:ot("kind",[c({kind:b("profile")}).strict(),c({kind:b("skill"),skillPath:CC}).strict(),c({kind:b("agent_action"),actionId:i().trim().min(1).max(240)}).strict()])}).strict();var im=i().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");i().regex(/^[a-z][a-z0-9_-]{0,119}$/);var zF={type:"object",properties:{},additionalProperties:!1};c({name:i().trim().min(1).max(240).optional(),description:i().max(4e3).optional(),skillPaths:p(im).max(100).optional(),assetPaths:p(im).max(100).optional()}).strict();c({actionId:i().trim().min(1).max(240),name:i().trim().min(1).max(240),description:i().max(4e3).default(""),inputSchema:le(i(),ce()).default(zF),skillPaths:p(im).max(100).default([]),assetPaths:p(im).max(100).default([])}).strict();const BF="openpond.connectedEvidence.v1",FF="connected-evidence-1",tu={files:100,sourceBytes:32*1024*1024,events:1e5,sessions:1e3,boundaries:5e3},Aa=i().min(1).max(500),uc=i().regex(/^[a-f0-9]{64}$/),VF=i().datetime().nullable(),nu=u().int().nonnegative().nullable(),RC=v(["native_chat","native_work","codex","claude_code","hermes","openclaw","opencode","grok_build","pi","oh_my_pi"]),KF=c({invocationId:Aa,inputTokens:nu,outputTokens:nu,cachedInputTokens:nu,totalTokens:nu,provenance:v(["billed_invocation","reported_invocation","reported_cumulative"])}).strict(),LS=c({id:Aa,sequence:u().int().nonnegative(),occurredAt:VF,kind:v(["message","tool_call","tool_result","compaction","artifact","terminal","usage","unknown"]),role:v(["user","assistant","system","tool"]).nullable(),callId:Aa.nullable(),parentId:Aa.nullable(),content:Ko(),usage:KF.nullable()}).strict(),WF=c({id:Aa,familyKey:Aa,projection:v(["turn","conversation"]),requestEventId:Aa,start:u().int().nonnegative(),end:u().int().positive(),inputHash:uc,outputHash:uc.nullable(),revisionHash:uc,terminal:v(["completed","failed","cancelled","unknown"]),coverage:c({answer:I(),context:v(["retained","compacted","unknown"]),process:v(["retained","partial","absent"]),artifacts:v(["retained","references_only","absent"]),replay:b("unavailable"),gaps:p(i().max(500)).max(100)}).strict()}).strict();c({schemaVersion:b(BF),normalizerVersion:b(FF),origin:RC,sessionId:Aa,branchId:Aa.nullable(),parentSessionId:Aa.nullable(),exporterVersion:i().max(200).nullable(),acquisition:c({machineId:Aa,sourceInstanceId:Aa}).strict().optional(),sourceFiles:p(c({path:Aa,contentHash:uc,sizeBytes:u().int().nonnegative()}).strict()).max(tu.files),events:p(LS).max(tu.events),unmappedEvents:p(LS).max(tu.events),boundaries:p(WF).max(tu.boundaries),warnings:p(i().max(500)).max(100),contentHash:uc}).strict();const GF=c({schemaVersion:b("openpond.humanResultView.v1"),executionId:i().min(1),executionHash:i().regex(/^[a-f0-9]{64}$/),selection:p(Cn).max(1e4),coverage:c({pending:u().int().nonnegative(),submitted:u().int().nonnegative(),accepted:u().int().nonnegative(),rejected:u().int().nonnegative(),cancelled:u().int().nonnegative()}).strict(),results:p(c({review:Cn,decision:Cn.nullable(),attemptIds:p(i().min(1)).min(1).max(2),mode:v(["individual","pairwise"]),origin:v(["hosted_retained","recorded_evidence","owner_attested_local","native_local"]),status:v(["pending","submitted","accepted","rejected","cancelled"]),grader:Cn,answers:p(Zs).max(100)}).strict()).max(1e4)}).strict(),qS=GF.extend({contentHash:i().regex(/^[a-f0-9]{64}$/)}).strict(),om=i().regex(/^[a-f0-9]{64}$/),jc=i().min(1).max(240),au={feedbackKey:jc,criterionId:jc},JF=ot("kind",[c({...au,kind:b("normalized_score"),minimum:u().finite(),maximum:u().finite(),passThreshold:u().min(0).max(1).optional()}).strict(),c({...au,kind:b("boolean")}).strict(),c({...au,kind:b("category")}).strict(),c({...au,kind:b("preference_score"),tieScore:u().min(0).max(1).nullable()}).strict()]),US=c({execution:W,resultHash:om,reviews:p(c({review:Cn,decision:Cn}).strict()).min(1).max(1e4)}).strict(),PC=c({rules:p(JF).min(1).max(100),baseline:US,candidate:US}).strict().superRefine((e,t)=>{new Set(e.rules.map(n=>n.feedbackKey)).size!==e.rules.length&&t.addIssue({code:"custom",message:"Select each Human feedback key once."})}),zS=c({manifest:uo,result:mo}).strict(),BS=c({id:jc,manifestHash:om,resultHash:om}).strict(),ZF=c({schemaVersion:b("openpond.humanComparisonProjection.v1"),teamId:jc,projectId:jc,selections:PC,original:c({baseline:BS,candidate:BS}).strict(),humanResults:c({baseline:qS,candidate:qS}).strict(),baseline:zS,candidate:zS}).strict(),Cg=ZF.extend({contentHash:om}).strict();function vh(e){throw new pi(e,409)}function YF(e,t){const n=Cg.parse(e),{contentHash:a,...o}=n;a!==ct(o)&&vh("human_comparison_projection_invalid");for(const r of["baseline","candidate"]){const s=Pr(n[r]),l=s.manifest.lineage,m=l?.humanProjection,d=n.original[r],f=n.selections[r];(!l||!m||m.originalManifest.id!==d.id||m.originalManifest.contentHash!==d.manifestHash||m.selectionHash!==ct(f)||m.rulesHash!==ct(n.selections.rules)||ct(l.execution)!==ct(f.execution)||s.manifest.teamId!==n.teamId||n.humanResults[r].contentHash!==f.resultHash)&&vh("human_comparison_projection_lineage_changed");const{contentHash:g,...x}=n.humanResults[r];(ct(x)!==g||x.executionId!==f.execution.id||x.executionHash!==f.execution.contentHash||ct(x.selection)!==ct(f.reviews.map(k=>k.review)))&&vh("human_comparison_human_result_changed")}return n}const AC=c({adapterId:T,placement:v(["local","remote","colocated","provider_native"]),runtimeVersion:i().trim().min(1).max(200),capabilityReceipt:H}).strict(),TC=c({maxTurns:u().int().positive().max(1e5),timeoutMs:u().int().positive().max(864e5),maxOutputBytes:u().int().positive().max(25e7),maximumSpendUsd:u().nonnegative().nullable()}).strict(),QF=c({schemaVersion:b("openpond.runManifest.v1"),id:T,harnessRelease:W,tasksetRelease:W,model:Am,runtimeTarget:AC,limits:TC,approval:c({id:T,contentHash:H}).strict().nullable(),createdAt:ye,metadata:Nn}).strict();QF.extend({contentHash:H}).strict();const XF=c({schemaVersion:b("openpond.attemptReceipt.v1"),id:T,runManifest:W,taskId:T,seed:i().trim().min(1).max(500),terminal:I(),failureClass:Wc.nullable(),outputHash:H.nullable(),traceHash:H,artifactRefs:p(Ma).max(1e5),graderEvidenceRefs:p(Ma).max(1e4),startedAt:ye,completedAt:ye,latencyMs:u().int().nonnegative(),costUsd:u().nonnegative().nullable(),legacyAttemptRef:T.nullable().default(null),metadata:Nn}).strict(),e5=XF.extend({contentHash:H}).strict(),t5=c({schemaVersion:b("openpond.evaluationResult.v1"),id:T,runManifest:W,harnessRelease:W,tasksetRelease:W,model:Am,receiptRefs:p(W).min(1).max(1e6),attemptCount:u().int().positive(),rewardEligibleCount:u().int().nonnegative(),terminalCount:u().int().nonnegative(),meanScore:u().min(0).max(1).nullable(),failureCounts:le(Wc,u().int().nonnegative()),authoredMetric:db.optional(),metadata:Nn}).strict(),n5=t5.extend({contentHash:H}).strict(),a5=c({schemaVersion:b("openpond.harnessCompatibility.v1"),id:T,baseHarnessRelease:W,candidateHarnessRelease:W,tasksetRelease:W,environmentHash:H,toolContractHash:H,policyHash:H,graderInterfaceHash:H,metadata:Nn}).strict();a5.extend({contentHash:H}).strict();const Eb=v(["scored","unscorable"]),Xm=v(["policy","environment","collector","verifier","provider","host","user","scheduler"]),EC=v(["completed","policy_failure","incomplete_output","task_deadline","environment_failure","collector_failure","verifier_failure","provider_failure","host_failure","infrastructure_timeout","cancelled"]),i5=c({schemaVersion:b("openpond.environmentRelease.v1"),id:T,revision:u().int().positive(),contract:h_,actionSchemaRef:bn.nullable(),observationSchemaRef:bn.nullable(),stateSchemaRef:bn.nullable(),artifactCollection:c({maxArtifacts:u().int().positive().max(1e5),maxTotalBytes:u().int().positive().max(1e10)}).strict(),adapterConformanceHashes:le(T,H),metadata:Nn}).strict(),Mb=i5.extend({contentHash:H}).strict(),o5=v(["collected","missing","skipped","failed"]),FS=v(["not_requested","passed","failed"]),r5=c({requiredOutputPath:i().trim().min(1).max(2e3).nullable(),collectedPath:i().trim().min(1).max(4e3).nullable(),declaredMediaType:i().trim().min(1).max(200).nullable(),detectedMediaType:i().trim().min(1).max(200).nullable(),artifact:Ma.nullable(),status:o5,parseStatus:FS,schemaStatus:FS,errorCode:T.nullable(),failureOwner:Xm.nullable(),evidenceRefs:p(Ma).max(1e4),metadata:Nn}).strict(),s5=c({schemaVersion:b("openpond.artifactManifest.v1"),id:T,attemptRef:W,entries:p(r5).max(1e5),createdAt:ye,metadata:Nn}).strict();s5.extend({contentHash:H}).strict();const l5=c({schemaVersion:b("openpond.verifierSetRelease.v1"),id:T,revision:u().int().positive(),graders:p(x_).min(1).max(1e3),isolation:c({processBoundary:v(["same_process","isolated_process","container"]),networkPolicy:b("none"),defaultTimeoutMs:u().int().positive().max(3e5)}).strict(),calibrationReceiptRefs:p(W).max(1e4),metadata:Nn}).strict(),jb=l5.extend({contentHash:H}).strict(),c5=c({verifierId:T,verifierVersion:i().trim().min(1).max(100),status:Eb,rawScore:u().finite().nullable(),normalizedScore:u().min(0).max(1).nullable(),weight:u().nonnegative().max(1e3),passed:I(),hardGate:I(),rewardEligible:I(),rewardContribution:u().min(0).max(1).nullable(),failureOwner:Xm.nullable(),feedback:p(i().max(2e4)).max(1e3),visibleEvidenceRefs:p(Ma).max(1e4),privilegedEvidenceRefs:p(Ma).max(1e4),metadata:Nn}).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"]})}),MC=c({schemaVersion:b("openpond.rewardReceipt.v1"),id:T,attemptRef:W,verifierSetRef:W,artifactManifestRef:W,status:Eb,reward:u().min(0).max(1).nullable(),learningEligible:I(),passed:I(),outcomeClass:EC,failureOwner:Xm.nullable(),components:p(c5).min(1).max(1e4),visibleEvidenceRefs:p(Ma).max(1e5),privilegedEvidenceRefs:p(Ma).max(1e5),supersedes:W.nullable(),createdAt:ye,metadata:Nn}).strict();function jC(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"]})}MC.superRefine(jC);MC.extend({contentHash:H}).strict().superRefine(jC);const d5=ot("kind",[c({kind:b("model"),model:Am,configurationHash:H}).strict(),c({kind:b("fixture")}).strict()]),u5=ot("kind",[c({kind:b("taskset"),environmentRelease:W,verifierSetRelease:W,policyHash:H}).strict(),c({kind:b("harness"),harnessRelease:W}).strict()]),OC=c({receiptId:T,taskId:T,seed:i().trim().min(1).max(500),fixtureId:T.nullable()}).strict(),m5=c({schemaVersion:b("openpond.tasksetRunManifest.v1"),id:T,tasksetRelease:W,packageHash:H,execution:u5,profileEvaluation:Ys.optional(),policy:d5,gradingRole:b("evaluation"),metricPolicy:id,population:p(OC).min(1).max(1e5),runtimeTarget:AC,limits:TC,createdAt:ye,metadata:Nn}).strict().superRefine((e,t)=>{new Set(e.population.map(n=>n.receiptId)).size!==e.population.length&&t.addIssue({code:"custom",path:["population"],message:"Run receipt identities must be unique."}),e.population.some(n=>n.fixtureId!==null!=(e.policy.kind==="fixture"))&&t.addIssue({code:"custom",path:["population"],message:"Only fixture runs require a fixture identity for every member."}),e.profileEvaluation&&(e.execution.kind!=="harness"||e.execution.harnessRelease.id!==e.profileEvaluation.harnessRelease.id||e.execution.harnessRelease.contentHash!==e.profileEvaluation.harnessRelease.contentHash)&&t.addIssue({code:"custom",path:["profileEvaluation"],message:"Profile evaluation must execute its exact bound Harness release."})}),ep=m5.safeExtend({contentHash:H}),p5=c({schemaVersion:b("openpond.profileEvaluationComparison.v1"),id:T,tasksetRelease:W,populationHash:H,environmentHash:H,metricPolicyHash:H,limitsHash:H,members:p(c({runManifest:W,metricResultHash:H,source:Ys,policy:ep.shape.policy,score:u().min(0).max(1).nullable()}).strict()).min(2).max(100),createdAt:ye}).strict(),f5=p5.extend({contentHash:H}).strict(),h5=c({profileId:T,sourceRevision:i().trim().min(1).max(240),harnessRelease:W}).strict(),g5=c({kind:v(["run","suite","comparison"]),id:T,contentHash:H}).strict(),v5=c({schemaVersion:b("openpond.profileEvaluationReport.v1"),id:T,createdAt:ye,testedSources:p(h5).min(1).max(100),tasksetReleases:p(W).min(1).max(100),metricPolicyHashes:p(H).min(1).max(100),modelConfigurationHashes:p(H).min(1).max(100),evidence:p(g5).min(1).max(100),summary:c({totalChecks:u().int().nonnegative(),passedChecks:u().int().nonnegative(),failedChecks:u().int().nonnegative(),unscoredChecks:u().int().nonnegative(),meanScore:u().min(0).max(1).nullable()}).strict()}).strict().superRefine((e,t)=>{const{summary:n}=e;n.passedChecks+n.failedChecks+n.unscoredChecks!==n.totalChecks&&t.addIssue({code:"custom",path:["summary"],message:"Report check counts must add up."}),new Set(e.evidence.map(({kind:a,id:o})=>`${a}:${o}`)).size!==e.evidence.length&&t.addIssue({code:"custom",path:["evidence"],message:"Report evidence must be unique."})}),b5=v5.safeExtend({contentHash:H}),y5=c({schemaVersion:b("openpond.profileEvaluationSuiteRun.v1"),id:T,suiteId:T,suiteHash:H,catalogHash:H,profileId:T,sourceRevision:i().trim().min(1).max(240),harnessRelease:W,members:p(c({definitionId:T,runManifest:W,runHash:H,passed:I(),score:u().min(0).max(1).nullable()}).strict()).min(1).max(1e3),passed:I(),createdAt:ye,completedAt:ye}).strict(),S5=y5.extend({contentHash:H}).strict(),$C=c({schemaVersion:b("openpond.optimizerTrainingSample.v1"),tokenIds:p(u().int().nonnegative()).min(2).max(32768),mask:p(I()).min(2).max(32768),logprobs:p(u().finite()).min(2).max(32768),temperatures:p(u().positive().finite()).min(2).max(32768),envName:i().trim().min(1).max(200),modelRequestId:i().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"})}),x5=c({id:T,environmentRelease:W,status:v(["completed","failed","timed_out","cancelled"]),startedAt:ye,completedAt:ye,traceRefs:p(Ma).max(1e4),metadata:Nn}).strict(),k5=c({receiptRef:W,status:Eb,value:u().min(0).max(1).nullable(),learningEligible:I(),passed:I(),outcomeClass:EC,failureOwner:Xm.nullable(),components:le(T,u().min(0).max(1).nullable())}).strict(),NC=c({schemaVersion:b("openpond.canonicalRolloutRecord.v1"),id:T,attemptRef:W,artifactManifestRef:W,tasksetRelease:W,environmentRelease:W,verifierSetRelease:W,harnessRelease:W,taskId:T,split:Xa,model:Am,seed:i().trim().min(1).max(500),reward:k5,traceRef:Ma,optimizerSample:$C.nullable(),environmentExecutions:p(x5).min(1).max(1e5),startedAt:ye,completedAt:ye,metadata:Nn}).strict();function DC(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."})}NC.superRefine(DC);c({...NC.shape,contentHash:H}).strict().superRefine(DC);const w5=i().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."),HC=vt([cl(),i().max(262144),u().finite(),c({integer:w5}).strict(),c({blobBase64:i().max(349528).regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/)}).strict()]),VS=i().min(1).max(128).refine(e=>!e.includes("\0")),I5=c({tables:p(c({name:VS,columns:p(c({name:VS,type:v(["INTEGER","REAL","TEXT","BLOB"])}).strict()).min(1).max(128),rows:p(p(HC).max(128)).max(4096)}).strict()).max(64)}).strict().superRefine((e,t)=>{const n=new Set;for(const[a,o]of e.tables.entries()){const r=o.name.toLowerCase();(n.has(r)||r.startsWith("sqlite_"))&&t.addIssue({code:"custom",path:["tables",a,"name"],message:"Table names must be unique and outside SQLite's reserved namespace."}),n.add(r),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."})}}),KS=c({schemaVersion:b("openpond.sqlExecution.v1"),snapshot:I5,sql:i().min(1).max(65536).refine(e=>!e.includes("\0")),maxRows:u().int().min(1).max(4096),maxResultBytes:u().int().min(256).max(262144)}).strict();ot("status",[c({status:b("completed"),columns:p(i()).max(128),rows:p(p(HC).max(128)).max(4096)}).strict(),c({status:b("rejected"),code:v(["invalid_query","multiple_statements","result_too_large","memory_limit"])}).strict()]);const iu=c({scope:v(["input","initialState","state","arguments"]),path:p(i().min(1).max(256)).max(16)}).strict(),WS={id:i().min(1).max(128),operation:v(["step","collect"]),toolName:i().min(1).max(500).optional(),timeoutMs:u().int().min(1).max(2e4)},_5=ot("kind",[c({...WS,kind:b("sqlite.v1"),sql:iu,snapshot:iu,maxRows:KS.shape.maxRows,maxResultBytes:KS.shape.maxResultBytes}).strict(),c({...WS,kind:b("javascript.v1"),source:iu,cases:iu,exportName:i().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."})}),C5=c({schemaVersion:b("openpond.javascriptEnvironment.v1"),id:i().trim().min(1).max(500),revision:u().int().positive(),module:bn.refine(e=>e.visibility==="host_private","Environment code belongs to the execution owner."),tools:p(Xc).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(_5).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)=>{mb(a.inputSchema).valid||t.addIssue({code:"custom",path:["tools",o,"inputSchema"],message:"Environment tools require a supported JSON schema."}),a.inputSchemaHash!==ct(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 r=e.tools.find(s=>s.name===a.toolName);a.operation==="step"&&!r&&t.addIssue({code:"custom",path:["executionServices",o,"toolName"],message:"Execution services must target a declared tool."}),a.timeoutMs>=Math.min(e.operationTimeoutMs,r?.timeoutMs??e.operationTimeoutMs)&&t.addIssue({code:"custom",path:["executionServices",o,"timeoutMs"],message:"Service budgets must leave time for the authored controller."})})}),R5=C5.safeExtend({contentHash:i().regex(/^[a-f0-9]{64}$/)});v(["create","reset","step","collect","destroy"]);c({state:le(i(),ce()),observation:le(i(),ce())}).strict();var P5=c({schemaVersion:b("openpond.connectedDatasetSource.v1"),kind:b("connected_activity"),id:i().min(1).max(240),profileId:i().min(1).max(240),title:i().min(1).max(500),sourceHash:i().regex(/^[a-f0-9]{64}$/),occurredAt:i().datetime(),licensingStatus:v(["pending","approved","review","blocked"]),secretScanStatus:v(["pending","passed","blocked"]),piiScanStatus:v(["pending","passed","review","blocked"]),origin:RC,sourceId:i().min(1).max(500),sessionId:i().min(1).max(500),normalizerVersion:i().min(1).max(200),projection:v(["turn","conversation"]),ownerUserId:i().min(1).max(500),purpose:b("recorded_evaluation"),metadata:le(i(),ce()).default({})}).strict(),Wa=i().trim().min(1).max(240),ho=i().trim().min(1),Fo=i().trim().min(8).max(256),LC=i().trim().min(1).max(1e3).refine(e=>!e.startsWith("/")&&!e.startsWith("\\")&&!e.split(/[\\/]/).includes(".."),"Artifact paths must be relative and stay inside the Dataset."),er=v(["train","validation","test","frozen_eval"]),A5=c({name:i().trim().min(1).max(500),semanticRole:v(["row_id","cluster_id","prompt","messages","demonstration","chosen","rejected","expected_output","privileged_context","reward","feedback","tag","metadata"]),logicalType:v(["string","integer","float","boolean","json","messages"]),nullable:I(),policy:v(["visible","privileged","metadata"])}),T5=c({schemaVersion:b("openpond.datasetSemanticSchema.v1"),fields:p(A5).min(1).max(1e4),schemaHash:Fo}),E5=c({id:Wa,split:er,path:LC,contentHash:Fo,schemaHash:Fo,sizeBytes:u().int().nonnegative(),rowCount:u().int().positive(),rowGroupCount:u().int().positive()}),Ob=c({schemaVersion:b("openpond.datasetArtifact.v1"),id:Wa,tasksetId:Wa,tasksetRevision:u().int().positive(),contentHash:Fo,format:b("parquet"),schema:T5,shards:p(E5).min(1).max(1e5),rowCount:u().int().positive(),splitCounts:le(er,u().int().nonnegative()),sourceReceiptRefs:p(Wa).min(1).max(1e5),mappingHash:Fo,qualityReportHash:Fo,createdAt:ho}),M5=c({schemaVersion:b("openpond.datasetArtifactSummary.v1"),artifactId:Wa,tasksetId:Wa,tasksetRevision:u().int().positive(),format:b("parquet"),rowCount:u().int().positive(),splitCounts:le(er,u().int().nonnegative()),sizeBytes:u().int().nonnegative(),contentHash:Fo,available:I(),unavailableReason:i().trim().min(1).max(2e3).nullable(),createdAt:ho}),j5=c({schemaVersion:b("openpond.datasetCatalogItem.v1"),tasksetId:Wa,tasksetRevision:u().int().positive(),artifactId:Wa.nullable(),name:i().trim().min(1).max(500),status:v(["draft","awaiting_disclosure_approval","awaiting_materialization_approval","materializing","validating","needs_review","baselining","ready","blocked","failed","archived"]),storageKind:v(["inline","parquet"]),rowCount:u().int().nonnegative(),splitCounts:le(er,u().int().nonnegative()),sizeBytes:u().int().nonnegative().nullable(),available:I(),unavailableReason:i().trim().min(1).max(2e3).nullable(),createdAt:ho,updatedAt:ho});c({schemaVersion:b("openpond.datasetCatalog.v1"),profileId:Wa,datasets:p(j5),generatedAt:ho});c({schemaVersion:b("openpond.datasetArtifactRegistry.v1"),manifest:Ob,profileId:Wa,storageRoot:i().trim().min(1).max(4e3),relativeManifestPath:LC,available:I(),unavailableReason:i().trim().min(1).max(2e3).nullable(),verifiedAt:ho.nullable(),createdAt:ho,updatedAt:ho});c({split:er.nullable().default(null),cursor:i().trim().min(1).max(2e3).nullable().default(null),limit:u().int().min(1).max(100).default(25),columns:p(i().trim().min(1).max(500)).max(100).default([])});c({schemaVersion:b("openpond.datasetRowPage.v1"),tasksetId:Wa,tasksetRevision:u().int().positive(),artifactHash:Fo,split:er.nullable(),rows:p(le(i(),ce())).max(100),nextCursor:i().max(2e3).nullable(),totalRows:u().int().nonnegative(),returnedRows:u().int().nonnegative()});var O5=c({schemaVersion:b("openpond.datasetStorageSettings.v1"),datasetStorePath:i().trim().min(1).max(4e3),updatedAt:ho}),$5=c({id:Wa,label:i().trim().min(1).max(500),path:i().trim().min(1).max(4e3),datasetStorePath:i().trim().min(1).max(4e3),kind:v(["local","network","removable","cache"]),configured:I(),mounted:I(),writable:I(),totalBytes:u().int().nonnegative().nullable(),freeBytes:u().int().nonnegative().nullable()});c({schemaVersion:b("openpond.datasetStorageState.v1"),settings:O5,storageRoots:p($5)});c({datasetStorePath:i().trim().min(1).max(4e3)});var Ls=i().trim().min(1).max(240),N5=i().trim().min(1),Xs=i().trim().min(8).max(256),D5=le(i(),ce()).default({}),H5=i().trim().min(7).max(256),L5=v(["pending","approved","review","blocked"]),tp=c({id:Ls,profileId:Ls,title:i().trim().min(1).max(500),sourceHash:Xs,occurredAt:N5,licensingStatus:L5,secretScanStatus:v(["pending","passed","blocked"]),piiScanStatus:v(["pending","passed","review","blocked"]),metadata:D5}),q5=tp.extend({schemaVersion:b("openpond.huggingFaceDatasetSource.v1"),kind:b("huggingface"),repositoryId:i().trim().regex(/^[^/\s]+\/[^/\s]+$/).max(500),repositoryUrl:i().url().max(2e3),revision:H5,configuration:i().trim().min(1).max(500),upstreamSplits:p(i().trim().min(1).max(500)).min(1).max(1e3),gated:I(),private:I(),declaredLicense:i().trim().min(1).max(500).nullable(),sourceFileHashes:p(Xs).min(1).max(1e5)}),U5=tp.extend({schemaVersion:b("openpond.uploadedFileDatasetSource.v1"),kind:b("uploaded_file"),originalFileNames:p(i().trim().min(1).max(500)).min(1).max(1e3),mediaTypes:p(i().trim().min(1).max(200)).min(1).max(1e3),sourceFileHashes:p(Xs).min(1).max(1e3),totalBytes:u().int().nonnegative(),parserVersion:i().trim().min(1).max(200)}),z5=tp.extend({schemaVersion:b("openpond.generatedDatasetSource.v1"),kind:b("generated"),generatorId:Ls,generatorVersion:i().trim().min(1).max(200),seed:u().int(),generatorHash:Xs}),B5=tp.extend({schemaVersion:b("openpond.learningBatchDatasetSource.v1"),kind:b("learning_batch"),batch:c({id:Ls,revision:u().int().positive(),contentHash:Xs}).strict(),taskDefinition:c({id:Ls,revision:u().int().positive(),contentHash:Xs}).strict(),admittedBy:Ls}),F5=ot("kind",[q5,U5,z5,B5]),V5=c({schemaVersion:b("openpond.harnessActionBinding.v1"),actionId:Ke,modelToolName:i().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:i().trim().min(1).max(1e3),inputSchema:le(i(),ce()),actionSchemaHash:Qe,agentRelease:He,implementationHash:Qe,runtimeBindingId:Ke,capabilityReceiptHash:Qe,sideEffect:v(["read","write"]),studentVisible:I(),timeoutMs:u().int().positive().max(36e5),episodeArgumentBindings:p(c({argument:Ke,source:b("case_id")}).strict()).max(20).default([])}).strict(),jt=i().trim().min(1).max(240),$b=i().trim().min(1),K5=i().trim().min(8).max(256),Nb=i().trim().regex(/^[a-f0-9]{64}$/),W5=i().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),hi=le(i(),ce()).default({}),np=jt.nullable();function md(e){const t=e.trim().replaceAll("\\","/");return!t||t.startsWith("/")||t==="."||t===".."?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function G5(e){const t=e.trim();return t.length>0&&t!=="."&&t!==".."&&!t.includes("/")&&!t.includes("\\")&&!t.includes("\0")}var el=er,qC=v(["general","benchmark"]),UC=c({schemaVersion:b("openpond.tasksetBenchmark.v1"),definitionId:jt,releaseId:jt,releaseHash:Nb,managedReleasePath:i().trim().min(1).max(1e3).refine(md,"Benchmark release paths must remain relative."),adaptationSplit:el,evaluationSplit:el,primaryMetric:v(["foreground_tokens","success_rate","latency_ms","cost_usd"]),qualityGate:v(["none","non_regression","all_pass"]),source:v(["builtin","imported"]),metadata:hi}),zC=c({schemaVersion:b("openpond.tasksetPreferenceComparisonBinding.v1"),releaseId:jt,releaseHash:Nb,publishedAt:$b,metadata:hi}),J5=c({status:v(["pending","granted","denied","revoked"]),scope:v(["metadata_only","selected_turns","full_session"]),grantedBy:np,grantedAt:$b.nullable(),purpose:b("task_authoring_and_evaluation")}),BC=c({schemaVersion:b("openpond.trainingSource.v1"),id:jt,profileId:jt,sessionId:jt,turnIds:p(jt).max(1e3).default([]),workspaceId:np,sourceHash:K5,clusterKey:jt,title:i().trim().min(1).max(500),occurredAt:$b,consent:J5,connectedAppIds:p(jt).max(100).default([]),secretScanStatus:v(["pending","passed","blocked"]),piiScanStatus:v(["pending","passed","review","blocked"]),licensingStatus:v(["pending","approved","review","blocked"]),metadata:hi}),FC=vt([BC,F5,P5]),Db=c({policyVisibleFields:p(jt).max(1e3).default([]),privilegedFields:p(jt).max(1e3).default([]),hiddenGraderRefs:p(jt).max(100).default([]),connectedAppScopes:p(jt).max(100).default([])}),Z5=c({id:jt,sourceRefId:jt,artifactRef:i().trim().min(1).max(4e3).refine(md,"Task asset references must be safe relative paths."),fileName:i().trim().min(1).max(500).refine(G5,"Task asset file names must not contain path separators."),mediaType:i().trim().min(1).max(200),sha256:Nb,sizeBytes:u().int().nonnegative().max(25e7),split:el,metadata:hi}),Y5=c({path:i().trim().min(1).max(1e3).refine(md,"Required output paths must stay inside the Work output directory."),mediaType:i().trim().min(1).max(200),schemaRef:jt.nullable().optional(),maxBytes:u().int().positive().max(1e7).optional(),metadata:hi}),ap=c({schemaVersion:b("openpond.taskData.v1"),id:jt,clusterKey:jt,split:el,input:le(i(),ce()),expectedOutput:le(i(),ce()).nullable(),policyVisibleContext:le(i(),ce()).default({}),privilegedContextRef:np,sourceRefs:p(jt).min(1).max(100),assets:p(Z5).max(1e3).optional(),resourceRefs:p(jt).max(1e3).optional(),requiredOutputs:p(Y5).max(100).optional(),tags:p(jt).max(100).default([]),metadata:hi}),Q5=c({id:jt,kind:v(["file","catalog","configuration","code_module"]),path:i().trim().min(1).max(1e3).refine(md,"Environment resource paths must remain relative."),mediaType:i().trim().min(1).max(200).nullable().optional(),visibility:v(["policy_visible","policy_hidden","privileged"]),required:I(),metadata:hi}),gl=c({id:jt,taskId:np,sourceRefs:p(jt).min(1).max(100),artifactRef:jt,approved:I(),confidence:u().min(0).max(1),metadata:hi}),VC=gl.extend({kind:b("demonstration"),prompt:i().max(1e5).nullable().default(null),response:i().max(2e5).nullable().default(null)}),KC=gl.extend({kind:b("preference"),prompt:i().max(1e5),chosen:i().max(2e5),rejected:i().max(2e5),rationale:i().max(1e5).nullable().default(null)}),WC=gl.extend({kind:b("correction"),original:i().max(2e5),corrected:i().max(2e5),rationale:i().max(1e5).nullable().default(null)}),GC=gl.extend({kind:b("feedback"),feedback:i().max(1e5),polarity:v(["positive","negative","mixed","neutral"])}),JC=gl.extend({kind:b("reward"),task:i().max(1e5),rules:p(c({id:jt,points:u().finite(),condition:i().trim().min(1).max(1e5)})).min(1).max(1e3),otherwisePoints:u().finite(),executable:I()}),ZC=gl.extend({kind:b("label"),labelKind:b("rubric"),task:i().max(1e5),criteria:p(c({id:jt,label:i().trim().min(1).max(500),description:i().trim().min(1).max(1e5)})).min(1).max(1e3),calibrationExamples:c({positive:i().trim().min(1).max(2e5),negative:i().trim().min(1).max(2e5),boundary:i().trim().min(1).max(2e5)})});ot("kind",[VC,KC,WC,GC,JC,ZC]);var YC=c({demonstrations:p(VC).max(1e5).default([]),preferences:p(KC).max(1e5).default([]),corrections:p(WC).max(1e5).default([]),feedback:p(GC).max(1e5).default([]),rewards:p(JC).max(1e5).default([]),labels:p(ZC).max(1e5).default([])}),QC=c({protocolVersion:b("openpond.taskEnvironment.v1"),kind:v(["chat","agent","program","stateful_harness","work"]),entrypoint:i().trim().min(1).max(1e3),stateful:I(),deterministicSeeds:I(),toolNames:p(jt).max(200).default([]),actionBindings:p(V5).max(200).optional(),lifecycle:p(v(["create","reset","step","grade","cleanup"])).min(1),defaultTimeoutMs:u().int().positive().max(36e5),networkPolicy:v(["none","declared_read_only","declared_scoped"]),resources:p(Q5).max(1e4).optional(),metadata:hi}),Hb=c({schemaVersion:b("openpond.tasksetCapabilities.v1"),taskKind:v(["chat","single_agent","multi_agent","custom_program"]),supportedSignals:p(v(["demonstration","preference","correction","feedback","reward","label"])),compatibleMethods:p(v(["none","retrieval","sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"])),rewardKinds:p(v(["none","exact","deterministic","model_judge","human"])),requiresTools:I(),requiresState:I(),requiresPrivilegedGrading:I(),environmentPlacements:p(v(["local","remote","colocated","provider_native"])),exportable:I(),portabilityBlockers:p(i().trim().min(1).max(2e3)).default([])}),ip=c({id:jt,version:i().trim().min(1).max(100),label:i().trim().min(1).max(500),weight:u().min(0).max(1e3).default(1),hardGate:I().default(!1),rewardEligible:I().default(!1),privileged:I().default(!1),metadata:hi}),X5=ip.extend({kind:v(["content","schema","file","diff","test","runtime_event","state"]),config:le(i(),ce())}),e3=ip.extend({kind:b("model_judge"),rubric:i().trim().min(1).max(5e4),judge:Pb,calibrationFixtureRefs:p(jt).min(1).max(500),calibrationStatus:v(["pending","passed","failed"]),temperature:u().min(0).max(2).default(0)}),t3=ip.extend({kind:b("human"),form:od.optional(),rubric:i().trim().min(1).max(5e4),reviewerRole:i().trim().min(1).max(500)}),n3=ip.extend({kind:b("custom_verifier"),runtime:b_.optional(),module:i().trim().min(1).max(1e3).refine(md,"Custom verifier modules must use a safe relative path."),exportName:W5,timeoutMs:u().int().positive().max(3e5),networkPolicy:b("none")}),op=vt([X5,e3,t3,n3]),Lb=v(["positive","negative","boundary","adversarial","prompt_injection","infrastructure_failure"]),XC=c({id:jt,taskId:jt,label:Lb,output:le(i(),ce()),infrastructureError:i().trim().min(1).max(1e4).nullable(),expectedPassed:I(),expectedRewardEligible:I(),metadata:hi});i().regex(/^[a-f0-9]{64}$/);var a3=c({environment:Mb,verifierSet:jb,javascript:R5}).strict();c({actions:p(c({name:i().min(1).max(64),arguments:le(i(),ce())}).strict()).max(1e3)}).strict();var i3=c({environment:Mb,verifierSet:jb}).strict(),o3=c({scopeId:i().trim().min(1).max(500),modelId:i().trim().min(1).max(500)}).strict();c({schemaVersion:b("openpond.modelTasksetDerivation.v1"),owner:o3,root:la,parent:la}).strict();var r3=c({taskset:w_,taskDefinition:cd,rewardBinding:Fm,rewards:p(sd).min(1).max(100),assets:p(Gm).max(1e3),executionResources:i3.optional(),execution:a3.optional(),instructionMode:b("per_task").optional()}).strict(),s3=c({batch:Sb,evidence:p(Wm).min(1).max(1e4),decisions:p(yb).min(1).max(1e4),sources:p(Km).min(1).max(1e4),assets:p(Gm).max(1e3)}).strict(),l3=64*1024*1024,c3=c({asset:di,base64:i().max(Math.ceil(l3/3)*4)}).strict();c({schemaVersion:b("openpond.connectedRewardCalibrationProjection.v1"),sourceReward:Xo,fixtureSet:di,calibrationCheck:lt,fixture:K_,fixtureHash:i().regex(/^[a-f0-9]{64}$/),checkResultHash:i().regex(/^[a-f0-9]{64}$/),independentCalibrationTask:b(!0),closureRef:di,graderId:i().min(1).max(240).optional()}).strict();var d3=r3.omit({taskset:!0,executionResources:!0}),u3=c({schemaVersion:b("openpond.tasksetPackage.v1"),taskset:w_,environment:Mb,verifierSet:jb,files:p(c3).max(1e4),modelResources:d3.optional(),learningResources:s3.optional()}).strict(),Mr=u3.extend({contentHash:i().regex(/^[a-f0-9]{64}$/)}).strict(),ji=i().trim().min(1).max(500),Cu=i().regex(/^[a-f0-9]{64}$/),m3=sB.pick({portableProjectId:!0,name:!0,objective:!0,defaultBaseModel:!0,defaultDestinationId:!0,sourceRevision:!0,sourceUpdatedAt:!0}).extend({trainingSetup:_b.omit({tasksetRef:!0,rewardBindingRef:!0,tasksetRelease:!0})}).strict();c({schemaVersion:b("openpond.tasksetPackagePublication.v1"),operationId:ji,modelProjectId:ji,expectedProjectEtag:Cu.nullable(),name:i().trim().min(1).max(200),description:i().max(5e3),buildIntent:v(["demonstrations","preferences","verifiable_reward","rubric","discovery"]),methodHint:v(["sft","dpo","grpo","ppo"]).nullable(),package:Mr,modelConfiguration:m3.optional(),evaluationPackage:Mr.optional(),selection:v(["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&&Tt(e.modelConfiguration.trainingSetup.evaluationTasksetRef)===Tt(g4(e.evaluationPackage.taskset)),"Evaluation package must match the selected immutable evaluation in Model configuration.");c({schemaVersion:b("openpond.tasksetPackageReceipt.v1"),teamId:ji,modelProjectId:ji,operationId:ji,taskset:em,packageHash:Cu,hostedTasksetId:ji,projectEtag:Cu,project:Jm.optional(),selection:v(["select","attach"]).optional(),evaluation:c({taskset:em,packageHash:Cu,hostedTasksetId:ji}).strict().optional()}).strict();c({schemaVersion:b("openpond.tasksetPackageReadback.v1"),teamId:ji,modelProjectId:ji,package:Mr}).strict();c({schemaVersion:b("openpond.tasksetReleasePackageReadback.v1"),teamId:ji,release:em,package:Mr}).strict();var $i=i().trim().min(1).max(240),Oc=i().trim().min(1),rm=i().trim().min(8).max(256),eR=le(i(),ce()).default({}),p3=$i.nullable(),f3=["work_capabilities","work_environment","work_list_files","work_read_file","work_read_document","work_write_file","work_write_docx","work_edit_file","work_delete_file","work_exec","work_save_output","work_stop"],h3=v(["draft","awaiting_disclosure_approval","awaiting_materialization_approval","materializing","validating","needs_review","baselining","ready","blocked","failed","archived"]),tR=v(["demonstrations","preferences","verifiable_reward","rubric","discovery"]),na=i().trim().max(1e5),nR=ot("kind",[c({kind:b("demonstrations"),behavior:na,examples:p(c({id:$i,prompt:na,response:na})).max(1e3).default([])}),c({kind:b("preferences"),preference:na,pairs:p(c({id:$i,prompt:na,chosen:na,rejected:na,rationale:na})).max(1e3).default([])}),c({kind:b("verifiable_reward"),task:na,rules:p(c({id:$i,points:u().finite(),condition:na})).max(1e3).default([]),otherwisePoints:u().finite().default(0)}),c({kind:b("rubric"),task:na,criteria:p(c({id:$i,label:i().trim().max(500),description:na})).max(1e3).default([]),positiveExample:na,negativeExample:na,boundaryExample:na})]),g3=c({path:i().trim().min(1).max(1e3),role:v(["environment","verifier","fixture"]),content:i().max(25e4)}),aR=c({primaryMethod:v(["sft","dpo","grpo","ppo","sdft","opsd","sdpo"]),bootstrap:c({method:b("sft"),purpose:b("trajectory_bootstrap"),demonstrationRefs:p($i).min(1).max(1e5),limitations:p(i().trim().min(1).max(5e3)).min(1).max(100)}).nullable()}),iR=v(["taskset_not_ready","demonstrations_missing","preference_pairs_missing","preference_pairs_invalid","executable_reward_missing","reward_not_calibrated","reward_model_missing","value_model_required","frozen_eval_missing"]),v3=c({method:v(["sft","dpo","grpo","ppo"]),status:v(["recommended","compatible","needs_dataset_work"]),reasonCodes:p(iR).default([]),reasons:p(i().trim().min(1).max(5e3)).default([])}),GS=c({code:$i,message:i().trim().min(1).max(5e3),path:i().trim().max(2e3).nullable()}),oR=c({schemaVersion:b("openpond.tasksetReadiness.v1"),tasksetId:$i,tasksetHash:rm,ready:I(),recommendedMethod:v(["none","retrieval","sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),trainingPath:aR.nullable().default(null),methodReadiness:p(v3).default([]),compatibleDestinationClasses:p(v(["export","custom","hosted_managed"])),blockers:p(GS).default([]),advisories:p(GS).default([]),warnings:p(i().trim().min(1).max(5e3)).default([]),generatedAt:Oc}),rR=c({attempt:u().int().positive(),summary:i().trim().min(1).max(5e3),createdAt:Oc}),b3=c({schemaVersion:b("openpond.taskAuthoringProvenance.v1"),model:Pb.nullable(),modelConfig:eR,skillHash:rm,promptTemplateVersion:i().trim().min(1).max(200),buildIntent:tR.default("demonstrations"),buildSpecification:nR.nullable().default(null),evidenceHashes:p(rm).max(1e5),tasksetSdkVersion:i().trim().min(1).max(100),sourceCommit:i().trim().min(1).max(256).nullable(),repairHistory:p(rR).max(1e3),createdAt:Oc}),$c=c({schemaVersion:b("openpond.taskset.v1"),id:$i,revision:u().int().positive().default(1),profileId:$i,profileRelease:hB.nullable().optional(),createImproveRunId:p3.default(null),name:i().trim().min(1).max(500),objective:i().trim().max(2e4),purpose:qC.default("general"),benchmark:UC.nullable().default(null),preferenceComparison:zC.nullable().default(null),status:h3,sourceRefs:p(FC).min(1).max(1e5),datasetArtifact:Ob.nullable().optional(),policy:Db,environment:QC,capabilities:Hb,metrics:id.optional(),tasks:p(ap).max(1e6),graders:p(op).min(1).max(1e3),graderFixtures:p(XC).max(1e5),learningSignals:YC,authoringProvenance:b3,readiness:oR.nullable(),contentHash:rm,createdAt:Oc,updatedAt:Oc,metadata:eR}).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 sR(e){return e.schemaVersion==="openpond.trainingSource.v1"}function y3(e,t={}){const n=$c.safeParse(e);if(!n.success)return{valid:!1,taskset:null,computedHash:null,issues:n.error.issues.map(s=>({code:"schema_invalid",severity:"error",message:s.message,path:s.path.join(".")}))};const a=n.data,o=[];w3(a,o),x3(a,o),I3(a,o),C3(a,o),R3(a,o),S3(a,o,t),P3(a,o),A3(a.capabilities,o,a),_3(a,o);const r=lR(a);return a.contentHash!==r&&o.push({code:"content_hash_mismatch",severity:"error",message:`Taskset contentHash is ${a.contentHash}, expected ${r}.`,path:"contentHash"}),{valid:!o.some(s=>s.severity==="error"),taskset:a,computedHash:r,issues:o}}function S3(e,t,n){const a=e.graders.length>0&&e.graders.every(s=>s.kind==="human");!a&&!e.graderFixtures.length&&!(n.allowUnscoredOnlineRewardBatch&&e.metadata.trainingMethod==="grpo"&&e.metadata.learning)&&t.push({code:"grader_fixtures_required",severity:"error",message:"Taskset admission requires authored grader fixtures.",path:"graderFixtures"});const o=new Set(e.tasks.map(s=>s.id)),r=new Set(["positive","negative","boundary","adversarial","prompt_injection","infrastructure_failure"]);for(const s of e.graderFixtures)!e.datasetArtifact&&!o.has(s.taskId)&&t.push({code:"grader_fixture_task_missing",severity:"warning",message:`Fixture ${s.id} references a task outside this Taskset revision (${s.taskId}).`,path:`graderFixtures.${s.id}.taskId`}),r.delete(s.label),s.label==="infrastructure_failure"&&!s.infrastructureError&&t.push({code:"infrastructure_fixture_error_missing",severity:"error",message:`Infrastructure fixture ${s.id} must declare an infrastructure error.`,path:`graderFixtures.${s.id}.infrastructureError`});for(const s of a?[]:r)t.push({code:"grader_fixture_missing",severity:"warning",message:`Taskset does not include the optional ${s} grader calibration fixture.`,path:"graderFixtures"})}function x3(e,t){const n=e.datasetArtifact;if(!n)return;(n.tasksetId!==e.id||n.tasksetRevision!==e.revision)&&t.push({code:"dataset_artifact_taskset_mismatch",severity:"error",message:"Dataset artifact identity does not match its Taskset revision.",path:"datasetArtifact"});const a=Object.values(n.splitCounts).reduce((m,d)=>m+d,0),o=n.shards.reduce((m,d)=>m+d.rowCount,0);(a!==n.rowCount||o!==n.rowCount)&&t.push({code:"dataset_artifact_row_count_mismatch",severity:"error",message:"Dataset artifact row, split, and shard counts do not agree.",path:"datasetArtifact.rowCount"});const r=new Map;for(const m of n.shards)r.set(m.split,(r.get(m.split)??0)+m.rowCount);for(const[m,d]of Object.entries(n.splitCounts))(r.get(m)??0)!==d&&t.push({code:"dataset_artifact_split_count_mismatch",severity:"error",message:`Dataset artifact ${m} shard counts do not match its manifest.`,path:`datasetArtifact.splitCounts.${m}`});const{contentHash:s,...l}=n;Tt(l)!==n.contentHash&&t.push({code:"dataset_artifact_hash_mismatch",severity:"error",message:"Dataset artifact manifest content hash is invalid.",path:"datasetArtifact.contentHash"})}function k3(e){return lR(e)}function lR(e){const{contentHash:t,status:n,readiness:a,updatedAt:o,...r}=e;return Tt(r)}function w3(e,t){for(const[n,a]of e.sourceRefs.entries())sR(a)&&a.consent.status!=="granted"&&t.push({code:"source_consent_missing",severity:"error",message:`Source ${a.id} is not consented.`,path:`sourceRefs.${n}.consent.status`}),a.secretScanStatus!=="passed"&&t.push({code:"source_secret_scan",severity:"error",message:`Source ${a.id} did not pass secret scanning.`,path:`sourceRefs.${n}.secretScanStatus`}),a.piiScanStatus!=="passed"&&t.push({code:"source_pii_scan",severity:"error",message:`Source ${a.id} has unresolved PII policy.`,path:`sourceRefs.${n}.piiScanStatus`}),a.licensingStatus!=="approved"&&t.push({code:"source_license",severity:"error",message:`Source ${a.id} has unresolved licensing policy.`,path:`sourceRefs.${n}.licensingStatus`})}function I3(e,t){const n=new Map;for(const o of e.tasks){const r=n.get(o.clusterKey)??new Set;r.add(o.split),n.set(o.clusterKey,r)}for(const[o,r]of n)r.size>1&&t.push({code:"split_cluster_contamination",severity:"error",message:`Source cluster ${o} appears in multiple splits: ${[...r].join(", ")}.`,path:"tasks"});(e.datasetArtifact?e.datasetArtifact.splitCounts.frozen_eval??0:e.tasks.filter(o=>o.split==="frozen_eval").length)===0&&t.push({code:"frozen_eval_missing",severity:"warning",message:"Add an independent test example before training.",path:"tasks"})}function _3(e,t){if(e.environment.kind!=="work")return;e.environment.entrypoint!=="openpond-work-v1"&&t.push({code:"work_entrypoint_invalid",severity:"error",message:"Work Tasksets must use the openpond-work-v1 entrypoint.",path:"environment.entrypoint"}),(!e.environment.lifecycle.includes("reset")||!e.environment.lifecycle.includes("cleanup"))&&t.push({code:"work_reset_lifecycle_missing",severity:"error",message:"Work attempts require reset and cleanup; filesystem state belongs to one attempt.",path:"environment.lifecycle"});const n=new Set(f3),a=e.environment.toolNames.filter(r=>!n.has(r));a.length&&t.push({code:"work_tool_unknown",severity:"error",message:`Work Taskset declares unknown tools: ${a.join(", ")}.`,path:"environment.toolNames"}),e.environment.toolNames.includes("work_save_output")||t.push({code:"work_output_tool_missing",severity:"error",message:"Work Tasksets must declare work_save_output.",path:"environment.toolNames"});for(const r of["create","reset","step","grade","cleanup"])e.environment.lifecycle.includes(r)||t.push({code:"work_lifecycle_incomplete",severity:"error",message:`Work Tasksets require the ${r} lifecycle stage.`,path:"environment.lifecycle"});const o=new Map(e.sourceRefs.map(r=>[r.id,r]));for(const[r,s]of e.tasks.entries()){const l=new Set,m=new Set;for(const[f,g]of(s.assets??[]).entries()){const x=`tasks.${r}.assets.${f}`;l.has(g.id)&&t.push({code:"work_asset_duplicate_id",severity:"error",message:`Task ${s.id} repeats asset id ${g.id}.`,path:`${x}.id`}),m.has(g.fileName)&&t.push({code:"work_asset_duplicate_name",severity:"error",message:`Task ${s.id} repeats staged file name ${g.fileName}.`,path:`${x}.fileName`}),l.add(g.id),m.add(g.fileName),s.sourceRefs.includes(g.sourceRefId)||t.push({code:"work_asset_task_source_missing",severity:"error",message:`Asset ${g.id} references source ${g.sourceRefId} outside task ${s.id}.`,path:`${x}.sourceRefId`});const k=o.get(g.sourceRefId);k?"sourceFileHashes"in k&&!k.sourceFileHashes.includes(g.sha256)&&t.push({code:"work_asset_hash_unregistered",severity:"error",message:`Asset ${g.id} hash is not registered by source ${g.sourceRefId}.`,path:`${x}.sha256`}):t.push({code:"work_asset_source_missing",severity:"error",message:`Asset ${g.id} references missing source ${g.sourceRefId}.`,path:`${x}.sourceRefId`}),k&&"kind"in k&&k.kind==="uploaded_file"&&!k.originalFileNames.includes(g.fileName)&&t.push({code:"work_asset_name_unregistered",severity:"error",message:`Asset ${g.id} file name is not registered by source ${g.sourceRefId}.`,path:`${x}.fileName`}),k&&"kind"in k&&k.kind==="uploaded_file"&&!k.mediaTypes.includes(g.mediaType)&&t.push({code:"work_asset_media_type_unregistered",severity:"error",message:`Asset ${g.id} media type is not registered by source ${g.sourceRefId}.`,path:`${x}.mediaType`}),g.split!==s.split&&t.push({code:"work_asset_split_mismatch",severity:"error",message:`Asset ${g.id} is assigned to ${g.split}, not task split ${s.split}.`,path:`${x}.split`})}const d=new Set;for(const[f,g]of(s.requiredOutputs??[]).entries()){const x=g.path.replaceAll("\\","/"),k=`tasks.${r}.requiredOutputs.${f}.path`;d.has(x)&&t.push({code:"work_output_duplicate_path",severity:"error",message:`Task ${s.id} repeats required output path ${x}.`,path:k}),d.add(x)}(s.requiredOutputs??[]).length===0&&t.push({code:"work_output_missing",severity:"error",message:`Work task ${s.id} must declare at least one required output.`,path:`tasks.${r}.requiredOutputs`})}}function C3(e,t){const n=new Set(e.policy.policyVisibleFields);for(const a of e.policy.privilegedFields)n.has(a)&&t.push({code:"privileged_field_visible",severity:"error",message:`Field ${a} is both policy-visible and privileged.`,path:"policy"});for(const a of e.tasks)a.privilegedContextRef&&Object.keys(a.policyVisibleContext).includes(a.privilegedContextRef)&&t.push({code:"privileged_context_leak",severity:"error",message:`Task ${a.id} exposes its privileged context reference.`,path:`tasks.${a.id}.policyVisibleContext`})}function R3(e,t){const n=new Set;for(const a of e.graders)n.has(a.id)&&t.push({code:"grader_duplicate",severity:"error",message:`Duplicate grader id ${a.id}.`,path:"graders"}),n.add(a.id),a.kind==="model_judge"&&a.rewardEligible&&a.calibrationStatus!=="passed"&&t.push({code:"judge_calibration_pending",severity:"warning",message:`Model judge ${a.id} is selected for reward without a passing advisory calibration report.`,path:`graders.${a.id}`}),a.kind==="model_judge"&&a.calibrationStatus==="passed"&&typeof a.metadata.calibrationEvidenceHash!="string"&&t.push({code:"judge_calibration_evidence_missing",severity:"warning",message:`Model judge ${a.id} declares calibration without an OpenPond fixture evidence hash.`,path:`graders.${a.id}.metadata.calibrationEvidenceHash`}),a.kind==="human"&&a.rewardEligible&&t.push({code:"human_online_reward",severity:"error",message:`Human grader ${a.id} cannot be an online optimizer reward.`,path:`graders.${a.id}`})}function P3(e,t){const n=new Set(e.tasks.map(o=>o.id)),a=new Set(e.sourceRefs.map(o=>o.id));for(const o of[...e.learningSignals.demonstrations,...e.learningSignals.preferences,...e.learningSignals.corrections,...e.learningSignals.feedback,...e.learningSignals.rewards,...e.learningSignals.labels])o.taskId&&!e.datasetArtifact&&!n.has(o.taskId)&&t.push({code:"learning_signal_task_missing",severity:"error",message:`Signal ${o.id} references missing task ${o.taskId}.`,path:`learningSignals.${o.kind}.${o.id}.taskId`}),o.sourceRefs.some(r=>!a.has(r))&&t.push({code:"learning_signal_source_missing",severity:"error",message:`Signal ${o.id} references a source outside the Dataset.`,path:`learningSignals.${o.kind}.${o.id}.sourceRefs`});for(const o of e.learningSignals.preferences)o.chosen.trim()===o.rejected.trim()&&t.push({code:"preference_pair_identical",severity:"error",message:`Preference ${o.id} has identical chosen and rejected responses.`,path:`learningSignals.preferences.${o.id}`});for(const o of e.learningSignals.rewards)o.executable||t.push({code:"reward_not_executable",severity:"warning",message:`Reward ${o.id} is a reviewed specification but has no executable verifier yet.`,path:`learningSignals.rewards.${o.id}.executable`})}function A3(e,t,n){!e.exportable&&e.portabilityBlockers.length===0&&t.push({code:"portability_reason_missing",severity:"error",message:"Non-exportable Tasksets must declare a portability blocker.",path:"capabilities.portabilityBlockers"}),e.compatibleMethods.includes("grpo")&&!e.rewardKinds.some(a=>a==="exact"||a==="deterministic"||a==="model_judge")&&t.push({code:"grpo_reward_missing",severity:"error",message:"GRPO compatibility requires a scalar reward kind.",path:"capabilities.rewardKinds"}),n?.capabilities.compatibleMethods.includes("sft")&&n.learningSignals.demonstrations.length===0&&t.push({code:"sft_demonstrations_missing",severity:"error",message:"SFT compatibility requires approved demonstrations.",path:"learningSignals.demonstrations"}),n?.capabilities.compatibleMethods.includes("dpo")&&n.learningSignals.preferences.length===0&&t.push({code:"dpo_preferences_missing",severity:"error",message:"DPO compatibility requires chosen and rejected response pairs.",path:"learningSignals.preferences"}),n&&(n.capabilities.compatibleMethods.includes("grpo")||n.capabilities.compatibleMethods.includes("ppo"))&&!n.learningSignals.rewards.some(a=>a.executable)&&!n.graders.some(a=>a.rewardEligible&&a.weight>0&&a.kind!=="human")&&t.push({code:"online_reward_not_executable",severity:"error",message:"GRPO/PPO compatibility requires an executable scalar reward.",path:"learningSignals.rewards"})}var Ts=i().trim().min(1).max(240),JS=i().trim().min(1),T3=i().trim().min(8).max(256),E3=i().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),M3=le(i(),ce()).default({});function ZS(e){const t=e.trim().replaceAll("\\","/");return!t||t.startsWith("/")||t==="."||t===".."?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}var cR=ap.extend({sourceRefs:p(Ts).max(100).default([])}),dR=v(["draft","validating","needs_review","published"]),j3=c({enabled:I(),candidateCount:u().int().min(2).max(4),minimumSamples:u().int().min(1).max(1e4).default(100),allowTies:I(),allowRejectAll:I(),rubric:i().trim().max(5e4),criteria:p(c({id:Ts,label:i().trim().min(1).max(500),description:i().trim().max(1e4),weight:u().nonnegative().max(1e3)})).max(100)}),O3=c({mode:v(["text","structured_json","artifacts"]),jsonSchema:le(i(),ce()).nullable(),renderer:c({module:i().trim().min(1).max(1e3).refine(ZS,"Renderer modules must use a safe relative path."),exportName:E3,configRef:i().trim().min(1).max(1e3).refine(ZS,"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"]})}),Ja=c({schemaVersion:b("openpond.tasksetDraft.v1"),id:Ts,revision:u().int().positive(),profileId:Ts,modelScope:c({modelId:Ts,expectedModelRevision:u().int().positive(),source:W4.optional()}).strict().nullable().default(null),name:i().trim().max(500),objective:i().trim().max(2e4),purpose:qC.default("general"),benchmark:UC.nullable().default(null),preferenceComparison:zC.nullable().default(null),status:dR,sourceRefs:p(FC).max(1e5).default([]),datasetArtifact:Ob.nullable().optional(),policy:Db,environment:QC,output:O3.default({mode:"text",jsonSchema:null,renderer:null}),capabilities:Hb,metrics:id,review:j3,tasks:p(cR).max(1e6).default([]),graders:p(op).max(1e3).default([]),graderFixtures:p(XC).max(1e5).default([]),learningSignals:YC,publishedTasksetRef:c({id:Ts,revision:u().int().positive(),contentHash:T3}).nullable(),createdAt:JS,updatedAt:JS,metadata:M3}).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"]})}),$3=6e6,N3=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 D3(e){const t=dd.parse(e);return!N3.has(t)&&!t.startsWith("source-artifacts/")}function YS(e,t){const n=D3(e);if(t.byteLength>$3)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)?QS(t):{encoding:"utf8",data:o}}catch{a=QS(t)}return{path:e,writable:n,content:a,sizeBytes:t.byteLength,contentHash:cC(t)}}function QS(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 XS=64*1024*1024,uR=i().regex(/^[a-f0-9]{64}$/),H3=c({path:dd,contentHash:uR,sizeBytes:u().int().nonnegative().max(XS),base64:i().max(XS)}).strict(),L3=c({schemaVersion:b("openpond.tasksetDraftWorkspace.v1"),draft:Ja,files:p(H3).max(1e4)}).strict(),Sie=L3.extend({contentHash:uR}).strict(),ex=class extends Error{issues;constructor(e){super(e.map(t=>t.message).join(`
|
|
190
|
-
`)),this.name="TasksetDraftPublishError",this.issues=e}};function q3(e){const t=[];e.name.trim()||t.push({code:"name_missing",message:"Name is required.",path:"name"}),e.objective.trim()||t.push({code:"objective_missing",message:"Objective is required.",path:"objective"}),!e.datasetArtifact&&e.tasks.length===0&&t.push({code:"tasks_missing",message:"Add at least one task or Dataset artifact.",path:"tasks"}),e.graders.length===0&&t.push({code:"graders_missing",message:"Add at least one grader.",path:"graders"}),!(e.graders.length>0&&e.graders.every(o=>o.kind==="human"))&&e.graderFixtures.length===0&&t.push({code:"grader_fixtures_missing",message:"Add grader fixtures before publishing.",path:"graderFixtures"});const a=new Set(e.sourceRefs.map(o=>o.id));for(const o of e.tasks)for(const r of o.sourceRefs)a.has(r)||t.push({code:"task_source_missing",message:`Task ${o.id} references missing source ${r}.`,path:`tasks.${o.id}.sourceRefs`});return t}function xie(e){const t=Ja.parse(e.draft),n=e.now??new Date().toISOString(),a=q3(t);if(a.length)throw new ex(a);const o=t.modelScope?.source;if(o&&e.tasksetId&&e.tasksetId!==o.tasksetId)throw new Error("Taskset draft publication differs from its prepared identity.");const r=o?.tasksetId||e.tasksetId?.trim()||t.publishedTasksetRef?.id||t.id.replace(/-draft$/,""),s=o?.tasksetRevision??(t.publishedTasksetRef?.id===r?t.publishedTasksetRef.revision+1:1),l=t.sourceRefs.length?t.sourceRefs:[U3(t,r,n)],m=l[0].id,d=t.tasks.map($=>ap.parse({...$,sourceRefs:$.sourceRefs.length?$.sourceRefs:[m],metadata:{exampleOrigin:"expert_authored",...$.metadata}})),f=t.capabilities.compatibleMethods.find($=>$!=="none"&&$!=="retrieval")??null,g=z3(t),x=t.graders.filter($=>$.rewardEligible&&$.weight>0&&$.kind!=="human"),k=f===null&&g==="verifiable_reward"&&x.length>0,C=f??(k?"grpo":null),R=$c.parse({schemaVersion:"openpond.taskset.v1",id:r,revision:s,profileId:t.profileId,profileRelease:null,createImproveRunId:null,name:t.name,objective:t.objective,purpose:t.purpose,benchmark:t.benchmark,preferenceComparison:t.preferenceComparison,status:"needs_review",sourceRefs:l,datasetArtifact:t.datasetArtifact??null,policy:t.policy,environment:t.environment,capabilities:k?{...t.capabilities,compatibleMethods:["grpo"],rewardKinds:[...new Set(x.map($=>$.kind==="model_judge"?"model_judge":"deterministic"))]}:t.capabilities,metrics:t.metrics,tasks:d,graders:t.graders,graderFixtures:t.graderFixtures,learningSignals:t.learningSignals,authoringProvenance:{schemaVersion:"openpond.taskAuthoringProvenance.v1",model:null,modelConfig:{},skillHash:Tt("openpond-taskset-draft-authoring-v1"),promptTemplateVersion:"taskset-draft-v1",buildIntent:g,buildSpecification:null,evidenceHashes:l.map($=>$.sourceHash),tasksetSdkVersion:"draft-v1",sourceCommit:null,repairHistory:[],createdAt:n},readiness:null,contentHash:"00000000",createdAt:s===1?t.createdAt:n,updatedAt:n,metadata:{...t.metadata,...o?{modelTasksetAuthoring:o.lineage}:{},tasksetReviewPolicy:t.review,tasksetOutputContract:t.output,...e.sourcePackageHash?{sourcePackageHash:e.sourcePackageHash}:{},...C?{trainingMethod:C}:{},diagnosis:{schemaVersion:"openpond.capabilityDiagnosis.v1",summary:t.objective,stableBehavior:[t.objective],changingKnowledge:[],requiredContext:[],requiredTools:t.environment.toolNames,intervention:C==="dpo"?"preference":C==="grpo"||C==="ppo"?"grpo_rft":C==="sft"?"sft":"no_training",trainingEligible:C!==null,rationale:C?[`The author selected ${C.toUpperCase()} compatibility.`]:["The Taskset is currently configured for evaluation only."],confidence:1}}}),E=$c.parse({...R,contentHash:k3(R)}),O=y3(E).issues.filter($=>$.severity==="error");if(O.length)throw new ex(O.map($=>({code:$.code,message:$.message,path:$.path})));return E}function U3(e,t,n){const a=Tt({draftId:e.id,draftRevision:e.revision,tasks:e.tasks});return{schemaVersion:"openpond.generatedDatasetSource.v1",kind:"generated",id:`source-${t}`,profileId:e.profileId,title:`${e.name} manual authoring`,sourceHash:a,occurredAt:n,licensingStatus:"approved",secretScanStatus:"passed",piiScanStatus:"passed",generatorId:"openpond-taskset-draft",generatorVersion:"1",seed:0,generatorHash:a,metadata:{draftId:e.id,draftRevision:e.revision}}}function z3(e){return e.learningSignals.preferences.length?"preferences":e.learningSignals.rewards.length?"verifiable_reward":e.learningSignals.labels.length?"rubric":!e.capabilities.compatibleMethods.some(t=>t!=="none"&&t!=="retrieval")&&e.graders.some(t=>t.rewardEligible&&t.weight>0&&t.kind!=="human")?"verifiable_reward":"demonstrations"}var qs=i().regex(/^[a-f0-9]{64}$/),mR=c({providerId:b("claude-code"),configurationHash:qs,executableHash:qs,version:i().regex(/^2\.\d+\.\d+$/),capabilityHash:qs,maximumRequestCostUsd:u().finite().positive().max(1e4),requestTimeoutMs:u().int().min(1e3).max(3e5),maximumTurns:u().int().min(1).max(100),holdOpen:I()}).strict();c({id:i().min(1).max(200),receiptId:i().min(1).max(200),sessionId:Pm(),operationId:i().min(1).max(200),action:v(["message","seal"]),text:i().max(262144).optional()}).strict().superRefine((e,t)=>{e.action==="message"&&!e.text?.trim()&&t.addIssue({code:"custom",message:"A human intervention requires a message."}),e.action==="seal"&&e.text!==void 0&&t.addIssue({code:"custom",message:"Sealing does not add a prompt."})});var B3=c({provider:b("claude-code"),sessionId:Pm(),requestId:i().min(1).max(200),modelId:i().min(1).max(500),runtime:mR,sourceHash:qs,outputHash:qs,traceHash:qs,runtimeEventRefs:p(i().min(1).max(200)).min(1).max(2e4),eventCount:u().int().positive().max(2e4),startedAt:on(),completedAt:on(),cleanupComplete:b(!0)}).strict().superRefine((e,t)=>{(e.runtimeEventRefs.length!==e.eventCount||new Set(e.runtimeEventRefs).size!==e.eventCount)&&t.addIssue({code:"custom",message:"Process event references must match the exact retained trace population."})}),rp=c({id:i().trim().min(1).max(240),revision:u().int().positive(),contentHash:i().regex(/^[a-f0-9]{64}$/),targetId:i().trim().min(1).max(240).nullable()}).strict(),F3=p(c({role:v(["system","user","assistant"]),content:i().max(1e5)}).strict()).max(100).superRefine((e,t)=>{e.reduce((n,a)=>n+a.content.length,0)>1e5&&t.addIssue({code:"custom",message:"Evaluation prompt exceeds 100,000 characters."})}),pR=c({schemaVersion:b("openpond.experimentAttemptGrade.v1"),selectionHash:i().regex(/^[a-f0-9]{64}$/),grades:p(R_).min(1).max(100),score:u().min(0).max(1).nullable(),passed:I(),rewardEligible:I(),gradingStatus:v(["scored","pending","unscorable","not_configured"]),failureClass:lC.nullable(),contentHash:i().regex(/^[a-f0-9]{64}$/)}).strict().superRefine((e,t)=>{const{contentHash:n,...a}=e;Tt(a)!==n&&t.addIssue({code:"custom",message:"Experiment grading integrity failed."});const o=e.grades.flatMap(r=>r.components);(o.length!==e.grades.length||new Set(o.map(r=>r.graderId)).size!==o.length)&&t.addIssue({code:"custom",message:"Each selected criterion requires exactly one distinct grader result."});for(const r of e.grades){const{contentHash:s,...l}=r;Tt(l)!==s&&t.addIssue({code:"custom",message:"A retained criterion changed."});for(const m of r.components){const{contentHash:d,...f}=m;Tt(f)!==d&&t.addIssue({code:"custom",message:"A retained grader result changed."})}}}),an=i().trim().min(1).max(200),wr=i().regex(/^[a-f0-9]{64}$/),fR=ot("kind",[c({kind:b("hosted_chat"),modelId:an,localRuntime:vt([c({providerId:b("custom-openai-compatible"),configurationHash:wr,maximumRequestCostUsd:u().finite().positive().max(1e4),requestTimeoutMs:u().int().min(1e3).max(3e5)}).strict(),mR]).optional(),candidate:c({artifactId:an,contentHash:wr,preparationId:an,dispatchId:an,baseProfileId:an,workerImageDigest:i().regex(/^sha256:[a-f0-9]{64}$/)}).strict().optional(),harness:ld.optional(),messages:F3.optional(),maxOutputTokens:u().int().min(1).max(1e6).default(1e5),temperature:u().min(0).max(2).default(0),topP:u().gt(0).max(1).default(1)}).strict(),c({kind:b("fixture"),fixtureId:an}).strict()]),V3=c({schemaVersion:b("openpond.modelStarterAttemptRequest.v1"),operationId:an,teamId:an,modelProjectId:an.nullable(),project:rp.optional(),taskset:la,taskId:an,environmentSeed:u().int().min(0).max(2147483647).default(0),policy:fR}).strict();c({modelProjectId:an.nullable(),taskset:la,afterTaskId:an.optional(),limit:u().int().min(1).max(100).default(25)}).strict();c({modelProjectId:an.nullable(),taskset:la,available:I(),unavailableReason:i().max(1e3).nullable(),models:p(c({id:an,name:i().max(500),maximumOutputTokens:u().int().min(1).max(1e6).optional()}).strict()).max(200),tasks:p(c({id:an,split:Xa,inputPreview:i().max(500),fixtures:p(c({id:an,label:i().max(200)}).strict()).max(1e3)}).strict()).max(100),nextCursor:an.nullable()}).strict();var qb=c({schemaVersion:b("openpond.modelStarterAttemptSummary.v1"),id:an,revision:u().int().positive(),request:V3,status:v(["queued","running","cancelling","completed","failed","cancelled"]),policySnapshot:c({modelId:an,provider:an,upstreamModelId:i().min(1).max(500),configurationHash:wr}).strict().nullable(),createdAt:on(),startedAt:on().nullable(),completedAt:on().nullable(),cleanupComplete:I(),resultAvailable:I(),score:u().min(0).max(1).nullable(),gradingStatus:v(["not_started","pending","scored","unscorable","not_configured"]).default("not_started"),passed:I().nullable(),outputPreview:i().max(500).nullable(),error:c({code:an,message:i().max(2e3)}).strict().nullable()}).strict().superRefine((e,t)=>{e.request.policy.kind==="fixture"!=(e.policySnapshot===null)&&t.addIssue({code:"custom",path:["policySnapshot"],message:"Fixture execution must not claim a model identity."}),e.status==="completed"&&(!e.cleanupComplete||!e.resultAvailable||!e.completedAt)&&t.addIssue({code:"custom",message:"Completed attempts require retained results and confirmed cleanup."})});c({modelProjectId:an,afterId:an.optional(),limit:u().int().min(1).max(100).default(25)}).strict();c({items:p(qb).max(100),nextCursor:an.nullable()}).strict();c({schemaVersion:b("openpond.modelStarterAttemptResult.v1"),attempt:qb,output:i().max(1048576).nullable(),messages:p(le(i(),ce())).max(4002),composition:Pc.nullable(),grade:R_.nullable().optional(),experimentGrade:pR.nullable().optional(),environment:c({status:v(["completed","budget_exhausted","cancelled","timed_out","policy_failure","environment_failure"]),collected:I(),definition:la,initialStateHash:wr.nullable(),finalStateHash:wr.nullable(),attemptHash:wr}).strict(),native:vb.optional(),providerRequestIds:p(an).max(1001),contentHash:wr}).strict().superRefine((e,t)=>{const n=e.attempt.request.policy.kind==="hosted_chat"?e.attempt.request.policy.harness:void 0;!!n!=!!e.native&&t.addIssue({code:"custom",path:["native"],message:"Standalone Harness results require their exact native evidence."}),e.native&&(!n||Tt(n)!==Tt(e.native.source)||e.native.modelConfigurationHash!==e.attempt.policySnapshot?.configurationHash||e.environment.initialStateHash!==null||e.environment.finalStateHash!==null||e.environment.status==="completed"&&(!e.environment.collected||e.output===null||e.native.partialOutputAvailable||e.native.outputHash!==Tt(e.output)))&&t.addIssue({code:"custom",path:["native"],message:"Native evidence differs from the admitted source, model or output."}),e.experimentGrade&&((e.grade||e.composition)&&t.addIssue({code:"custom",message:"Selected Experiment grading cannot claim another grade population."}),(!["completed","failed"].includes(e.attempt.status)||!e.attempt.resultAvailable||e.attempt.score!==e.experimentGrade.score||e.attempt.gradingStatus!==e.experimentGrade.gradingStatus||e.attempt.passed!==(e.experimentGrade.score===null?null:e.experimentGrade.passed))&&t.addIssue({code:"custom",message:"Experiment grading differs from its retained attempt summary."})),e.grade&&(e.composition&&t.addIssue({code:"custom",path:["grade"],message:"An ordinary grade cannot also claim a Reward composition."}),(!["completed","failed"].includes(e.attempt.status)||!e.attempt.resultAvailable||e.attempt.score!==e.grade.score||e.attempt.gradingStatus!==e.grade.gradingStatus||e.attempt.passed!==(e.grade.score===null?null:e.grade.passed))&&t.addIssue({code:"custom",path:["grade"],message:"Ordinary grade differs from its terminal attempt summary."}))});var hs=i().trim().min(1).max(240),bh=i().regex(/^[a-f0-9]{64}$/),hR=c({kind:b("hosted_harness"),modelId:hs,candidate:c({artifactId:hs,contentHash:bh,preparationId:hs,dispatchId:hs,baseProfileId:hs,workerImageDigest:i().regex(/^sha256:[a-f0-9]{64}$/)}).strict().optional(),sourceCandidate:Ys.shape.sourceCandidate,reasoningEffort:v(["off","low","medium","high","xhigh","max"]).optional(),profileRepositoryId:hs,source:Ys,modelConfigurationHash:bh,packageHash:bh,externalDatasetBinding:Wo.optional()}).strict().superRefine((e,t)=>{JSON.stringify(e.externalDatasetBinding??null)!==JSON.stringify(e.source.externalDatasetBinding??null)&&t.addIssue({code:"custom",message:"The policy and source must bind the same external Dataset recipe."}),JSON.stringify(e.sourceCandidate??null)!==JSON.stringify(e.source.sourceCandidate??null)&&t.addIssue({code:"custom",message:"The policy and prepared source must bind the same actual source candidate."})}),ci=i().trim().min(1).max(200),gR=i().regex(/^[a-f0-9]{64}$/),K3=ot("kind",[fR.options[0],c({kind:b("fixture")}).strict(),hR]),vl=c({schemaVersion:b("openpond.modelTasksetRunRequest.v1"),operationId:ci,teamId:ci,modelProjectId:ci.nullable(),name:i().trim().min(1).max(200).optional(),project:rp.optional(),taskset:la,policy:K3,population:p(OC).min(1).max(1e4)}).strict().superRefine((e,t)=>{new Set(e.population.map(n=>n.receiptId)).size!==e.population.length&&t.addIssue({code:"custom",path:["population"],message:"Run receipt identities must be unique."}),e.population.some(n=>n.fixtureId!==null!=(e.policy.kind==="fixture"))&&t.addIssue({code:"custom",path:["population"],message:"Only fixture runs require a fixture identity for every member."}),e.population.some(n=>!/^(0|[1-9][0-9]*)$/.test(n.seed)||Number(n.seed)>2147483647)&&t.addIssue({code:"custom",path:["population"],message:"Hosted environment seeds must be integers from 0 to 2147483647."}),e.policy.kind==="hosted_harness"&&e.modelProjectId!==null&&t.addIssue({code:"custom",path:["modelProjectId"],message:"A Harness target retains its released Profile binding separately from Model artifacts."}),e.policy.kind==="hosted_harness"&&new Set(e.population.map(n=>Ib([n.taskId,n.seed]))).size!==e.population.length&&t.addIssue({code:"custom",path:["population"],message:"Harness case identities must be unique for each task and seed."})}),vR=c({schemaVersion:b("openpond.modelTasksetRunSummary.v1"),id:ci,revision:u().int().positive(),teamId:ci,modelProjectId:ci.nullable(),name:i().trim().min(1).max(200).optional(),project:rp.optional(),operationId:ci,taskset:la,policyKind:v(["hosted_chat","fixture","hosted_harness"]),manifestHash:gR,status:v(["queued","running","cancelling","completed","failed","cancelled"]),totalCount:u().int().min(1).max(1e4),counts:c({pending:u().int().nonnegative(),running:u().int().nonnegative(),completed:u().int().nonnegative(),failed:u().int().nonnegative(),cancelled:u().int().nonnegative()}).strict(),createdAt:on(),startedAt:on().nullable(),completedAt:on().nullable(),cleanupComplete:I(),resultAvailable:I(),score:u().min(0).max(1).nullable(),metricName:i().min(1).max(240),error:c({code:ci,message:i().max(2e3)}).strict().nullable()}).strict().superRefine((e,t)=>{Object.values(e.counts).reduce((n,a)=>n+a,0)!==e.totalCount&&t.addIssue({code:"custom",path:["counts"],message:"Run counts must account for the complete population."}),e.status!=="completed"&&e.score!==null&&t.addIssue({code:"custom",path:["score"],message:"Only completed evaluations publish a metric value."}),["completed","failed","cancelled"].includes(e.status)&&(!e.completedAt||e.counts.pending||e.counts.running)&&t.addIssue({code:"custom",message:"Terminal runs require complete population accounting."}),e.status==="cancelled"&&!e.cleanupComplete&&t.addIssue({code:"custom",message:"Cancelled runs require confirmed cleanup."}),e.resultAvailable&&!["completed","failed","cancelled"].includes(e.status)&&t.addIssue({code:"custom",message:"Run results require terminal population accounting."}),e.status==="completed"&&(!e.cleanupComplete||!e.resultAvailable)&&t.addIssue({code:"custom",message:"Completed evaluations require retained results and confirmed cleanup."})}),bR=c({summary:vR,request:vl,manifest:ep,policySnapshot:qb.shape.policySnapshot}).strict();c({modelProjectId:ci.optional(),projectId:rp.shape.id.optional(),afterId:ci.optional(),limit:u().int().min(1).max(100).default(25)}).strict();c({items:p(vR).max(100),nextCursor:ci.nullable()}).strict();c({schemaVersion:b("openpond.modelTasksetRunResult.v1"),run:bR,receipts:p(e5).min(1).max(1e4),metric:db.nullable(),contentHash:gR}).strict();var yR=i().min(1).max(200).refine(e=>!["__proto__","prototype","constructor"].includes(e),"Use an ordinary field name."),W3=p(yR).min(1).max(20),tx=v(["input","output","expectedOutput","evaluatorContext"]),G3=c({destination:tx,path:W3,source:tx,sourcePath:p(yR).max(20)}).strict(),Ub=p(G3).max(100).superRefine((e,t)=>{for(const[n,a]of e.entries())e.slice(0,n).some(o=>o.destination===a.destination&&(nx(o.path,a.path)||nx(a.path,o.path)))&&t.addIssue({code:"custom",path:[n,"path"],message:"Mapped destination paths must not overlap."})});function nx(e,t){return e.length<=t.length&&e.every((n,a)=>n===t[a])}var ra=i().trim().min(1).max(200),jr=i().regex(/^[a-f0-9]{64}$/),pd=c({id:ra,revision:u().int().positive(),contentHash:jr}).strict(),Li=c({id:ra,version:i().min(1).max(200),contentHash:jr,name:i().trim().min(1).max(500).optional(),feedbackKey:rd,release:pd.nullable(),mappings:Ub.optional()}).strict(),zb=c({id:ra,version:i().min(1).max(200),contentHash:jr,mappings:Ub}).strict(),Bb=c({operationId:ra,id:ra.optional(),expectedRevision:u().int().nonnegative(),request:vl,maximumCostUsd:u().finite().positive().max(1e4),graders:p(zb).min(1).max(100).optional()}).strict().superRefine((e,t)=>{e.request.name||t.addIssue({code:"custom",path:["request","name"],message:"Name this Experiment before saving it."}),!!e.id!=e.expectedRevision>0&&t.addIssue({code:"custom",path:["expectedRevision"],message:"An update requires its saved definition revision."}),Math.round(e.maximumCostUsd*1e6)<1&&t.addIssue({code:"custom",path:["maximumCostUsd"],message:"The budget must be at least $0.000001."}),e.graders&&new Set(e.graders.map(n=>n.id)).size!==e.graders.length&&t.addIssue({code:"custom",path:["graders"],message:"Select each grader once."})}),J3=c({schemaVersion:b("openpond.experimentDefinition.v1"),id:ra,teamId:ra,revision:u().int().positive(),request:vl,maximumCostUsd:u().finite().positive().max(1e4),graders:p(Li).min(1).max(100),createdAt:on(),updatedAt:on()}).strict();J3.extend({contentHash:jr});c({operationId:ra,definition:pd}).strict();c({projectId:ra.optional(),datasetHash:jr.optional(),search:i().trim().max(200).optional(),status:v(["queued","running","cancelling","completed","failed","cancelled"]).optional(),afterId:ra.optional(),limit:u().int().min(1).max(100).default(30)}).strict();c({definition:pd.nullable(),configurationHash:jr.optional(),admissionRequestHash:jr.optional(),sourceExperimentId:ra.optional(),maximumCostUsd:u().finite().positive().max(1e4),graders:p(Li).min(1).max(100)}).strict().superRefine((e,t)=>{e.definition===null&&(!e.configurationHash||!e.admissionRequestHash)&&t.addIssue({code:"custom",path:["configurationHash"],message:"A flat Experiment requires its sealed configuration hash."})});c({operationId:ra,profileRepositoryId:ra,definitionId:ra,modelId:ra,reasoningEffort:v(["off","low","medium","high","xhigh","max"]).optional(),maximumCostUsd:u().finite().positive().max(1e4),externalDatasetBinding:Wo.optional(),sourceCandidate:hR.shape.sourceCandidate}).strict();c({request:vl,manifest:ep,maximumCostUsd:u().finite().positive().max(1e4),graders:p(Li).min(1).max(100)}).strict();var ax=i().trim().min(1).max(200),fd=c({operationId:ax,request:vl,maximumCostUsd:u().finite().positive().max(1e4),graders:p(zb).min(1).max(100).optional(),sourceExperimentId:ax.optional()}).strict().superRefine((e,t)=>{e.request.name||t.addIssue({code:"custom",path:["request","name"],message:"Name this Experiment before starting it."}),e.operationId!==e.request.operationId&&t.addIssue({code:"custom",path:["request","operationId"],message:"Use one operation identity for this Experiment."}),Math.round(e.maximumCostUsd*1e6)<1&&t.addIssue({code:"custom",path:["maximumCostUsd"],message:"The spending cap must be at least $0.000001."}),e.graders&&new Set(e.graders.map(n=>n.id)).size!==e.graders.length&&t.addIssue({code:"custom",path:["graders"],message:"Select each grader once."})}),Kt=i().trim().min(1).max(200),Ni=i().regex(/^[a-f0-9]{64}$/),sm=c({id:Kt,contentHash:Ni}).strict(),kie=c({available:I(),reason:i().max(1e3).nullable(),origin:Vm.nullable()}).strict(),SR=c({schemaVersion:b("openpond.postTrainingAttachment.v1"),binding:c({kind:v(["preparation","policy"]),id:Kt,revision:u().int().positive(),contentHash:Ni}).strict(),projectId:Kt.nullable(),automatic:I(),maximumSpendUsd:u().finite().positive().max(1e4),experiments:p(c({id:Kt,configuration:fd}).strict()).min(1).max(20),acceptancePlan:Y_.nullable()}).strict().superRefine((e,t)=>{if(new Set(e.experiments.map(n=>n.id)).size!==e.experiments.length&&t.addIssue({code:"custom",message:"Attach each evaluation once."}),e.experiments.reduce((n,a)=>n+a.configuration.maximumCostUsd,0)>e.maximumSpendUsd+1e-9&&t.addIssue({code:"custom",message:"Attached evaluation budgets exceed the total approved budget."}),e.experiments.some(n=>(n.configuration.request.project?.id??null)!==e.projectId)&&t.addIssue({code:"custom",message:"Attached experiments must use the training Project."}),e.acceptancePlan){const n=new Set(e.acceptancePlan.checks.map(o=>o.id));e.acceptancePlan.checks.some(o=>!e.experiments.some(r=>r.id===o.id))&&t.addIssue({code:"custom",message:"Select the frozen Experiment for each acceptance check."}),e.acceptancePlan.maximumSpendUsd+e.experiments.filter(o=>!n.has(o.id)).reduce((o,r)=>o+r.configuration.maximumCostUsd,0)>e.maximumSpendUsd+1e-9&&t.addIssue({code:"custom",message:"Paired acceptance and diagnostic ceilings exceed the approved evaluation budget."})}});function wie(e){const{modelId:t,candidate:n,...a}=e.request.policy.kind==="fixture"?{modelId:null,candidate:null,...e.request.policy}:e.request.policy;return"modelConfigurationHash"in a&&delete a.modelConfigurationHash,{dataset:{id:e.request.taskset.id,contentHash:e.request.taskset.contentHash},populationHash:Tt(e.request.population.map(o=>({caseId:o.taskId,seed:o.seed,fixtureId:o.fixtureId}))),executionHash:Tt({settings:a,graders:e.graders??null})}}var Z3=c({baseline:sm,checks:p(c({id:Kt,sourceRunId:Kt,sourceManifestHash:Ni,targetConfigurationHash:Ni,executionHash:Ni,populationHash:Ni,evaluator:sm,feedbackKey:Kt,output:v(["boolean","score"]),unit:i().min(1).max(80)}).strict()).min(1).max(100)}).strict(),Y3=v(["waiting_for_training","ready","preparing","queued","running","cleaning","completed","failed","blocked","cancelled","budget_exhausted"]),Q3=c({schemaVersion:b("openpond.postTrainingSummary.v1"),id:Kt,teamId:Kt,jobId:Kt,revision:u().int().positive(),planHash:Ni,automatic:I(),candidate:sm.nullable(),state:Y3,total:u().int().positive(),completed:u().int().nonnegative(),failed:u().int().nonnegative(),requiredOutcome:v(["none","pending","passed","failed","blocked"]),reason:i().max(500).nullable(),groupId:Kt.nullable(),experimentIds:p(Kt).max(20),updatedAt:on()}).strict().superRefine((e,t)=>{e.completed+e.failed>e.total&&t.addIssue({code:"custom",message:"Evaluation totals are inconsistent."}),["preparing","queued","running","cleaning","completed"].includes(e.state)&&!e.candidate&&t.addIssue({code:"custom",message:"Evaluation execution requires the exact trained candidate."})}),Iie=c({operationId:Kt,expectedRevision:u().int().positive(),planHash:Ni}).strict();c({operationId:Kt,attachment:SR}).strict();c({id:Kt,teamId:Kt,ownerUserId:Kt,attachment:SR,qualification:Z3.nullable(),contentHash:Ni,createdAt:on()}).strict();function _ie(e){return!!(e&&["preparing","queued","running","cleaning"].includes(e.state))}var Cie=c({teamId:Kt,actorId:Kt,projectId:Kt.nullable(),configuration:Jm,batches:p(Sb).max(1e4),sources:p(Km).max(1e4),definitions:p(cd).max(1e4),experiments:p(c({id:Kt,name:i().max(500),configuration:fd,graders:p(c({feedbackKey:Kt,name:i().max(500),ref:sm}).strict()).max(100)}).strict()).max(1e4)}).strict();v(["prepare","start","cancel","publish","attach"]);var Rie=c({teamId:Kt,actorId:Kt,configuration:Jm,policy:D_,inspection:C4,iterations:p(c({iteration:H_,evals:Q3.nullable()}).strict()).max(100),nextCursor:Kt.nullable()}).strict(),Pie=c({id:Kt,expectedRevision:u().int().positive(),policyHash:Ni,operationId:Kt,action:v(["pause","resume","reserve","cancel-iteration","retry-iteration"]),iterationId:Kt.optional(),iterationRevision:u().int().positive().optional()}).strict(),Us=i().trim().min(1).max(240),X3=Mt.extend({revision:u().int().positive()}).strict(),e6=X3.extend({teamId:Us,jobId:Us,plan:Mt,baseline:Mt,candidate:Mt,state:F4.shape.state,updatedAt:i().datetime()}).strict();c({schemaVersion:b("openpond.trainingAcceptanceGroupPage.v1"),teamId:Us,jobId:Us,groups:p(e6).max(100),nextCursor:Us.nullable()}).strict();c({cursor:Us.optional(),limit:u().int().min(1).max(100).default(25)}).strict();var Ba=i().trim().min(1).max(191),Nc=i().regex(/^[a-f0-9]{64}$/),t6=c({schemaVersion:b("openpond.trainingPreparationRequest.v1"),teamId:Ba,operationId:Ba,projectId:Ba.nullable(),configuration:c({id:Ba,expectedRevision:u().int().positive(),expectedEtag:Nc}).strict(),origin:Vm.optional(),batch:la,name:i().trim().min(1).max(191),maximumSpendUsd:u().finite().positive().max(1e6)}).strict(),n6=c({schemaVersion:b("openpond.trainingPreparationPlan.v1"),id:Ba,creatorUserId:Ba,request:t6,requestHash:Nc,source:iw(()=>kR),submissionHash:Nc,createdAt:i().datetime({offset:!0})}).strict(),a6=n6.extend({contentHash:Nc}).strict(),i6=c({schemaVersion:b("openpond.trainingPreparationReceipt.v1"),plan:a6,revision:u().int().positive(),state:v(["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:Nc,expectedRevision:u().int().positive()}).strict();c({projectId:Ba.optional(),state:v(["prepared","submitted","cancelled"]).optional(),afterId:Ba.optional(),limit:u().int().min(1).max(100).default(25)}).strict();c({schemaVersion:b("openpond.trainingPreparationPage.v1"),teamId:Ba,items:p(i6).max(100),nextCursor:Ba.nullable()}).strict();c({schemaVersion:b("openpond.trainingHarnessSourcePublication.v1"),harnessRelease:He,sourcePackageHash:i().regex(/^[a-f0-9]{64}$/),sizeBytes:u().int().positive().max(Z4)}).strict();p(c({id:i().trim().min(1)}).catchall(ce())).min(1).max(1e3);c({binding:Fm,rewards:p(sd).min(1).max(100)}).strict();var o6=c({id:i().trim().min(1),clusterKey:i().trim().min(1),split:v(["train","validation","frozen_eval"])}).passthrough();c({schemaVersion:b("openpond.trainingEvaluationSource.v1"),taskset:la,tasks:p(o6).min(1).max(1e4),assets:p(c({path:i().trim().min(1).max(2e3),sha256:i().regex(/^[a-f0-9]{64}$/),sizeBytes:u().int().nonnegative(),encoding:b("base64"),content:i().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 Vn=i().trim().min(1).max(500),Ea=i().regex(/^[a-f0-9]{64}$/),mi=i().datetime({offset:!0});c({schemaVersion:b("openpond.trainingInputArtifactUpload.v2"),kind:v(["portable_training_bundle","reward_model_dataset"]),idempotencyKey:i().trim().min(1).max(500),sourceManifest:Mt,payload:ce(),contentHash:Ea}).strict();c({schemaVersion:b("openpond.trainingInputArtifact.v2"),kind:v(["portable_training_bundle","reward_model_dataset"]),sourceManifest:Mt,artifactRef:i().trim().min(1).max(2e3),contentHash:Ea,sizeBytes:u().int().positive(),createdAt:mi}).strict();var xR=v(["reward_model_train","policy_optimize"]),r6=v(["queued","admitting","provisioning","running","stopping","cancelling","succeeded","failed","cancelled"]),s6=c({id:Vn,version:i().trim().min(1).max(200).nullable().default(null),required:I().default(!0)}).strict(),kR=c({origin:Vm.optional(),modelProject:c({id:Vn,portableProjectId:Vn,revision:u().int().positive(),contentHash:Ea}).strict(),harnessRunManifest:Mt,harnessRelease:Mt,taskset:la,tasksetRelease:Mt,evaluation:c({taskset:la,dataset:Mt}).strict().nullable().optional(),dataset:Mt,evidenceSets:p(Mt).max(1e4)}).strict(),l6=c({kind:b("reward_model_train"),baseModel:Lr,preferenceDatasetRelease:Mt,processorRelease:Mt,recipe:c({schemaVersion:b("openpond.rewardModelRecipe.v1"),method:b("reward_model"),parameterization:b("lora_with_scalar_head")}).catchall(ce())}).strict(),c6=c({kind:b("deterministic"),grader:Mt,composer:Mt.nullable().default(null)}).strict(),d6=c({kind:b("learned_reward"),rewardModelVersion:Mt,qualificationReport:Mt.nullable().default(null),evaluationReferences:p(Mt).max(1e3).default([]),scorerArtifact:c({artifactRef:i().trim().min(1).max(2e3),contentHash:Ea,executionReceipt:Mt}).strict(),processorRelease:Mt,rewardComposerRelease:Mt}).strict(),u6=c({kind:b("policy_optimize"),baseModel:Lr,recipe:tC,rewardSource:ot("kind",[c6,d6]),resumeFrom:Mt.nullable().default(null)}).strict(),m6=ot("kind",[l6,u6]),p6=c({approvalHash:Ea,approvedAt:mi,exportApproved:I(),maximumSpendUsd:u().nonnegative(),retentionDays:u().int().nonnegative().nullable(),region:i().trim().min(1).max(200).nullable().default(null)}).strict();c({schemaVersion:b("openpond.trainingJobSubmission.v2"),idempotencyKey:i().trim().min(1).max(500),name:i().trim().min(1).max(200),source:kR,job:m6,requestedCapabilities:p(s6).max(1e3),placementObjective:v(["fast","balanced","economical"]),budget:c({maximumSpendUsd:u().nonnegative(),maximumWallSeconds:u().int().positive()}).strict(),approval:p6,contentHash:Ea}).strict().superRefine((e,t)=>{e.approval.maximumSpendUsd!==e.budget.maximumSpendUsd&&t.addIssue({code:"custom",path:["approval","maximumSpendUsd"],message:"Approved spend must equal the immutable Job budget."})});var f6=c({schemaVersion:b("openpond.trainingJob.v2"),id:Vn,teamId:Vn,kind:xR,modelProjectId:Vn,portableProjectId:Vn,sourceProjectRevision:u().int().positive(),submissionHash:Ea,state:r6,phase:i().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:i().trim().min(1).max(5e3).nullable(),createdAt:mi,updatedAt:mi,completedAt:mi.nullable()}).strict();c({schemaVersion:b("openpond.trainingJobPage.v2"),jobs:p(f6).max(1e3),nextCursor:i().trim().min(1).max(2e3).nullable()}).strict();var Aie=c({schemaVersion:b("openpond.trainingJobEvent.v2"),id:Vn,jobId:Vn,sequence:u().int().nonnegative(),type:Vn,phase:i().trim().min(1).max(200),message:i().trim().min(1).max(5e3).nullable(),data:le(i(),ce()).default({}),createdAt:mi}).strict();c({schemaVersion:b("openpond.trainingJobLog.v2"),jobId:Vn,sequence:u().int().nonnegative(),level:v(["debug","info","warning","error"]),message:i().max(2e4),createdAt:mi}).strict();c({expectedVersion:u().int().nonnegative()}).strict();var h6=c({schemaVersion:b("openpond.trainingJobOutput.v2"),id:Vn,jobId:Vn,kind:v(["checkpoint","adapter","scorer","metrics","evaluation","trace","receipt"]),artifactRef:i().trim().min(1).max(2e3),contentHash:Ea,sizeBytes:u().int().nonnegative(),metadata:le(i(),ce()).default({}),createdAt:mi}).strict(),g6=c({schemaVersion:b("openpond.trainingExecutionReceipt.v2"),id:Vn,teamId:Vn,jobId:Vn,submissionHash:Ea,manifestHash:Ea,recipeHash:Ea,capabilityHash:Ea,runtimeRelease:Mt,inputs:p(Mt).max(1e4),outputs:p(Mt).max(1e4),spendUsd:u().nonnegative(),durationSeconds:u().nonnegative(),cleanupComplete:I(),issuer:Vn,issuedAt:mi,signature:i().trim().min(1).max(1e4).nullable()}).strict(),Tie=c({schemaVersion:b("openpond.trainingJobOutputs.v2"),outputs:p(h6).max(1e4),receipt:g6.nullable()}).strict();c({schemaVersion:b("openpond.trainingApiError.v2"),code:i().trim().min(1).max(200),message:i().trim().min(1).max(5e3),retryable:I().default(!1),requestId:i().trim().min(1).max(500).nullable().default(null),details:le(i(),ce()).default({})}).strict();c({schemaVersion:b("openpond.trainingCapabilities.v2"),capabilityHash:Ea,jobKinds:p(xR),methods:p(i().trim().min(1).max(200)),placements:p(v(["local","remote","colocated","provider_native"])),controls:c({cancel:I(),stopAfterGroup:I(),resumeFromCheckpoint:I()}).strict(),limits:c({maximumSpendUsd:u().nonnegative(),maximumWallSeconds:u().int().positive(),maximumArtifactBytes:u().int().positive()}).strict(),checkedAt:mi,expiresAt:mi}).strict();var qi=Ja.shape.id,fi=u().int().positive(),Or=i().regex(/^[a-f0-9]{64}$/),qr={teamId:qi,modelId:qi};c({schemaVersion:b("openpond.tasksetDraftCreate.v1"),operationId:qi,modelId:qi,expectedModelRevision:fi,name:Ja.shape.name}).strict();c({schemaVersion:b("openpond.tasksetDraftSourceDescriptor.v1"),...qr,expectedModelRevision:fi,sourcePackageHash:Or}).strict();c({schemaVersion:b("openpond.tasksetDraftReadback.v1"),...qr,draft:Ja,workspaceHash:Or,projectEtag:Or}).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 v6=c({id:qi,revision:fi,name:Ja.shape.name,status:dR,updatedAt:Ja.shape.updatedAt,sourceTasksetRef:lt.nullable()}).strict();c({schemaVersion:b("openpond.tasksetDraftList.v1"),...qr,drafts:p(v6).max(100),nextCursor:i().min(1).max(2e3).nullable()}).strict();c({expectedDraftRevision:fi,draft:Ja}).strict();c({expectedDraftRevision:fi,expectedModelRevision:fi}).strict();var b6=c({expectedDraftRevision:fi,expectedWorkspaceHash:Or}).strict();c({schemaVersion:b("openpond.tasksetDraftValidation.v1"),...qr,draftId:qi,draftRevision:fi,workspaceHash:Or,valid:I(),issues:p(c({code:i().min(1),severity:v(["warning","error"]),message:i(),path:i().nullable()}).strict()),packageHash:Or.nullable(),tasksetRef:lt.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.");b6.extend({operationId:qi,expectedPackageHash:Or,expectedTasksetRef:lt}).strict();c({schemaVersion:b("openpond.tasksetDraftFileList.v1"),...qr,draftId:qi,draftRevision:fi,files:p(Q_).max(10020)}).strict();c({schemaVersion:b("openpond.tasksetDraftFileReadback.v1"),...qr,draftId:qi,draftRevision:fi,file:G4}).strict();c({schemaVersion:b("openpond.tasksetDraftDeletion.v1"),...qr,draftId:qi,revision:fi,deleted:b(!0)}).strict();Ja.shape.id;u().int().positive();var ro=i().trim().min(1).max(500),y6=c({projectId:ro.optional(),tasksetId:ro.optional(),draftId:ro.optional(),taskId:ro.optional(),query:i().trim().max(1e3).default(""),split:v(["train","validation","test","frozen_eval"]).optional(),after:i().min(1).max(2e3).optional(),limit:u().int().min(1).max(100).default(30)}).strict(),S6=c({id:ro,method:v(["code","judge","human"]),required:I()}),wR=c({tasksetId:ro,tasksetName:i(),tasksetRevision:u().int().positive(),tasksetHash:i(),taskId:ro,ordinal:u().int().nonnegative(),title:i(),description:i(),split:i(),scoring:p(S6),configuration:v(["configured","needs_reward","needs_checks"]),draftId:ro.nullable().default(null),modelId:ro.nullable().default(null)}),x6=c({items:p(wR).max(100),nextCursor:i().nullable()});function Eie(e,t){if(N4({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((r,s)=>({file:r,path:`${n}/${String(s).padStart(4,"0")}.txt`})),o={schemaVersion:"openpond.taskIntakeSources.v1",format:e.format,previewHash:e.contentHash,files:a.map(({file:r,path:s})=>({originalPath:r.path,retainedPath:s}))};return[...a.map(({file:r,path:s})=>YS(s,new TextEncoder().encode(r.text))),YS(`${n}/manifest.json`,new TextEncoder().encode(JSON.stringify(o)))]}function Mie(e,t,n){const a=F_.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(f=>f.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=cR.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(f=>f.id===m.id);if(d&&Tt(d)!==Tt(m))throw new Error(`Task ${m.id} already exists with different content. Import will not replace saved edits.`);d||o.push(m)}const r=new Map;for(const s of o)for(const l of[`family:${s.clusterKey}`,`input:${Tt(s.input)}`]){if(r.has(l)&&r.get(l)!==s.split)throw new Error("The imported task family or request already occurs in another split.");r.set(l,s.split)}return Ja.parse({...e,tasks:o})}const Sa=i().trim().min(1).max(240),zo=i().trim().min(1),IR=le(i(),ce()).default({}),_R=v(["nominated","needs_review","approved_for_creation","creating","needs_task_review","baselining","ready_for_export","rejected","dismissed","retired","blocked"]),CR=v(["no_training","prompting","retrieval","sft","preference","grpo_rft","sdft_opsd","sdpo","agentic_rl"]),k6=c({id:Sa,kind:v(["repeated_success","accepted_correction","agent_action_recurrence","outcome_linked_change","frontier_cost","expert_label","runtime_feedback"]),sourceRefIds:p(Sa).min(1).max(1e4),occurredAt:zo,signature:i().trim().min(1).max(2e3),summary:i().trim().min(1).max(5e3),confidence:u().min(0).max(1),consented:I(),metadata:IR}),w6=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)}),I6=c({tactic:CR,eligible:I(),reasons:p(i().trim().min(1).max(5e3)).min(1).max(100),blockers:p(i().trim().min(1).max(5e3)).max(100).default([]),requiredSignals:p(i().trim().min(1).max(500)).max(100).default([]),generatedBy:v(["decision_table","baseline_reassessment"])}),RR=c({schemaVersion:b("openpond.taskCandidate.v1"),id:Sa,profileId:Sa,status:_R,fingerprint:i().trim().min(1).max(512),title:i().trim().min(1).max(500),summary:i().trim().min(1).max(1e4),workflowSignature:i().trim().min(1).max(2e3),evidence:p(k6).min(1).max(1e5),scorecard:w6,recommendation:I6,mergedIntoId:Sa.nullable(),createdAt:zo,updatedAt:zo,metadata:IR}),sp=c({schemaVersion:b("openpond.taskMinerConfig.v1"),enabled:I().default(!1),localOnly:I().default(!0),observationWindowDays:u().int().min(1).max(365).default(30),minimumRecurrence:u().int().min(2).max(100).default(3),clustering:b("hybrid_deterministic_first").default("hybrid_deterministic_first"),consentRequired:I().default(!0)});c({items:p(RR),generatedAt:zo,config:sp});c({status:_R.optional(),mergeIntoId:Sa.nullable().optional()});c({profileId:Sa,sourceIds:p(Sa).max(1e5).default([]),sessionIds:p(Sa).max(1e5).default([]),config:sp.optional()});const _6=c({schemaVersion:b("openpond.taskMinerRun.v1"),id:Sa,profileId:Sa,status:v(["queued","running","cancelling","cancelled","succeeded","failed"]),config:sp,sourceIds:p(Sa).max(1e5),sessionIds:p(Sa).max(1e5).default([]),progress:c({stage:v(["queued","ingesting","preparing","clustering","persisting","complete"]),processedSources:u().int().nonnegative(),totalSources:u().int().nonnegative(),candidatesFound:u().int().nonnegative(),skippedSources:u().int().nonnegative().default(0)}),candidateIds:p(Sa).max(1e5),cancelRequested:I(),error:i().trim().min(1).max(2e4).nullable(),createdAt:zo,startedAt:zo.nullable(),completedAt:zo.nullable(),updatedAt:zo});var C6=c({id:Ke,purpose:i().trim().min(1).max(500),audience:v(["orchestrator","environment","privileged_scorer","trainer","infrastructure"]),required:I(),ttlSeconds:u().int().positive().max(86400),scopes:p(i().trim().min(1).max(500)).max(100).default([])}).strict(),R6=c({declarationId:Ke,leaseRef:i().trim().min(8).max(1e3),audience:C6.shape.audience,expiresAt:At}).strict(),Fb=c({adapterId:Ke,placement:v(["local","remote","colocated","provider_native"]),capabilityReceipt:Qe,runtimeVersion:i().trim().min(1).max(200),dataPlane:c({provider:Ke,dataPlaneId:Ke,cellId:Ke,runnerPoolId:Ke,runtimeImageDigest:i().regex(/^sha256:[a-f0-9]{64}$/),capabilityReceipt:Qe}).strict().nullable()}).strict(),Vb=c({adapterId:Ke,kind:v(["local","ssh","managed","custom"]),deviceOrPool:i().trim().min(1).max(1e3),capabilityReceipt:Qe,provider:Ke.nullable()}).strict(),Kb=c({adapterId:Ke,workerVersion:i().trim().min(1).max(200),workerImageDigest:i().regex(/^sha256:[a-f0-9]{64}$/).nullable(),upstreamRevision:i().trim().min(1).max(500),capabilityReceipt:Qe}).strict(),P6=c({schemaVersion:b("openpond.harnessRunManifest.v1"),id:Ke,harnessRelease:He,datasetRelease:He,evidenceSets:p(He).max(1e4),model:c({source:i().trim().min(1).max(200),revision:i().trim().min(1).max(500),artifactHash:Qe.nullable(),tokenizerRevision:i().trim().min(1).max(500),chatTemplateHash:Qe}).strict(),recipe:c({method:i().trim().min(1).max(100),version:i().trim().min(1).max(200),configHash:Qe}).strict(),runtimeTarget:Fb,computeTarget:Vb,engine:Kb,resolvedBundleHash:Qe,secretLeaseRefs:p(R6).max(1e3),approval:c({approvalHash:Qe,approvedAt:At,maximumSpendUsd:u().nonnegative().nullable()}).strict(),createdAt:At}).strict(),A6=P6.extend({contentHash:Qe}).strict(),T6=c({schemaVersion:b("openpond.resolvedTrainingBundle.v1"),projection:b("trainer"),harnessRelease:He,datasetRelease:He,evidenceSetRelease:He.nullable(),files:p(c({path:i().trim().min(1).max(2e3),sha256:Qe,sizeBytes:u().int().nonnegative()}).strict()).max(1e5)}).strict();T6.extend({contentHash:Qe}).strict();var PR=c({name:b("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 yt=i().trim().min(1).max(240),xa=i().trim().min(1),tl=i().trim().min(8).max(256),Wb=le(i(),ce()).default({}),Di=yt.nullable(),E6=v(["slash_train","session_menu","bulk_selection","training_page","task_candidate"]),M6=v(["defaults","customize"]),j6=v(["automated","manual"]);c({schemaVersion:b("openpond.trainingSourceEstimate.v1"),sessionId:yt,messageCount:u().int().nonnegative(),estimatedTokens:u().int().nonnegative(),textBytes:u().int().nonnegative()});c({query:i().max(500).default(""),offset:u().int().nonnegative().default(0),limit:u().int().min(1).max(100).default(20),candidates:p(c({sessionId:yt,title:i().trim().min(1).max(500),updatedAt:xa})).max(500).default([])});const O6=c({sessionId:yt,title:i().trim().min(1).max(500),updatedAt:xa,snippet:i().max(2e3).nullable()});c({schemaVersion:b("openpond.trainingChatSearchResult.v1"),query:i(),offset:u().int().nonnegative(),limit:u().int().positive(),total:u().int().nonnegative(),hasMore:I(),indexedChats:u().int().nonnegative(),totalChats:u().int().nonnegative(),indexing:I(),entries:p(O6)});const Gb=v(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]),$6=c({graderId:yt.nullable(),path:i().trim().min(1).max(1e3),language:v(["javascript","typescript","python","json","text"]),content:i().max(2e6),sha256:tl,declaredSha256:tl.nullable(),integrity:v(["verified","unverified","mismatch"])}),N6=c({protocolVersion:i().trim().min(1).max(200),module:i().trim().min(1).max(1e3),moduleSha256:tl,command:p(i().max(2e3)).max(100),cwd:i().trim().min(1).max(4e3),maxTurns:u().int().positive().max(100)});c({schemaVersion:b("openpond.tasksetGraderDetails.v1"),taskset:Xt,sourceTasksetId:yt,graders:p(op).max(1e3),runtime:N6.nullable(),sources:p($6).max(1e3),unavailableReason:i().max(2e3).nullable()});const D6=c({id:yt,taskIndex:u().int().nonnegative(),label:Lb,output:le(i(),ce()),infrastructureError:i().trim().min(1).max(1e4).nullable(),expectedPassed:I(),expectedRewardEligible:I(),metadata:Wb}),H6=c({schemaVersion:b("openpond.taskAttempt.v1"),id:yt,tasksetId:yt,taskId:yt,split:el,attempt:u().int().nonnegative(),seed:u().int(),modelRef:Sn.nullable(),startedAt:xa,completedAt:xa,output:le(i(),ce()),runtimeEventRefs:p(yt).max(1e4).default([]),artifactRefs:p(yt).max(1e4).default([]),privilegedOutcomeRef:Di,infrastructureError:i().trim().min(1).max(1e4).nullable(),costUsd:u().nonnegative().nullable(),latencyMs:u().int().nonnegative(),userInterventions:u().int().nonnegative().default(0),metadata:Wb}),L6=c({schemaVersion:b("openpond.taskAttemptArtifact.v1"),id:yt,tasksetId:yt,taskId:yt,attemptId:yt,kind:v(["raw_model_response","runtime_trace","environment_state","grader_evidence","output_artifact"]),path:i().trim().min(1).max(4e3),mediaType:i().trim().min(1).max(200).nullable().optional(),sha256:tl,sizeBytes:u().int().nonnegative(),createdAt:xa,metadata:Wb}),q6=c({graderId:yt,graderVersion:i().trim().min(1).max(100),score:u().min(0).max(1).nullable(),passed:I(),hardGate:I(),rewardEligible:I(),feedback:i().trim().max(2e4).nullable(),evidenceRefs:p(yt).max(1e4).default([]),judge:Sn.nullable().optional().default(null),calibrationStatus:v(["not_applicable","pending","passed","failed"])}),U6=c({schemaVersion:b("openpond.gradeResult.v1"),id:yt,attemptId:yt,graderSetHash:tl,score:u().min(0).max(1).nullable(),passed:I(),components:p(q6).min(1).max(1e3),failureClass:Gb.nullable(),feedback:p(i().trim().min(1).max(2e4)).max(1e3).default([]),rewardEligible:I(),rewardComposition:Pc.optional(),createdAt:xa});v(["stable_hash_top_n","rft_easy_curriculum_v1"]);const z6=c({schemaVersion:b("openpond.graderAuditReport.v1"),id:yt,tasksetId:yt,tasksetHash:tl,fixtureRefs:p(yt).min(1).max(1e5),gradeRefs:p(yt).min(1).max(1e5),passed:I(),hackingChecksPassed:I(),leakageChecksPassed:I(),infrastructureSafetyPassed:I(),failures:p(c({fixtureId:yt,label:Lb,gradeId:yt,reason:i().trim().min(1).max(5e3)})).max(1e5),createdAt:xa}),B6=c({schemaVersion:b("openpond.capabilityDiagnosis.v1"),summary:i().trim().min(1).max(1e4),stableBehavior:p(i().trim().min(1).max(5e3)).max(100).default([]),changingKnowledge:p(i().trim().min(1).max(5e3)).max(100).default([]),requiredContext:p(i().trim().min(1).max(5e3)).max(100).default([]),requiredTools:p(yt).max(100).default([]),intervention:CR,trainingEligible:I(),rationale:p(i().trim().min(1).max(5e3)).min(1).max(100),confidence:u().min(0).max(1)}),F6=c({id:yt,sourceId:yt,sourceTurnId:Di,split:el,origin:v(["extracted","corrected","synthetic","expert_authored"]),inputPrompt:i().trim().min(1).max(1e5),expectedOutputText:i().trim().min(1).max(2e5).nullable(),rationale:i().trim().min(1).max(5e3)}),V6=c({schemaVersion:b("openpond.taskDesignProposal.v1"),id:yt,name:i().trim().min(1).max(500),objective:i().trim().min(1).max(2e4),diagnosis:B6.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:Hb.shape.taskKind,sourceIds:p(yt).min(1).max(1e5),assumptions:p(i().trim().min(1).max(5e3)).max(1e3),successCriteria:p(i().trim().min(1).max(5e3)).min(1).max(1e3),proposedGraders:p(op).max(1e3).default([]),graderFixtures:p(D6).max(1e5).default([]),generatedFiles:p(g3).max(1e3).default([]),proposedExamples:p(F6).max(1e5).default([]),proposedMethod:oR.shape.recommendedMethod,trainingPath:aR.nullable().default(null),policy:Db,warnings:p(i().trim().min(1).max(5e3)).default([]),createdAt:xa}),K6=5;function jie(e,t="New model"){const n=e?.trim().split(/\s+/).filter(Boolean)??[];return n.length===0?t:n.slice(0,K6).join(" ")}const hd=c({schemaVersion:b("openpond.baseModelPreference.v1"),modelId:yt,revision:i().trim().min(1).max(256).nullable(),tokenizerRevision:i().trim().min(1).max(256).nullable(),chatTemplateHash:i().trim().min(8).max(256).nullable(),modelAssetId:Di,source:v(["managed","local","builtin"])}),W6=c({schemaVersion:b("openpond.taskCreationRequest.v1"),id:yt,profileId:yt,surface:E6,mode:M6,entryMode:j6.default("manual"),resourceIntent:v(["workproduct","dataset"]).default("workproduct"),buildIntent:tR.default("demonstrations"),buildSpecification:nR.nullable().default(null),objective:i().trim().min(1).max(2e4).nullable(),methodHint:v(["sft","dpo","grpo","ppo"]).nullable().default(null),preferredBaseModelId:yt.nullable().default(null),preferredBaseModel:hd.nullable().default(null),sourceIds:p(yt).max(1e5),candidateId:Di,analysisModel:Sn.nullable(),analysisReasoningEffort:$m.nullable().default(null),createImproveRunId:Di.default(null),targetIntent:c({kind:v(["agent","skill","extension","model","configuration"]).nullable(),id:Di,displayName:i().trim().min(1).max(500).nullable(),operation:v(["create","improve"])}).default({kind:"model",id:null,displayName:null,operation:"create"}),disclosure:c({status:v(["not_required","pending","approved","declined"]),content:b("raw_excerpts"),sourceIds:p(yt).max(1e5),providerModel:Sn.nullable(),approvalId:Di,approvedAt:xa.nullable()}).default({status:"not_required",content:"raw_excerpts",sourceIds:[],providerModel:null,approvalId:null,approvedAt:null}),createdAt:xa}),AR=c({schemaVersion:b("openpond.taskCreationSnapshot.v1"),id:yt,request:W6,state:v(["planning","awaiting_disclosure_approval","awaiting_questions","recommendation_ready","awaiting_materialization_approval","materializing","validating","ready","blocked","failed","cancelled"]),proposal:V6.nullable(),materializedTasksetId:Di,disclosureApprovalId:Di,materializationApprovalId:Di,blockingQuestions:p(c({id:yt,kind:v(["objective","consent","success_signal","privacy_licensing","interpretation"]),prompt:i().trim().min(1).max(5e3),answer:i().trim().min(1).max(2e4).nullable()})).default([]),transcript:p(c({id:yt,role:v(["user","assistant","system","tool"]),text:i().max(1e5),createdAt:xa})).max(1e4).default([]),repairHistory:p(rR).max(1e3).default([]),blockedReason:i().trim().min(1).max(1e4).nullable(),createdAt:xa,updatedAt:xa});c({schemaVersion:b("openpond.taskCreationTranscript.v1"),creationId:yt,profileId:yt,messages:AR.shape.transcript,updatedAt:xa});const Es=i().trim().min(1).max(240),Ru=i().trim().min(1),Rg=i().trim().min(8).max(256),TR=le(i(),ce()).default({}),G6=v(["created","inspecting","awaiting_source_review","awaiting_mapping","awaiting_materialization_approval","materializing","validating","ready","cancelling","cancelled","failed"]),ER=c({schemaVersion:b("openpond.huggingFaceDatasetLocator.v1"),repositoryId:i().trim().regex(/^[^/\s]+\/[^/\s]+$/).max(500),repositoryUrl:i().url().max(2e3),requestedRevision:i().trim().min(1).max(256).nullable()}),J6=c({path:i().trim().min(1).max(1e3),logicalType:i().trim().min(1).max(500),nullable:I(),sampleValues:p(ce()).max(5)}),Z6=c({configuration:i().trim().min(1).max(500),split:i().trim().min(1).max(500),rowCount:u().int().nonnegative().nullable(),sizeBytes:u().int().nonnegative().nullable()}),Y6=c({schemaVersion:b("openpond.huggingFaceDatasetInspection.v1"),id:Es,locator:ER,resolvedRevision:i().trim().min(7).max(256),title:i().trim().min(1).max(500),description:i().max(2e4).nullable(),declaredLicense:i().trim().min(1).max(500).nullable(),gated:I(),private:I(),configurations:p(i().trim().min(1).max(500)).min(1).max(1e3),splits:p(Z6).min(1).max(1e4),columns:p(J6).min(1).max(1e4),previewRows:p(le(i(),ce())).max(25),sourceFiles:p(c({path:i().trim().min(1).max(2e3),configuration:i().trim().min(1).max(500),split:i().trim().min(1).max(500),revision:i().trim().min(7).max(256),sizeBytes:u().int().nonnegative().nullable(),contentHash:Rg.nullable()})).max(1e5),inspectedAt:Ru,metadata:TR}),Q6=v(["row_id","cluster_id","prompt","messages","demonstration","chosen","rejected","expected_output","privileged_context","reward","feedback","tag","metadata"]),X6=c({sourcePath:i().trim().min(1).max(1e3),target:Q6,transform:v(["identity","string","json","messages","numeric","math_final_answer"]),policy:v(["visible","privileged","metadata"]),required:I()}),MR=c({schemaVersion:b("openpond.datasetImportMapping.v1"),sourceSchemaHash:Rg,configuration:i().trim().min(1).max(500),upstreamSplits:p(i().trim().min(1).max(500)).min(1).max(1e3),preset:v(["prompt_only","prompt_completion","messages","preference","prompt_expected_answer","prompt_privileged_solution","prompt_feedback"]),bindings:p(X6).min(1).max(1e4),nullPolicy:v(["reject","drop","preserve"]),invalidRowPolicy:v(["reject_import","drop_with_receipt"]),splitPolicy:c({seed:u().int(),assignments:le(i(),er),validationPercent:u().min(0).max(100),frozenEvalPercent:u().min(0).max(100)}),importerVersion:i().trim().min(1).max(200),mappingHash:Rg}),eV=c({phase:v(["idle","metadata","download","mapping","parquet_write","verification","publish"]),completedBytes:u().int().nonnegative(),totalBytes:u().int().nonnegative().nullable(),completedRows:u().int().nonnegative(),totalRows:u().int().nonnegative().nullable(),message:i().trim().min(1).max(2e3).nullable()}),tV=c({schemaVersion:b("openpond.datasetImportJob.v1"),id:Es,profileId:Es,sourceKind:v(["huggingface","uploaded_file"]),status:G6,locator:ER.nullable(),inspection:Y6.nullable(),mapping:MR.nullable(),progress:eV,targetStorageRoot:i().trim().min(1).max(4e3).nullable(),tasksetId:Es.nullable(),tasksetRevision:u().int().positive().nullable(),artifactId:Es.nullable(),error:i().trim().min(1).max(2e4).nullable(),cancellationRequested:I(),createdAt:Ru,updatedAt:Ru,completedAt:Ru.nullable(),metadata:TR});c({profileId:Es,url:i().trim().min(1).max(2e3)});c({name:i().trim().min(1).max(500),objective:i().trim().min(1).max(2e4),mapping:MR,targetStorageRoot:i().trim().min(1).max(4e3).nullable(),licenseApproved:I().default(!1)});var mc=i().trim().min(1).max(200),Pg=c({operationId:mc,execution:He,executionKind:b("recorded_evidence").optional(),graders:p(Xo).min(1).max(100),maximumCostUsd:u().finite().min(1e-6).max(1e4),mappings:p(c({graderId:mc,fields:Ub}).strict()).max(100).optional()}).strict().superRefine((e,t)=>{new Set(e.graders.map(n=>n.id)).size!==e.graders.length&&t.addIssue({code:"custom",path:["graders"],message:"Select each grader once."}),e.mappings&&(new Set(e.mappings.map(n=>n.graderId)).size!==e.mappings.length||e.mappings.some(n=>!e.graders.some(a=>a.id===n.graderId)))&&t.addIssue({code:"custom",path:["mappings"],message:"Map each selected grader at most once."})}),nV=c({schemaVersion:b("openpond.experimentScoringPass.v1"),id:mc,teamId:mc,revision:u().int().positive(),request:Pg,graders:p(Li).min(1).max(100),status:v(["queued","running","cancelling","completed","failed","cancelled"]),totalCount:u().int().min(1).max(1e4),counts:c({pending:u().int().nonnegative(),running:u().int().nonnegative(),scored:u().int().nonnegative(),unavailable:u().int().nonnegative(),failed:u().int().nonnegative(),cancelled:u().int().nonnegative()}).strict(),resultAvailable:I(),createdAt:on(),startedAt:on().nullable(),completedAt:on().nullable(),error:c({code:mc,message:i().max(2e3)}).strict().nullable()}).strict();nV.extend({contentHash:i().regex(/^[a-f0-9]{64}$/)});var jR=c({sourcePass:He,graders:Pg.shape.graders,mappings:Pg.shape.mappings,maximumCostUsd:u().finite().positive().max(1e4)}).strict(),OR=c({externalDatasetBinding:Wo,scoring:jR.optional(),modelId:i().min(1).max(300),maximumCostUsd:u().finite().positive().max(1e4)}).strict(),Jb=c({source:v(["local","github","openpond_git"]),repositoryId:i().trim().min(1),profileId:i().trim().min(1)}).strict(),Ht=i().min(1).max(240),ha=i().regex(/^[a-f0-9]{64}$/),pc=c({schemaVersion:b("openpond.experimentImprovement.v1"),id:Ht,operationId:Ht,requestHash:ha,actorId:Ht,teamId:Ht,projectId:Ht.nullable(),ownerWorkspaceId:Ht,ownerRevision:u().int().nonnegative(),ownerSourceRevision:i().min(1).max(500),baseRelease:He,profileRef:Jb,baseProfileSourceRevision:i().min(1).max(500),evidence:c({manifest:uo,result:mo}).strict(),component:c({kind:v(["skill","workflow","agent","instruction"]),path:i().min(1).max(2e3),workflowId:Ht.optional()}).strict(),mode:v(["manual","llm_assisted"]),status:v(["draft","authoring_queued","authoring","frozen","testing","ready_for_review","adopting","accepted","rolled_back","declined","failed","cancelled"]),revision:u().int().positive(),limits:c({maximumCostUsd:u().finite().positive(),maximumAuthoringSteps:u().int().min(1).max(500),maximumDurationMs:u().int().min(1e3).max(864e5)}).strict(),authoringSteps:u().int().nonnegative().max(500),work:c({sessionId:Ht,turnId:Ht,revision:u().int().positive(),startedAt:i().datetime()}).strict().nullable(),frozen:c({release:He,sourceRevision:i().min(1).max(500),profileSourceRevision:i().min(1).max(500),authoringHash:ha,partitionHash:ha,executableSourceHash:ha,protectedClosureHash:ha,candidateRevision:u().int().positive(),diff:p(c({path:i(),before:ha.nullable(),after:ha.nullable()}).strict()).max(1e4)}).strict().nullable(),test:c({recipe:OR,recipeHash:i().regex(/^[a-f0-9]{64}$/),baselineOperationId:i(),candidateOperationId:i(),cancelRequestedAt:i().datetime().nullable(),dispatching:c({kind:v(["baseline","candidate"]),token:Ht,pid:u().int().positive(),processStart:i().nullable(),startedAt:i().datetime()}).strict().nullable()}).strict().nullable(),comparison:c({baseline:c({manifest:uo,result:mo}).strict(),candidate:c({manifest:uo,result:mo}).strict(),frozenHash:ha,humanProjection:Cg.optional()}).strict().nullable(),adoptionIntent:c({operationId:Ht,expectedOwnerRevision:u().int().nonnegative(),frozenHash:ha,humanProjection:Cg.optional()}).strict().nullable(),acceptance:He.nullable(),rollback:He.nullable(),error:i().max(2e3).nullable(),createdAt:i().datetime(),updatedAt:i().datetime(),contentHash:ha}).strict();function Oie(e){const t=pc.parse(e),{contentHash:n,...a}=t;if(Tt(a)!==n)throw new Error("Improvement state integrity failed.");if(Pr(t.evidence),t.evidence.manifest.teamId!==t.teamId||t.evidence.result.status!=="completed"||!t.evidence.result.cases.some(o=>o.status==="completed"))throw new Error("Improvement requires usable completed owner evidence.");if(t.test&&(Tt(t.test.recipe)!==t.test.recipeHash||xg(t.test.recipe.externalDatasetBinding).profileId!==t.profileRef.profileId))throw new Error("The test recipe changed its exact selected Profile.");if(t.comparison?.humanProjection){const o=YF(t.comparison.humanProjection);if(o.teamId!==t.teamId||o.projectId!==t.projectId||Tt(o.baseline)!==Tt(t.comparison.baseline)||Tt(o.candidate)!==Tt(t.comparison.candidate))throw new Error("Human comparison projection differs from its exact owner evidence.")}if(t.comparison&&(Pr(t.comparison.baseline),Pr(t.comparison.candidate),!t.frozen||t.comparison.frozenHash!==Tt(t.frozen)||!e4(t.comparison.baseline,t.comparison.candidate).comparable))throw new Error("Improvement comparison is not bound to a comparable frozen candidate.");if(t.status==="ready_for_review"&&(!t.frozen||!t.comparison))throw new Error("Improvement is missing qualification.");if(t.status==="adopting"&&(!t.adoptionIntent||!t.frozen||t.adoptionIntent.frozenHash!==Tt(t.frozen)))throw new Error("Improvement adoption intent is not bound to its tested revision.");if(t.status==="accepted"&&(!t.acceptance||!t.comparison||!t.frozen))throw new Error("Improvement acceptance is missing its exact qualification receipt.");if(t.status==="rolled_back"&&(!t.acceptance||!t.rollback))throw new Error("Profile rollback is missing its durable owner receipt.");return t}var $ie=c({states:p(pc).max(50),nextCursor:Ht.nullable()}).strict(),aV=c({operationId:Ht,ownerWorkspaceId:Ht,expectedOwnerRevision:u().int().nonnegative(),baseRelease:He,profileRef:Jb,profileSourceRevision:i().min(1).max(500),projectId:Ht.nullable(),evidence:He,component:pc.shape.component,mode:pc.shape.mode,limits:pc.shape.limits}).strict(),Nie=ot("operation",[c({operation:b("list"),limit:u().int().min(1).max(50).default(30),cursor:Ht.optional()}).strict(),c({operation:b("options"),evidence:He}).strict(),c({operation:b("start"),request:aV}).strict(),c({operation:v(["read","humanComparisonOptions"]),id:Ht}).strict(),c({operation:b("instructions"),id:Ht}).strict(),c({operation:b("edit"),id:Ht,revision:u().int().positive(),expectedFileHash:ha,text:i().max(25e4)}).strict(),c({operation:b("mode"),id:Ht,revision:u().int().positive(),mode:v(["manual","llm_assisted"])}).strict(),c({operation:b("author"),id:Ht,revision:u().int().positive(),modelId:Ht,prompt:i().min(1).max(2e4)}).strict(),c({operation:v(["freeze","finishAuthoring","useCandidate","discard","cancel","rollback"]),id:Ht,revision:u().int().positive()}).strict(),c({operation:b("test"),id:Ht,revision:u().int().positive(),recipe:OR}).strict(),c({operation:b("compare"),id:Ht,revision:u().int().positive(),baseline:He,candidate:He,humanSelections:PC.optional()}).strict()]),$R=c({teamId:Ht,evidence:He,scoring:jR.optional(),profiles:p(c({id:ha,name:i(),profileRef:Jb,ownerWorkspaceId:Ht,ownerRevision:u().int().nonnegative(),baseRelease:He,profileSourceRevision:i(),components:p(c({kind:v(["skill","instruction","agent","workflow"]),path:i(),agentId:i().optional(),workflowId:i().optional(),label:i(),binding:Wo}).strict()).max(500)}).strict()).max(100)}).strict(),iV=c({candidateId:Ht,actorId:Ht,teamId:Ht,projectId:Ht.nullable(),candidateRevision:u().int().positive(),recipeHash:ha,baseline:c({manifest:uo,result:mo}).strict(),candidate:c({manifest:uo,result:mo}).strict(),contentHash:ha}).strict();function Die(e){const t=iV.parse(e),{contentHash:n,...a}=t;if(Tt(a)!==n)throw new Error("Accepted Human discovery integrity failed.");for(const o of[t.baseline,t.candidate])if(Pr(o),o.manifest.teamId!==t.teamId||o.manifest.lineage?.humanProjection)throw new Error("Discovery must retain original owner evidence.");return t}var nn=i().trim().min(1).max(240),Hi=i().regex(/^[a-f0-9]{64}$/),Zb=c({schemaVersion:b("openpond.advancedRefinerEvaluation.v1"),operationId:nn,actorId:nn,teamId:nn,projectId:nn.nullable(),mode:v(["review_quality","downstream_adaptation"]),profileRef:c({source:v(["local","github","openpond_git"]),repositoryId:nn,profileId:nn}).strict(),sourceRevision:i().min(1).max(500),baselineRelease:He,refinerRelease:He,evidence:He,externalDatasetBinding:Wo,adaptationDatasetBinding:Wo,privateClosureHash:Hi,adaptationTaskIds:p(nn).min(1).max(1e4),holdoutTaskIds:p(nn).min(1).max(1e4),adaptationSplit:v(["train","validation","test","frozen_eval"]),holdoutSplit:v(["train","validation","test","frozen_eval"]),environmentPolicy:ot("kind",[c({kind:b("resettable"),environmentHash:Hi}).strict(),c({kind:b("frozen_observations"),environmentHash:Hi}).strict()]),maximumCostUsd:u().finite().positive().max(1e4),maximumDurationMs:u().int().min(1e3).max(864e5),maximumModelSteps:u().int().min(1).max(1e3),contentHash:Hi}).strict();function Hie(e){const t=Zb.parse(e),{contentHash:n,...a}=t;if(Tt(a)!==n)throw new Error("Advanced Refiner evaluation admission changed.");const o=xg(t.externalDatasetBinding);if(o.profileId!==t.profileRef.profileId||o.protectedProfileClosureHash!==t.privateClosureHash)throw new Error("Advanced evaluation changed its Profile or protected evaluator closure.");if(t.adaptationSplit===t.holdoutSplit||new Set([...t.adaptationTaskIds,...t.holdoutTaskIds]).size!==t.adaptationTaskIds.length+t.holdoutTaskIds.length)throw new Error("Adaptation and private holdout must be disjoint ordered cases.");const r=xg(t.adaptationDatasetBinding);if(r.profileId!==o.profileId||r.packageHash!==o.packageHash||Tt(r.dataset)!==Tt(o.dataset)||Tt(r.target)!==Tt(o.target)||r.protectedProfileClosureHash!==o.protectedProfileClosureHash)throw new Error("This native advanced adapter needs separate adaptation and holdout recipes from the same exact released package and target.");if(r.split!==t.adaptationSplit||o.split!==t.holdoutSplit)throw new Error("Advanced split policies differ from their exact admitted recipes.");const s=new Set(o.population.map(m=>m.taskId)),l=new Set(r.population.map(m=>m.taskId));if(t.holdoutTaskIds.some(m=>!s.has(m))||t.adaptationTaskIds.some(m=>!l.has(m)))throw new Error("Advanced evaluation selected cases outside its exact Dataset recipe.");return t}var oV=c({pin:Zb,modelId:nn,profileId:nn,model:Pb,seed:u().int(),reasoningEffort:v(["none","off","low","medium","high","xhigh","max"]).nullable()}).strict(),rV=ot("operation",[c({operation:b("start"),request:oV}).strict(),c({operation:v(["read","cancel","resume"]),id:nn}).strict(),c({operation:b("list")}).strict()]),sV=c({taskId:nn,sourceCaseHash:Hi,reviewSessionId:nn,reviewTurnId:nn,inputHarness:He,trigger:He,decision:v(["no_action","route_deterministically","queue_refiner"]),outcome:He.nullable(),proposal:He.nullable(),validations:p(He).max(100),grade:c({id:nn,contentHash:Hi,score:u().min(0).max(1).nullable(),passed:I(),failureClass:i().nullable()}).strict(),resetComplete:I()}).strict(),lV=c({schemaVersion:b("openpond.advancedRefinerReviewReceipt.v1"),id:nn,runId:nn,pinHash:Hi,ownerActorId:nn,teamId:nn,privateClosureHash:Hi,refinerRelease:He,cases:p(sV).min(1).max(1e4),reviewScore:u().min(0).max(1).nullable(),completedCases:u().int().nonnegative(),noActionCases:u().int().nonnegative(),routedCases:u().int().nonnegative(),proposalCases:u().int().nonnegative(),costUsd:u().finite().nonnegative().nullable(),cleanupComplete:I(),createdAt:i().datetime(),contentHash:Hi}).strict(),ix=$R.shape.profiles.element,Lie=$R.extend({profiles:p(ix.extend({components:p(ix.shape.components.element.extend({adaptationSplits:p(c({split:v(["train","validation","test","frozen_eval"]),taskIds:p(nn)})),environmentHash:Hi,resettable:I(),reviewQuality:I()}))})),refinerReleases:p(He),activeRefiner:He.nullable(),models:p(c({id:nn,profileId:nn,name:i(),location:v(["local","hosted"])}))}),cV=c({operation:b("prepare"),evidence:He,profileOptionId:nn,componentLabel:nn,mode:v(["review_quality","downstream_adaptation"]),adaptationSplit:v(["train","validation","test","frozen_eval"]),operationId:nn,refinerRelease:He,maximumCostUsd:u().positive(),maximumDurationMs:u().int().positive(),maximumModelSteps:u().int().positive()}).strict();vt([rV,cV,c({operation:b("options"),evidence:He}).strict()]);var dV=c({modelRequests:u().int().nonnegative(),knownSpendUsd:u().nonnegative(),totalSpendUsd:u().nonnegative().nullable(),heldUsd:u().nonnegative(),uncertainRequests:u().int().nonnegative()}).strict();const Oo=T.nullable(),eo=u().int().nonnegative(),uV=i().regex(/^[a-f0-9]{40}$/),mV=c({name:i().trim().min(1).max(160),startedAt:ye,completedAt:ye,durationMs:u().nonnegative(),clock:v(["monotonic","provider","wall"]),outcome:v(["succeeded","failed","cancelled"])}).strict(),pV=c({schemaVersion:b("openpond.correlatedTelemetryReceipt.v1"),stage:v(["training","evaluation","deployment","inference"]),correlation:c({modelRunId:Oo,modelVersionId:Oo,policyVersion:eo.nullable(),taskId:Oo,rolloutGroupId:Oo,providerResourceId:Oo,deploymentId:Oo,inferenceRequestId:Oo}).strict(),spans:p(mV).max(1e4),usage:c({promptTokens:eo.nullable(),generatedTokens:eo.nullable(),gpuSeconds:u().nonnegative().nullable(),workerActiveSeconds:u().nonnegative().nullable(),optimizerSteps:eo.nullable(),rolloutGroups:eo.nullable(),successfulTrajectories:eo.nullable(),failedTrajectories:eo.nullable(),peakGpuMemoryBytes:eo.nullable(),peakGpuUtilizationPercent:u().min(0).max(100).nullable()}).strict(),resource:c({provider:T,resourceIds:p(T).max(1e3),gpuType:i().trim().min(1).max(300).nullable(),gpuCount:eo.nullable(),baseProfileId:Oo,baseRepository:i().trim().min(1).max(512).nullable(),baseRevision:uV.nullable(),adapterContentHash:H.nullable()}).strict(),cost:c({currency:b("USD"),providerReportedUsd:u().nonnegative().nullable(),quotedHourlyUsd:u().nonnegative().nullable(),estimatedUsd:u().nonnegative().nullable(),methodologyVersion:i().trim().min(1).max(160),pricingInputs:le(i().trim().min(1).max(160),u().finite()),unitEstimates:le(i().trim().min(1).max(160),u().nonnegative())}).strict(),recordedAt:ye,contentHash:H}).strict(),Rn=i().trim().min(1).max(240),go=i().regex(/^[a-f0-9]{64}$/),qo=i().datetime({offset:!0}),On=c({id:Rn,contentHash:go}).strict(),fV=On.extend({revision:u().int().positive()}).strict(),NR=c({providerId:Rn,modelId:i().trim().min(1).max(300)}).strict(),lp=v(["correction","sibling_verification","cumulative_known","development","retained","frozen_final","training_eligible"]),hV=c({taskId:Rn,taskContentHash:go,panelRole:lp,passLabel:Rn.nullable(),optimizerEligible:I(),criticalInvariantIds:p(Rn).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."})}),gV=c({schemaVersion:b("openpond.continualBenchIssuePacket.v1"),id:Rn,revision:u().int().positive(),contentHash:go,familyId:Rn,familyLabel:i().trim().min(1).max(500),severity:v(["low","medium","high","critical"]),cases:p(hV).min(2).max(1e4),duplicateEvidence:On,leakageEvidence:On,priorExposureEvidence:On,observedAt:qo,reviewedAt:qo,queuedAt:qo.nullable(),runAt:qo.nullable(),createdBy:Rn,createdAt:qo}).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."})}),vV=c({id:Rn,role:lp,passLabel:Rn.nullable(),taskset:fV,familyIds:p(Rn).min(1).max(1e5),taskCount:u().int().positive().max(1e6),sealedAt:qo}).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."})}),yh=ot("kind",[c({kind:b("base_model"),id:Rn,revision:i().trim().min(1).max(500),contentHash:go}).strict(),c({kind:b("model_version"),id:Rn,contentHash:go}).strict(),c({kind:b("external_reference"),id:Rn,model:NR,providerRevision:i().trim().min(1).max(500),contentHash:go}).strict()]),bV=c({scheduleEntryId:Rn,ordinal:u().int().nonnegative(),label:Rn,role:v(["seed","daily_residual","rank_candidate","weekly_rollup","full_refresh"]),parentRule:v(["base_model","previous_release","seed_release","accepted_daily_head","accepted_seed"]),trainableRank:u().int().positive().max(1024),correctionPanelIds:p(Rn).min(1).max(1e3),optimizerGroupsPerTask:u().int().positive().max(1e3),trajectoriesPerGroup:u().int().min(4).max(1e3)}).strict(),yV=c({revision:u().int().positive(),requireAllAttemptsTerminal:b(!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:I(),authorizedClaims:p(v(["systems_complete","correction_absorbed","issue_generalized","continually_current","frontier_pareto_result"])).min(1).max(5)}).strict(),SV=c({schemaVersion:b("openpond.continualBenchmarkProtocol.v1"),id:Rn,revision:u().int().positive(),contentHash:go,ownerId:Rn,createdAt:qo,sealedAt:qo,creationReceipt:On,predecessorSeries:c({id:Rn,revision:u().int().positive(),contentHash:go}).strict().nullable(),scenarioPack:On,issueFamilyLedger:On,issuePacketRelease:On,panels:p(vV).min(6).max(1e4),grader:On,judge:c({release:On,rubricRelease:On,calibrationRelease:On,model:NR}).strict().nullable(),policies:c({base:yh,master:yh.nullable(),externalReferences:p(yh).min(1).max(20)}).strict(),invariants:c({systemPromptHash:go,toolSchema:On,application:On,harness:On,runtime:On,workerImage:On,autoRefiner:c({enabled:I(),release:On.nullable()}).strict()}).strict(),schedule:p(bV).min(1).max(1e3),evaluation:c({seeds:p(u().int()).min(3).max(100),repetitions:u().int().min(3).max(20),powerRule:On,pairedBootstrapSamples:u().int().min(1e3).max(1e6),confidenceLevel:b(.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:yV}).strict().superRefine((e,t)=>{const n=e.panels.map(r=>r.id);new Set(n).size!==n.length&&t.addIssue({code:"custom",path:["panels"],message:"Protocol panel ids must be unique."});for(const r of["development","retained","frozen_final","training_eligible"])e.panels.filter(s=>s.role===r).length!==1&&t.addIssue({code:"custom",path:["panels"],message:`A protocol requires exactly one ${r} panel.`});[...e.schedule].sort((r,s)=>r.ordinal-s.ordinal).some((r,s)=>r.ordinal!==s)&&t.addIssue({code:"custom",path:["schedule"],message:"Protocol schedule ordinals must be contiguous from zero."});const o=new Set(n);e.schedule.some(r=>r.correctionPanelIds.some(s=>!o.has(s)))&&t.addIssue({code:"custom",path:["schedule"],message:"Every scheduled correction panel must belong to the protocol."})}),xV=v(["draft","active","completed","archived"]),kV=v(["draft","ready","queued","running","candidate","accepted","rejected","no_signal","failed","cancelled"]),DR=v(["seed","daily_residual","rank_candidate","weekly_rollup","full_refresh"]),wV=v(["base_model","previous_release","seed_release","accepted_daily_head","accepted_seed"]),IV=v(["seed_taskset","nightly_selection","daily_cohort_union","eligible_task_pool"]),_V=v(["live_client","evaluation_attempt","replay_evidence","manual"]),CV=c({id:T,ordinal:u().int().nonnegative(),label:i().trim().min(1).max(100),role:DR,parentRule:wV,taskSource:IV,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."})}),RV=c({id:T,version:u().int().positive(),requireCheckpoint:I(),requireAppliedOptimizerUpdate:I(),minimumCurrentCohortMeanImprovement:u().finite(),maximumRetainedMeanRegression:u().finite().nonnegative(),blockCriticalInvariantRegression:I(),automaticDailyAdvancement:I()}).strict(),PV=c({schemaVersion:b("openpond.modelComparisonSeries.v1"),id:T,profileId:T,modelProjectId:T,name:i().trim().min(1).max(500),objective:i().trim().min(1).max(2e4),status:xV,revision:u().int().positive(),productionBinding:c({role:b("chat_manual"),roleTargetId:T}).strict(),baseModel:c({id:T,revision:i().trim().min(1).max(256)}).strict(),seedTaskset:Xt,eligibleTaskPool:Xt,evaluationTasksets:c({development:Xt,retained:Xt,frozenFinal:Xt}).strict(),grader:W,benchmarkProtocol:SV.nullable().default(null),automaticEvaluation:c({enabled:I()}).strict().default({enabled:!1}),residualProfile:c({profileId:T,serializedEnvelopeRank:u().int().positive().max(1024),maximumEnabledRank:u().int().positive().max(1024),topology:b("uniform_block_masked")}).strict(),schedule:p(CV).min(1).max(1e3),scheduleSealedAt:ye.nullable(),advancementPolicy:RV,executionPolicy:c({startWhenReady:b(!1)}).strict(),acceptedSeedEntryId:T.nullable(),acceptedDailyHeadEntryId:T.nullable(),promotedBindingId:T.nullable(),createdBy:T,createdAt:ye,updatedAt:ye}).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 r=e.schedule.filter(m=>m.role==="rank_candidate");r.length===1&&t.addIssue({code:"custom",path:["schedule"],message:"A causal rank comparison requires at least two rank candidates."}),new Set(r.map(m=>m.trainableRank)).size!==r.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."})}),HR=c({source:_V,taskIds:p(T).min(1).max(1e5),observedFrom:ye,observedTo:ye,reviewedAt:ye,reviewedBy:T,sourceTaskset:Xt}).strict(),AV=HR.extend({derivedFamilyKeys:p(T).min(1).max(1e5),familyDerivation:c({algorithm:T,sourceTasksetHash:H}).strict(),selectionHash:H}).strict(),LR=ot("kind",[c({kind:b("base_model"),id:T,revision:i().trim().min(1).max(256)}).strict(),c({kind:b("model_version"),id:T,contentHash:H}).strict()]),TV=c({id:T,branchOrdinal:u().int().nonnegative(),rank:u().int().positive().max(1024),offsetStart:u().int().nonnegative(),offsetEnd:u().int().positive(),optimizationRole:v(["frozen","trainable"]),artifactLineageId:T.nullable()}).strict().superRefine((e,t)=>{e.offsetEnd-e.offsetStart!==e.rank&&t.addIssue({code:"custom",path:["offsetEnd"],message:"Block offsets must span exactly the declared rank."})}),EV=c({disposition:v(["advance","hold","no_signal"]),policy:c({id:T,version:u().int().positive()}).strict(),reasonCodes:p(T).min(1).max(100),summary:i().trim().min(1).max(5e3),decidedBy:T,decidedAt:ye}).strict(),MV=c({evaluationRunId:T,modelVersionId:T,taskset:Xt,grader:W,cohortRole:v(["current","correction","sibling_verification","cumulative_known","development","retained","prior_disclosed","frozen_final"]),panelId:T.nullable().default(null),protocol:c({id:T,revision:u().int().positive(),contentHash:H}).strict().nullable().default(null)}).strict(),jV=c({attemptOrdinal:u().int().positive(),trainingPlanId:T.nullable(),modelRunId:T.nullable(),terminalStatus:v(["failed","cancelled"]),queuedAt:ye.nullable(),startedAt:ye.nullable(),completedAt:ye}).strict(),nl=c({seriesId:T,entryId:T,scheduleEntryId:T,ordinal:u().int().nonnegative(),releaseHash:H}).strict(),OV=c({schemaVersion:b("openpond.modelComparisonSeriesEntry.v1"),id:T,seriesId:T,profileId:T,modelProjectId:T,scheduleEntryId:T,releaseHash:H,ordinal:u().int().nonnegative(),label:i().trim().min(1).max(100),role:DR,branch:v(["daily","rank_candidate","weekly_rollup","full_refresh"]),status:kV,parent:LR,taskset:Xt,sourceTasksets:p(Xt).min(1).max(1e3),taskSelection:AV.nullable(),trainableRank:u().int().positive().max(1024),serializedEnvelopeRank:u().int().positive().max(1024),enabledCumulativeRank:u().int().positive().max(1024),trainableBlockId:T,residualBlocks:p(TV).min(1).max(1024),attemptOrdinal:u().int().positive().default(1),priorRunAttempts:p(jV).max(100).default([]),trainingPlanId:T.nullable(),modelRunId:T.nullable(),modelVersionId:T.nullable(),evaluations:p(MV).max(1e5),decision:EV.nullable(),promotionBindingId:T.nullable(),queuedAt:ye.nullable(),startedAt:ye.nullable(),completedAt:ye.nullable(),createdAt:ye,updatedAt:ye}).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 r=e.priorRunAttempts.map(s=>s.attemptOrdinal);(e.priorRunAttempts.length!==e.attemptOrdinal-1||r.some((s,l)=>s!==l+1))&&t.addIssue({code:"custom",path:["priorRunAttempts"],message:"Prior Run attempts must be a contiguous history before the active attempt."})});c({seriesId:T,scheduleEntryId:T,taskSelection:HR.nullable(),expectedSeriesRevision:u().int().positive()}).strict();const $V=v(["base_reference","lora_adapter"]),qR=c({baseModel:c({source:b("huggingface"),repoId:T,revision:i().regex(/^[a-f0-9]{40}$/),configHash:H,tokenizerHash:H,licenseId:T,gated:I()}).strict(),processor:c({repository:T,revision:i().regex(/^[a-f0-9]{40}$/),configHash:H}).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."})}),NV=c({schemaVersion:b("openpond.modelVersion.v1"),id:T,modelId:T,profileId:T,version:u().int().nonnegative(),kind:$V,status:v(["available","failed"]),baseModel:hd,taskset:Xt,comparisonSeriesEntry:nl.nullable().optional(),evaluationTasksetRef:Xt.nullable().optional(),releaseGraph:c({resolvedBundleHash:H,profileRelease:Xt,harnessRelease:W,agentRelease:W.nullable(),grader:c({id:T,contentHash:H}).strict()}).strict(),artifactLineageId:T.nullable(),adapterStatus:v(["not_trained","trained"]),createdAt:ye,contentHash:H}).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."})}),DV=c({schemaVersion:b("openpond.rewardModelVersion.v1"),id:T,modelId:T,profileId:T,version:u().int().positive(),role:b("reward"),status:v(["available","failed"]),scope:v(["synthetic_smoke","human_preference"]),baseModel:hd,runtime:qR.nullable().default(null),taskset:Xt,preferenceDatasetRelease:W,releaseGraph:c({resolvedBundleHash:H,profileRelease:Xt,harnessRelease:W,grader:c({id:T,contentHash:H}).strict()}).strict(),artifacts:c({checkpoint:W.extend({objectRef:i().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/),files:p(c({path:i().trim().min(1).max(512),sizeBytes:u().int().positive(),sha256:H}).strict()).min(4).max(128)}).strict(),adapter:W,scalarHead:W,bucketHead:W.nullable(),processorRelease:W}).strict(),qualificationReport:W.nullable(),createdAt:ye,contentHash:H}).strict(),HV=c({schemaVersion:b("openpond.rewardModelRunReceipt.v1"),provider:T,providerRunId:T,resolvedBundleHash:H,finalCheckpoint:W.extend({objectRef:i().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/)}).strict(),adapter:W,scalarHead:W,bucketHead:W.nullable(),processorRelease:W,optimizerEvidence:W,managedExecutionReceipt:W.nullable().default(null),parameterDeltaHash:H,cleanup:c({computeReleased:I(),providerTerminalObserved:I()}).strict(),contentHash:H}).strict(),LV=C$(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:b("openpond.rewardModelRun.v1"),id:T,rewardModelId:T,rewardModelVersionId:T.nullable(),profileId:T,role:b("reward"),scope:v(["synthetic_smoke","human_preference"]),status:v(["prepared","running","succeeded","failed","cancelled"]),taskset:Xt,tasksetRelease:W,preferenceDatasetRelease:W,recipeRelease:W,destinationId:T,quote:c({maximumSpendUsd:u().positive(),hourlyCostUsd:u().nonnegative().nullable()}).strict(),managedRunId:T.nullable(),progress:c({completedSteps:u().int().nonnegative(),totalSteps:u().int().positive(),latestLoss:u().finite().nullable()}).strict(),receipt:HV.nullable(),qualificationReport:W.nullable(),accruedSpendUsd:u().nonnegative().nullable(),failureOwner:v(["authoring","admission","provider","runner","artifact","qualification","cleanup"]).nullable(),failure:i().trim().min(1).max(5e3).nullable(),startedAt:ye,completedAt:ye.nullable(),updatedAt:ye}).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."})}),qV=c({schemaVersion:b("openpond.modelRunReceipt.v1"),provider:T,providerRunId:T,assignmentHash:H,resultHash:H,transcriptHash:H,traceHash:H.nullable(),resolvedBundleHash:H,artifactPath:i().trim().min(1).max(2e3),cleanup:c({computeReleased:I(),tunnelClosed:I()}).strict(),telemetry:pV.nullable().default(null),contentHash:H}).strict(),No=c({inputTokens:u().int().nonnegative(),outputTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative(),costUsd:u().nonnegative().nullable()}).strict(),ox=i().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),Yb=c({phase:v(["baseline","adaptation","candidate_adaptation","candidate"]),taskId:T,attemptId:T,sessionId:T.nullable(),turnId:T.nullable(),passed:I(),score:u().min(0).max(1).nullable(),failureClass:Gb.nullable(),inputTokens:u().int().nonnegative(),outputTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative(),latencyMs:u().int().nonnegative(),costUsd:u().nonnegative().nullable(),startedAt:ye}).strict(),rx=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(),UR=c({target:b("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:I(),passed:I(),cohorts:c({adaptation:rx,heldOut:rx}).strict()}).strict(),Qb=c({baseline:No,adaptation:No,candidateAdaptation:No,candidate:No,refiner:No,grader:No}).strict(),UV=c({usage:Qb,observedSpendUsd:u().nonnegative(),attempts:p(Yb).max(1e4)}).strict(),zV=c({id:T,contentHash:H,artifactPath:i().trim().min(1).max(2e3)}).strict(),BV=c({schemaVersion:b("openpond.modelEvaluationReceipt.v1"),benchmarkId:T,resultManifest:c({id:T,contentHash:H,artifactPath:i().trim().min(1).max(2e3)}).strict(),stages:c({baseline:W,adaptation:W,refiner:W,candidateAdaptation:W,candidate:W,comparison:W}).strict(),usage:Qb,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:I(),heldOutCandidatePassed:I(),passed:I()}).strict(),foregroundTokenDelta:u().int(),foregroundTokenDeltaPercent:u().finite().nullable(),taskEfficiency:UR.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:I()}).strict(),evidenceSnapshot:W,lineage:c({adaptationEvidenceHash:H,refinerInputHash:H,refinerOutcomeHash:H,validationHash:H,applyReceiptHash:H,candidateRelease:W,valid:I()}).strict(),invalidReasons:p(i().trim().min(1).max(2e3)).max(100),attempts:p(Yb).max(1e4).default([]),terminalClassification:v(["improved","no_improvement","regressed","inconclusive","cancelled","infrastructure_failure"]),profileGit:c({ref:i().trim().min(1).max(2e3),commit:ox,baseCommit:ox}).strict().nullable(),contentHash:H}).strict(),FV=c({schemaVersion:b("openpond.modelEvaluationStopReceipt.v1"),benchmarkId:T,terminalClassification:b("inconclusive"),stopReason:v(["candidate_harness_unchanged","candidate_lineage_invalid"]),reason:i().trim().min(1).max(5e3),stoppedAfter:b("refiner"),baselineHarness:W,candidateHarness:W,refiner:c({id:T,contentHash:H,outcomeCount:u().int().nonnegative()}).strict(),usage:Qb,budget:c({maximumSpendUsd:u().nonnegative(),observedSpendUsd:u().nonnegative(),enforced:I()}).strict(),evidenceSnapshot:W,attempts:p(Yb).max(1e4),contentHash:H}).strict(),sx=c({level:b(.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."})}),VV=c({schemaVersion:b("openpond.modelComparisonBenchmarkReceipt.v1"),benchmarkId:b("model-comparison"),target:c({kind:v(["base_model","model_version","external_reference"]),label:i().trim().min(1).max(300),modelVersionId:T.nullable(),model:Sn.nullable()}).strict(),taskset:Xt,grader:W,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:sx.nullable()}).strict(),judge:c({judgeModel:Sn,judgeRelease:W,rubricRelease:W,calibrationRelease:W,score:u().min(0).max(100),scoreCi95:sx,comparisonCount:u().int().positive(),wins:u().int().nonnegative(),ties:u().int().nonnegative(),losses:u().int().nonnegative(),referenceLabel:i().trim().min(1).max(300)}).strict().superRefine((e,t)=>{e.wins+e.ties+e.losses!==e.comparisonCount&&t.addIssue({code:"custom",message:"Judge win, tie, and loss counts must equal comparisonCount."})}).nullable(),attempts:p(c({attemptId:T.nullable().default(null),taskId:T,seed:u().int(),repetition:u().int().nonnegative(),status:v(["succeeded","failed"]),deterministicScore:u().finite().nullable(),passed:I().nullable(),judgeScore:u().min(0).max(100).nullable(),judgePreference:v(["win","tie","loss"]).nullable(),transcriptHash:H.nullable(),traceHash:H.nullable(),transcriptArtifact:c({artifactPath:i().trim().min(1).max(2e3),jsonPointer:i().trim().min(1).max(1e3)}).strict().nullable().default(null),traceArtifact:c({artifactPath:i().trim().min(1).max(2e3),jsonPointer:i().trim().min(1).max(1e3)}).strict().nullable().default(null),latencyMs:u().int().nonnegative().nullable().default(null),failureClass:Gb.nullable()}).strict()).max(1e5),usage:c({policy:No.nullable(),judge:No.nullable(),observedSpendUsd:u().nonnegative().nullable(),evaluationGpuSeconds:u().nonnegative().nullable().default(null)}).strict(),managedServing:c({jobId:T,terminalState:v(["completed","cancelled","failed","budget_exhausted"]),sourcePolicyVersion:u().int().nonnegative(),sourceAdapterSha256:H.nullable(),servedPolicyVersion:u().int().nonnegative().nullable(),servedAdapterSha256:H.nullable(),accruedSpendUsd:u().nonnegative(),cleanupAttestationHash:H,resourceCount:u().int().nonnegative(),activeResourceCount:b(0)}).strict().nullable().default(null),evidenceSnapshot:c({id:T,contentHash:H,artifactPath:i().trim().min(1).max(2e3)}).strict(),completedAt:ye,contentHash:H}).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."})}),KV=c({advancedEvaluation:Zb.optional(),benchmarkId:b("harness-refiner"),model:Sn,upstreamModel:c({providerId:T,modelId:i().trim().min(1).max(300),revision:i().trim().min(1).max(300),pricing:c({version:i().trim().min(1).max(300),source:i().trim().min(1).max(300),effectiveAt:ye,inputUsdPerMillionTokens:u().nonnegative(),cachedInputUsdPerMillionTokens:u().nonnegative(),outputUsdPerMillionTokens:u().nonnegative()}).strict().optional()}).strict(),reasoningEffort:i().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:v(["baseline","adaptation","candidate_adaptation","candidate"]),split:i().trim().min(1).max(100),taskIds:p(T).min(1).max(1e5),attemptCount:u().int().positive()}).strict()).length(4)}).strict(),WV=c({benchmarkId:b("model-comparison"),target:c({kind:v(["base_model","model_version","external_reference"]),label:i().trim().min(1).max(300),modelVersionId:T.nullable(),model:Sn.nullable()}).strict(),grader:W,judge:c({model:Sn,release:W,rubricRelease:W,calibrationRelease:W,referenceLabel:i().trim().min(1).max(300)}).strict().nullable(),seeds:p(u().int()).min(1).max(100),repetitions:u().int().positive().max(20),maximumSpendUsd:u().nonnegative(),series:c({id:T,protocol:c({id:T,revision:u().int().positive(),contentHash:H}).strict()}).strict().nullable().default(null),panel:c({id:T,role:v(["correction","sibling_verification","cumulative_known","development","retained","frozen_final"]),passLabel:T.nullable()}).strict().nullable().default(null),comparisonPair:c({entryId:T,parent:LR,candidateModelVersionId:T}).strict().nullable().default(null),attemptPlan:p(c({stage:b("comparison"),split:i().trim().min(1).max(100),taskIds:p(T).min(1).max(1e5),attemptCount:u().int().positive()}).strict()).length(1)}).strict(),GV=vt([KV,WV]),JV=c({schemaVersion:b("openpond.modelRun.v1"),id:T,modelId:T,modelVersionId:T.nullable(),profileId:T,kind:v(["rollout_smoke","training","evaluation"]),status:v(["prepared","running","succeeded","failed","cancelled"]),method:v(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]).nullable(),destinationId:T.nullable(),taskset:Xt,comparisonSeriesEntry:nl.nullable().optional(),evaluationTasksetRef:Xt.nullable().optional(),harnessRelease:W.nullable().optional(),quote:c({maximumSpendUsd:u().nonnegative(),hourlyCostUsd:u().nonnegative().nullable()}).strict().nullable(),evaluation:GV.nullable().default(null),evaluationProgress:c({stage:v(["baseline","adaptation","refiner","candidate_adaptation","candidate","comparison"]),completedAttempts:u().int().nonnegative(),totalAttempts:u().int().positive(),accounting:UV.nullable().default(null),advancedAccounting:dV.optional(),evidenceSnapshot:zV.nullable().default(null)}).strict().nullable().default(null),reward:c({raw:u(),components:le(i(),u())}).strict().nullable(),receipt:vt([qV,BV,FV,VV,lV]).nullable(),adapterArtifactLineageId:T.nullable(),failure:i().trim().min(1).max(5e3).nullable(),startedAt:ye,completedAt:ye.nullable(),updatedAt:ye}).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"&&e.receipt.schemaVersion!=="openpond.advancedRefinerReviewReceipt.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 qie(e){const t=new Map;for(const C of e.attempts){const R=`${C.phase}\0${C.taskId}`,E=t.get(R);(!E||C.startedAt>E.startedAt||C.startedAt===E.startedAt&&C.attemptId>E.attemptId)&&t.set(R,C)}const n=[...t.values()],a=[["adaptation","adaptation","candidate_adaptation"],["held_out","baseline","candidate"]].flatMap(([C,R,E])=>{const A=new Map(n.filter(O=>O.phase===E).map(O=>[O.taskId,O]));return n.filter(O=>O.phase===R).flatMap(O=>{const $=A.get(O.taskId);return $?[{cohort:C,taskId:O.taskId,baseline:O,refined:$,tokenDelta:$.totalTokens-O.totalTokens}]:[]})}),o=new Set(n.filter(C=>C.phase==="baseline"||C.phase==="adaptation").map(C=>C.taskId)).size,r=e.targetTaskCount??o;if(!Number.isInteger(r)||r<0)throw new Error("Benchmark task-efficiency target must be a non-negative integer.");const s={adaptation:new Set(n.filter(C=>C.phase==="adaptation").map(C=>C.taskId)).size,held_out:new Set(n.filter(C=>C.phase==="baseline").map(C=>C.taskId)).size},l=(C,R)=>({targetTaskCount:R,comparedTaskCount:C.length,passedTaskCount:C.filter(E=>E.tokenDelta<0).length,failedTaskCount:C.filter(E=>E.tokenDelta>=0).length,lowerTaskCount:C.filter(E=>E.tokenDelta<0).length,higherTaskCount:C.filter(E=>E.tokenDelta>0).length,unchangedTaskCount:C.filter(E=>E.tokenDelta===0).length}),m=l(a,r),d=a.reduce((C,R)=>C+R.baseline.totalTokens,0),f=a.reduce((C,R)=>C+R.refined.totalTokens,0),g=f-d,x=a.length===r;return{summary:UR.parse({target:"all_tasks_lower",...m,baselineTokens:d,refinedTokens:f,tokenDelta:g,tokenDeltaPercent:d>0?g/d*100:null,complete:x,passed:x&&m.passedTaskCount===r,cohorts:{adaptation:l(a.filter(C=>C.cohort==="adaptation"),s.adaptation),heldOut:l(a.filter(C=>C.cohort==="held_out"),s.held_out)}}),pairs:a}}const ZV=v(["measuring","up_to_date","needs_attention"]),YV=v(["fixed","retained","regressed","unresolved","unavailable"]),lx=c({evaluationRunId:T,attemptKey:T,artifactPath:i().trim().min(1).max(2e3),jsonPointer:i().trim().min(1).max(1e3),transcriptHash:H.nullable(),traceHash:H.nullable()}).strict(),Ag=c({level:b(.95),lower:u().finite(),upper:u().finite()}).strict(),QV=c({panelId:T,panelRole:lp,passLabel:T.nullable(),taskset:Xt,attempted:u().int().nonnegative(),available:u().int().nonnegative(),passed:u().int().nonnegative(),strictSuccess:u().min(0).max(1).nullable(),strictSuccessCi95:Ag.nullable(),judgeScore:u().min(0).max(100).nullable(),judgeScoreCi95:Ag.nullable()}).strict(),XV=c({schemaVersion:b("openpond.modelCurrencySnapshot.v1"),id:T,contentHash:H,seriesId:T,protocol:c({id:T,revision:u().int().positive(),contentHash:H}).strict(),entryId:T,passLabel:T,parent:ot("kind",[c({kind:b("base_model"),id:T,revision:i().trim().min(1).max(500)}).strict(),c({kind:b("model_version"),id:T,contentHash:H}).strict()]),candidate:c({kind:b("model_version"),id:T,contentHash:H}).strict(),sources:c({evaluationRunIds:p(T).max(1e5),attemptIds:p(T).max(1e6),tasksets:p(Xt).max(1e4),grader:W,judge:W.nullable(),calibration:W.nullable()}).strict(),matches:p(c({key:T,panelId:T,panelRole:lp,taskId:T,issueFamilyId:T,seed:u().int(),repetition:u().int().nonnegative(),classification:YV,parentPassed:I().nullable(),candidatePassed:I().nullable(),parentAttempt:lx.nullable(),candidateAttempt:lx.nullable()}).strict()).max(1e6),taskIds:c({fixed:p(T).max(1e6),retained:p(T).max(1e6),regressed:p(T).max(1e6),unresolved:p(T).max(1e6),unavailable:p(T).max(1e6)}).strict(),panels:p(QV).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:Ag.nullable(),exactPairedBinaryPValue:u().min(0).max(1).nullable(),pairedBootstrapSamples:u().int().positive()}).strict(),criteria:c({allRequiredAttemptsTerminal:I(),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:W}).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:H,toolSchema:W,application:W,harness:W,runtime:W,grader:W,autoRefinerEnabled:I()}).strict(),evidenceState:ZV,evidenceReasons:p(T).max(100),projectedAt:ye}).strict(),Pu=ot("kind",[c({kind:b("base_model"),id:T,revision:i().trim().min(1).max(500),label:i().trim().min(1).max(300)}).strict(),c({kind:b("model_version"),id:T,label:i().trim().min(1).max(300)}).strict(),c({kind:b("captured_model"),id:T,label:i().trim().min(1).max(300)}).strict()]),fc=vt([c({source:b("evaluation_run").default("evaluation_run"),evaluationRunId:T,attemptId:T,modelLabel:i().trim().min(1).max(300).nullable().default(null),modelVersionId:T.nullable().default(null),reward:u().finite().nullable(),components:le(i(),u().finite()).default({})}).strict(),c({source:b("imported_response"),modelLabel:i().trim().min(1).max(300),modelVersionId:T.nullable().default(null),response:ce().refine(e=>e!==void 0,"An imported model response is required."),reward:u().finite().nullable().default(null),components:le(i(),u().finite()).default({})}).strict()]),e9=vt([c({taskId:T,target:Pu,attempt:fc}).strict(),c({taskId:T,target:v(["base","current"]).default("current"),attempt:fc}).strict(),c({taskId:T,target:v(["base","current"]).default("current"),evaluationRunId:T,attemptId:T,reward:u().finite().nullable(),components:le(i(),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:b("openpond.continualLearningDailyBatchManifest.v1"),id:T,seriesId:T,scheduleEntryId:T,dayOrdinal:u().int().positive().max(1e4),sourceTaskset:Xt,taskIds:p(T).min(1).max(1e3),observedAttempts:p(e9).max(1e3).default([]),sourceFileName:i().trim().min(1).max(500).nullable().default(null),availableAt:ye}).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}:${a9(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 t9=c({schemaVersion:b("openpond.continualLearningDailyBatch.v1"),id:T,seriesId:T,scheduleEntryId:T,dayOrdinal:u().int().positive().max(1e4),label:i().trim().min(1).max(100),runMode:v(["automatic","manual"]).optional(),source:v(["json_upload","sealed_fixture"]),sourceFileName:i().trim().min(1).max(500).nullable(),sourceTaskset:Xt,tasks:p(c({taskId:T,taskContentHash:H,familyKey:T,disposition:v(["include","defer","exclude"]).nullable(),oracleReview:v(["pending","confirmed","needs_correction"]),note:i().trim().max(2e3),observedAttempt:fc.nullable(),baselineAttempt:fc.nullable().default(null),responses:p(c({target:Pu,attempt:fc}).strict()).max(100).default([]),stagedAt:ye.nullable().default(null),queuedEntry:nl.nullable().default(null)}).strict()).min(1).max(1e3),intakeEvaluation:c({status:v(["awaiting","running","ready","failed"]),requestedTargets:p(v(["base","current"])).max(2).default(["base","current"]),requestedPolicies:p(Pu).max(100).default([]),runs:p(c({target:Pu,runId:T}).strict()).max(100).default([]),baselineRunId:T.nullable(),currentRunId:T.nullable(),currentPolicy:ot("kind",[c({kind:b("base_model"),id:T}).strict(),c({kind:b("model_version"),id:T}).strict()]).nullable(),failure:i().trim().min(1).max(2e3).nullable()}).strict().default({status:"awaiting",requestedTargets:["base","current"],requestedPolicies:[],runs:[],baselineRunId:null,currentRunId:null,currentPolicy:null,failure:null}),status:v(["pending","reviewed","queued"]),queuedEntry:nl.nullable(),reviewedBy:T.nullable(),reviewedAt:ye.nullable(),availableAt:ye,revision:u().int().positive(),createdAt:ye,updatedAt:ye}).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 r=o.responses.map(s=>zR(s.target));new Set(r).size!==r.length&&t.addIssue({code:"custom",path:["tasks",a,"responses"],message:"A task cannot repeat a model response target."})}const n=e.tasks.every(a=>a.disposition!==null&&a.oracleReview!=="pending"&&(a.oracleReview!=="needs_correction"||a.note.length>0));e.status!=="pending"&&!n&&t.addIssue({code:"custom",path:["tasks"],message:"Every task requires a decision and oracle review before the day completes."}),e.status==="queued"!=(e.queuedEntry!==null)&&t.addIssue({code:"custom",path:["queuedEntry"],message:"Only a queued day carries an exact series-entry reference."}),e.status==="pending"&&(e.reviewedAt!==null||e.reviewedBy!==null)&&t.addIssue({code:"custom",path:["reviewedAt"],message:"A pending day cannot carry reviewer completion identity."}),e.status!=="pending"&&(e.reviewedAt===null||e.reviewedBy===null)&&t.addIssue({code:"custom",path:["reviewedAt"],message:"Reviewed identity is required after a day review completes."})}),n9=c({schemaVersion:b("openpond.continualBenchIssueReview.v1"),id:T,seriesId:T,scheduleEntryId:T,passLabel:T,packet:gV,splitManifest:c({id:T,contentHash:H}).strict(),decisions:p(c({taskId:T,disposition:v(["include","defer","exclude"]).nullable(),note:i().trim().max(2e3)}).strict()).min(2).max(1e4),status:v(["pending","reviewed","queued"]),queuedEntry:nl.nullable(),reviewedBy:T.nullable(),reviewedAt:ye.nullable(),revision:u().int().positive(),createdAt:ye,updatedAt:ye}).strict().superRefine((e,t)=>{const n=[...e.packet.cases.map(r=>r.taskId)].sort(),a=[...e.decisions.map(r=>r.taskId)].sort();JSON.stringify(n)!==JSON.stringify(a)&&t.addIssue({code:"custom",path:["decisions"],message:"Review decisions must cover the exact issue-packet cases."});const o=e.decisions.every(r=>r.disposition!==null&&r.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 zR(e){return`${e.kind}:${e.id}`}function a9(e){return typeof e=="string"?e:zR(e)}const oi=i().trim().min(1).max(240),Ha=i().trim().min(8).max(256),BR=v(["grpo","dapo","gspo-token"]),Dc=c({id:oi,revision:i().trim().min(1).max(256),tokenizerRevision:i().trim().min(1).max(256),chatTemplateHash:Ha}),i9=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()}),o9=c({method:b("grpo"),groupSize:u().int().min(2).max(128),normalization:b("group_standardized"),advantageEpsilon:u().positive().max(.01).default(1e-8),loss:BR,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:PR}),FR=c({method:b("ppo"),valueModel:Dc,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)}),r9=ot("method",[o9,FR]),VR=c({rewardModelVersion:c({id:oi,contentHash:Ha}).strict(),qualificationReport:c({id:oi,contentHash:Ha}).strict().nullable().default(null),evaluationReferences:p(c({id:oi,contentHash:Ha}).strict()).max(1e3).default([]),checkpoint:c({id:oi,contentHash:Ha,objectRef:i().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/),files:p(c({path:i().trim().min(1).max(512),sizeBytes:u().int().positive(),sha256:Ha}).strict()).min(4).max(128)}).strict(),runtime:qR,processorRelease:c({id:oi,contentHash:Ha}).strict(),rewardComposerRelease:c({id:oi,contentHash:Ha}).strict(),executionReceipt:c({id:oi,contentHash:Ha}).strict()}).strict(),KR=c({schemaVersion:b("openpond.policyOptimization.v1"),policyModel:Dc,referenceModel:Dc,dataset:c({tasksetId:oi,tasksetHash:Ha,split:b("train"),selectionStrategy:v(["stable_hash_top_n","rft_easy_curriculum_v1"]),selectionSeed:u().int(),maxExamples:u().int().positive().max(1e5)}),sampler:c({temperature:u().min(0).max(2),topP:u().min(0).max(1),maxOutputTokens:u().int().positive().max(32768),maxTurns:u().int().positive().max(1e3),concurrency:u().int().positive().max(1e3)}),environment:c({id:oi,version:i().trim().min(1).max(256),toolContractHash:Ha}),reward:c({graderId:oi,graderHash:Ha,learnedPreference:VR.nullable().default(null)}),kl:c({coefficient:u().nonnegative().nullable(),referenceConstraint:b("fixed_reference")}),budgets:i9,checkpointEverySteps:u().int().positive(),seed:u().int(),evaluationSplit:b("frozen_eval"),optimizer:r9}),$e=i().trim().min(1).max(240),Ot=i().trim().min(1),bt=i().trim().min(8).max(256),gd=le(i(),ce()).default({}),WR=c({schemaVersion:b("openpond.localModelChatConfiguration.v1").default("openpond.localModelChatConfiguration.v1"),profile:v(["efficient","full_harness","custom"]).default("efficient"),systemPromptMode:v(["lean","full_harness","custom"]).default("lean"),customSystemPrompt:i().max(2e4).nullable().default(null),contextWindowTokens:u().int().min(128).max(32768).default(1024),maxOutputTokens:u().int().min(1).max(512).default(64),temperature:u().min(0).max(2).default(0),repetitionPenalty:u().min(.5).max(2).default(1.1),noRepeatNgramSize:u().int().min(0).max(10).default(3),compaction:v(["off","when_needed"]).default("when_needed"),keepWarmSeconds:u().int().min(0).max(3600).default(300),updatedAt:Ot.nullable().default(null)}),s9=WR.parse({}),l9=c({schemaVersion:b("openpond.managedAdapterServingProjection.v1"),teamId:$e.nullable().default(null),source:b("sandbox_managed_rl"),sourceRef:$e,canonicalArtifactId:$e.nullable(),canonicalArtifactState:v(["imported_unvalidated","evaluating","promotable","rejected","deleted"]).nullable(),canonicalDeploymentId:$e.nullable(),canonicalDeploymentState:v(["requested","deploying","ready","degraded","deleting","deleted","failed"]).nullable(),state:v(["pending","imported","ready","failed"]),customerBindingAllowed:I().default(!1),artifactContentHash:bt.nullable().default(null),baseProfileId:$e.nullable().default(null),publishedAt:Ot.nullable(),lastSyncedAt:Ot,lastError:i().trim().min(1).max(5e3).nullable()});function Uie(e){const t=e.managedServing;return!!(t?.source==="sandbox_managed_rl"&&t.canonicalArtifactState==="promotable"&&t.customerBindingAllowed)}function GR(e){return e.state==="ready"&&e.canonicalArtifactState==="promotable"&&e.canonicalDeploymentState==="ready"&&e.customerBindingAllowed&&!!e.teamId&&!!e.canonicalArtifactId&&!!e.canonicalDeploymentId}function zie(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"&&GR(t)&&t.canonicalArtifactId&&t.canonicalDeploymentId?{kind:"sandbox_customer_binding",evaluationArtifactId:null,canonicalArtifactId:t.canonicalArtifactId,canonicalDeploymentId:t.canonicalDeploymentId}:null}function Bie(e){const t=e.managedServing;return t?GR(t)&&t.canonicalArtifactId&&t.canonicalDeploymentId?{kind:"sandbox_serving",canonicalArtifactId:t.canonicalArtifactId,canonicalDeploymentId:t.canonicalDeploymentId}:null:{kind:"source_artifact",canonicalArtifactId:null,canonicalDeploymentId:null}}const Xb="openpond.crossSystemOperations.v1",Fie="1.0.0",JR="openpond.crossSystemTools.v1",c9=["search_crm","query_billing","search_support","run_python"],d9=v(["train","validation","frozen_eval"]),u9=v(["easy","medium","hard"]),m9=v(["renewal_risk_v2"]);v(["renewal_exposure","collections_prioritization","invoice_reconciliation","sla_escalation","contract_billing_mismatch"]);c({seed:u().int().nonnegative(),split:d9,difficulty:u9,scenarioProfile:m9.optional()});const Sh={anyOf:[{type:"string",minLength:1,maxLength:256},{type:"null"}],default:null},xh={type:"integer",minimum:1,maximum:50,default:25},ZR=[{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:Sh,limit:xh}}},{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:Sh,limit:xh}}},{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:Sh,limit:xh}}},{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}}}}],vd=w9({schemaVersion:JR,tools:ZR}),p9=[`Use only the four registered synthetic Cross-System Operations tools. Contract ${vd}.`,"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(" "),f9=15;function h9(e="auto"){return[p9,"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: ${f9}.`,`Registered tool signatures: ${ZR.map(g9).join("; ")}`].join(`
|
|
191
|
-
`)}h9();function g9(e){const t=lm(e.parameters),n=lm(t.properties),a=YR(t.required),o=Object.fromEntries(a.map(r=>[r,Au(n[r])]));return`${e.name}(${JSON.stringify(o)})`}function Au(e){const t=lm(e),n=Tg(t.anyOf);if(n.length)return n.map(Au).join("|");const a=Tg(t.enum);if(a.length)return a.join("|");if(t.type==="array")return[Au(t.items)];if(t.type==="object"){const o=lm(t.properties),r=YR(t.required);return Object.fromEntries(r.map(s=>[s,Au(o[s])]))}return typeof t.type=="string"?t.type:"unknown"}function lm(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Tg(e){return Array.isArray(e)?e:[]}function YR(e){return Tg(e).filter(t=>typeof t=="string")}const cm=v(c9),v9=ot("kind",[c({kind:b("model"),turn:u().int().nonnegative(),content:i().max(1e5)}),c({kind:b("tool_call"),turn:u().int().nonnegative(),callId:i().trim().min(1).max(240),name:cm,arguments:le(i(),ce())}),c({kind:b("tool_result"),turn:u().int().nonnegative(),callId:i().trim().min(1).max(240),name:cm,ok:I(),result:ce(),rows:u().int().nonnegative(),bytes:u().int().nonnegative(),durationMs:u().int().nonnegative(),error:i().trim().min(1).max(2e4).nullable()}),c({kind:b("final"),turn:u().int().nonnegative(),content:i().max(1e5)})]),b9=c({schemaVersion:b(Xb),id:i().trim().min(1).max(240),worldId:i().trim().min(1).max(240),taskId:i().trim().min(1).max(240),toolContractHash:b(vd),modelRef:c({providerId:i().trim().min(1),modelId:i().trim().min(1)}).nullable(),status:v(["completed","budget_exhausted","cancelled","infrastructure_failure"]),steps:p(v9).max(1e3),startedAt:i().trim().min(1),completedAt:i().trim().min(1),infrastructureError:i().trim().min(1).max(2e4).nullable(),metadata:le(i(),ce()).default({})}),y9=c({schemaVersion:b(Xb),trajectoryId:i().trim().min(1).max(240),outcome:v(["correct","incorrect","parse_failure","budget_exhausted","tool_schema_violation","infrastructure_failure","cancelled"]),reward:u().min(0).max(1.15).nullable(),rewardEligible:I(),exactAnswer:I(),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:I()}),parsedAnswer:ce().nullable(),feedback:p(i().trim().min(1).max(5e3)).max(100)}),S9=c({id:i().trim().min(1).max(240),type:b("function"),function:c({name:cm,arguments:i().max(2e4)})}),QR=c({role:v(["system","user","assistant","tool"]),content:i().max(2e5).nullable(),tool_call_id:i().trim().min(1).max(240).optional(),tool_calls:p(S9).max(4).optional()});c({schemaVersion:b(Xb),id:i().trim().min(1).max(240),taskId:i().trim().min(1).max(240),worldId:i().trim().min(1).max(240),trajectoryId:i().trim().min(1).max(240),toolContractHash:b(vd),approval:c({status:b("approved"),approvedBy:i().trim().min(1).max(240),approvedAt:i().trim().min(1)}),messages:p(QR).min(3).max(1e3)});const x9=c({tasksetTaskId:i().trim().min(1).max(240),environmentTaskId:i().trim().min(1).max(240),family:v(["renewal_exposure","collections_prioritization","invoice_reconciliation","sla_escalation","contract_billing_mismatch"]),prompt:i().trim().min(1).max(1e5),finalAnswer:i().trim().min(1).max(2e5),trajectoryId:i().trim().min(1).max(240),trajectoryHash:i().trim().min(8).max(256),toolNames:p(cm).min(1).max(100),toolCallCount:u().int().positive(),messageCount:u().int().min(3),reward:u().min(0).max(1.15),messages:p(QR).min(3).max(1e3)}),k9=c({status:b("approved"),approvedBy:i().trim().min(1).max(240),approvedAt:i().trim().min(1),previewHash:i().trim().min(8).max(256),trajectoryCount:u().int().positive()});c({schemaVersion:b("openpond.crossSystemExpertBootstrapPreview.v1"),tasksetId:i().trim().min(1).max(240),tasksetHash:i().trim().min(8).max(256),tasksetRevision:u().int().positive(),previewHash:i().trim().min(8).max(256),toolContractHash:b(vd),status:v(["ready_for_review","approved"]),approval:k9.nullable(),tasks:p(x9).min(1).max(100)});function w9(e){const t=Eg(e);let n=2166136261,a=2654435769;for(let o=0;o<t.length;o+=1){const r=t.charCodeAt(o);n=Math.imul(n^r,16777619),a=Math.imul(a^r,2246822507)}return`${JR}:${cx(n)}${cx(a)}`}function Eg(e){return Array.isArray(e)?`[${e.map(Eg).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${Eg(n)}`).join(",")}}`:JSON.stringify(e)}function cx(e){return(e>>>0).toString(16).padStart(8,"0")}const I9=c({schemaVersion:b("openpond.singleTurnPolicyTrajectory.v1"),id:$e,taskId:$e,status:v(["completed","infrastructure_failure"]),promptHash:bt,responseText:i().max(2e6),infrastructureError:i().trim().min(1).max(1e4).nullable(),startedAt:Ot,completedAt:Ot,metadata:gd}),_9=c({schemaVersion:b("openpond.ppoTrajectory.v1"),id:$e,taskId:$e,policyModelId:$e,referenceModelId:$e,valueModelId:$e,steps:p(c({index:u().int().nonnegative(),observationHash:bt,actionTokenIds:p(u().int().nonnegative()).min(1),terminated:I(),truncated:I(),reward:u(),policyLogProbability:u(),referenceLogProbability:u(),valuePrediction:u(),return:u(),advantage:u(),mask:u().min(0).max(1)})).min(1).max(1e5),createdAt:Ot}),C9=c({schemaVersion:b("openpond.exactAnswerVerifierResult.v1"),outcome:v(["correct","incorrect","parse_failure","infrastructure_failure"]),graderSetHash:bt,score:u().min(0).max(1).nullable(),passed:I(),rewardEligible:I(),expectedAnswerHash:bt,extractedAnswer:i().max(2e4).nullable(),feedback:p(i().trim().min(1).max(2e4)).max(1e3)}),R9=c({schemaVersion:b("openpond.rolloutTrajectoryReceipt.v1"),id:$e,jobId:$e,planId:$e,tasksetId:$e,tasksetHash:bt,taskId:$e,split:b("train"),correlationId:$e,provider:$e,providerTrace:c({invocationId:$e,experimentId:$e,rolloutId:$e,runId:$e,rowId:$e}),optimizerMethod:v(["grpo","ppo"]).default("grpo"),evidenceLevels:c({requested:v(["trajectory","aggregate","provider_reported"]),observed:v(["trajectory","aggregate","provider_reported"]),providerReported:v(["trajectory","aggregate","provider_reported"])}).default({requested:"trajectory",observed:"trajectory",providerReported:"provider_reported"}),budgetUsage:c({rollouts:u().int().nonnegative(),environmentExecutions:u().int().nonnegative(),inputTokens:u().int().nonnegative(),outputTokens:u().int().nonnegative(),optimizerSteps:u().int().nonnegative(),costUsd:u().nonnegative()}).default({rollouts:0,environmentExecutions:0,inputTokens:0,outputTokens:0,optimizerSteps:0,costUsd:0}),environment:c({id:$e,version:i().trim().min(1).max(256),worldId:$e,worldHash:bt,toolContractHash:bt}),policy:c({modelId:$e,checkpointId:$e.nullable(),completionParametersHash:bt}),status:v(["received","running","succeeded","failed"]),failureClass:v(["policy_failure","parse_failure","tool_schema_violation","budget_exhausted","cancelled","environment_failure","infrastructure_failure"]).nullable(),reward:c({eligible:I(),raw:u().min(0).max(1.15).nullable(),normalized:u().min(0).max(1).nullable(),components:le(i(),u())}),trajectory:vt([b9,I9,_9]).nullable(),verifier:vt([y9,C9]).nullable(),providerStatus:le(i(),ce()).default({}),receivedAt:Ot,startedAt:Ot.nullable(),completedAt:Ot.nullable(),updatedAt:Ot}),Vie="dataset-exact-answer",Kie="dataset-exact-answer-v1",Wie="no-tools-v1",tr=v(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),cp=v(["lora","full"]),Ur=v(["openpond_managed"]),P9=c({schemaVersion:b("openpond.sftRecipe.v1"),method:b("sft"),parameterization:b("lora"),baseModel:c({id:$e,revision:i().trim().min(1).max(256),tokenizerRevision:i().trim().min(1).max(256),chatTemplateHash:bt}),dataset:c({trainSplit:b("train"),validationSplit:v(["validation","frozen_eval"]),completionOnly:I(),maxSequenceLength:u().int().positive().max(32768),maxExamples:u().int().positive().max(1e5).default(1e3),selectionStrategy:b("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($e).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:$e,input:le(i(),ce()),expectedOutput:le(i(),ce()),tags:p($e).max(100).default([])});c({id:$e,prompt:i().min(1).max(5e5),chosen:i().min(1).max(5e5),rejected:i().min(1).max(5e5),sourceRefs:p($e).min(1).max(1e4)});c({id:$e,input:le(i(),ce()),tags:p($e).max(100).default([])});c({schemaVersion:b("openpond.rewardModelRecipe.v1"),method:b("reward_model"),parameterization:b("lora_with_scalar_head"),runScope:v(["synthetic_smoke","human_preference"]),baseModel:c({id:$e,revision:i().trim().min(1).max(256),tokenizerRevision:i().trim().min(1).max(256),processorRevision:i().trim().min(1).max(256),chatTemplateHash:bt}).strict(),tasksetRelease:W,preferenceDatasetRelease:W,processorRelease:W,input:c({kind:b("structured_text"),serialization:v(["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($e).min(1).max(100)}).strict(),heads:c({scalar:b("pooled_hidden_state_linear"),bucket:v(["none","three_class"]).default("three_class")}).strict(),loss:c({ranking:b("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 A9=c({schemaVersion:b("openpond.rftRecipe.v1"),method:b("grpo"),parameterization:b("lora"),baseModel:c({id:$e,revision:i().trim().min(1).max(256),tokenizerRevision:i().trim().min(1).max(256),chatTemplateHash:bt}),dataset:c({trainSplit:b("train"),validationSplit:v(["validation","frozen_eval"]),maxPromptTokens:u().int().positive().max(32768),maxExamples:u().int().positive().max(1e5).default(1e3),selectionStrategy:v(["stable_hash_top_n","rft_easy_curriculum_v1"]).default("stable_hash_top_n")}),lora:c({rank:u().int().positive().max(256)}),rollout:c({groupSize:u().int().min(2).max(64),concurrency:u().int().positive().max(32),maxTurns:u().int().positive().max(100),maxOutputTokens:u().int().positive().max(8192),temperature:u().min(0).max(2),topP:u().positive().max(1),seed:u().int()}),optimizer:c({learningRate:u().positive(),maxSteps:u().int().positive().max(1e5),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:PR}),loss:c({method:BR.default("grpo"),klBeta:u().min(0).nullable().default(null)}).default({method:"grpo",klBeta:null}),reward:c({graderId:$e,graderHash:bt,environmentId:$e,environmentVersion:i().trim().min(1).max(256),toolContractHash:bt,learnedPreference:VR.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:KR.nullable().default(null),continuation:c({schemaVersion:b("openpond.crossJobContinuationRequest.v1"),parentArtifact:W,sourceArtifact:c({jobId:$e,artifactId:$e,checkpointId:$e,contentHash:bt}).strict(),optimizerMode:v(["continue","reset"])}).strict().optional()}),T9=c({schemaVersion:b("openpond.dpoRecipe.v1"),method:b("dpo"),parameterization:b("lora"),policyModel:Dc,referenceModel:Dc,dataset:c({trainSplit:b("train"),validationSplit:v(["validation","frozen_eval"]),maxPairs:u().int().positive().max(1e5),maxPromptTokens:u().int().positive().max(32768),maxCompletionTokens:u().int().positive().max(32768),selectionStrategy:b("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($e).min(1).max(100)}),loss:c({variant:b("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:b("openpond.dpoReferenceLogprobs.v1"),cacheKey:bt,invalidationHash:bt}),resourceLimits:c({cpuThreads:u().int().positive().max(256),memoryBytes:u().int().positive(),wallTimeMs:u().int().positive()})}),E9=c({schemaVersion:b("openpond.ppoRecipe.v1"),method:b("ppo"),parameterization:b("lora"),policyOptimization:KR.extend({optimizer:FR}),lora:c({rank:u().int().positive().max(256),alpha:u().positive().max(1024),dropout:u().min(0).max(1),targetModules:p($e).min(1).max(100)}),valueHead:c({initialization:b("policy_hidden_state_linear"),optimizerLearningRate:u().positive(),artifactName:b("value_head.safetensors")}),policyLearningRate:u().positive(),resume:c({checkpointId:$e.nullable(),policyHash:bt,referenceHash:bt,valueModelHash:bt,optimizerStateHash:bt.nullable()}),resourceLimits:c({cpuThreads:u().int().positive().max(256),memoryBytes:u().int().positive(),wallTimeMs:u().int().positive()})}),M9=c({schemaVersion:b("openpond.unsupportedRecipe.v1"),method:tr.exclude(["sft","dpo","grpo","ppo"]),parameterization:cp,unsupportedReason:i().trim().min(1).max(5e3)}),XR=vt([P9,T9,A9,E9,M9]),j9=c({schemaVersion:b("openpond.trainingDestinationCapabilities.v1"),destinationId:Ur,available:I(),methods:p(tr),parameterizations:p(cp),modelAllowlist:p($e).default([]),maxDatasetBytes:u().int().nonnegative().nullable(),environmentPlacements:p(v(["none","local","remote","colocated","provider_native"])),nonProduction:I(),unavailableReason:i().trim().min(1).max(5e3).nullable(),checkedAt:Ot}),O9=c({destinationId:Ur,available:I(),methods:p(tr),parameterizations:p(cp),nonProduction:I(),unavailableReason:i().trim().min(1).max(5e3).nullable()}),$9=c({schemaVersion:b("openpond.baseModelCandidate.v1"),selectionKey:$e,label:i().trim().min(1).max(500),sourceLabel:i().trim().min(1).max(500),preference:hd,available:I(),nonProduction:I(),unavailableReason:i().trim().min(1).max(5e3).nullable(),methods:p(tr),executionOptions:p(O9).min(1)}),N9=c({code:$e,severity:v(["warning","error"]),path:i().trim().max(2e3).nullable(),message:i().trim().min(1).max(5e3)}),D9=c({schemaVersion:b("openpond.trainingCompatibility.v1"),compatible:I(),destinationId:Ur,tasksetId:$e,recipeMethod:tr,issues:p(N9),checkedAt:Ot}),H9=vt([iR,v(["destination_unavailable","destination_method_unsupported","destination_model_unsupported","destination_parameterization_unsupported","experimental_destination"])]);c({method:tr,state:v(["recommended","compatible","needs_dataset_work","destination_unavailable","experimental_destination"]),reasonCodes:p(H9).default([]),reasons:p(i().trim().min(1).max(5e3)).default([]),destinationId:Ur.nullable().default(null)});v(["small","standard","custom","small_experiment"]);const L9=aC,eP=c({schemaVersion:b("openpond.trainingPlan.v1"),id:$e,modelId:$e,tasksetId:$e,tasksetHash:bt,comparisonSeriesEntry:nl.nullable().optional(),evaluationTasksetRef:Xt.nullable().optional(),harnessRelease:W.nullable().optional(),modelImprovementQualification:W.nullable().optional(),destinationId:Ur,recipe:XR,environmentPlacement:v(["none","local","remote","colocated","provider_native"]),compatibility:D9,dataPolicy:c({exportApproved:I(),approvedSourceIds:p($e),retentionDays:u().int().nonnegative().nullable(),region:i().trim().min(1).max(200).nullable()}),estimatedCostUsd:u().nonnegative().nullable(),createdAt:Ot,contentHash:bt}),q9=c({path:i().trim().min(1).max(2e3),sha256:bt,sizeBytes:u().int().nonnegative(),role:v(["manifest","task_data","grader","environment","recipe","policy","provenance"])}),ey=c({schemaVersion:b("openpond.trainingBundle.v1"),id:$e,planId:$e,tasksetId:$e,tasksetHash:bt,recipeHash:bt,files:p(q9).min(1).max(1e6),totalSizeBytes:u().int().nonnegative(),sourceIds:p($e),excludedSourceIds:p($e),containsRawChats:b(!1),containsSecrets:b(!1),containsHiddenGraderAssets:b(!1),createdAt:Ot,contentHash:bt});c({schemaVersion:b("openpond.trainingBundleExport.v1"),manifest:ey,files:p(c({path:i().trim().min(1).max(2e3),sha256:bt,sizeBytes:u().int().nonnegative(),encoding:b("base64"),content:i()})).min(1),contentHash:bt});c({schemaVersion:b("openpond.trainingPreparedStart.v1"),plan:eP,bundle:ey,approvalActor:$e.nullable(),preparedAt:Ot});c({schemaVersion:b("openpond.trainingApproval.v1"),evaluationTasksetRef:Xt.nullable().optional(),id:$e,planId:$e,bundleHash:bt,harnessRelease:W.nullable().optional(),modelImprovementQualification:W.nullable().optional(),destinationId:Ur,modelId:$e,method:tr,parameterization:cp,maximumCostUsd:u().nonnegative().nullable(),approvedBy:$e,approvedAt:Ot});c({schemaVersion:b("openpond.trainingJobSourceSnapshot.v1"),evaluationTasksetRef:Xt.nullable().optional(),modelProjectId:$e,sourceProjectRevision:u().int().positive(),profileId:$e,taskset:c({id:$e,revision:u().int().positive(),contentHash:bt}).strict(),tasksetRelease:W,harnessRelease:W,baseModel:hd,method:tr}).strict();const U9=v(["queued","starting","running","cancelling","cancelled","succeeded","failed","reconciling"]),tP=c({schemaVersion:b("openpond.trainingJob.v1"),id:$e,planId:$e,bundleHash:bt,approvalId:$e,destinationId:Ur,status:U9,nonProduction:I(),workerPid:u().int().positive().nullable(),startedAt:Ot.nullable(),completedAt:Ot.nullable(),error:i().trim().min(1).max(2e4).nullable(),createdAt:Ot,updatedAt:Ot,metadata:gd}),z9=c({schemaVersion:b("openpond.trainingJobEvent.v1"),id:$e,jobId:$e,sequence:u().int().nonnegative(),type:v(["queued","start","progress","metric","checkpoint","cancel","complete","failure","reconcile"]),timestamp:Ot,payload:gd}),B9=c({schemaVersion:b("openpond.sftStepMetric.v1"),step:u().int().nonnegative(),maxSteps:u().int().positive(),timestamp:Ot,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()}),F9=c({schemaVersion:b("openpond.policyOptimizationMetric.v1"),method:v(["grpo","ppo"]),step:u().int().nonnegative(),timestamp:Ot,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()}),V9=c({schemaVersion:b("openpond.managedTrainingRunEvidence.v2"),provider:$e,providerRunId:$e,state:$e,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:$e,gpuType:i().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:$e,policyVersion:u().int().nonnegative(),sha256:bt.nullable(),sizeBytes:u().int().nonnegative().nullable()}).nullable(),movement:c({adapterDeltaNorm:u().nonnegative().nullable()}),evaluations:p(c({reference:c({id:$e,contentHash:bt}).nullable().optional(),kind:v(["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:I().nullable()})),canonicalPublication:c({state:$e.nullable(),artifactId:$e.nullable()}),syncedAt:Ot}),dx=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()}),ux=c({status:v(["scored","unavailable"]),score:u().min(0).max(1).nullable(),passed:I(),rewardEligible:I(),failureClass:v(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),feedback:p(i().trim().min(1).max(2e4)).max(1e3),components:p(c({graderId:$e,score:u().min(0).max(1).nullable(),passed:I(),feedback:i().trim().max(2e4).nullable()})).max(1e3)}),K9=c({taskId:$e,input:le(i(),ce()),baseOutput:le(i(),ce()).nullable(),trainedOutput:le(i(),ce()).nullable(),baseGrade:ux.nullable(),trainedGrade:ux.nullable()}),W9=c({schemaVersion:b("openpond.trainingEvaluationSummary.v1"),jobId:$e,tasksetId:$e,base:dx,trained:dx,meanScoreDelta:u().min(-1).max(1).nullable(),examples:p(K9).max(1e6)});c({schemaVersion:b("openpond.trainingRunDetail.v1"),job:tP,events:p(z9),stepMetrics:p(B9),policyMetrics:p(F9).default([]),managedEvidence:V9.nullable().default(null),evaluation:W9.nullable(),generatedAt:Ot});const G9=c({schemaVersion:b("openpond.trainingArtifact.v1"),id:$e,jobId:$e,kind:v(["adapter","checkpoint","metrics","log","manifest","evaluation"]),path:i().trim().min(1).max(4e3),sha256:bt,sizeBytes:u().int().nonnegative(),baseModelId:$e.nullable(),baseModelRevision:i().trim().min(1).max(256).nullable(),tokenizerRevision:i().trim().min(1).max(256).nullable(),chatTemplateHash:bt.nullable(),nonProduction:I(),createdAt:Ot,metadata:gd}),J9=c({schemaVersion:b("openpond.modelArtifactLineage.v1"),id:$e,modelId:$e,artifactId:$e,jobId:$e,tasksetId:$e,tasksetHash:bt,graderHash:bt,planHash:bt,bundleHash:bt,recipeHash:bt,workerVersion:i().trim().min(1).max(256),trainerVersion:i().trim().min(1).max(256),importedAt:Ot,frozenEvaluationArtifactId:$e.nullable(),promotable:I(),pinned:I().default(!1),status:v(["imported","rejected"]).default("imported"),rejectedAt:Ot.nullable().default(null),rejectionReason:i().trim().min(1).max(5e3).nullable().default(null),chatConfiguration:WR.default(s9),managedServing:l9.nullable().default(null)}),Z9=v(["chat_manual","agent","extension","authoring_optimizer"]),Y9=c({schemaVersion:b("openpond.modelBinding.v1"),id:$e,profileId:$e,role:Z9,roleTargetId:$e,modelArtifactLineageId:$e,tasksetId:$e,evaluationArtifactId:$e.nullable(),status:v(["active","rolled_back"]),priorBindingId:$e.nullable(),rollbackTargetBindingId:$e.nullable(),promotedBy:$e,promotedAt:Ot,rolledBackAt:Ot.nullable(),metadata:gd});c({schemaVersion:b("openpond.trainingActivity.v1"),profileId:$e,active:I(),activeCounts:c({jobs:u().int().nonnegative(),creations:u().int().nonnegative(),minerRuns:u().int().nonnegative(),datasetImports:u().int().nonnegative()}),revision:bt,generatedAt:Ot});c({schemaVersion:b("openpond.tasksetOperationalState.v1"),tasksetId:$e,attempts:p(H6),artifacts:p(L6),grades:p(U6),evaluationResults:p(n5).default([]),generatedAt:Ot});const Q9=c({schemaVersion:b("openpond.trainingState.v1"),profileId:$e,sources:p(BC),creations:p(AR),tasksetDrafts:p(Ja).default([]),tasksets:p($c),benchmarkRuns:p($f()).default([]),benchmarkComparisons:p($f()).default([]),datasetImports:p(tV).default([]),datasetArtifacts:p(M5).default([]),graderAuditReports:p(z6),evaluationResults:p($f()).default([]),candidates:p(RR),minerConfig:sp,minerRuns:p(_6).default([]),modelProjects:p(L9).default([]),modelVersions:p(NV).default([]),modelRuns:p(JV).default([]),comparisonSeries:p(PV).default([]),comparisonSeriesEntries:p(OV).default([]),modelCurrencySnapshots:p(XV).default([]),continualBenchIssueReviews:p(n9).default([]),continualLearningDailyBatches:p(t9).default([]),rewardModelVersions:p(DV).default([]),rewardModelRuns:p(LV).default([]),modelTasksets:p($c).default([]),plans:p(eP),bundles:p(ey),jobs:p(tP),artifacts:p(G9),models:p(J9),rolloutReceipts:p(R9).default([]),modelBindings:p(Y9).default([]),destinations:p(j9),baseModelCandidates:p($9).default([]),activityRevision:bt.optional(),generatedAt:Ot}),X9=v(["trajectory","reward","demonstration","preference","correction","critique","targeted_feedback","grader_evidence","infrastructure_failure"]),eK=c({datasetRelease:W,harnessRelease:W,evidenceSetRelease:W.nullable(),profileRelease:W.nullable(),model:c({source:i().trim().min(1).max(200),revision:i().trim().min(1).max(500),artifactHash:H.nullable()}).strict(),environmentHash:H,graderHash:H,toolContractHash:H,verificationReceiptHash:H.nullable()}).strict(),xo=c({schemaVersion:b("openpond.learningSignal.v1"),id:T,taskId:T.nullable(),episodeId:T.nullable(),policyVersion:u().int().nonnegative().nullable(),lineage:eK,approved:I(),verifier:v(["deterministic","model_judge","human","none"]),createdAt:ye,contentHash:H,metadata:le(i(),ce()).default({})}).strict(),tK=xo.extend({kind:b("trajectory"),payload:c({traceRef:i().trim().min(1).max(2e3),traceHash:H,terminal:I(),failureClass:v(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),optimizerSample:$C.nullable().optional()}).strict()}).strict(),nK=xo.extend({kind:b("reward"),payload:c({reward:u().finite(),components:le(i(),u().finite()),eligible:I(),graderEvidenceRefs:p(T).max(1e3)}).strict()}).strict(),aK=xo.extend({kind:b("demonstration"),payload:c({prompt:i().max(5e5),response:i().max(1e6)}).strict()}).strict(),iK=xo.extend({kind:b("preference"),payload:c({prompt:i().max(5e5),chosen:i().max(1e6),rejected:i().max(1e6),rationale:i().max(5e5).nullable()}).strict()}).strict(),oK=xo.extend({kind:b("correction"),payload:c({original:i().max(1e6),corrected:i().max(1e6),rationale:i().max(5e5).nullable()}).strict()}).strict(),rK=xo.extend({kind:b("critique"),payload:c({response:i().max(1e6),critique:i().max(5e5),severity:v(["note","warning","error"])}).strict()}).strict(),sK=xo.extend({kind:b("targeted_feedback"),payload:c({turnIndex:u().int().nonnegative(),target:v(["reasoning","tool","answer","policy"]),feedback:i().max(5e5)}).strict()}).strict(),lK=xo.extend({kind:b("grader_evidence"),payload:c({graderId:T,score:u().finite().nullable(),passed:I(),privilegedArtifactRefs:p(i().trim().min(1).max(2e3))}).strict()}).strict(),cK=xo.extend({kind:b("infrastructure_failure"),approved:b(!1),verifier:b("none"),payload:c({code:T,phase:T,retryable:I(),rewardEligible:b(!1)}).strict()}).strict(),nP=ot("kind",[tK,nK,aK,iK,oK,rK,sK,lK,cK]);c({schemaVersion:b("openpond.learningSignalBatch.v1"),manifestId:T,manifestHash:H,sequence:u().int().nonnegative(),signals:p(nP).min(1).max(1e5),contentHash:H}).strict();const dK=c({id:T,turn:u().int().nonnegative(),kind:v(["message","tool_call","terminal"]),name:T.nullable(),arguments:le(i(),ce()),content:i().max(1e6).nullable(),contentHash:H}).strict(),uK=c({actionId:T,turn:u().int().nonnegative(),terminal:I(),output:le(i(),ce()),artifactRefs:p(i().trim().min(1).max(2e3)),contentHash:H}).strict(),mK=c({sequence:u().int().nonnegative(),type:v(["created","reset","action","observation","terminal","graded","feedback","failure","collected","destroyed"]),timestamp:ye,payloadHash:H,metadata:le(i(),ce()).default({})}).strict(),mx=c({graderId:T,graderVersion:i().trim().min(1).max(200),score:u().finite().nullable(),passed:I(),rewardEligible:I(),failureClass:v(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),feedback:p(i().max(5e5)),visibleEvidenceRefs:p(i().trim().min(1).max(2e3)),privilegedEvidenceRefs:p(i().trim().min(1).max(2e3)),contentHash:H}).strict();c({schemaVersion:b("openpond.harnessRunTrace.v1"),manifest:W,taskId:T,seed:i().trim().min(1).max(500),events:p(mK).max(1e6),actions:p(dK).max(1e5),observations:p(uK).max(1e5),graderEvidence:p(mx).max(1e4),learningSignals:p(nP).max(1e5),terminal:I(),failureClass:mx.shape.failureClass,artifactHash:H,contentHash:H}).strict();const pK=i().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"),fK=v(["instruction","skill","skill_resource","agent","workflow","dependency_lock","program","asset"]),hK=c({id:T,kind:fK,path:pK,parentId:T.nullable(),mediaType:i().trim().min(1).max(200),visibility:v(["policy","verifier","host_private"]),portability:v(["portable","local_only"])}).strict().superRefine((e,t)=>{e.kind==="skill_resource"!=(e.parentId!==null)&&t.addIssue({code:"custom",message:"only Skill resources require parentId",path:["parentId"]})});c({schemaVersion:b("openpond.harnessSourceManifest.v1"),name:i().trim().min(1).max(240),files:p(hK).min(2).max(1e5),toolDeclarations:p(Xc).max(200),capabilityRequirements:p(Bv).max(200),lifecycle:iI,graderInterface:oI,runtimeProtocol:i().trim().min(1).max(500),metadata:le(i(),ce()).default({})}).strict().superRefine((e,t)=>{const n=new Set,a=new Map,o=new Set;for(const[r,s]of e.files.entries())n.has(s.id)&&t.addIssue({code:"custom",message:"file ids must be unique",path:["files",r,"id"]}),o.has(s.path)&&t.addIssue({code:"custom",message:"file paths must be unique",path:["files",r,"path"]}),n.add(s.id),a.set(s.id,s.kind),o.add(s.path);for(const[r,s]of e.files.entries())s.parentId&&!n.has(s.parentId)?t.addIssue({code:"custom",message:"parentId must reference a declared Skill",path:["files",r,"parentId"]}):s.parentId&&a.get(s.parentId)!=="skill"&&t.addIssue({code:"custom",message:"parentId must reference a primary Skill file",path:["files",r,"parentId"]});e.files.filter(r=>r.kind==="dependency_lock").length!==1&&t.addIssue({code:"custom",message:"exactly one dependency lock is required",path:["files"]}),e.files.filter(r=>r.kind==="program").length!==1&&t.addIssue({code:"custom",message:"exactly one Harness program is required",path:["files"]})});c({rootPath:i(),sourcePath:i(),binding:eL,currentRelease:hS,releases:p(hS),transitions:p(tL)}).strict();c({profile:lI,activate:I().default(!0),reason:i().trim().min(1).max(1e4),actor:i().trim().min(1).max(240).default("local-user"),authoringSkillHash:i().regex(/^[a-f0-9]{64}$/).nullable().default(null)}).strict();c({release:W,reason:i().trim().min(1).max(1e4),actor:i().trim().min(1).max(240).default("local-user")}).strict();const gK=c({schemaVersion:b("openpond.trainingEngineCapabilities.v1"),adapterId:T,available:I(),methods:p(i().trim().min(1).max(100)),signalKinds:p(X9),modelFamilies:p(i().trim().min(1).max(200)),precisions:p(v(["fp32","fp16","bf16","tf32","int8","int4"])),topologies:p(i().trim().min(1).max(200)),workerProtocolVersion:i().trim().min(1).max(200),upstreamRevision:i().trim().min(1).max(500),workerImageDigest:i().regex(/^sha256:[a-f0-9]{64}$/).nullable().default(null),capabilityReceipt:H,checkedAt:ye,unavailableReason:i().trim().min(1).max(5e3).nullable()}).strict(),vK=c({schemaVersion:b("openpond.computeTargetCapabilities.v1"),adapterId:T,kind:v(["local","ssh","managed","custom"]),provider:T.nullable(),available:I(),devices:p(c({id:T,kind:v(["cpu","gpu","accelerator"]),vendor:i().trim().min(1).max(200),name:i().trim().min(1).max(500),memoryBytes:u().int().nonnegative().nullable(),runtime:i().trim().min(1).max(200)}).strict()),supportsWorkerImages:I(),supportsArtifactTransfer:I(),supportsCancellation:I(),capabilityReceipt:H,checkedAt:ye,unavailableReason:i().trim().min(1).max(5e3).nullable()}).strict(),bK=c({schemaVersion:b("openpond.harnessRuntimeCapabilities.v1"),adapterId:T,available:I(),placements:p(v(["local","remote","colocated","provider_native"])),lifecycle:p(v(["create","reset","step","grade","collect","destroy"])),deterministicReplay:I(),privilegedIsolation:I(),capabilityReceipt:H,checkedAt:ye,unavailableReason:i().trim().min(1).max(5e3).nullable()}).strict();c({schemaVersion:b("openpond.resolvedTrainingPlan.v1"),manifest:A6,recipe:XR,runtime:Fb,compute:Vb,engine:Kb,execution:c({trainingPlanId:T,approvalId:T}).strict().nullable(),maximumSpendUsd:u().nonnegative().nullable(),approvalHash:H,contentHash:H}).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,r]of n)JSON.stringify(o)!==JSON.stringify(r)&&t.addIssue({code:"custom",path:[a],message:`${a} must exactly match the Harness Run Manifest`});e.recipe.method!==e.manifest.recipe.method&&t.addIssue({code:"custom",path:["recipe","method"],message:"Recipe method must match the Harness Run Manifest"}),e.approvalHash!==e.manifest.approval.approvalHash&&t.addIssue({code:"custom",path:["approvalHash"],message:"Approval hash must match the Harness Run Manifest"}),e.maximumSpendUsd!==e.manifest.approval.maximumSpendUsd&&t.addIssue({code:"custom",path:["maximumSpendUsd"],message:"Maximum spend must match the Harness Run Manifest"})});c({schemaVersion:b("openpond.adapterValidationReceipt.v1"),adapterId:T,valid:I(),issues:p(c({code:T,path:i().trim().max(2e3).nullable(),message:i().trim().min(1).max(5e3)}).strict()),capabilityReceipt:H,planHash:H,createdAt:ye,contentHash:H}).strict();c({runId:T,adapterId:T,protocolVersion:v(["openpond.training.v2","adapter.native.v1"]).default("adapter.native.v1"),routeFamily:v(["training_v2","adapter_native"]).default("adapter_native"),routeId:T.optional(),providerJobId:i().trim().min(1).max(1e3).nullable(),tenantId:T.optional(),leaseId:T.nullable(),manifestHash:H.optional(),inputBundleHash:H.optional(),createdAt:ye}).strict();c({runId:T,state:v(["queued","preparing","running","cancelling","cancelled","succeeded","failed"]),phase:i().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:ye,errorCode:T.nullable()}).strict();c({runId:T,manifestHash:H,artifacts:p(c({kind:v(["checkpoint","adapter","metrics","trace","evaluation","receipt"]),objectRef:i().trim().min(1).max(2e3),sha256:H,sizeBytes:u().int().nonnegative(),metadata:le(i(),ce()).optional()}).strict()),contentHash:H}).strict();const Mg=v(["ready","model_download_required","compute_setup_required","provider_managed","unsupported"]),yK=c({id:T,label:i().trim().min(1).max(500),description:i().trim().min(1).max(2e3),destinationId:T,computeAdapterId:T,runtimeAdapterId:T,engineAdapterId:T,methods:p(i().trim().min(1).max(100)),capabilityPills:p(i().trim().min(1).max(100)),executionMode:v(["local_worker","provider_native"]),approvalPolicy:c({providerId:Nr,providerLabel:i().trim().min(1).max(200),settingsActionLabel:i().trim().min(1).max(500).nullable(),exportApprovalRequired:I(),exportDescription:i().trim().min(1).max(2e3).nullable(),preparationRequired:I(),minimumSpendUsd:u().nonnegative(),maximumSpendUsd:u().positive(),defaultMaximumSpendUsd:u().positive(),minimumRetentionDays:u().int().positive(),maximumRetentionDays:u().int().positive(),defaultRetentionDays:u().int().positive(),methodRequirement:i().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:I(),unavailableReason:i().trim().min(1).max(5e3).nullable()}).strict(),SK=c({selectionKey:T,label:i().trim().min(1).max(500),source:v(["local","builtin","huggingface","managed","search"]),modelId:i().trim().min(1).max(1e3),revision:i().trim().min(1).max(500).nullable(),tokenizerRevision:i().trim().min(1).max(500).nullable(),chatTemplateHash:H.nullable(),modelAssetId:T.nullable(),expectedBytes:u().int().nonnegative().nullable(),cached:I(),known:I(),searchResolved:I(),computeAdapterIds:p(T),engineAdapterIds:p(T),preparationState:Mg,reason:i().trim().min(1).max(5e3).nullable(),compatibilities:p(c({targetId:T,methods:p(i().trim().min(1).max(100)),state:Mg,reason:i().trim().min(1).max(5e3).nullable()}).strict())}).strict();c({schemaVersion:b("openpond.trainingCatalog.v1"),models:p(SK).max(1e5),engines:p(gK),compute:p(vK),runtimes:p(bK),targets:p(yK),generatedAt:ye,contentHash:H}).strict();c({schemaVersion:b("openpond.trainingPreparationPlan.v1"),modelRunId:T,state:Mg,reason:i().trim().min(1).max(5e3).nullable(),runtime:Fb.nullable(),compute:Vb.nullable(),engine:Kb.nullable(),downloads:p(c({kind:b("model"),label:i().trim().min(1).max(500),expectedBytes:u().int().nonnegative(),digest:i().trim().min(8).max(500),cached:I(),state:v(["ready","required","downloading","cancelled","failed"]),progress:u().min(0).max(1).nullable(),cancellable:I(),diskImpactBytes:u().int().nonnegative()}).strict()),dataMovement:p(c({direction:v(["upload","download","none"]),label:i().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:b(!1),contentHash:H}).strict();const dp=32e3,xK=v(["steer","message","followup","queued","result"]),kK=v(["pending","included","resolved","cancelled","rejected"]),ty=c({id:i().min(1),sequence:u().int().nonnegative(),sessionId:i().min(1),senderSessionId:i().min(1).nullable(),senderKind:v(["user","task","runtime"]),kind:xK,body:i().trim().min(1).max(dp),payload:le(i(),ce()).default({}),idempotencyKey:i().min(1).max(200),replyTo:i().min(1).nullable(),expectedTurnId:i().min(1).nullable(),turnId:i().min(1).nullable(),requestIds:p(i()),state:kK,revision:u().int().positive(),createdAt:i(),updatedAt:i(),error:i().nullable()}).strict();c({expectedTurnId:i().trim().min(1),idempotencyKey:i().trim().min(1).max(200),prompt:i().trim().min(1).max(dp)}).strict();ot("action",[c({action:b("resume"),expectedRevision:u().int().positive()}).strict(),c({action:b("cancel"),expectedRevision:u().int().positive()}).strict(),c({action:b("edit"),expectedRevision:u().int().positive(),body:i().trim().min(1).max(dp)}).strict(),c({action:b("steer"),expectedRevision:u().int().positive(),expectedTurnId:i().trim().min(1)}).strict()]);const wK=c({id:i().min(1),sessionId:i().min(1),turnId:i().min(1),targetSessionId:i().min(1).nullable(),targetTurnId:i().min(1).nullable(),targetInputId:i().min(1).nullable().default(null),afterSequence:u().int().nonnegative(),deadline:i(),state:v(["waiting","message","completed","failed","interrupted","unavailable","timeout","cancelled"]),createdAt:i(),updatedAt:i()}).strict(),IK=c({sessionId:i(),activeTurnId:i().nullable(),acceptingInput:I(),paused:I(),inputs:p(ty),waits:p(wK)});c({sessionId:i().min(1),provider:i().min(1),title:i(),targetRevision:i().min(1),managedSessionId:i().nullable(),latestTurnId:i().nullable(),activeTurnId:i().nullable(),paused:I(),approvalBlocked:I(),canSendFollowup:I(),canSteer:I(),unavailableReason:i().nullable(),inbox:IK}).strict();c({authority:b("user_click"),mode:v(["followup","steer"]),expectedTargetRevision:i().min(1),expectedTurnId:i().min(1).optional(),prompt:i().trim().min(1).max(dp),idempotencyKey:i().trim().min(1).max(200),recommendationId:i().min(1).max(200).optional()}).strict().superRefine((e,t)=>{e.mode==="steer"&&!e.expectedTurnId&&t.addIssue({code:"custom",path:["expectedTurnId"],message:"Active steering requires the exact observed turn."}),e.mode==="followup"&&e.expectedTurnId&&t.addIssue({code:"custom",path:["expectedTurnId"],message:"Follow-up messages are delivered at the next turn boundary."})});var aP=i().regex(/^[a-f0-9]{64}$/),_K=c({request:vl,maximumCostUsd:u().finite().positive().max(1e4),graders:p(Li).min(1).max(100),admissionRequestHash:aP.optional(),sourceExperimentId:i().trim().min(1).max(200).optional()}).strict(),CK=_K.extend({configurationHash:aP}).strict();bR.extend({configuration:CK}).strict();var Gie=c({teamId:i().trim().min(1).max(240),items:p(c({name:i().trim().min(1).max(500),source:ld,ready:I(),reason:i().min(1).max(2e3).nullable()}).strict()).max(8),nextCursor:i().min(1).max(8192).nullable()}).strict();i().trim().min(1).max(200);var Vl=i().trim().min(1).max(500),iP=i().regex(/^[a-f0-9]{64}$/),RK=c({schemaVersion:b("openpond.experimentCaseInspection.v1"),teamId:Vl,executionId:Vl,manifestHash:iP,receiptId:Vl,taskId:Vl,seed:i().min(1),input:le(i(),ce()).nullable(),output:ce().nullable(),error:i().nullable(),events:p(le(i(),ce())).max(25),nextEventCursor:Vl.nullable(),eventCount:u().int().nonnegative()}).strict();RK.extend({contentHash:iP}).strict();function PK(e){return JSON.stringify(e.release?["reward",e.release.id,e.release.revision,e.release.contentHash,e.feedbackKey]:["dataset",e.id,e.version,e.contentHash,e.feedbackKey])}function AK(e){const t=new Map;for(const n of e){const a=PK(n),o=t.get(a);o?o.aliases.push(n):t.set(a,{key:a,grader:n,aliases:[n]})}return[...t.values()]}function Jie(e){const t=AK(e),n=new Map;for(const a of t){const o=n.get(a.grader.feedbackKey);if(o&&o!==a.key)throw new Error(`Different selected grader releases use feedback key "${a.grader.feedbackKey}". Select one, or publish graders with distinct feedback keys.`);n.set(a.grader.feedbackKey,a.key);const r=JSON.stringify(a.grader.mappings??[]);if(a.aliases.some(s=>JSON.stringify(s.mappings??[])!==r))throw new Error(`Aliases of grader "${a.grader.feedbackKey}" have different field mappings. Select one alias and review its mappings.`)}return t.map(a=>a.grader)}var Ir=i().trim().min(1).max(240),Zie=c({profileRef:c({source:v(["local","github","openpond_git"]),repositoryId:Ir,profileId:Ir}).strict(),sourceRevision:i().min(1).max(500),harnessRelease:He,catalogHash:i().regex(/^[a-f0-9]{64}$/).nullable(),definitions:p(I_).max(1e3),suites:p(__).max(100),runs:p(c({profileRef:c({source:v(["local","github","openpond_git"]),repositoryId:Ir,profileId:Ir}).strict(),manifest:ep,metric:db,gradeRefs:p(He),receiptRefs:p(He),passRate:u().min(0).max(1),passed:I(),completedAt:on(),contentHash:i().regex(/^[a-f0-9]{64}$/)}).strict()).max(1e3),comparisons:p(f5).max(1e3),suiteRuns:p(S5).max(1e3),reports:p(b5).max(1e3)}).strict();c({teamId:Ir,profileRepositoryId:Ir,trainingProjectId:Ir.optional()}).strict();var dm=lt.shape.id,TK=c({schemaVersion:b("openpond.modelBatchReviewInspection.v1"),packageHash:i().regex(/^[a-f0-9]{64}$/),definition:cd,binding:Fm,evidence:p(Wm).min(1).max(1e4),decisions:p(yb).min(1).max(1e4)}).strict(),Yie=c({schemaVersion:b("openpond.modelBatchReviewRequest.v1"),operationId:dm,modelId:dm,expectedModelRevision:u().int().positive(),tasksetRef:lt,rewardBindingRef:lt.nullable(),definition:c({name:i().trim().min(1).max(500).optional(),instructions:i().trim().min(1).max(2e4).optional(),inputSchema:Lt.optional(),outputSchema:Lt.optional(),requiredOutputs:cd.shape.requiredOutputs}).strict(),examples:p(c({evidence:lt,input:Lt.optional(),expected:Lt.nullable().optional(),evaluatorContext:Lt.nullable().optional(),proposedTarget:Lt.nullable().optional()}).strict()).max(1e4)}).strict(),EK=c({schemaVersion:b("openpond.modelBatchReviewReceipt.v1"),operationId:dm,modelId:dm,source:Km,evidence:p(Wm).min(1).max(1e4),proposals:p(N_).max(1e4)}).strict();p(c({asset:di,sourcePath:i().min(1)}).strict()).max(1e4);c({draft:Ja,filePaths:p(c({assetId:i().min(1),paths:p(dd).min(1).max(1e4)}).strict()).max(1e4)}).strict();const gn=i().trim().min(1).max(200),sa=i().regex(/^[a-f0-9]{64}$/),oP=v(["queued","running","cancelling","completed","failed","cancelled","interrupted"]),rP=c({providerId:v(["openpond","custom-openai-compatible","claude-code"]),modelId:i().trim().min(1).max(500),configurationHash:sa,maxOutputTokens:u().int().positive().max(262144),temperature:u().min(0).max(2).optional(),topP:u().positive().max(1).optional(),messages:p(c({role:v(["system","user","assistant"]),content:i().max(262144)}).strict()).max(200)}).strict();c({configuration:Bb,package:Mr}).strict();c({configuration:Bb,expectedPackageHash:sa.optional()}).strict();c({schemaVersion:b("openpond.localExperimentDefinition.v1"),location:b("local"),id:gn,teamId:gn,ownerActorId:gn,revision:u().int().positive(),configuration:Bb,model:rP,packageHash:sa,graders:p(Li).min(1).max(100),availableGraders:p(Li).min(1).max(1e3),createdAt:on(),updatedAt:on(),contentHash:sa}).strict();c({operationId:gn,definition:pd}).strict();c({teamId:gn,id:gn}).strict();c({teamId:gn,projectId:gn.optional(),status:oP.optional(),datasetHash:sa.optional(),search:i().max(100).optional(),afterId:gn.optional(),limit:u().int().min(1).max(100).default(30)}).strict();const ny=c({schemaVersion:b("openpond.localExperimentExecution.v1"),location:b("local"),id:gn,teamId:gn,ownerActorId:gn,operationId:gn,definition:pd,kind:v(["target","scoring"]),executionHash:sa,sourceExecution:c({id:gn,executionHash:sa}).strict().nullable(),packageHash:sa,maximumCostUsd:u().finite().positive(),status:oP,createdAt:on(),completedAt:on().nullable(),counts:c({pending:u().int().nonnegative(),running:u().int().nonnegative(),completed:u().int().nonnegative(),failed:u().int().nonnegative(),cancelled:u().int().nonnegative(),unknown:u().int().nonnegative()}).strict(),usage:c({knownCostUsd:u().finite().nonnegative(),costUsd:u().finite().nonnegative().nullable(),heldUsd:u().finite().nonnegative(),uncertainRequests:u().int().nonnegative()}).strict(),cleanupComplete:I(),error:i().max(2e3).nullable()}).strict(),MK=ny.omit({definition:!0});function ay(e,t){e.kind==="scoring"!=(e.sourceExecution!==null)&&t.addIssue({code:"custom",message:"Only retained scoring passes name an original execution."}),["completed","failed","cancelled","interrupted"].includes(e.status)&&(!e.completedAt||e.counts.pending||e.counts.running)&&t.addIssue({code:"custom",message:"Terminal local execution requires complete population accounting."}),["completed","cancelled"].includes(e.status)&&!e.cleanupComplete&&t.addIssue({code:"custom",message:"Successful completion or cancellation requires confirmed local transport cleanup."}),e.usage.uncertainRequests>0&&e.usage.costUsd!==null&&t.addIssue({code:"custom",message:"Uncertain provider charges cannot claim a measured total."})}ny.superRefine(ay);const bd=MK.superRefine(ay);c({configuration:fd,package:Mr}).strict();const Qie=c({configuration:fd,expectedPackageHash:i().regex(/^[a-f0-9]{64}$/).optional()}).strict(),px=c({configuration:fd,model:rP,packageHash:i().regex(/^[a-f0-9]{64}$/),graders:p(Li).min(1).max(100),availableGraders:p(Li).min(1).max(1e3),retainedConfigurationHash:i().regex(/^[a-f0-9]{64}$/).optional(),configurationHash:i().regex(/^[a-f0-9]{64}$/)}).strict().superRefine((e,t)=>{const{configurationHash:n,...a}=e;ct(a)!==n&&t.addIssue({code:"custom",message:"Local configuration snapshot bytes changed."})}),{definition:Xie,...jK}=ny.shape,iy=c({...jK,kind:b("target"),...px.shape}).strict().superRefine((e,t)=>{const n={configuration:e.configuration,model:e.model,packageHash:e.packageHash,graders:e.graders,availableGraders:e.availableGraders,...e.retainedConfigurationHash?{retainedConfigurationHash:e.retainedConfigurationHash}:{},configurationHash:e.configurationHash};ay(e,t),px.safeParse(n).success||t.addIssue({code:"custom",message:"Local Experiment configuration changed."}),(e.operationId!==e.configuration.operationId||e.teamId!==e.configuration.request.teamId||e.maximumCostUsd!==e.configuration.maximumCostUsd)&&t.addIssue({code:"custom",message:"Local Experiment differs from its sealed admission."})}),eoe=c({items:p(iy).max(100),nextCursor:i().nullable()}).strict();c({teamId:i().min(1).max(200),id:i().min(1).max(200),configurationHash:i().regex(/^[a-f0-9]{64}$/).optional()}).strict();const OK=c({operationId:gn,execution:c({id:gn,executionHash:sa}).strict(),graderPackage:Mr,graders:p(zb).min(1).max(100),maximumCostUsd:u().finite().positive().max(1e4)}).strict(),toe=OK.omit({graderPackage:!0}),$K=vb,NK=c({sessionId:gn,turnId:gn,source:Ys,profileRef:Bi,admissionHash:sa,modelConfigurationHash:sa,traceHash:sa,runtimeEventRefs:p(gn).max(1e4),startedAt:on(),completedAt:on(),outputHash:sa,partialOutputAvailable:I()}).strict(),sP=c({receiptId:gn,taskId:gn,seed:i(),status:v(["pending","running","completed","failed","cancelled","unknown"]),input:le(i(),ce()),policyVisibleContext:le(i(),ce()),output:i().nullable(),messages:p(ce()).max(4002),grade:pR.nullable(),error:i().nullable(),native:$K.optional(),profileNative:NK.optional(),externalProcess:B3.optional()}).strict(),noe=c({execution:vt([iy,bd]),cases:p(sP).max(1e4),contentHash:sa}).strict(),DK=c({items:p(c({sequence:u().int().positive(),type:i().min(1),payload:ce()}).strict()).max(500),nextCursor:u().int().positive().nullable()}).strict(),aoe=c({location:b("local"),execution:vt([iy,bd]),case:sP,trace:DK}).strict(),ioe=c({items:p(bd).max(100),nextCursor:gn.nullable()}).strict(),ooe=c({execution:bd,graders:p(Li).min(1).max(100),graderPackageHash:sa}).strict(),fx=c({execution:bd,manifest:uo,result:mo}).strict().superRefine((e,t)=>{try{if(Pr(e),e.manifest.id!==e.execution.id||e.manifest.teamId!==e.execution.teamId||e.manifest.lineage?.execution.id!==(e.execution.sourceExecution?.id??e.execution.id)||e.manifest.lineage.execution.contentHash!==(e.execution.sourceExecution?.executionHash??e.execution.executionHash)||e.manifest.lineage.scoringPassId!==(e.execution.kind==="scoring"?e.execution.id:null)||e.manifest.maximumCostUsd!==e.execution.maximumCostUsd)throw new Error("Portable evidence differs from its retained local execution.")}catch(n){t.addIssue({code:"custom",message:n instanceof Error?n.message:"Local portable evidence verification failed."})}}),roe=c({location:b("local"),baseline:fx,candidate:fx}).strict(),gs=i().trim().min(1).max(240),kh=i().regex(/^[a-f0-9]{64}$/),soe=c({location:b("local"),harnesses:p(c({id:gs,name:i().max(500),source:ld}).strict()).max(100),profiles:p(c({id:gs,name:i().max(500),profileRef:Bi,sourceRevision:i().min(1).max(500),harnessRelease:c({id:gs,contentHash:kh}).strict(),definitionId:gs,definitionHash:kh,taskset:c({id:gs,revision:u().int().positive(),contentHash:kh}).strict(),taskCount:u().int().nonnegative(),taskIds:p(gs).max(1e4),seeds:p(i()).max(1e4)}).strict()).max(100)}).strict(),HK=c({id:Pm(),action:v(["advanced-refiner-start","experiment-evaluation-schedule"]),intentHash:i().regex(/^[a-f0-9]{64}$/),createdAt:on(),reviewedIntent:ce().nullable(),command:ce().nullable(),phase:v(["reviewed","dispatching"]).nullable(),recoveryReady:I()}).strict().superRefine((e,t)=>{e.recoveryReady!==(e.reviewedIntent!==null&&e.command!==null&&e.phase!==null)&&t.addIssue({code:"custom",message:"Only the actual retained intent and command admit automatic recovery."})}),loe=c({items:p(HK).max(100),nextCursor:Pm().nullable()}).strict(),LK={teamInvitations:e=>B(e,"/v1/team-invitations"),decideTeamInvitation:(e,t,n)=>B(e,`/v1/team-invitations/${t}`,{method:"POST",body:JSON.stringify({token:n})}),organizations:e=>B(e,"/v1/organizations"),createOrganization:(e,t)=>B(e,"/v1/organizations",{method:"POST",body:JSON.stringify(t)}),updateOrganization:(e,t,n)=>B(e,`/v1/organizations/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),organizationMembers:(e,t)=>B(e,`/v1/organizations/${encodeURIComponent(t)}/members`),upsertOrganizationMember:(e,t,n)=>B(e,`/v1/organizations/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify(n)}),organizationMcpServer:(e,t)=>B(e,`/v1/organizations/${encodeURIComponent(t)}/mcp-server`),generateOrganizationMcpServer:(e,t,n)=>B(e,`/v1/organizations/${encodeURIComponent(t)}/mcp-server`,{method:"POST",body:JSON.stringify(n)}),setOrganizationMcpServerStatus:(e,t,n)=>B(e,`/v1/organizations/${encodeURIComponent(t)}/mcp-server/${n}`,{method:"POST"})},qK={taskInbox:(e,t)=>B(e,`/v1/sessions/${encodeURIComponent(t)}/inbox`),steerTurn:(e,t,n)=>B(e,`/v1/sessions/${encodeURIComponent(t)}/turns/steer`,{method:"POST",body:JSON.stringify(n)}),queueTaskInput:(e,t,n,a)=>B(e,`/v1/sessions/${encodeURIComponent(t)}/inbox`,{method:"POST",body:JSON.stringify({input:n,idempotencyKey:a})}),updateTaskInput:(e,t,n,a)=>B(e,`/v1/sessions/${encodeURIComponent(t)}/inbox/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(a)}),sendTurn:(e,t,n)=>B(e,`/v1/sessions/${t}/turns`,{method:"POST",body:JSON.stringify(n)}),runSessionCommand:(e,t,n)=>B(e,`/v1/sessions/${encodeURIComponent(t)}/commands`,{method:"POST",body:JSON.stringify(n)}),recordPreflightTurnFailure:(e,t,n)=>B(e,`/v1/sessions/${t}/preflight-turns/failure`,{method:"POST",body:JSON.stringify(n)}),listCreateImproveRuns:(e,t={})=>B(e,`/v1/create-improve-runs?${UK(t).toString()}`),getCreateImproveRun:(e,t)=>B(e,`/v1/create-improve-runs/${encodeURIComponent(t)}`),getCreateImproveCandidateDiff:(e,t,n)=>B(e,`/v1/create-improve-runs/${encodeURIComponent(t)}/candidates/${encodeURIComponent(n)}/diff`),applyCreateImproveAction:(e,t,n)=>B(e,`/v1/create-improve-runs/${encodeURIComponent(t)}/actions`,{method:"POST",body:JSON.stringify(n)}),interruptTurn:(e,t,n)=>B(e,`/v1/sessions/${t}/turns/interrupt`,{method:"POST",body:JSON.stringify({reason:n})}),compactSession:(e,t,n={reason:"manual"})=>B(e,`/v1/sessions/${t}/compact`,{method:"POST",body:JSON.stringify(n)}),workspaceTool:(e,t,n)=>B(e,`/v1/sessions/${t}/workspace-tools`,{method:"POST",body:JSON.stringify(n)}),ensureCloudWorkspaceReady:(e,t,n)=>B(e,`/v1/sessions/${encodeURIComponent(t)}/workspace/ensure-ready`,{method:"POST",body:JSON.stringify(n)})};function UK(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 zK={sandboxFiles:(e,t,n={})=>{const a=new URLSearchParams({list:"1"});return n.path&&a.set("path",n.path),n.recursive!==void 0&&a.set("recursive",String(n.recursive)),n.maxEntries!==void 0&&a.set("maxEntries",String(n.maxEntries)),B(e,`/v1/sandboxes/${encodeURIComponent(t)}/files?${a.toString()}`)},sandboxUploadFile:(e,t,n)=>B(e,`/v1/sandboxes/${encodeURIComponent(t)}/files`,{method:"POST",body:JSON.stringify(n)}),preserveSandboxSource:(e,t,n={})=>B(e,`/v1/sandboxes/${encodeURIComponent(t)}/preserve-source`,{method:"POST",body:JSON.stringify(n)}),sandboxDownloadFile:async(e,t,n,a={})=>{const o=new URLSearchParams({path:n});a.offsetBytes!==void 0&&o.set("offsetBytes",String(a.offsetBytes)),a.maxBytes!==void 0&&o.set("maxBytes",String(a.maxBytes));const r=await B(e,`/v1/sandboxes/${encodeURIComponent(t)}/files?${o.toString()}`);return{...r,contents:r.file.isBinary?"":LE(r.file.contentsBase64)}}},BK={sandboxGitStatus:(e,t)=>B(e,`/v1/sandboxes/${encodeURIComponent(t)}/git/status`),sandboxGitDiff:(e,t,n)=>B(e,`/v1/sandboxes/${encodeURIComponent(t)}/git/diff`,{method:"POST",body:JSON.stringify(n)})},FK={connectedAppStatus:(e,t={})=>{const n=o0(t);return n.set("status",t.status??"all"),B(e,`/v1/connected-apps/status${n.size>0?`?${n.toString()}`:""}`)},integrationConnections:(e,t={})=>{const n=o0(t);return t.status&&n.set("status",t.status),B(e,`/v1/integrations/connections${n.size>0?`?${n.toString()}`:""}`)},sandboxIntegrationLeases:(e,t)=>B(e,`/v1/sandboxes/${encodeURIComponent(t)}/integrations`),attachSandboxIntegrationConnection:(e,t,n)=>B(e,`/v1/sandboxes/${encodeURIComponent(t)}/integrations`,{method:"POST",body:JSON.stringify(n)}),removeSandboxIntegrationLease:(e,t,n)=>B(e,`/v1/sandboxes/${encodeURIComponent(t)}/integrations`,{method:"DELETE",body:JSON.stringify({leaseId:n})})},VK={listSandboxProjects:(e,t)=>{const n=new URLSearchParams({teamId:t.teamId});return B(e,`/v1/sandbox-projects?${n.toString()}`)},getSandboxProject:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return B(e,`/v1/sandbox-projects/${encodeURIComponent(t)}?${a.toString()}`)},getSandboxProjectWorkspace:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return B(e,`/v1/sandbox-projects/${encodeURIComponent(t)}/workspace?${a.toString()}`)},upsertSandboxProject:(e,t)=>B(e,"/v1/sandbox-projects",{method:"POST",body:JSON.stringify(t)}),syncSandboxProject:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return B(e,`/v1/sandbox-projects/${encodeURIComponent(t)}/sync?${a.toString()}`,{method:"POST"})},uploadSandboxProjectSource:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId}),{teamId:o,...r}=n;return B(e,`/v1/sandbox-projects/${encodeURIComponent(t)}/source?${a.toString()}`,{method:"POST",body:JSON.stringify(r)})},archiveSandboxProject:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return B(e,`/v1/sandbox-projects/${encodeURIComponent(t)}?${a.toString()}`,{method:"DELETE"})},listSandboxAgents:(e,t)=>{const n=new URLSearchParams({teamId:t.teamId});return B(e,`/v1/sandbox-agents?${n.toString()}`)},upsertSandboxAgent:(e,t)=>B(e,"/v1/sandbox-agents",{method:"POST",body:JSON.stringify(t)}),runSandboxAgent:(e,t,n)=>B(e,`/v1/sandbox-agents/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify(n)}),runProfileAction:(e,t)=>B(e,"/v1/profile/run",{method:"POST",body:JSON.stringify(t)})},KK={sandbox:(e,t)=>B(e,`/v1/sandboxes/${encodeURIComponent(t)}`)},WK={...FK,...VK,...KK,...BK,...zK},GK={communities:(e,t)=>{const n=new URLSearchParams;return t&&n.set("cursor",t),B(e,`/v1/communities${n.size?`?${n}`:""}`)},communityPreview:(e,t)=>B(e,`/v1/communities/${encodeURIComponent(t)}/preview`),communityRules:(e,t)=>B(e,`/v1/communities/${encodeURIComponent(t)}/rules/current`),joinCommunity:(e,t,n)=>B(e,`/v1/communities/${encodeURIComponent(t)}/join`,{method:"POST",body:JSON.stringify({acceptedRulesVersionId:n})}),acceptCommunityRules:(e,t,n)=>B(e,`/v1/communities/${encodeURIComponent(t)}/rules/accept`,{method:"POST",body:JSON.stringify({acceptedRulesVersionId:n})}),leaveCommunity:(e,t)=>B(e,`/v1/communities/${encodeURIComponent(t)}/leave`,{method:"POST",body:"{}"}),communityChannels:(e,t)=>B(e,`/v1/communities/${encodeURIComponent(t)}/channels`),communityMessages:(e,t,n,a={})=>{const o=new URLSearchParams;return a.beforeSequence!=null&&o.set("beforeSequence",String(a.beforeSequence)),a.limit!=null&&o.set("limit",String(a.limit)),B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages${o.size?`?${o}`:""}`)},sendCommunityMessage:(e,t,n,a)=>B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages`,{method:"POST",body:JSON.stringify(a)}),editCommunityMessage:(e,t,n,a,o)=>B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages/${encodeURIComponent(a)}`,{method:"PATCH",body:JSON.stringify({body:o})}),deleteCommunityMessage:(e,t,n,a)=>B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages/${encodeURIComponent(a)}`,{method:"DELETE",body:"{}"}),markCommunityRead:(e,t,n,a)=>B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/read`,{method:"POST",body:JSON.stringify({sequence:a})}),setCommunityChannelMuted:(e,t,n,a)=>B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/mute`,{method:"POST",body:JSON.stringify({muted:a})}),searchCommunityMembers:(e,t,n={})=>{const a=new URLSearchParams;return n.query&&a.set("query",n.query),n.cursor&&a.set("cursor",n.cursor),n.limit!=null&&a.set("limit",String(n.limit)),B(e,`/v1/communities/${encodeURIComponent(t)}/members/search${a.size?`?${a}`:""}`)},updateCommunityNotifications:(e,t,n)=>B(e,`/v1/communities/${encodeURIComponent(t)}/notifications`,{method:"POST",body:JSON.stringify({mode:n})}),communityEvents:(e,t,n={})=>{const a=new URLSearchParams;return n.after!=null&&a.set("after",String(n.after)),n.limit!=null&&a.set("limit",String(n.limit)),B(e,`/v1/communities/${encodeURIComponent(t)}/events${a.size?`?${a}`:""}`)},communityRealtimeSession:(e,t)=>B(e,`/v1/communities/${encodeURIComponent(t)}/realtime-session`),uploadCommunityAttachment:(e,t,n,a)=>B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/attachments/upload`,{method:"POST",body:JSON.stringify({attachment:a})}),communityAttachmentDownload:(e,t,n,a)=>B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/attachments/${encodeURIComponent(a)}/download`)},oy="openpond-app-server-url",Hc="openpond-app-token",JK=750;function lP(){return window.location.protocol!=="http:"&&window.location.protocol!=="https:"?null:window.location.origin&&window.location.origin!=="null"?window.location.origin:null}function jg(e){const t=e.getItem(oy)?.trim(),n=e.getItem(Hc)?.trim();return t&&n?{serverUrl:t,token:n}:null}function um(e){if(!e)return null;try{const t="__openpond_storage_probe__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return null}}function vs(e,t){e.setItem(oy,t.serverUrl),e.setItem(Hc,t.token)}function hx(e,t){const n=jg(e);n?.serverUrl!==t.serverUrl||n.token!==t.token||(e.removeItem(oy),e.removeItem(Hc))}function ZK(){const e=window.__OPENPOND_WEB_CONNECTION__,t=e?.serverUrl?.trim(),n=e?.token?.trim();return t&&n?{serverUrl:t,token:n}:null}function YK(){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()||lP();return!a||!n?null:{serverUrl:a,token:n}}function QK(){window.location.hash&&window.history.replaceState(null,"",`${window.location.pathname}${window.location.search}`)}function ou(e,t){t&&(e.some(n=>n.serverUrl===t.serverUrl&&n.token===t.token)||e.push(t))}function XK(){const e=[],t=um(window.sessionStorage),n=um(window.localStorage),a=lP(),o=t?.getItem(Hc)??n?.getItem(Hc);return ou(e,null),ou(e,a&&o?{serverUrl:a,token:o.trim()}:null),ou(e,t?jg(t):null),ou(e,n?jg(n):null),e}async function wh(e){const t=new AbortController,n=window.setTimeout(()=>t.abort(),JK);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 eW(){if(window.openpond)return window.openpond.getConnection();const e=um(window.sessionStorage),t=um(window.localStorage),n=YK();if(n&&await wh(n.serverUrl))return t&&vs(t,n),e&&vs(e,n),QK(),{...n,platform:navigator.platform};const a=ZK();if(a&&await wh(a.serverUrl))return t&&vs(t,a),e&&vs(e,a),{...a,platform:navigator.platform};const o=XK();for(const r of o){if(await wh(r.serverUrl))return t&&vs(t,r),e&&vs(e,r),{...r,platform:navigator.platform};e&&hx(e,r),t&&hx(t,r)}throw new Error("No reachable OpenPond app server. Start `openpond ui` again and open the full printed URL.")}const ie={...GK,bootstrap:e=>B(e,"/v1/bootstrap?refreshCodex=1"),localProjectActions:(e,t)=>B(e,`/v1/projects/${encodeURIComponent(t)}/actions`),extensionCatalog:e=>B(e,"/v1/extensions"),extensionPreview:(e,t)=>B(e,"/v1/extensions/preview",{method:"POST",body:JSON.stringify(t)}),extensionAdd:(e,t)=>B(e,"/v1/extensions",{method:"POST",body:JSON.stringify(t)}),extensionUpdate:(e,t,n={})=>B(e,`/v1/extensions/github/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repo)}/update`,{method:"POST",body:JSON.stringify(n)}),extensionUpdateAll:e=>B(e,"/v1/extensions/update-all",{method:"POST"}),extensionRemove:(e,t)=>B(e,`/v1/extensions/github/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repo)}`,{method:"DELETE"}),skillSourceFile:(e,t,n,a)=>B(e,`/v1/skills/${t}/${encodeURIComponent(n)}/source?path=${encodeURIComponent(a)}`),teamChatMembers:(e,t)=>B(e,`/v1/team-chat/members?teamId=${encodeURIComponent(t)}`),teamChatAgents:(e,t)=>B(e,`/v1/team-chat/agents?teamId=${encodeURIComponent(t)}`),teamChatThreads:(e,t)=>B(e,`/v1/team-chat/threads?teamId=${encodeURIComponent(t)}`),teamChatRealtimeSession:(e,t)=>B(e,`/v1/team-chat/realtime-session?teamId=${encodeURIComponent(t)}`),teamChatEvents:(e,t,n={})=>{const a=new URLSearchParams({teamId:t});return n.after!=null&&a.set("after",String(n.after)),n.limit!=null&&a.set("limit",String(n.limit)),B(e,`/v1/team-chat/events?${a.toString()}`)},teamChatGeneral:(e,t)=>B(e,"/v1/team-chat/threads/general",{method:"POST",body:JSON.stringify({teamId:t})}),teamChatDm:(e,t,n)=>B(e,"/v1/team-chat/threads/dm",{method:"POST",body:JSON.stringify({teamId:t,otherUserId:n})}),teamChatThread:(e,t,n,a={})=>{const o=new URLSearchParams({teamId:t});return a.beforeSequence!=null&&o.set("beforeSequence",String(a.beforeSequence)),a.limit!=null&&o.set("limit",String(a.limit)),B(e,`/v1/team-chat/threads/${encodeURIComponent(n)}?${o.toString()}`)},uploadTeamChatAttachment:(e,t,n)=>B(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/attachments/upload`,{method:"POST",body:JSON.stringify(n)}),teamChatAttachmentDownload:(e,t,n)=>B(e,`/v1/team-chat/attachments/${encodeURIComponent(n)}/download?teamId=${encodeURIComponent(t)}`),sendTeamChatMessage:(e,t,n)=>B(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/messages`,{method:"POST",body:JSON.stringify(n)}),createTeamChatAgentRun:(e,t,n)=>B(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/agent-runs`,{method:"POST",body:JSON.stringify(n)}),teamChatAgentConversation:(e,t,n)=>B(e,`/v1/team-chat/agent-runs/${encodeURIComponent(n)}?teamId=${encodeURIComponent(t)}`),editTeamChatMessage:(e,t,n,a)=>B(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/messages/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(a)}),deleteTeamChatMessage:(e,t,n,a)=>B(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/messages/${encodeURIComponent(n)}`,{method:"DELETE",body:JSON.stringify({teamId:a})}),markTeamChatRead:(e,t,n,a)=>B(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/read`,{method:"POST",body:JSON.stringify({teamId:n,sequence:a})}),setTeamChatThreadMuted:(e,t,n,a)=>B(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/mute`,{method:"POST",body:JSON.stringify({teamId:n,muted:a})}),createTeamChatAiThread:(e,t,n)=>B(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/ai-threads`,{method:"POST",body:JSON.stringify(n)}),teamChatAiThread:(e,t,n)=>B(e,`/v1/team-chat/ai-threads/${encodeURIComponent(n)}?teamId=${encodeURIComponent(t)}`),sendTeamChatAiTurn:(e,t,n)=>B(e,`/v1/team-chat/ai-threads/${encodeURIComponent(t)}/turns`,{method:"POST",body:JSON.stringify(n)}),executeTeamChatAiTurn:(e,t,n)=>B(e,`/v1/team-chat/ai-turns/${encodeURIComponent(t)}/execute`,{method:"POST",body:JSON.stringify({teamId:n})}),cancelTeamChatAiTurnExecution:(e,t,n)=>B(e,`/v1/team-chat/ai-turns/${encodeURIComponent(t)}/execute/cancel`,{method:"POST",body:JSON.stringify({teamId:n})}),usage:(e,t={})=>{const n=gx(t),a=n.size?`?${n.toString()}`:"";return B(e,`/v1/usage${a}`)},usageRecords:(e,t={})=>{const n=gx(t);t.sessionId&&n.set("sessionId",t.sessionId),t.turnId&&n.set("turnId",t.turnId),t.limit!==void 0&&n.set("limit",String(t.limit));const a=n.size?`?${n.toString()}`:"";return B(e,`/v1/usage/records${a}`)},usageTurnCache:(e,t)=>B(e,`/v1/usage/turn-cache?sessionId=${encodeURIComponent(t)}`),runtimeEventsPage:(e,t={})=>{const n=new URLSearchParams;t.sessionId&&n.set("sessionId",t.sessionId),t.afterSequence!==void 0&&n.set("afterSequence",String(t.afterSequence)),t.beforeSequence!==void 0&&t.beforeSequence!==null&&n.set("beforeSequence",String(t.beforeSequence)),t.limit!==void 0&&n.set("limit",String(t.limit));const a=n.size?`?${n.toString()}`:"";return B(e,`/v1/events/page${a}`)},workOutputs:e=>B(e,"/v1/work/outputs"),harnessHistory:e=>B(e,"/v1/harness"),refinerHistory:e=>B(e,"/v1/refiner"),updateRefinerProfile:(e,t)=>B(e,"/v1/refiner/update",{method:"POST",body:JSON.stringify(t)}),activateRefinerRelease:(e,t)=>B(e,"/v1/refiner/activate",{method:"POST",body:JSON.stringify(t)}),rollbackRefinerRelease:(e,t)=>B(e,"/v1/refiner/rollback",{method:"POST",body:JSON.stringify(t)}),updateHarnessBackgroundReview:(e,t)=>B(e,"/v1/harness/background-review",{method:"POST",body:JSON.stringify(t)}),reviewHarnessEvaluation:(e,t)=>B(e,"/v1/harness/evaluation-review",{method:"POST",body:JSON.stringify(t)}),updateHarnessEvaluationReviewSchedule:(e,t)=>B(e,"/v1/harness/evaluation-review/settings",{method:"POST",body:JSON.stringify(t)}),harnessReleaseDiff:(e,t)=>B(e,"/v1/harness/diff",{method:"POST",body:JSON.stringify(t)}),rollbackHarness:(e,t)=>B(e,"/v1/harness/rollback",{method:"POST",body:JSON.stringify(t)}),reviewHarnessProposal:(e,t)=>B(e,"/v1/harness/review",{method:"POST",body:JSON.stringify(t)}),runSubagentLifecycleAction:(e,t,n)=>B(e,`/v1/subagents/${encodeURIComponent(t)}/lifecycle`,{method:"POST",body:JSON.stringify(n)}),trainingState:(e,t)=>B(e,`/v1/training?profileId=${encodeURIComponent(t)}`),trainingActivity:(e,t)=>B(e,`/v1/training/activity?profileId=${encodeURIComponent(t)}`),portableTrainingCatalog:(e,t="",n)=>{const a=new URLSearchParams;return t.trim()&&a.set("query",t.trim()),n&&a.set("method",n),B(e,`/v1/training/catalog${a.size?`?${a.toString()}`:""}`)},datasetCatalog:(e,t)=>B(e,`/v1/training/datasets?profileId=${encodeURIComponent(t)}`),trainingRunDetail:(e,t,n={})=>B(e,`/v1/training/jobs/${encodeURIComponent(t)}/detail?evaluation=${n.includeEvaluation===!1?"false":"true"}`),candidateReview:(e,t,n=!1,a="models")=>B(e,`/v1/training/${a}/${encodeURIComponent(t)}/candidate-decision?refresh=${n}`),recordCandidateReview:(e,t,n,a="models")=>B(e,`/v1/training/${a}/${encodeURIComponent(t)}/candidate-decision`,{method:"POST",body:JSON.stringify(n)}),candidateReviewHistory:(e,t,n,a="models")=>B(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),B(e,`/v1/training/jobs/${encodeURIComponent(t)}/evaluations/${encodeURIComponent(n.id)}/tasks?${o}`)},trainingRequest:(e,t,n,a="POST")=>B(e,`/v1/training${t}`,{method:a,body:a==="GET"||a==="DELETE"?void 0:JSON.stringify(n)}),datasetStorageState:e=>B(e,"/v1/settings/dataset-storage"),updateDatasetStorage:(e,t)=>B(e,"/v1/settings/dataset-storage",{method:"PATCH",body:JSON.stringify({datasetStorePath:t})}),hostedSavedWork:e=>B(e,"/v1/saved-work"),createHostedSavedWork:(e,t)=>B(e,"/v1/saved-work",{method:"POST",body:JSON.stringify(t)}),updateHostedSavedWork:(e,t,n)=>B(e,`/v1/saved-work/schedules/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),deleteHostedSavedWork:(e,t)=>B(e,`/v1/saved-work/schedules/${encodeURIComponent(t)}`,{method:"DELETE"}),runHostedSavedWork:(e,t,n)=>B(e,`/v1/saved-work/schedules/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify({clientRequestId:n})}),chatWorkflows:(e,t)=>{const n=t?`?sessionId=${encodeURIComponent(t)}`:"";return B(e,`/v1/chat-workflows${n}`)},createChatWorkflow:(e,t)=>B(e,"/v1/chat-workflows",{method:"POST",body:JSON.stringify(t)}),updateChatWorkflow:(e,t,n)=>B(e,`/v1/chat-workflows/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),deleteChatWorkflow:(e,t)=>B(e,`/v1/chat-workflows/${encodeURIComponent(t)}`,{method:"DELETE"}),runChatWorkflow:(e,t)=>B(e,`/v1/chat-workflows/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify({})}),localAgentSchedules:(e,t={})=>{const n=new URLSearchParams;t.localProjectId&&n.set("localProjectId",t.localProjectId);const a=n.size?`?${n.toString()}`:"";return B(e,`/v1/local-agent-schedules${a}`)},syncLocalAgentSchedules:e=>B(e,"/v1/local-agent-schedules/sync",{method:"POST",body:JSON.stringify({})}),patchLocalAgentSchedule:(e,t,n)=>B(e,`/v1/local-agent-schedules/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),runLocalAgentSchedule:(e,t,n={})=>B(e,`/v1/local-agent-schedules/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify(n)}),localAgentScheduleRuns:(e,t,n={})=>{const a=new URLSearchParams;n.limit!==void 0&&a.set("limit",String(n.limit));const o=a.size?`?${a.toString()}`:"";return B(e,`/v1/local-agent-schedules/${encodeURIComponent(t)}/runs${o}`)},refreshOpenPondAccounts:e=>B(e,"/v1/openpond/accounts/refresh",{method:"POST",body:JSON.stringify({})}),refreshOpenPondAccount:e=>B(e,"/v1/openpond/account?refresh=1"),loadMoreOpenPondApps:(e,t)=>B(e,`/v1/openpond/apps/more?offset=${encodeURIComponent(String(t.offset))}&limit=${encodeURIComponent(String(t.limit))}`),switchOpenPondAccount:(e,t)=>B(e,"/v1/openpond/accounts/switch",{method:"POST",body:JSON.stringify(t)}),removeOpenPondAccount:(e,t)=>B(e,"/v1/openpond/accounts",{method:"DELETE",body:JSON.stringify(t)}),signOutOpenPondAccount:e=>B(e,"/v1/openpond/accounts/logout",{method:"POST",body:JSON.stringify({})}),saveOpenPondAccount:(e,t)=>B(e,"/v1/openpond/accounts/login",{method:"POST",body:JSON.stringify(t)}),updateOpenPondAccountConfig:(e,t)=>B(e,"/v1/openpond/accounts/config",{method:"PATCH",body:JSON.stringify(t)}),savePreferences:(e,t)=>B(e,"/v1/preferences",{method:"PATCH",body:JSON.stringify(t)}),saveProviderSettings:(e,t)=>B(e,"/v1/providers",{method:"PATCH",body:JSON.stringify(t)}),providerSettings:e=>B(e,"/v1/providers"),loadProviderModels:(e,t,n={})=>{const a=new URLSearchParams;n.query?.trim()&&a.set("query",n.query.trim()),n.limit&&a.set("limit",String(n.limit));const o=a.size?`?${a.toString()}`:"";return B(e,`/v1/providers/${encodeURIComponent(t)}/models${o}`)},refreshProviderModels:(e,t,n)=>B(e,`/v1/providers/${encodeURIComponent(t)}/models`,{method:"POST",body:JSON.stringify(n)}),saveProviderCredential:(e,t,n)=>B(e,`/v1/providers/${encodeURIComponent(t)}/credential`,{method:"PUT",body:JSON.stringify(n)}),deleteProviderCredential:(e,t,n)=>B(e,`/v1/providers/${encodeURIComponent(t)}/credential`,{method:"DELETE",body:JSON.stringify(n)}),startOpenAiSubscriptionAuth:(e,t)=>B(e,"/v1/providers/openai/subscription-auth",{method:"POST",body:JSON.stringify(t)}),validateProviderCredential:(e,t,n)=>B(e,`/v1/providers/${encodeURIComponent(t)}/validate`,{method:"POST",body:JSON.stringify(n)}),savePersonalization:(e,t)=>B(e,"/v1/personalization",{method:"PATCH",body:JSON.stringify(t)}),recordClientDiagnostic:(e,t)=>B(e,"/v1/diagnostics/client",{method:"POST",body:JSON.stringify(t)}),profileCurrent:e=>B(e,"/v1/profile"),profileCatalog:e=>B(e,"/v1/profile/catalog"),profileWorkflows:e=>B(e,"/v1/profile/workflows"),profileEvaluations:e=>B(e,"/v1/profile/evaluations"),profileEvaluationDiscovery:(e,t,n)=>B(e,"/v1/profile/evaluations/discover",{method:"POST",body:JSON.stringify({profileRef:t}),signal:n}),profileEvaluationPrepare:(e,t)=>B(e,"/v1/profile/evaluations/prepare",{method:"POST",body:JSON.stringify(t)}),profileEvaluationRun:(e,t)=>B(e,"/v1/profile/evaluations/run",{method:"POST",body:JSON.stringify(t)}),profileEvaluationRunSuite:(e,t)=>B(e,"/v1/profile/evaluations/run-suite",{method:"POST",body:JSON.stringify(t)}),profileEvaluationCompare:(e,t)=>B(e,"/v1/profile/evaluations/compare",{method:"POST",body:JSON.stringify({id:`comparison-${crypto.randomUUID()}`,runIds:t})}),profileEvaluationSaveReport:(e,t,n)=>B(e,"/v1/profile/evaluations/reports",{method:"POST",body:JSON.stringify({id:`report-${crypto.randomUUID()}`,evidenceKind:t,evidenceId:n})}),profileSelect:(e,t)=>B(e,"/v1/profile/select",{method:"POST",body:JSON.stringify({ref:t})}),profileRemove:(e,t)=>B(e,"/v1/profile/remove",{method:"POST",body:JSON.stringify({ref:t})}),profilePublicationPreview:(e,t)=>B(e,"/v1/profile/publication/preview",{method:"POST",body:JSON.stringify(t)}),profilePublicationPublish:(e,t)=>B(e,"/v1/profile/publication/publish",{method:"POST",body:JSON.stringify(t)}),profileInstall:(e,t)=>B(e,"/v1/profile/install",{method:"POST",body:JSON.stringify(t)}),profileUpdate:(e,t)=>B(e,"/v1/profile/update",{method:"POST",body:JSON.stringify({ref:t})}),profileInit:(e,t)=>B(e,"/v1/profile/init",{method:"POST",body:JSON.stringify(t)}),profileLoad:(e,t)=>B(e,"/v1/profile/load",{method:"POST",body:JSON.stringify(t)}),profileCheck:(e,t)=>B(e,"/v1/profile/check",{method:"POST",body:JSON.stringify(t)}),profileAgentRename:(e,t,n)=>B(e,`/v1/profile/agents/${encodeURIComponent(t)}/name`,{method:"PATCH",body:JSON.stringify(n)}),profileCommit:(e,t)=>B(e,"/v1/profile/commit",{method:"POST",body:JSON.stringify(t)}),profilePush:(e,t)=>B(e,"/v1/profile/push",{method:"POST",body:JSON.stringify(t)}),workspaceLspSettingsStatus:e=>B(e,"/v1/lsp/settings-status"),workspaceLspRuntimeStatus:e=>B(e,"/v1/lsp/status"),restartWorkspaceLsp:e=>B(e,"/v1/lsp/restart",{method:"POST"}),remoteAccess:e=>B(e,"/v1/remote-access"),enableRemoteAccess:e=>B(e,"/v1/remote-access/enable",{method:"POST"}),disableRemoteAccess:e=>B(e,"/v1/remote-access/disable",{method:"POST"}),voiceTranscriptionStatus:(e,t={})=>B(e,"/v1/audio/transcriptions/status",{signal:t.signal}),transcribeVoice:(e,t,n={})=>B(e,"/v1/audio/transcriptions",{method:"POST",body:JSON.stringify(t),signal:n.signal}),createSession:(e,t)=>B(e,"/v1/sessions",{method:"POST",body:JSON.stringify(t)}),patchSession:(e,t,n)=>B(e,`/v1/sessions/${t}`,{method:"PATCH",body:JSON.stringify(n)}),codexHistoryThread:(e,t,n={})=>{const a=new URLSearchParams;n.limit!==void 0&&a.set("limit",String(n.limit)),n.tail&&a.set("tail","1");const o=a.size?`?${a.toString()}`:"";return B(e,`/v1/codex-history/${encodeURIComponent(t)}${o}`)},codexHistoryThreadIncremental:(e,t,n={})=>{const a=new URLSearchParams({incremental:"1"});return n.afterEventId&&a.set("afterEventId",n.afterEventId),n.limit!==void 0&&a.set("limit",String(n.limit)),n.revision&&a.set("revision",n.revision),n.tail&&a.set("tail","1"),B(e,`/v1/codex-history/${encodeURIComponent(t)}?${a.toString()}`)},sendCodexHistoryTurn:(e,t,n)=>B(e,`/v1/codex-history/${encodeURIComponent(t)}/turns`,{method:"POST",body:JSON.stringify(n)}),interruptCodexHistoryTurn:(e,t)=>B(e,`/v1/codex-history/${encodeURIComponent(t)}/turns/interrupt`,{method:"POST"}),patchSidebarAppPreference:(e,t,n)=>B(e,`/v1/sidebar/apps/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),reorderSidebarApps:(e,t)=>B(e,"/v1/sidebar/apps/reorder",{method:"POST",body:JSON.stringify(t)}),sidebarFiles:e=>B(e,"/v1/sidebar/files"),patchSidebarFile:(e,t)=>B(e,"/v1/sidebar/files",{method:"PATCH",body:JSON.stringify(t)}),workspaceStatus:(e,t,n=!1,a={})=>B(e,`/v1/workspaces/${encodeURIComponent(t)}${n?"?ensure=1":""}`,{signal:a.signal}),createWorkspaceBranch:(e,t,n)=>B(e,`/v1/workspaces/${encodeURIComponent(t)}/branches`,{method:"POST",body:JSON.stringify(n)}),checkoutWorkspaceBranch:(e,t,n)=>B(e,`/v1/workspaces/${encodeURIComponent(t)}/branch`,{method:"PATCH",body:JSON.stringify(n)}),workspaceDiff:(e,t,n={})=>B(e,`/v1/workspaces/${encodeURIComponent(t)}/diff`,{signal:n.signal}),workspaceFile:(e,t,n)=>B(e,`/v1/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}`),saveWorkspaceFile:(e,t,n)=>B(e,`/v1/workspaces/${encodeURIComponent(t)}/file`,{method:"PATCH",body:JSON.stringify(n)}),signWorkspaceImageUrl:(e,t)=>B(e,"/v1/assets/workspace-image-url",{method:"POST",body:JSON.stringify(t)}),signLocalImageUrl:(e,t)=>B(e,"/v1/assets/local-image-url",{method:"POST",body:JSON.stringify(t)}),signLocalVideoUrl:(e,t)=>B(e,"/v1/assets/local-video-url",{method:"POST",body:JSON.stringify(t)}),signChatAttachmentImageUrl:(e,t)=>B(e,"/v1/assets/chat-attachment-image-url",{method:"POST",body:JSON.stringify(t)}),chatAttachmentFile:(e,t)=>B(e,"/v1/assets/chat-attachment-file",{method:"POST",body:JSON.stringify(t)}),workspaceLspTouch:(e,t,n,a={})=>B(e,`/v1/workspaces/${encodeURIComponent(t)}/lsp/touch`,{method:"POST",body:JSON.stringify(n),signal:a.signal}),workspaceLspAction:(e,t,n)=>B(e,`/v1/workspaces/${encodeURIComponent(t)}/lsp/action`,{method:"POST",body:JSON.stringify(n)}),workspaceTemplateConfig:(e,t)=>B(e,`/v1/openpond/apps/${encodeURIComponent(t)}/template-config`),...LK,...WK,createLocalProject:(e,t)=>B(e,"/v1/projects",{method:"POST",body:JSON.stringify(t)}),updateLocalProjectAgentSetup:(e,t,n)=>B(e,`/v1/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),uploadLocalProjectCloudSource:(e,t,n)=>B(e,`/v1/projects/${encodeURIComponent(t)}/cloud-source`,{method:"POST",body:JSON.stringify(n)}),previewLocalProjectCloudSource:(e,t,n={})=>{const a=new URLSearchParams;n.branch?.trim()&&a.set("branch",n.branch.trim());const o=a.toString()?`?${a.toString()}`:"";return B(e,`/v1/projects/${encodeURIComponent(t)}/cloud-source/preview${o}`)},deleteLocalProject:(e,t)=>B(e,`/v1/projects/${encodeURIComponent(t)}`,{method:"DELETE"}),gitAvailability:e=>B(e,"/v1/system/git"),installMacOSCommandLineTools:e=>B(e,"/v1/system/git/install-command-line-tools",{method:"POST",body:JSON.stringify({})}),...qK,resolveApproval:(e,t,n)=>B(e,`/v1/approvals/${t}`,{method:"POST",body:JSON.stringify(n)})};function gx(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 tW=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),nW=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,a)=>a?a.toUpperCase():n.toLowerCase()),vx=e=>{const t=nW(e);return t.charAt(0).toUpperCase()+t.slice(1)},cP=(...e)=>e.filter((t,n,a)=>!!t&&t.trim()!==""&&a.indexOf(t)===n).join(" ").trim(),aW=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var iW={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 oW=y.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:a,className:o="",children:r,iconNode:s,...l},m)=>y.createElement("svg",{ref:m,...iW,width:t,height:t,stroke:e,strokeWidth:a?Number(n)*24/Number(t):n,className:cP("lucide",o),...!r&&!aW(l)&&{"aria-hidden":"true"},...l},[...s.map(([d,f])=>y.createElement(d,f)),...Array.isArray(r)?r:[r]]));const rt=(e,t)=>{const n=y.forwardRef(({className:a,...o},r)=>y.createElement(oW,{ref:r,iconNode:t,className:cP(`lucide-${tW(vx(e))}`,`lucide-${e}`,a),...o}));return n.displayName=vx(e),n};const rW=[["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"}]],sW=rt("activity",rW);const lW=[["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"}]],cW=rt("archive-restore",lW);const dW=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],uW=rt("arrow-left",dW);const mW=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}]],dP=rt("bookmark",mW);const pW=[["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"}]],uP=rt("bookmark-x",pW);const fW=[["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"}]],bx=rt("book-open-text",fW);const hW=[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]],gW=rt("bot",hW);const vW=[["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"}]],ru=rt("boxes",vW);const bW=[["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"}]],mP=rt("calendar-clock",bW);const yW=[["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"}]],pP=rt("chart-column-stacked",yW);const SW=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Ai=rt("check",SW);const xW=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],Tu=rt("circle-check",xW);const kW=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Go=rt("chevron-down",kW);const wW=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Jo=rt("chevron-right",wW);const IW=[["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"}]],mm=rt("circle-alert",IW);const _W=[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]],up=rt("cloud",_W);const CW=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],RW=rt("credit-card",CW);const PW=[["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"}]],AW=rt("download",PW);const TW=[["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"}]],Ih=rt("external-link",TW);const EW=[["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"}]],fP=rt("file-output",EW);const MW=[["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"}]],ry=rt("file-text",MW);const jW=[["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"}]],hP=rt("folder",jW);const OW=[["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"}]],sy=rt("folder-git-2",OW);const $W=[["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"}]],NW=rt("git-branch",$W);const DW=[["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"}]],HW=rt("github",DW);const LW=[["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"}]],gP=rt("earth",LW);const qW=[["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"}]],UW=rt("circle-question-mark",qW);const zW=[["path",{d:"M2 5h20",key:"1fs1ex"}],["path",{d:"M6 12h12",key:"8npq4p"}],["path",{d:"M9 19h6",key:"456am0"}]],BW=rt("list-filter",zW);const FW=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],ly=rt("loader-circle",FW);const VW=[["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"}]],KW=rt("maximize-2",VW);const WW=[["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"}]],mp=rt("message-square",WW);const GW=[["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"}]],yd=rt("ellipsis",GW);const JW=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],vP=rt("panel-left",JW);const ZW=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],Og=rt("panel-right",ZW);const YW=[["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"}]],cy=rt("pin",YW);const QW=[["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"}]],dy=rt("pin-off",QW);const XW=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],e8=rt("plus",XW);const t8=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],n8=rt("power",t8);const a8=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],i8=rt("refresh-cw",a8);const o8=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]],r8=rt("rotate-ccw",o8);const s8=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],l8=rt("search",s8);const c8=[["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"}]],bP=rt("settings",c8);const d8=[["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"}]],uy=rt("shapes",d8);const u8=[["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"}]],$g=rt("shield",u8);const m8=[["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"}]],pp=rt("square-pen",m8);const p8=[["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"}]],yP=rt("square-terminal",p8);const f8=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],yx=rt("user-round",f8);const h8=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Sd=rt("x",h8);const g8=[["polyline",{points:"22 12 16 12 14 15 10 15 8 12 2 12",key:"o97t9d"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}]],my=rt("inbox",g8);const v8=[["path",{d:"M3 5h.01",key:"18ugdj"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 19h.01",key:"noohij"}],["path",{d:"M8 5h13",key:"1pao27"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 19h13",key:"m83p4d"}]],b8=rt("list",v8);const y8=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],S8=rt("terminal",y8);function x8({platform:e}){return!py()||SP(e)?null:S.jsxs("div",{className:"window-controls","aria-label":"Window controls",children:[S.jsx("button",{type:"button",className:"window-control minimize",title:"Minimize",onClick:()=>{_h("minimize")},children:S.jsx(Go,{size:14})}),S.jsx("button",{type:"button",className:"window-control maximize",title:"Maximize",onClick:()=>{_h("toggleMaximize")},children:S.jsx(KW,{size:12})}),S.jsx("button",{type:"button",className:"window-control close",title:"Close",onClick:()=>{_h("close")},children:S.jsx(Sd,{size:13})})]})}function SP(e){const t=e?.toLowerCase()??"";return t==="darwin"||t.includes("mac")}function py(){if(typeof window>"u")return!1;const e=window.openpond;return!!(e?.minimizeWindow||e?.toggleMaximizeWindow||e?.closeWindow)}async function _h(e){const t=window.openpond;if(!(t&&(e==="minimize"?await t.minimizeWindow?.():e==="toggleMaximize"?await t.toggleMaximizeWindow?.():await t.closeWindow?.())!==!1)){if(e==="toggleMaximize"&&document.fullscreenEnabled){document.fullscreenElement?await document.exitFullscreen():await document.documentElement.requestFullscreen();return}if(e==="close"){window.close();return}console.warn("Window controls require the Electron desktop shell.")}}const k8=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"r6nss1"}]],xP=rt("house",k8);function w8({value:e,options:t,disabled:n,compact:a,className:o,icon:r,placement:s="bottom",label:l,tooltip:m,searchable:d=!1,floating:f=!1,onChange:g}){const[x,k]=y.useState(!1),[C,R]=y.useState(""),E=y.useRef(null),[A,O]=y.useState();y.useLayoutEffect(()=>{if(!x||!f)return;function P(){const j=E.current?.getBoundingClientRect();if(!j)return;const N=window.innerHeight-j.bottom-12,z=j.top-12,D=N<180&&z>N;O({position:"fixed",left:Math.max(12,j.left),width:Math.min(j.width,window.innerWidth-24),minWidth:0,maxWidth:"calc(100vw - 24px)",right:"auto",top:D?"auto":j.bottom+5,bottom:D?window.innerHeight-j.top+5:"auto",maxHeight:Math.max(80,Math.min(320,D?z-5:N-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)}},[x,f]);const $=t.find(P=>P.value===e)??t[0],M=C.trim().toLowerCase(),w=M?t.filter(P=>[P.label,P.shortLabel,P.description].some(j=>j?.toLowerCase().includes(M))):t;return y.useEffect(()=>{if(!x){R("");return}function P(N){E.current?.contains(N.target)||k(!1)}function j(N){N.key==="Escape"&&k(!1)}return document.addEventListener("pointerdown",P),document.addEventListener("keydown",j),()=>{document.removeEventListener("pointerdown",P),document.removeEventListener("keydown",j)}},[x]),S.jsxs("div",{className:`dropdown-select ${o??""} ${a?"compact":""} ${s==="top"?"open-up":""}`,"data-tooltip":m,ref:E,children:[S.jsxs("button",{type:"button",className:`dropdown-trigger ${x?"active":""}`,disabled:n,"aria-label":l,"aria-haspopup":"menu","aria-expanded":x,onClick:()=>k(P=>!P),children:[r,S.jsx("span",{children:$?.shortLabel??$?.label??e}),S.jsx(Go,{size:14})]}),x&&S.jsxs("div",{className:"dropdown-menu",role:"menu",style:f?A:void 0,children:[d?S.jsxs("label",{className:"dropdown-search",onClick:P=>P.stopPropagation(),children:[S.jsxs("span",{className:"sr-only",children:["Search ",l]}),S.jsx("input",{autoFocus:!0,placeholder:`Search ${l.toLowerCase()}`,value:C,onChange:P=>R(P.target.value)})]}):null,w.map(P=>S.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||(g(P.value),R(""),k(!1))},children:[S.jsxs("span",{children:[P.icon==="plus"?S.jsx(e8,{size:13}):null,S.jsx("span",{children:P.label})]}),P.description&&S.jsx("small",{children:P.description})]},P.value)),w.length?null:S.jsx("div",{className:"dropdown-empty",children:"No matches"})]})]})}const coe=[{value:"chat",label:"Chat"},{value:"work",label:"Work"}];function kP(e){return e==="chat"?"New chat":"New task"}const Ng=["get-started","home","inbox","models","datasets","graders","experiments","tasks","tasksets","labeling","rewards","evaluations","runs","versions","serving"],I8={"get-started":"Get started",home:"Home",inbox:"Inbox",models:"Models",datasets:"Datasets",graders:"Graders",experiments:"Experiments",tasks:"Tasks",tasksets:"Tasksets",labeling:"Labeling",rewards:"Rewards",evaluations:"Runs",runs:"Runs",versions:"Versions",serving:"Serving"},_8={tasks:["drafts"],tasksets:["drafts","formats","batches"],rewards:["scorers","combined"],evaluations:["results","review","comparisons"],runs:["series","new"]},C8={datasets:["tasks","experiments","graders","versions"],graders:["overview","checks","usage","versions"],experiments:["overview","cases","compare","configuration"],tasksets:["overview","tasks","reward","attempts","releases"],rewards:["definition","usage","evidence"],evaluations:["overview","comparison","activity"],runs:["details","metrics","evaluation","rollouts","activity","artifacts"],versions:["overview","metrics","evaluation","rollouts","activity","artifacts"]};function Fa(e="models",t=null,n={}){return e==="evaluations"&&n.collection==="review"?Fa("labeling",t,{...n,collection:"default"}):{page:e,modelId:["get-started","home","inbox","datasets","graders","experiments"].includes(e)?null:t,collection:e==="evaluations"?"results":"default",resourceId:null,detailTab:null,query:"",after:null,...n}}function fy(e){const t=e.pathname.split("/").filter(Boolean);if(t[0]!=="models"&&t[0]!=="console")return null;let n;try{n=t.slice(1).map(decodeURIComponent)}catch{return null}if(n.some(te=>!te.trim()||te.length>2e3||te.includes("\0")))return null;const a=n[0]&&!Ng.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(),r=o??"models";if(!Ng.includes(r)||o==="models"||a&&r==="get-started")return null;let s=r==="evaluations"?"results":"default";if(_8[r]?.includes(n[0]))s=n.shift();else if(r==="evaluations"&&n.length)return null;if(r==="experiments"&&n[0]==="history")return null;const l=n.shift()??null,m=n.shift()??null;if(n.length||m&&!l||(r==="models"||r==="get-started"||r==="home")&&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&&!C8[r]?.includes(m))return null}if(r==="serving"&&m)return null;const d=new URLSearchParams(e.search??"");if([...d.keys()].some(te=>!["model","q","after","source","project","pass","dataset","revision","hash","sort","location","kind","review_source","review_snapshot","review_boundary","review_revision"].includes(te))||[...d.keys()].some(te=>d.getAll(te).length!==1))return null;const f=["review_source","review_snapshot","review_boundary","review_revision"],g=f.some(te=>d.has(te));if(g&&(r!=="datasets"||l||d.get("location")==="local"||f.some(te=>!d.get(te))||[d.get("review_source"),d.get("review_boundary")].some(te=>!te.trim()||te.length>500||te.includes("\0"))||[d.get("review_snapshot"),d.get("review_revision")].some(te=>!/^[a-f0-9]{64}$/.test(te))))return null;const x=g?{id:d.get("review_source"),snapshotHash:d.get("review_snapshot"),boundaryId:d.get("review_boundary"),boundaryRevisionHash:d.get("review_revision")}:void 0,k=d.get("sort");if(k!==null&&(r!=="datasets"||!["id","name","updated"].includes(k)))return null;const C=d.has("revision")?Number(d.get("revision")):void 0,R=d.get("hash")??void 0,E=["datasets","graders"].includes(r);if((C!==void 0||R!==void 0)&&(!l||!E||!Number.isSafeInteger(C)||C<=0||!/^[a-f0-9]{64}$/.test(R??"")))return null;const A=d.get("source");if(A!==null&&(r!=="labeling"&&(r!=="evaluations"||s!=="review")||!A.trim()||A.length>500)||d.has("dataset")&&(r!=="datasets"||!l||d.get("dataset")!=="release"))return null;const O=["home","inbox","datasets","graders","experiments"].includes(r),$=r==="runs"&&!!(l?.startsWith("hosted-run:")||l?.startsWith("hosted-policy:")),M=d.get("location");if(M!==null&&(!O||!["local","hosted"].includes(M)))return null;const w=d.get("kind");if(w!==null&&(r!=="experiments"||!l||M==="local"||w!=="recorded_evidence")||t[0]==="console"&&!O)return null;const P=d.get("project")==="all"?null:d.get("project"),j=d.get("pass");if([P,j].some(te=>te!==null&&(!te.trim()||te.length>240))||!O&&!$&&(P||j)||r!=="experiments"&&j||(O||$)&&a||j&&!l)return null;const N=d.get("model");if(O&&N!==null||a&&N&&a!==N)return null;const z=a??N;if(r==="get-started"&&d.size!==0)return null;const D=d.get("q")??"",F=d.get("after");return z!==null&&(!z.trim()||z.length>500)||D.length>1e3||F!==null&&(!F.trim()||F.length>2e3)?null:Fa(r,z,{...x?{reviewSource:x}:{},collection:s,resourceId:l,detailTab:m,query:D,after:F,...w?{executionKind:"recorded_evidence"}:{},...M?{executionLocation:M}:{},...k?{sort:k}:{},...C!==void 0?{revision:C,contentHash:R}:{},...d.get("dataset")==="release"?{datasetKind:"release"}:{},...t[0]==="console"?{area:"console"}:{},...O||$?{...d.has("project")?{projectId:P}:{},...d.has("pass")?{passId:j}:{}}:{},...A!==null?{sourceId:A}:{}})}function fp(e){const t=[e.area==="console"?"/console":"/models"];if(e.modelId&&t.push(encodeURIComponent(e.modelId)),e.page==="evaluations"&&e.collection==="review")return fp(Fa("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.page==="datasets"&&!e.resourceId&&e.reviewSource&&(n.set("review_source",e.reviewSource.id),n.set("review_snapshot",e.reviewSource.snapshotHash),n.set("review_boundary",e.reviewSource.boundaryId),n.set("review_revision",e.reviewSource.boundaryRevisionHash)),e.executionLocation&&n.set("location",e.executionLocation),e.projectId?n.set("project",e.projectId):e.projectId===null&&["home","inbox","datasets","graders","experiments"].includes(e.page)&&n.set("project","all"),e.page==="datasets"&&e.resourceId&&e.datasetKind==="release"&&n.set("dataset","release"),e.page==="datasets"&&e.sort&&n.set("sort",e.sort),e.revision!==void 0&&e.contentHash&&e.resourceId&&["datasets","graders"].includes(e.page)&&(n.set("revision",String(e.revision)),n.set("hash",e.contentHash)),e.passId&&n.set("pass",e.passId),e.page==="experiments"&&e.resourceId&&e.executionKind&&n.set("kind",e.executionKind),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 R8(e,t){return Fa(e.page,t,{...e.area?{area:e.area}:{},...["home","inbox","datasets","graders","experiments"].includes(e.page)&&e.projectId!==void 0?{projectId:e.projectId}:{},collection:e.collection==="new"||e.collection==="drafts"?"default":e.collection})}function doe(e,t,n=null){return{...e,resourceId:t,detailTab:n,after:null,...t!==e.resourceId?{revision:void 0,contentHash:void 0}:{}}}const pm=new Set,Dg=new Set,P8=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"]),Hg={apps:"/apps",outputs:"/outputs",projects:"/projects",scheduled:"/workflows","get-started":"/get-started",team:"/team",community:"/community"};let Lg=!1,qg="",Eu=null,wP=null,Lc="",ri=0,Kl=null,hc=!1,Ch=null,Mu=!1;function hy(e){const t=fy(e);if(t)return{kind:"models",route:t};const n=e.pathname.split("/").filter(Boolean);if(n[0]==="models"||n[0]==="console")return{kind:"models_unavailable",pathname:e.pathname,search:e.search??""};if(n[0]==="settings"&&n.length===2&&P8.has(n[1])){const o=gy(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(Hg).find(o=>Hg[o]===e.pathname);return a?{kind:"view",view:a}:null}function IP(e){if(e.kind==="models")return fp(e.route);if(e.kind==="models_unavailable")return`${e.pathname}${e.search}`;if(e.kind==="settings"){const t=gy(e.returnTo??null);return`/settings/${e.section}${t?`?${new URLSearchParams({returnTo:t})}`:""}`}return e.kind==="chat"?e.sessionId?`/chat/${encodeURIComponent(e.sessionId)}`:"/chat/new":Hg[e.view]}function A8(e){const t=e?.kind==="settings"?gy(e.returnTo??null):null;if(t){const n=new URL(t,"https://local.openpond.invalid"),a=fy(n);if(a)return{kind:"models",route:a}}return{kind:"chat",sessionId:null}}function gy(e){if(!e||e.length>6e3||!["/models","/console"].some(a=>e.startsWith(a))||e.startsWith("//"))return null;const t=new URL(e,"https://local.openpond.invalid");if(t.origin!=="https://local.openpond.invalid"||t.hash)return null;const n=fy(t);return n?fp(n):null}function xd(){return`${window.location.pathname}${window.location.search}`}function vy(){if(typeof window>"u")return;const e=Lg?Lc:xd();e!==qg&&(qg=e,Eu=hy(new URL(e,window.location.origin)),wP=Eu?.kind==="models"?Eu.route:null)}function _P(){qg="",vy();for(const e of Dg)e()}async function by(e){if(Mu)return!1;Mu=!0;try{for(const t of[...pm].reverse())if(!await t(e))return!1;return!0}finally{Mu=!1}}function yy(e){return{...window.history.state,openpondNavigationIndex:e}}async function T8(){const e=xd(),t=typeof window.history.state?.openpondNavigationIndex=="number"?window.history.state.openpondNavigationIndex:ri-1;if(Kl&&t===ri){const a=Kl;Kl=null,a();return}if(Ch===t||pm.size===0){Ch=null,Lc=e,ri=t,window.history.replaceState(yy(ri),"",e),_P();return}if(t===ri)return;if(hc||Mu){Kl??=()=>{},window.history.go(ri-t);return}hc=!0;const n=t-ri;try{await new Promise(a=>{Kl=a,window.history.go(-n)}),await by(e)&&(Ch=t,window.history.go(n))}finally{hc=!1}}function Sy(){if(Lg||typeof window>"u")return;const e=hy(window.location);Lc=e?IP(e):xd(),ri=typeof window.history.state?.openpondNavigationIndex=="number"?window.history.state.openpondNavigationIndex:0,window.history.replaceState(yy(ri),"",Lc),window.addEventListener("popstate",T8),Lg=!0}function CP(e){return Dg.add(e),Sy(),()=>{Dg.delete(e)}}function uoe(e){return pm.add(e),Sy(),()=>{pm.delete(e)}}async function moe(e){!hc&&await by(xd())&&e()}function E8(){return y.useSyncExternalStore(CP,()=>(vy(),wP),()=>null)}function M8(){return y.useSyncExternalStore(CP,()=>(vy(),Eu),()=>null)}async function Vt(e,t="push"){if(typeof window>"u"||(Sy(),hc))return!1;if(e.kind==="settings"&&!e.returnTo){const a=hy(window.location),o=a?.kind==="models"?fp(a.route):a?.kind==="settings"?a.returnTo:void 0;o&&(e={...e,returnTo:o})}const n=IP(e);return xd()===n?!0:await by(n)?(t==="push"&&ri++,window.history[t==="replace"?"replaceState":"pushState"](yy(ri),"",n),Lc=n,_P(),!0):!1}function Ar(e,t="push"){return Vt({kind:"models",route:e},t)}function j8({experience:e="work",beginNewChat:t}){return S.jsx("div",{className:"sidebar-new-task",children:S.jsxs("button",{className:"sidebar-row sidebar-task-row sidebar-new-task-entry",type:"button",onClick:async()=>{await Vt({kind:"chat",sessionId:null})&&t(null)},children:[S.jsx("span",{className:"conversation-source-icon","aria-hidden":"true",children:S.jsx(pp,{size:18})}),S.jsx("span",{children:kP(e)})]})})}function O8({productArea:e="chat",setSectionMenuOpen:t,setSelectedAppId:n,setSelectedProjectId:a,setSelectedSessionId:o,setView:r,view:s,modelProjects:l=[],modelTrainingActivityByProjectId:m={}}){const d=E8(),f=d?.modelId??null,g=d?.page??"models";function x(){n(null),a(null),o(null),t(null)}async function k(A){await Ar(Fa(A,["home","inbox","datasets","graders","experiments"].includes(A)?null:f,{...e==="console"?{area:"console"}:{},...d?.projectId!==void 0?{projectId:d.projectId}:{}}))&&(x(),r("labs"))}async function C(A){await Ar(R8(d??Fa(),A||null))&&(x(),r("labs"))}async function R(A){await Vt({kind:"view",view:A})&&(x(),r(A))}const E=f?m[f]??null:null;return S.jsxs("nav",{className:"sidebar-nav","aria-label":"Primary",children:[e!=="chat"?S.jsxs(S.Fragment,{children:[["home","inbox","datasets","graders","experiments"].includes(g)?null:S.jsxs("div",{className:"sidebar-model-project-picker",children:[S.jsx("span",{className:"sidebar-nav-group-label",children:"Model"}),S.jsx(w8,{label:"Model",searchable:l.length>8,value:f??"",options:[{value:"",label:"All models"},...f&&!l.some(A=>A.id===f)?[{value:f,label:"Unavailable model",disabled:!0}]:[],...l.map(A=>({value:A.id,label:A.name}))],onChange:A=>{C(A)}})]}),Ng.filter(A=>e==="console"?["home","inbox","datasets","graders","experiments"].includes(A):A!=="home"&&A!=="tasksets"&&A!=="evaluations").map(A=>{const O={"get-started":ru,home:xP,inbox:my,models:sW,datasets:ru,graders:$g,experiments:Tu,tasks:ru,tasksets:ru,labeling:Tu,rewards:$g,evaluations:Tu,runs:pP,versions:NW,serving:up}[A];return S.jsxs("button",{className:`nav-command ${s==="labs"&&(g===A||A==="runs"&&g==="evaluations")?"active":""}`,"aria-current":s==="labs"&&(g===A||A==="runs"&&g==="evaluations")?"page":void 0,type:"button",onClick:()=>{k(A)},children:[S.jsx(O,{size:16}),S.jsx("span",{children:I8[A]}),A==="runs"&&E?S.jsx("span",{className:"sidebar-running-dot","aria-label":E.label}):null]},A)})]}):null,e==="chat"?S.jsxs(S.Fragment,{children:[S.jsxs("button",{className:`nav-command nav-command-prominent ${s==="scheduled"?"active":""}`,"aria-label":"Workflows",type:"button",onClick:()=>{R("scheduled")},children:[S.jsx(mP,{size:18}),S.jsx("span",{children:"Workflows"})]}),S.jsxs("button",{className:`nav-command nav-command-prominent ${s==="outputs"?"active":""}`,"aria-label":"Outputs",type:"button",onClick:()=>{R("outputs")},children:[S.jsx(fP,{size:18}),S.jsx("span",{children:"Outputs"})]}),S.jsxs("button",{className:`nav-command nav-command-prominent ${s==="apps"?"active":""}`,"aria-label":"Apps",type:"button",onClick:()=>{R("apps")},children:[S.jsx(uy,{size:18}),S.jsx("span",{children:"Apps"})]}),S.jsxs("button",{className:`nav-command nav-command-prominent ${s==="projects"?"active":""}`,"aria-label":"Projects",type:"button",onClick:()=>{R("projects")},children:[S.jsx(sy,{size:18}),S.jsx("span",{children:"Projects"})]})]}):null]})}const RP=Of({chatMode:v(["chat","work"]).optional(),sidebarPresentation:v(["grouped","inbox"]).optional(),notificationMode:v(["all","direct_mentions","none"]).optional(),learningNoticeDismissed:I().optional(),sidebarVisibility:Of({showCodexChats:I(),onlyRunningTasks:I()}).optional(),scheduledWorkView:v(["calendar","list"]).optional(),editorControlsVisible:I().optional(),voiceNoticeAcknowledged:I().optional(),lessonProgress:le(i().min(1).max(200),Of({completed:I(),currentTime:u().finite().nonnegative(),duration:u().finite().positive(),updatedAt:u().finite().nonnegative()})).refine(e=>Object.keys(e).length<=200,"Too many lessons").optional()}),Ug={"openpond:last-chat-task-mode":"chatMode","openpond.sidebar.presentation.v1":"sidebarPresentation","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"},zg=new Set;let gc=null,vo=null,li={},qc={},Rh=!1,ju=0,zs=null,Sx=0;const $8="openpond-client-choices-changed";function xy(){zg.forEach(e=>e()),typeof window<"u"&&window.dispatchEvent(new Event($8))}function N8(){return zs}function D8(e){return zg.add(e),()=>{zg.delete(e)}}function al(e){const t=y.useRef(e);t.current=e,y.useEffect(()=>D8(()=>t.current()),[])}async function xx(e){const t=++Sx,n=await B(e,"/v1/configuration");if(n.clientState?.revision===null){const o=H8();if(Object.keys(o.patch).length){n.clientState=await B(e,"/v1/configuration",{method:"POST",body:JSON.stringify({action:"client-state",owner:n.clientState.owner,patch:o.patch,importOnly:!0})});for(const r of o.keys)try{window.localStorage.removeItem(r)}catch{}}}if(t!==Sx)return;const a=gc?.serverUrl!==e.serverUrl||gc?.token!==e.token||vo?.owner!==n.clientState?.owner;a&&(ju++,li={},qc={},zs=null),gc=e,(a||(n.clientState?.revision??0)>=(vo?.revision??0))&&(vo=n.clientState),xy()}async function ky(){if(Rh||!gc||!vo||!Object.keys(li).length)return;Rh=!0;const e=li,t=gc,n=vo.owner,a=ju;li={},qc=e;try{const o=await B(t,"/v1/configuration",{method:"POST",body:JSON.stringify({action:"client-state",owner:n,patch:e})});a===ju&&(vo=o,zs=null)}catch(o){a===ju&&(li={...e,...li},zs=`Preference changes have not been saved. ${o instanceof Error?o.message:String(o)}`)}finally{qc={},Rh=!1,xy(),!zs&&Object.keys(li).length&&ky()}}function poe(){zs=null,ky()}const Vo={getItem(e){const t=Ug[e];if(!t)return null;const n={...vo?.value,...qc,...li}[t];return n===void 0?null:typeof n=="string"?n:JSON.stringify(n)},setItem(e,t){if(!vo)return;const n=Ug[e];if(!n)throw new Error("Unregistered client preference.");let a;try{a=JSON.parse(t)}catch{a=t}const o=RP.parse({[n]:a});JSON.stringify({...vo.value,...qc,...li}[n])!==JSON.stringify(o[n])&&(li={...li,...o},xy(),ky())}};function H8(){const e={},t=[];if(typeof window>"u")return{patch:e,keys:t};for(const[n,a]of Object.entries(Ug))try{const o=window.localStorage.getItem(n);if(o===null)continue;let r;try{r=JSON.parse(o)}catch{r=o}const s=RP.safeParse({[a]:r});s.success&&(Object.assign(e,s.data),t.push(n))}catch{}return{patch:e,keys:t}}function PP(e){return e.replace(/\s+\(default\)$/i,"").replace(/^(?:openai|anthropic|google|xai|deepseek|qwen|meta-llama)\//i,"").replace(/^gpt-/i,"GPT-")}const Ou=5,Bn=15,Bg=10,Dt={defaultChatProvider:Tr,subagents:aN(),codexPermissionMode:Nv,codexReasoningEffort:Dv,openPondCommandAccessMode:Om,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:""}}}},foe={activeTemplateId:"default",customized:!1,soul:"",soulPath:null,updatedAt:null,templates:[]},AP=[{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"}],Ph=[{value:"openpond",label:"OpenPond Chat"},{value:"codex",label:"OpenAI Codex",description:"Codex login"}],L8=["openai","xai","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],q8=["openpond","codex","claude-code","grok-build","opencode",...L8],TP=new Set(q8),EP=[{value:$v,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"}],hoe=[{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."}],Fg=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"xhigh",label:"Extra High",shortLabel:"Extra High"}],U8=[{value:"off",label:"Off"},...Fg,{value:"max",label:"Max"}],goe=[{value:"ask",label:"Ask",description:"Ask before running shell commands."},{value:"full-access",label:"Full access",description:"Run shell commands without approval prompts."}],voe=[{value:"auto",label:"Auto",description:"Use installed language servers when available."},{value:"off",label:"Off",description:"Disable editor language servers."}],boe=[{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 wy(e){return e.kind==="local"}function z8(e){return e.kind==="cloud"}function kt(e,t){return`${e}:${t}`}function MP(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 _r(e){return`${e.type}:${e.id}`}function fm(e){const t=e.currentTarget.getBoundingClientRect();return e.clientY<t.top+t.height/2?"before":"after"}function hm(e,t,n,a="before"){if(t===n)return e;const o=e.filter(s=>s!==t),r=o.indexOf(n);return r===-1?e:(o.splice(a==="after"?r+1:r,0,t),o)}function kx(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function B8(e,t){if(!t)return e;const n=new Map(e.map(r=>[r.key,r])),a=t.map(r=>n.get(r)).filter(r=>!!r),o=new Set(a.map(r=>r.key));return[...a,...e.filter(r=>!o.has(r.key))]}function Iy(e,t){return e?.statuses?.[t]??null}function jP(e,t){return e?.providers?.[t]??null}function _y(e,t){return e?.modelCaches?.[t]??null}function F8(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:PP(e.displayName||e.id),description:t.join(" · ")||void 0}}function V8(e){return e==="openpond"?AP:e==="codex"||e==="openai"?EP:[]}function K8(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 yoe(e){return TP.has(e)}function Vg(e,t={}){if(!e)return t.localOnly,Ph;const n=t.includeUnavailable??!1,a=t.enabledOnly??!1,o=[];for(const r of Iv){if(!["openpond","codex","openai","claude-code","grok-build","opencode"].includes(r)||!TP.has(r)||t.localOnly&&r==="openpond")continue;const s=Iy(e,r);s&&(!n&&(r==="codex"&&!s.available&&!s.credential.connected||r!=="openpond"&&r!=="codex"&&!s.enabled)||a&&r!=="openpond"&&!s.enabled||a&&r==="codex"&&!s.available&&!s.credential.connected||o.push({value:r,label:r==="openpond"?"OpenPond Chat":s.displayName,description:r==="openpond"?void 0:s.available?"Connected":s.credential.connected?"Configured":s.routing.localByok?"Set up key":s.enabled?"Enabled":void 0}))}return o.length>0?o:Ph}function Uc(e,t){const a=(_y(t,e)?.models??[]).filter(l=>e!=="openpond"||l.id!==Ws).map(F8),o=jP(t,e),r=[...o?.modelOverrides??[],o?.defaultModel].filter(l=>!!l?.trim()&&(e!=="openpond"||l!==Ws)).map(l=>({value:l,label:PP(l)})),s=e==="openpond"&&a.length>0?[]:V8(e);return K8([...a,...r,...s])}function OP(e,t,n){if(e!=="openpond")return Fg;const a=_y(n,e)?.models.find(r=>r.id===t)?.capabilities;if(!a?.reasoningEfforts.length)return Fg;const o=new Set(a.reasoningEfforts);return U8.filter(r=>o.has(r.value))}function W8(e,t,n){const a=OP(e,t,n),o=e==="openpond"&&(t==="gpt-6-luna"||t==="gpt-6-sol"||t==="claude-opus-5-5")?"medium":"high";return a.some(r=>r.value===o)?o:a[0]?.value??"high"}function G8(e,t,n,a){return OP(e,t,a).some(o=>o.value===n)?n:W8(e,t,a)}function J8(e,t,n){if(e==="codex"||e==="openai")return!0;const a=t.trim();if(!a)return!1;const o=_y(n,e)?.models.find(r=>r.id===a);return o?!!o.capabilities.reasoning:Uc(e,n).some(r=>r.value===a&&/\breasoning\b/i.test(r.description??""))}function gm(e,t){const n=jP(t,e)?.defaultModel?.trim();if(n)return n;const a=Iy(t,e)?.defaultModel?.trim();if(a)return a;const o=Uc(e,t)[0]?.value?.trim();return o||(e==="codex"?$v:e==="openpond"?Ws:"")}function nr(e,t,n){const a=t?.trim();if(a&&["opencode","grok-build","claude-code"].includes(e))return a;if(e==="codex"&&(a==="codex-default"||a==="gpt-5.5"))return $v;const o=Uc(e,n);return a&&o.some(r=>r.value===a)||a&&e!=="codex"&&o.length===0&&!n?a:gm(e,n)}function $P(e,t){const n=e.modelRef?.providerId??e.provider;return{provider:n,model:nr(n,e.modelRef?.modelId,t)}}function Cy(e,t,n){return nr(e,t,n)||void 0}function ii(e,t,n){const a=Cy(e,t,n);return a?{providerId:e,modelId:a}:void 0}function wx(e){return e==="full-access"?{approvalPolicy:"never",sandbox:"danger-full-access"}:{approvalPolicy:"on-request",sandbox:"workspace-write"}}function La(e){const t=e?.defaultChatProvider??Dt.defaultChatProvider;return{defaultChatProvider:t,defaultChatModel:nr(t,e?.defaultChatModel),subagents:xc.parse(e?.subagents??Dt.subagents),codexPermissionMode:e?.codexPermissionMode??Dt.codexPermissionMode,codexReasoningEffort:e?.codexReasoningEffort??Dt.codexReasoningEffort,openPondCommandAccessMode:e?.openPondCommandAccessMode??Dt.openPondCommandAccessMode,defaultBranchPrefix:NP(e?.defaultBranchPrefix),defaultNewProjectDirectory:e?.defaultNewProjectDirectory??Dt.defaultNewProjectDirectory,defaultTeamId:e?.defaultTeamId?.trim()||null,advancedWorkspaceControls:e?.advancedWorkspaceControls??Dt.advancedWorkspaceControls,steerActiveResponses:e?.steerActiveResponses??Dt.steerActiveResponses,contextCompaction:{autoEnabled:e?.contextCompaction?.autoEnabled??Dt.contextCompaction.autoEnabled,triggerPercent:e?.contextCompaction?.triggerPercent??Dt.contextCompaction.triggerPercent,summaryModel:e?.contextCompaction?.summaryModel??Dt.contextCompaction.summaryModel},training:{defaultModelRef:e?.training?.defaultModelRef??Dt.training.defaultModelRef,creationMode:e?.training?.creationMode??Dt.training.creationMode,autoApproveEvidence:e?.training?.autoApproveEvidence??Dt.training.autoApproveEvidence},sidebarWidth:e?.sidebarWidth??Dt.sidebarWidth,diffPanelWidth:e?.diffPanelWidth??Dt.diffPanelWidth,sidebarSectionsCollapsed:{pinned:e?.sidebarSectionsCollapsed?.pinned??Dt.sidebarSectionsCollapsed.pinned,projects:e?.sidebarSectionsCollapsed?.projects??Dt.sidebarSectionsCollapsed.projects,cloudProjects:e?.sidebarSectionsCollapsed?.cloudProjects??Dt.sidebarSectionsCollapsed.cloudProjects,chats:e?.sidebarSectionsCollapsed?.chats??Dt.sidebarSectionsCollapsed.chats,savedForLater:e?.sidebarSectionsCollapsed?.savedForLater??Dt.sidebarSectionsCollapsed.savedForLater},editor:{languageServers:e?.editor?.languageServers??Dt.editor.languageServers,diagnosticsWhileEditing:e?.editor?.diagnosticsWhileEditing??Dt.editor.diagnosticsWhileEditing,checkOnSave:e?.editor?.checkOnSave??Dt.editor.checkOnSave,languages:{typescript:{mode:e?.editor?.languages?.typescript?.mode??Dt.editor.languages.typescript.mode,customCommand:e?.editor?.languages?.typescript?.customCommand??Dt.editor.languages.typescript.customCommand},python:{mode:e?.editor?.languages?.python?.mode??Dt.editor.languages.python.mode,customCommand:e?.editor?.languages?.python?.customCommand??Dt.editor.languages.python.customCommand},rust:{mode:e?.editor?.languages?.rust?.mode??Dt.editor.languages.rust.mode,customCommand:e?.editor?.languages?.rust?.customCommand??Dt.editor.languages.rust.customCommand}}}}}function NP(e){const t=e?.trim()??Dt.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 Soe(e,t){return e==="openpond"?"OpenPond Chat":Iy(t,e)?.displayName??(e==="codex"?"OpenAI Codex":e)}function xoe(e,t,n){if(n){const a=Uc(n,t).find(o=>o.value===e);if(a)return a.label}if(t)for(const a of Iv){const o=Uc(a,t).find(r=>r.value===e);if(o)return o.label}return[...AP,...EP].find(a=>a.value===e)?.label??e}function Z8(e,t){return t==="chat"?e.filter(n=>n.experience==="chat"):e.filter(n=>n.experience==="work"||n.experience==="development")}function Y8(e){return e.experience==="chat"?"Chat":"Work"}const Ry="taskDraft";function DP(e){if(e?.experience!=="work")return null;const t=e.metadata?.[Ry];if(!t||typeof t!="object"||Array.isArray(t))return null;const n=t.prompt;return typeof n=="string"&&n.trim()?n:null}function zc(e){return DP(e)!==null}function Q8(e){return(e.split(/\r?\n/u).map(n=>n.trim()).find(Boolean)||"Task draft").slice(0,64)}function Ah(e,t,n=new Date().toISOString()){const a={version:1,prompt:t,savedAt:n};return{...e??{},[Ry]:a}}function X8(e){const t={...e??{}};return delete t[Ry],t}function Ms(e){const t=su(e.metadata?.trainingTasksetId)??su(e.metadata?.tasksetId);return t?{id:t,name:su(e.metadata?.trainingTasksetName)??su(e.metadata?.tasksetName)??eG(t)}:null}function eG(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 su(e){return typeof e=="string"&&e.trim()?e.trim():null}const tG="codex_history_";function Jt(e){return!!e?.startsWith(tG)}function HP(e){const t=[],n=new Set;for(const a of e)for(const o of[a.workspacePath,a.path]){const r=hp(o);if(!r)continue;const s=`${a.id}:${r}`;n.has(s)||(n.add(s),t.push({projectId:a.id,path:r}))}return t.sort((a,o)=>o.path.length-a.path.length)}function nG(e,t,n,a=new Set){if(e.localProjectId&&t.has(e.localProjectId))return e.localProjectId;if(e.workspaceKind==="local_project"&&e.workspaceId&&t.has(e.workspaceId))return e.workspaceId;if(e.metadata?.workspaceTarget==="hybrid"&&e.cwd){const r=LP(e.cwd,n);if(r)return r}if(e.cloudProjectId&&a.has(e.cloudProjectId))return e.cloudProjectId;if(!e.cwd||e.workspaceKind==="sandbox"||e.workspaceKind==="sandbox_template"||e.workspaceKind==="sandbox_app"||!qP(e))return null;const o=hp(e.cwd);if(!o)return null;for(const r of n)if(Py(o,r.path))return r.projectId;return null}function Ix(e,t,n,a=new Set){if(e.localProjectId&&t.has(e.localProjectId))return kt("local",e.localProjectId);if(e.workspaceKind==="local_project"&&e.workspaceId&&t.has(e.workspaceId))return kt("local",e.workspaceId);if(e.metadata?.workspaceTarget==="hybrid"&&e.cwd){const r=LP(e.cwd,n);if(r)return kt("local",r)}if(e.cloudProjectId&&a.has(e.cloudProjectId))return kt("cloud",e.cloudProjectId);if(!e.cwd||e.workspaceKind==="sandbox"||e.workspaceKind==="sandbox_template"||e.workspaceKind==="sandbox_app"||!qP(e))return null;const o=hp(e.cwd);if(!o)return null;for(const r of n)if(Py(o,r.path))return kt("local",r.projectId);return null}function LP(e,t){const n=hp(e);if(!n)return null;for(const a of t)if(Py(n,a.path))return a.projectId;return null}function qP(e){return e.workspaceKind==="local_project"||e.provider==="codex"||Jt(e.id)}function hp(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 Py(e,t){const n=_x(e),a=_x(t);return n===a||n.startsWith(`${a}/`)}function _x(e){return/^[A-Z]:\//.test(e)?e.toLowerCase():e}const Cx=[{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"}],aG=[{value:"recent",label:"Recent first"},{value:"manual",label:"Manual order"}];function Th(e){const t=[];if(e.filter==="done")t.push(...e.doneSessions.filter(o=>!Ms(o)));else if(e.filter==="all")t.push(...e.activeSessions.filter(o=>!Ms(o)),...e.doneSessions.filter(o=>!Ms(o)));else if(e.filter==="tasksets")t.push(...e.activeSessions.filter(o=>Rx(o,e.selectedTasksetId)),...e.doneSessions.filter(o=>Rx(o,e.selectedTasksetId)));else for(const o of e.activeSessions)Ms(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=>$u(o,{inProgressSessionIds:e.inProgressSessionIds,onlyRunningTasks:e.onlyRunningTasks,showCodexChats:e.showCodexChats})),a=e.previewSessionIds?new Map(e.previewSessionIds.map((o,r)=>[o,r])):null;return e.sort==="recent"?n.sort((o,r)=>Tx(o,r,a)):n.sort((o,r)=>{const s=a?.get(o.id),l=a?.get(r.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!==r.order?o.order-r.order:Tx(o,r)})}function $u(e,t){return t.showCodexChats===!1&&(e.provider==="codex"||Jt(e.id))?!1:!t.onlyRunningTasks||t.inProgressSessionIds.has(e.id)}function Rx(e,t){const n=Ms(e);return!!(n&&(!t||n.id===t))}function Px(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 Ax(e,t,n){const a=new Set(t);let o=0;return e.map(r=>{if(!a.has(r))return r;const s=n[o];return o+=1,s??r})}function Tx(e,t,n=null){const a=vc(e),o=vc(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 r=Date.parse(t.updatedAt)-Date.parse(e.updatedAt);return r!==0?r:e.title.localeCompare(t.title)}function vc(e){return e.pinned&&!e.savedForLater&&!e.archived}const lu={showCodexChats:!0,onlyRunningTasks:!1},UP="openpond.sidebar-task-visibility.v1";function Ex(e=zP()){try{const t=e?.getItem(UP);if(!t)return lu;const n=JSON.parse(t);return{showCodexChats:typeof n.showCodexChats=="boolean"?n.showCodexChats:lu.showCodexChats,onlyRunningTasks:typeof n.onlyRunningTasks=="boolean"?n.onlyRunningTasks:lu.onlyRunningTasks}}catch{return lu}}function Mx(e,t=zP()){try{t?.setItem(UP,JSON.stringify(e))}catch{}}function zP(){return typeof window>"u"?null:Vo}function BP(e){return`${e.kind}:${e.id}`}function Bc(e,t){return!!(e&&t&&e.kind===t.kind&&e.id===t.id)}function iG(e){return{kind:"session",id:e}}function oG(e){return{kind:"project",id:e}}function rG(e){return{kind:"draft",id:e}}function sG(e){return e.selectedSessionId?iG(e.selectedSessionId):e.selectedProjectId?oG(e.selectedProjectId):rG(e.selectedAppId?`app:${e.selectedAppId}`:"new-chat")}function lG(e){if(!e.previousScope||e.previousScope.kind!=="draft"||e.activeScope.kind!=="session")return[...e.tabs];if(Bc(e.previousScope,e.activeScope))return[...e.tabs];const t=e.now??Date.now();return e.tabs.map(n=>Bc(n.scope,e.previousScope)?{...n,scope:e.activeScope,updatedAt:t}:n)}function koe(e,t){return e.filter(n=>Bc(n.scope,t))}function woe(e,t){return!!(e&&Bc(e.scope,t))}function cG(e){const t={};for(const n of e){const a=BP(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=uG(o.status,n.status,n.commandStatus),t[a]=o}return t}function dG(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 uG(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 FP(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=pG(e),r=t?.linkedCloudSourceKnown===!1&&!!e.headCommit;return o?a.push(o):r?a.push("upload required"):e.diverged?(e.ahead>0&&a.push(Bo("ahead",e.ahead)),e.behind>0&&a.push(Bo("behind",e.behind)),a.push("diverged")):(e.ahead>0&&a.push(Bo("ahead",e.ahead)),e.behind>0&&a.push(Bo("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 VP(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 r=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),f=!!(o?.projectId&&n?.headCommit&&!o.lastUploadedCommit),g=fG(n);return g?`${r} / ${g}`:f?`${r} / upload required`:`${r} / ${d||!m?"needs sync":"setup ready"}`}function mG(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(KP(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 pG(e){return e.linkedSourceHeadCommit?e.divergedFromLinkedSource?"diverged":e.aheadOfLinkedSource>0?Bo("local ahead",e.aheadOfLinkedSource):e.behindLinkedSource>0?Bo("cloud ahead",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"sync unknown":null:null}function fG(e){return e?.linkedSourceHeadCommit?e.dirty?"local dirty files not in cloud":e.divergedFromLinkedSource?"diverged from local":e.aheadOfLinkedSource>0?Bo("cloud behind local",e.aheadOfLinkedSource):e.behindLinkedSource>0?Bo("cloud ahead local",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"source check unavailable":"synced":null}function Bo(e,t){return`${e} by ${KP(t)}`}function KP(e){return`${e} commit${e===1?"":"s"}`}function hG({size:e=14,className:t}){return S.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:[S.jsx("path",{d:"M12 13v8"}),S.jsx("path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242"}),S.jsx("path",{d:"m8 17 4-4 4 4"})]})}function WP({kind:e,linkedCloud:t=!1,open:n=!1,className:a,baseSize:o=15}){const r=e==="cloud"?"cloud":n?"folder-open":"folder";return S.jsx("span",{className:["project-kind-icon",e,t?"linked-cloud":"",a??""].filter(Boolean).join(" "),"aria-hidden":"true",children:S.jsxs("svg",{className:`lucide lucide-${r} 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"?S.jsx(bG,{}):n?S.jsx(vG,{}):S.jsx(gG,{}),t&&e==="local"?S.jsx(yG,{}):null]})})}function gG(){return S.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 vG(){return S.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 bG(){return S.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 yG(){return S.jsxs("g",{className:"project-kind-icon-cloud-badge",children:[S.jsx("circle",{cx:"18",cy:"17",r:"5"}),S.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 vm=qT();function SG({title:e,pinned:t,savedForLater:n,archived:a,onRename:o,onTogglePin:r,onToggleSaveForLater:s,onDockRight:l,onArchive:m}){const d=y.useRef(null),f=y.useRef(null),[g,x]=y.useState(null),k=[...o?[{label:"Rename",Icon:pp,action:o}]:[],{label:t?"Unpin":"Pin",Icon:t?dy:cy,action:r},...s?[{label:n?"Return to active":"Save for later",Icon:n?uP:dP,action:s}]:[],...l?[{label:"Open in right panel",Icon:Og,action:l}]:[],{label:a?"Reopen":"Mark done",Icon:a?cW:Ai,action:m}];function C(R=!1){x(null),R&&d.current?.focus()}return y.useEffect(()=>{if(!g)return;f.current?.querySelector("button")?.focus();const R=A=>{!f.current?.contains(A.target)&&!d.current?.contains(A.target)&&x(null)},E=()=>x(null);return document.addEventListener("pointerdown",R),window.addEventListener("resize",E),()=>{document.removeEventListener("pointerdown",R),window.removeEventListener("resize",E)}},[g]),S.jsxs(S.Fragment,{children:[S.jsx("div",{className:`sidebar-row-actions sidebar-task-menu-trigger${g?" is-open":""}`,children:S.jsx("button",{ref:d,type:"button",className:"sidebar-row-action","aria-label":`More actions for task ${e}`,"aria-haspopup":"menu","aria-expanded":!!g,draggable:!1,onDoubleClick:R=>R.stopPropagation(),onClick:R=>{if(R.stopPropagation(),g){C(!0);return}const E=R.currentTarget.getBoundingClientRect();x({left:Math.max(8,Math.min(E.right-192,window.innerWidth-200)),top:Math.max(8,Math.min(E.bottom+4,window.innerHeight-(k.length*32+17)))})},children:S.jsx(yd,{size:16})})}),g&&vm.createPortal(S.jsx("div",{ref:f,role:"menu","aria-label":`Actions for ${e}`,className:"sidebar-task-menu",style:g,onClick:R=>R.stopPropagation(),onDoubleClick:R=>R.stopPropagation(),onBlur:R=>{R.currentTarget.contains(R.relatedTarget)||C()},onKeyDown:R=>{R.stopPropagation();const E=Array.from(R.currentTarget.querySelectorAll("button")),A=E.indexOf(document.activeElement);if(R.key==="Escape"&&(R.preventDefault(),C(!0)),["ArrowDown","ArrowUp","Home","End"].includes(R.key)){R.preventDefault();const O=R.key==="Home"?0:R.key==="End"?E.length-1:(A+(R.key==="ArrowDown"?1:-1)+E.length)%E.length;E[O]?.focus()}},children:k.map(({label:R,Icon:E,action:A},O)=>S.jsxs("button",{type:"button",role:"menuitem",className:O===k.length-1?"task-menu-done":void 0,onClick:()=>{C(!0),A()},children:[S.jsx(E,{size:15}),R]},R))}),document.body)]})}function xG({session:e,onSave:t,onClose:n}){const[a,o]=y.useState(e.title),r=y.useRef(null);y.useEffect(()=>{const m=r.current;m&&(m.focus(),m.select())},[]),y.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 S.jsx("div",{className:"git-dialog-backdrop rename-chat-backdrop",role:"presentation",onMouseDown:n,children:S.jsxs("section",{className:"git-dialog rename-chat-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"rename-chat-title",onMouseDown:m=>m.stopPropagation(),children:[S.jsx("h2",{id:"rename-chat-title",children:"Rename chat"}),S.jsx("textarea",{ref:r,className:"rename-chat-input",value:a,rows:1,maxLength:200,onChange:m=>o(m.target.value),onKeyDown:l,"aria-label":"Chat title"}),S.jsxs("div",{className:"git-dialog-footer",children:[S.jsx("button",{type:"button",className:"git-dialog-secondary",onClick:n,children:"Cancel"}),S.jsx("button",{type:"button",className:"git-dialog-primary",autoFocus:!0,onClick:s,disabled:!a.trim(),children:"Save"})]})]})})}const kG=24;function wG({title:e}){const t=y.useRef(e),[n,a]=y.useState(e);return y.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 r=Array.from(e);let s=0;a("");const l=window.setInterval(()=>{s+=1,a(r.slice(0,s).join("")),s>=r.length&&window.clearInterval(l)},kG);return()=>window.clearInterval(l)},[e]),S.jsx("span",{className:"sidebar-task-title-text","aria-label":e||"New task",children:n||"New task"})}const IG="/";function ya(e){return`${IG}${e.replace(/^\.?\//,"")}`}const Ay=ya("openpond-icon.png"),_G=ya("openpond-wordlogo-white.png"),Ioe=ya("tutorials/what-is-an-openpond-agent-poster.png"),_oe=ya("tutorials/what-is-an-openpond-agent.vtt"),Coe=ya("tutorials/how-to-make-an-agent-poster.png"),Roe=ya("tutorials/how-to-make-an-agent.vtt");function Poe(e){return ya(`tutorials/how-to-make-an-agent-${e}-poster.png`)}function Aoe(e){return ya(`tutorials/how-to-make-an-agent-${e}.vtt`)}const jx={github:ya("connected-apps/github.svg"),google:ya("connected-apps/google.svg"),microsoft_teams:ya("connected-apps/microsoft.svg"),mcp:ya("connected-apps/openpond-mcp.svg"),slack:ya("connected-apps/slack.svg"),x:ya("connected-apps/x.svg")};function Toe(e){return jx[e]??jx.mcp}const CG={codex:"Codex","claude-code":"Claude Code",opencode:"OpenCode","grok-build":"Grok Build"};function RG({session:e}){const t=CG[e.provider],n=t??(e.provider==="openpond"?"OpenPond":e.provider);return S.jsx("span",{className:"conversation-source-icon",role:"img","aria-label":n,title:n,children:t?S.jsx("img",{src:`/agent-sources/${e.provider}.svg`,alt:""}):e.provider==="openpond"?S.jsx("img",{src:Ay,alt:""}):e.metadata?.nativeSource?S.jsx(S8,{size:15,"aria-hidden":"true"}):e.provider==="openai"?S.jsx(gW,{size:15,"aria-hidden":"true"}):S.jsx(mp,{size:15,"aria-hidden":"true"})})}var Nu={exports:{}},PG=Nu.exports,Ox;function AG(){return Ox||(Ox=1,(function(e,t){(function(n,a){e.exports=a()})(PG,(function(){var n=1e3,a=6e4,o=36e5,r="millisecond",s="second",l="minute",m="hour",d="day",f="week",g="month",x="quarter",k="year",C="date",R="Invalid Date",E=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,A=/\[([^\]]+)]|YYYY|YY|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,O={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(re){var K=["th","st","nd","rd"],L=re%100;return"["+re+(K[(L-20)%10]||K[L]||K[0])+"]"}},$=function(re,K,L){var de=String(re);return!de||de.length>=K?re:""+Array(K+1-de.length).join(L)+re},M={s:$,z:function(re){var K=-re.utcOffset(),L=Math.abs(K),de=Math.floor(L/60),X=L%60;return(K<=0?"+":"-")+$(de,2,"0")+":"+$(X,2,"0")},m:function re(K,L){if(K.date()<L.date())return-re(L,K);var de=12*(L.year()-K.year())+(L.month()-K.month()),X=K.clone().add(de,g),Z=L-X<0,pe=K.clone().add(de+(Z?-1:1),g);return+(-(de+(L-X)/(Z?X-pe:pe-X))||0)},a:function(re){return re<0?Math.ceil(re)||0:Math.floor(re)},p:function(re){return{M:g,y:k,w:f,d,D:C,h:m,m:l,s,ms:r,Q:x}[re]||String(re||"").toLowerCase().replace(/s$/,"")},u:function(re){return re===void 0}},w="en",P={};P[w]=O;var j="$isDayjsObject",N=function(re){return re instanceof te||!(!re||!re[j])},z=function re(K,L,de){var X;if(!K)return w;if(typeof K=="string"){var Z=K.toLowerCase();P[Z]&&(X=Z),L&&(P[Z]=L,X=Z);var pe=K.split("-");if(!X&&pe.length>1)return re(pe[0])}else{var ee=K.name;P[ee]=K,X=ee}return!de&&X&&(w=X),X||!de&&w},D=function(re,K){if(N(re))return re.clone();var L=typeof K=="object"?K:{};return L.date=re,L.args=arguments,new te(L)},F=M;F.l=z,F.i=N,F.w=function(re,K){return D(re,{locale:K.$L,utc:K.$u,x:K.$x,$offset:K.$offset})};var te=(function(){function re(L){this.$L=z(L.locale,null,!0),this.parse(L),this.$x=this.$x||L.x||{},this[j]=!0}var K=re.prototype;return K.parse=function(L){this.$d=(function(de){var X=de.date,Z=de.utc;if(X===null)return new Date(NaN);if(F.u(X))return new Date;if(X instanceof Date)return new Date(X);if(typeof X=="string"&&!/Z$/i.test(X)){var pe=X.match(E);if(pe){var ee=pe[2]-1||0,me=(pe[7]||"0").substring(0,3);return Z?new Date(Date.UTC(pe[1],ee,pe[3]||1,pe[4]||0,pe[5]||0,pe[6]||0,me)):new Date(pe[1],ee,pe[3]||1,pe[4]||0,pe[5]||0,pe[6]||0,me)}}return new Date(X)})(L),this.init()},K.init=function(){var L=this.$d;this.$y=L.getFullYear(),this.$M=L.getMonth(),this.$D=L.getDate(),this.$W=L.getDay(),this.$H=L.getHours(),this.$m=L.getMinutes(),this.$s=L.getSeconds(),this.$ms=L.getMilliseconds()},K.$utils=function(){return F},K.isValid=function(){return this.$d.toString()!==R},K.isSame=function(L,de){var X=D(L);return this.startOf(de)<=X&&X<=this.endOf(de)},K.isAfter=function(L,de){return D(L)<this.startOf(de)},K.isBefore=function(L,de){return this.endOf(de)<D(L)},K.$g=function(L,de,X){return F.u(L)?this[de]:this.set(X,L)},K.unix=function(){return Math.floor(this.valueOf()/1e3)},K.valueOf=function(){return this.$d.getTime()},K.startOf=function(L,de){var X=this,Z=!!F.u(de)||de,pe=F.p(L),ee=function(Fe,Xe){var Ze=F.w(X.$u?Date.UTC(X.$y,Xe,Fe):new Date(X.$y,Xe,Fe),X);return Z?Ze:Ze.endOf(d)},me=function(Fe,Xe){return F.w(X.toDate()[Fe].apply(X.toDate("s"),(Z?[0,0,0,0]:[23,59,59,999]).slice(Xe)),X)},be=this.$W,je=this.$M,ke=this.$D,ue="set"+(this.$u?"UTC":"");switch(pe){case k:return Z?ee(1,0):ee(31,11);case g:return Z?ee(1,je):ee(0,je+1);case f:var Ie=this.$locale().weekStart||0,Le=(be<Ie?be+7:be)-Ie;return ee(Z?ke-Le:ke+(6-Le),je);case d:case C:return me(ue+"Hours",0);case m:return me(ue+"Minutes",1);case l:return me(ue+"Seconds",2);case s:return me(ue+"Milliseconds",3);default:return this.clone()}},K.endOf=function(L){return this.startOf(L,!1)},K.$set=function(L,de){var X,Z=F.p(L),pe="set"+(this.$u?"UTC":""),ee=(X={},X[d]=pe+"Date",X[C]=pe+"Date",X[g]=pe+"Month",X[k]=pe+"FullYear",X[m]=pe+"Hours",X[l]=pe+"Minutes",X[s]=pe+"Seconds",X[r]=pe+"Milliseconds",X)[Z],me=Z===d?this.$D+(de-this.$W):de;if(Z===g||Z===k){var be=this.clone().set(C,1);be.$d[ee](me),be.init(),this.$d=be.set(C,Math.min(this.$D,be.daysInMonth())).$d}else ee&&this.$d[ee](me);return this.init(),this},K.set=function(L,de){return this.clone().$set(L,de)},K.get=function(L){return this[F.p(L)]()},K.add=function(L,de){var X,Z=this;L=Number(L);var pe=F.p(de),ee=function(je){var ke=D(Z);return F.w(ke.date(ke.date()+Math.round(je*L)),Z)};if(pe===g)return this.set(g,this.$M+L);if(pe===k)return this.set(k,this.$y+L);if(pe===d)return ee(1);if(pe===f)return ee(7);var me=(X={},X[l]=a,X[m]=o,X[s]=n,X)[pe]||1,be=this.$d.getTime()+L*me;return F.w(be,this)},K.subtract=function(L,de){return this.add(-1*L,de)},K.format=function(L){var de=this,X=this.$locale();if(!this.isValid())return X.invalidDate||R;var Z=L||"YYYY-MM-DDTHH:mm:ssZ",pe=F.z(this),ee=this.$H,me=this.$m,be=this.$M,je=X.weekdays,ke=X.months,ue=X.meridiem,Ie=function(Xe,Ze,Be,Ge){return Xe&&(Xe[Ze]||Xe(de,Z))||Be[Ze].slice(0,Ge)},Le=function(Xe){return F.s(ee%12||12,Xe,"0")},Fe=ue||function(Xe,Ze,Be){var Ge=Xe<12?"AM":"PM";return Be?Ge.toLowerCase():Ge};return Z.replace(A,(function(Xe,Ze){return Ze||(function(Be){switch(Be){case"YY":return String(de.$y).slice(-2);case"YYYY":return F.s(de.$y,4,"0");case"M":return be+1;case"MM":return F.s(be+1,2,"0");case"MMM":return Ie(X.monthsShort,be,ke,3);case"MMMM":return Ie(ke,be);case"D":return de.$D;case"DD":return F.s(de.$D,2,"0");case"d":return String(de.$W);case"dd":return Ie(X.weekdaysMin,de.$W,je,2);case"ddd":return Ie(X.weekdaysShort,de.$W,je,3);case"dddd":return je[de.$W];case"H":return String(ee);case"HH":return F.s(ee,2,"0");case"h":return Le(1);case"hh":return Le(2);case"a":return Fe(ee,me,!0);case"A":return Fe(ee,me,!1);case"m":return String(me);case"mm":return F.s(me,2,"0");case"s":return String(de.$s);case"ss":return F.s(de.$s,2,"0");case"SSS":return F.s(de.$ms,3,"0");case"Z":return pe}return null})(Xe)||pe.replace(":","")}))},K.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},K.diff=function(L,de,X){var Z,pe=this,ee=F.p(de),me=D(L),be=(me.utcOffset()-this.utcOffset())*a,je=this-me,ke=function(){return F.m(pe,me)};switch(ee){case k:Z=ke()/12;break;case g:Z=ke();break;case x:Z=ke()/3;break;case f:Z=(je-be)/6048e5;break;case d:Z=(je-be)/864e5;break;case m:Z=je/o;break;case l:Z=je/a;break;case s:Z=je/n;break;default:Z=je}return X?Z:F.a(Z)},K.daysInMonth=function(){return this.endOf(g).$D},K.$locale=function(){return P[this.$L]},K.locale=function(L,de){if(!L)return this.$L;var X=this.clone(),Z=z(L,de,!0);return Z&&(X.$L=Z),X},K.clone=function(){return F.w(this.$d,this)},K.toDate=function(){return new Date(this.valueOf())},K.toJSON=function(){return this.isValid()?this.toISOString():null},K.toISOString=function(){return this.$d.toISOString()},K.toString=function(){return this.$d.toUTCString()},re})(),ve=te.prototype;return D.prototype=ve,[["$ms",r],["$s",s],["$m",l],["$H",m],["$W",d],["$M",g],["$y",k],["$D",C]].forEach((function(re){ve[re[1]]=function(K){return this.$g(K,re[0],re[1])}})),D.extend=function(re,K){return re.$i||(re(K,te,D),re.$i=!0),D},D.locale=z,D.isDayjs=N,D.unix=function(re){return D(1e3*re)},D.en=P[w],D.Ls=P,D.p={},D}))})(Nu)),Nu.exports}var TG=AG();const GP=o1(TG);var Du={exports:{}},EG=Du.exports,$x;function MG(){return $x||($x=1,(function(e,t){(function(n,a){e.exports=a()})(EG,(function(){return function(n,a,o){n=n||{};var r=a.prototype,s={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"};function l(d,f,g,x){return r.fromToBase(d,f,g,x)}o.en.relativeTime=s,r.fromToBase=function(d,f,g,x,k){for(var C,R,E,A=g.$locale().relativeTime||s,O=n.thresholds||[{l:"s",r:44,d:"second"},{l:"m",r:89},{l:"mm",r:44,d:"minute"},{l:"h",r:89},{l:"hh",r:21,d:"hour"},{l:"d",r:35},{l:"dd",r:25,d:"day"},{l:"M",r:45},{l:"MM",r:10,d:"month"},{l:"y",r:17},{l:"yy",d:"year"}],$=O.length,M=0;M<$;M+=1){var w=O[M];w.d&&(C=x?o(d).diff(g,w.d,!0):g.diff(d,w.d,!0));var P=(n.rounding||Math.round)(Math.abs(C));if(E=C>0,P<=w.r||!w.r){P<=1&&M>0&&(w=O[M-1]);var j=A[w.l];k&&(P=k(""+P)),R=typeof j=="string"?j.replace("%d",P):j(P,f,w.l,E);break}}if(f)return R;var N=E?A.future:A.past;return typeof N=="function"?N(R):N.replace("%s",R)},r.to=function(d,f){return l(d,f,this,!0)},r.from=function(d,f){return l(d,f,this)};var m=function(d){return d.$u?o.utc():o()};r.toNow=function(d){return this.to(m(this),d)},r.fromNow=function(d){return this.from(m(this),d)}}}))})(Du)),Du.exports}var jG=MG();const OG=o1(jG);GP.extend(OG);let Kg=Date.now(),cu;const du=new Set,Nx=()=>Kg;function $G(e){return du.add(e),cu||(Kg=Date.now(),cu=setInterval(()=>{Kg=Date.now();for(const t of du)t()},3e4)),()=>{du.delete(e),du.size===0&&(clearInterval(cu),cu=void 0)}}function JP({value:e,className:t}){const n=y.useSyncExternalStore($G,Nx,Nx),a=e==null?null:GP(e);return a?.isValid()?S.jsx("time",{className:t,dateTime:a.toISOString(),title:`Last activity ${a.format("MMM D, YYYY h:mm A")}`,children:a.from(n)}):null}const NG=2650,DG=304,HG=260;function LG(){return{animationDelay:`${-(Date.now()%NG)}ms`}}function qG(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 Eh({label:e,actions:t,actionsVisible:n=!1,className:a,titleAccessory:o,children:r,collapsed:s=!1,titleActive:l=!1,onTitleClick:m,onToggleCollapsed:d}){return S.jsxs("section",{className:["sidebar-section",a,n?"actions-visible":""].filter(Boolean).join(" "),children:[S.jsxs("div",{className:"section-header",children:[S.jsxs("div",{className:"section-title-row",children:[m?S.jsxs("div",{className:"section-title-combo",children:[S.jsx("button",{type:"button",className:`section-title-link${l?" active":""}`,onClick:m,children:S.jsx("span",{children:e})}),d&&S.jsx("button",{type:"button",className:"section-chevron-button","aria-label":`${s?"Expand":"Collapse"} ${e}`,"aria-expanded":!s,onClick:d,children:s?S.jsx(Jo,{size:13}):S.jsx(Go,{size:13})})]}):d?S.jsxs("button",{type:"button",className:"section-title-button","aria-label":`${s?"Expand":"Collapse"} ${e}`,"aria-expanded":!s,onClick:d,children:[S.jsx("span",{children:e}),s?S.jsx(Jo,{size:13}):S.jsx(Go,{size:13})]}):S.jsx("span",{children:e}),o]}),t&&S.jsx("div",{className:"section-actions",children:t})]}),!s&&S.jsx("div",{className:"sidebar-section-body",children:r})]})}function Dx({children:e,expanded:t=!1,onClick:n}){return S.jsx("button",{type:"button",className:"sidebar-show-more",onClick:n,children:e??(t?"Show less":"Show more")})}function Mh({session:e,selected:t,icon:n,archived:a=!1,nested:o=!1,dragging:r,placeholder:s,running:l,goalRuntime:m,subagentRuntime:d,terminalIndicator:f,projectLabel:g,inbox:x=!1,activityAt:k,ariaDescribedBy:C,childSessionCount:R=0,childSessionsExpanded:E=!1,onSelect:A,onToggleChildSessions:O,onTogglePin:$,onToggleSaveForLater:M,onDockRight:w,onArchive:P,onDragStart:j,onDragEnd:N,onDragOver:z,onDrop:D,onRename:F}){const[te,ve]=y.useState(!1),re=m?.status==="queued",K=m?.tone==="active"&&!re,L=(d?.activeCount??0)>0,de=R>0&&!!O,X=L||K||!re&&(l??e.status==="active"),Z=L&&d?d.label:K&&m?zG(m):"Running",pe=["sidebar-task-row",zc(e)?"is-draft":"",X?"has-running-dot":"",x?"sidebar-inbox-row":""].filter(Boolean).join(" "),ee=y.useMemo(LG,[]),me=S.jsx(SG,{title:e.title,pinned:!!e.pinned,savedForLater:!!e.savedForLater,archived:a,onRename:F?()=>ve(!0):void 0,onTogglePin:$,onToggleSaveForLater:M,onDockRight:w,onArchive:P}),be=S.jsxs(Ty,{selected:t,dataSessionId:e.id,dragging:r,nested:o,placeholder:s,className:pe||void 0,ariaExpanded:de?E:void 0,ariaDescribedBy:C,onSelect:A,onDragStart:j,onDragEnd:N,onDragOver:z,onDrop:D,onDoubleClick:F?()=>ve(!0):void 0,children:[S.jsx("span",{className:"sidebar-source-slot",children:n??S.jsx(RG,{session:e})}),S.jsxs("span",{className:"sidebar-title-slot",children:[de?S.jsx("button",{type:"button",className:"sidebar-child-toggle","data-tooltip":E?"Hide subagent conversations":"Show subagent conversations","aria-label":`${E?"Hide":"Show"} ${R} subagent ${R===1?"conversation":"conversations"}`,"aria-expanded":E,onClick:ke=>{ke.stopPropagation(),O?.()},children:E?S.jsx(Go,{size:13}):S.jsx(Jo,{size:13})}):null,S.jsxs("span",{className:"row-label-shell",title:e.title,children:[S.jsx("span",{className:"sidebar-session-title-line",children:S.jsx("span",{className:"row-label sidebar-task-title","data-overflowing":"false",onPointerEnter:qG,children:S.jsx(wG,{title:e.title})})}),x?S.jsxs("span",{className:"sidebar-inbox-project",children:[g?S.jsxs(S.Fragment,{children:[S.jsx("span",{className:"sidebar-inbox-project-name",children:g}),S.jsx("span",{"aria-hidden":"true",children:"|"})]}):null,S.jsx(JP,{value:k??e.createdAt})]}):null]})]}),S.jsxs("div",{className:"row-meta",children:[S.jsxs("span",{className:"row-meta-status",children:[f?S.jsx(ZP,{indicator:f}):null,X?S.jsx("span",{className:`sidebar-running-dot${L?" subagent":K?" goal":""}`,style:ee,"aria-label":Z}):null]}),me,x?S.jsx("button",{type:"button",className:"sidebar-inbox-done","aria-label":`${a?"Reopen":"Mark done"}: ${e.title}`,title:a?"Reopen":"Mark done (does not stop running work)",onClick:ke=>{ke.stopPropagation(),P()},children:a?S.jsx(r8,{size:19}):S.jsx(Ai,{size:21})}):null]})]}),je=te&&F?S.jsx(xG,{session:e,onSave:ke=>F(e,ke),onClose:()=>ve(!1)}):null;return S.jsxs(S.Fragment,{children:[be,je]})}function UG({file:e,selected:t=!1,placeholder:n,onSelect:a,onTogglePin:o,onToggleSaveForLater:r,onDragStart:s,onDragEnd:l,onDragOver:m,onDrop:d}){const f=e.path.split("/").at(-1)??e.path,g=`${e.workspaceName} · ${e.path}`;return S.jsxs(Ty,{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?S.jsx(ry,{size:15}):S.jsx(mm,{size:15}),S.jsx("span",{className:"row-label-shell",title:g,children:S.jsx("span",{className:"row-label",children:f})}),S.jsx("div",{className:"row-meta",children:S.jsxs("div",{className:"sidebar-row-actions",children:[S.jsx(bm,{label:e.status==="pinned"?"Unpin file":"Pin file",onClick:o,children:e.status==="pinned"?S.jsx(dy,{size:13}):S.jsx(cy,{size:13})}),S.jsx(bm,{label:e.status==="saved_for_later"?"Remove from Save for later":"Save file for later",onClick:r,children:e.status==="saved_for_later"?S.jsx(uP,{size:13}):S.jsx(dP,{size:13})})]})})]})}function zG(e){return e.actionLabel}function BG({kind:e="local",project:t,pinned:n=!1,selected:a,expanded:o=!1,disclosure:r=!0,workspaceState:s,cloudLinkTrusted:l=!0,cloudLinkWarning:m=null,placeholder:d,terminalIndicator:f,onSelect:g,onNewChat:x,onMoveToCloud:k,onWorkspaceTargetSelect:C,onTogglePin:R,onRemove:E,onDragStart:A,onDragEnd:O,onDragOver:$,onDrop:M}){const[w,P]=y.useState(!1),j=y.useRef(null),[N,z]=y.useState({}),D=!!k||!!E,F=e==="local"&&l!==!1&&!!t.linkedSandboxProject?.projectId,te=y.useCallback(()=>{if(typeof window>"u")return;const K=j.current?.getBoundingClientRect();if(!K)return;const L=Math.max(12,window.innerWidth-DG-12),de=Math.max(12,window.innerHeight-HG),X=Math.max(12,Math.min(K.right+10,L)),Z=Math.max(12,Math.min(K.top-4,de)),pe={"--sidebar-project-locations-left":`${Math.round(X)}px`,"--sidebar-project-locations-top":`${Math.round(Z)}px`};z(ee=>ee["--sidebar-project-locations-left"]===pe["--sidebar-project-locations-left"]&&ee["--sidebar-project-locations-top"]===pe["--sidebar-project-locations-top"]?ee:pe)},[]),ve=y.useCallback(()=>{te(),g()},[g,te]);function re(){P(!1)}return S.jsxs("div",{ref:j,className:["sidebar-project-row-shell",w?"project-menu-open":""].filter(Boolean).join(" "),onFocusCapture:te,onPointerEnter:te,children:[S.jsxs(Ty,{selected:a,placeholder:d,className:["sidebar-project-row",w?"project-menu-open":""].filter(Boolean).join(" "),ariaExpanded:r?o:void 0,onSelect:ve,onDragStart:A,onDragEnd:O,onDragOver:$,onDrop:M,children:[S.jsx(WP,{kind:e,linkedCloud:F,open:e==="local"&&o,className:"sidebar-row-icon",baseSize:15}),S.jsx("span",{className:"row-label-shell",children:S.jsxs("span",{className:"sidebar-project-title-line",children:[S.jsx("span",{className:"row-label",children:t.name}),S.jsxs("span",{className:"sidebar-row-updated-at",children:[S.jsx("span",{"aria-hidden":"true",children:"| "}),S.jsx(JP,{value:t.updatedAt})]}),r?S.jsx("span",{className:"sidebar-project-caret","aria-hidden":"true",children:o?S.jsx(Go,{size:13}):S.jsx(Jo,{size:13})}):null]})}),S.jsxs("div",{className:"row-meta",children:[S.jsx("span",{className:"row-meta-status",children:f?S.jsx(ZP,{indicator:f}):null}),S.jsxs("div",{className:"sidebar-row-actions",children:[S.jsx(bm,{label:n?"Unpin project":"Pin project",onClick:R,children:n?S.jsx(dy,{size:13}):S.jsx(cy,{size:13})}),D&&S.jsx(n7,{open:w,onToggleOpen:()=>P(K=>!K)}),S.jsx(bm,{label:"New task",onClick:x,children:S.jsx(pp,{size:13})})]})]})]}),S.jsx(FG,{kind:e,project:t,workspaceState:s,cloudLinkTrusted:l,cloudLinkWarning:m,onWorkspaceTargetSelect:C,style:N}),w&&S.jsx(a7,{onClose:re,onMoveToCloud:k?()=>{re(),k()}:void 0,onRemove:()=>{re(),E()}})]})}function ZP({indicator:e}){return S.jsx("span",{className:`sidebar-terminal-indicator ${e.status}`,"data-tooltip":e.label,"aria-label":e.label,title:e.label,children:S.jsx(yP,{size:13})})}function FG({kind:e,project:t,workspaceState:n,cloudLinkTrusted:a,cloudLinkWarning:o,onWorkspaceTargetSelect:r,style:s}){const l=WG(e,t,n,a,o);return S.jsxs("aside",{className:"sidebar-project-locations-popover","aria-label":`${t.name} status`,style:s,children:[S.jsx("div",{className:"sidebar-project-locations-title",children:t.name}),S.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(" "),f=S.jsxs(S.Fragment,{children:[S.jsx("span",{className:["sidebar-project-location-icon",m.key].filter(Boolean).join(" "),"aria-hidden":"true",children:m.icon}),S.jsx("span",{className:"sidebar-project-location-copy",children:S.jsx(VG,{value:m.value})})]});return m.actionTarget?S.jsx("button",{type:"button",className:d,"data-workspace-target":m.actionTarget,disabled:m.disabled||!r,title:m.disabledReason??void 0,onClick:g=>{g.stopPropagation(),!m.disabled&&r?.(m.actionTarget)},children:f},m.key):S.jsx("div",{className:d,children:f},m.key)})})]})}function VG({value:e}){const t=KG(e);return S.jsxs("span",{className:"sidebar-project-location-value","aria-label":e,children:[t.branch?S.jsxs(S.Fragment,{children:[S.jsx("span",{className:"sidebar-project-location-branch",children:t.branch}),S.jsx("span",{className:"sidebar-project-location-separator","aria-hidden":"true",children:"/"})]}):null,S.jsx("span",{className:"sidebar-project-location-status",children:t.status})]})}function KG(e){const n=e.indexOf(" / ");return n===-1?{branch:null,status:e}:{branch:e.slice(0,n),status:e.slice(n+3)}}function WG(e,t,n,a=!0,o=null){return e==="cloud"?JG(t):GG(t,n,a,o)}function GG(e,t,n=!0,a=null){const o=ZG(e,t,n),r=YG(t),s=XG(e,n),l=n===!1&&a;return[{key:"local",value:o,tone:r?"attention":"local",icon:e.source==="git"?S.jsx(sy,{size:13}):S.jsx(hP,{size:13}),actionTarget:"local"},{key:"cloud",value:l||(s?e7(e,t,n):"not in cloud"),tone:l?"attention":"cloud",icon:S.jsx(up,{size:13}),actionTarget:s?"cloud":"upload_cloud"}]}function JG(e){return[{key:"cloud",value:t7(e),tone:e.syncedAt?"cloud":"attention",icon:S.jsx(up,{size:13}),actionTarget:"cloud"}]}function ZG(e,t,n){const a=QG(e,t);return t?t.error?`${a} / status unavailable`:t.initialized?FP(t,{branch:e.linkedSandboxProject?.defaultBranch??null,linkedCloudSourceKnown:e.linkedSandboxProject?.projectId&&n?!!e.linkedSandboxProject.lastUploadedCommit||!t.headCommit:!0}):`${a} / not checked out`:`${a} / available`}function YG(e){return!!(e?.dirty||(e?.changedFilesCount??0)>0||(e?.untrackedFilesCount??0)>0)}function QG(e,t){return t?.currentBranch??t?.defaultBranch??e.linkedSandboxProject?.defaultBranch??"local"}function XG(e,t=!0){return!!(t&&e.linkedSandboxProject?.projectId||e.linkedOpenPondApp?.appId)}function e7(e,t,n){return VP(e,null,t,{cloudLinkTrusted:n})}function t7(e){const t=e.defaultBranch??"main",n=e.syncedAt?"setup ready":"needs setup";return`${t} / ${n}`}function n7({open:e,onToggleOpen:t}){return S.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:S.jsx(yd,{size:13})})}function a7({onClose:e,onMoveToCloud:t,onRemove:n}){return S.jsxs(S.Fragment,{children:[S.jsx("button",{type:"button",className:"sidebar-project-menu-backdrop","aria-label":"Close project actions",onClick:a=>{a.stopPropagation(),e()}}),S.jsxs("div",{className:"section-menu-popover sidebar-project-row-popover",role:"menu",children:[t&&S.jsxs("button",{type:"button",role:"menuitem",onClick:a=>{a.stopPropagation(),t()},children:[S.jsx(hG,{size:13}),S.jsx("span",{children:"Move to Cloud"})]}),S.jsxs("button",{type:"button",role:"menuitem",onClick:a=>{a.stopPropagation(),n()},children:[S.jsx(Sd,{size:13}),S.jsx("span",{children:"Remove from Projects"})]})]})]})}function Ty({children:e,className:t,dataSessionId:n,dragging:a,iconless:o=!1,nested:r=!1,placeholder:s=!1,selected:l,ariaExpanded:m,ariaDescribedBy:d,onSelect:f,onDragStart:g,onDragEnd:x,onDragOver:k,onDrop:C,onDoubleClick:R}){const E=!!g;return S.jsx("div",{className:["sidebar-row",t??"",l?"selected":"",a?"dragging":"",o?"iconless":"",r?"nested":"",s?"placeholder":""].filter(Boolean).join(" "),draggable:E,"data-session-id":n,role:"button",tabIndex:0,"aria-expanded":m,"aria-describedby":d,onClick:f,onDoubleClick:R,onKeyDown:A=>{A.target===A.currentTarget&&(A.key==="Enter"||A.key===" ")&&(A.preventDefault(),f())},onDragStart:g,onDragEnd:x,onDragEnter:A=>{k&&(A.preventDefault(),A.dataTransfer.dropEffect="move",k(A))},onDragOver:A=>{k&&(A.preventDefault(),A.dataTransfer.dropEffect="move",k(A))},onDrop:A=>{C&&(A.preventDefault(),C(A))},children:e})}function bm({children:e,label:t,onClick:n}){return S.jsx("button",{type:"button",className:"sidebar-row-action","data-tooltip":t,"aria-label":t,onClick:a=>{a.stopPropagation(),n()},children:e})}function i7({filter:e,activityOrder:t=!1,groupByProject:n,noun:a,onFilterChange:o,onGroupByProjectChange:r,onOnlyRunningTasksChange:s,onShowCodexChatsChange:l,onTasksetChange:m,onSortChange:d,onlyRunningTasks:f,openMenu:g,setOpenMenu:x,showCodexChats:k,sort:C,selectedTasksetId:R,tasksets:E}){const A=y.useRef(null),[O,$]=y.useState(!1),w=E.find(N=>N.id===R)?.name??Cx.find(N=>N.value===e)?.label??"Active",P=g==="tasks-filter",j=g==="chats";return y.useEffect(()=>{if(!P&&!j)return;function N(z){A.current?.contains(z.target)||x(null)}return document.addEventListener("pointerdown",N),()=>document.removeEventListener("pointerdown",N)},[P,x,j]),S.jsxs("div",{className:"sidebar-task-list-controls",ref:A,children:[S.jsxs("div",{className:"section-menu",children:[S.jsx("button",{type:"button",className:`section-icon ${j?"active":""}`,"aria-label":`${a==="tasks"?"Task":"Chat"} list options`,"aria-haspopup":"menu","aria-expanded":j,onClick:()=>x(N=>N==="chats"?null:"chats"),children:S.jsx(yd,{size:14})}),j?S.jsxs("div",{className:"section-menu-popover",role:"menu","aria-label":`${a==="tasks"?"Task":"Chat"} list options`,children:[S.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":k,onClick:()=>l(!k),children:[S.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:k?S.jsx(Ai,{size:13}):null}),S.jsx("span",{children:"Show Codex chats, including pinned"})]}),S.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":f,onClick:()=>s(!f),children:[S.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:f?S.jsx(Ai,{size:13}):null}),S.jsxs("span",{children:["Only running ",a,", including pinned"]})]}),a==="tasks"&&!t?S.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":n,onClick:()=>r(!n),children:[S.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:n?S.jsx(Ai,{size:13}):null}),S.jsx("span",{children:"Group by project"})]}):null,t?S.jsx("p",{className:"empty-row",children:"Latest activity first"}):aG.map(N=>S.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":C===N.value,onClick:()=>{d(N.value),x(null)},children:[S.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:C===N.value?S.jsx(Ai,{size:13}):null}),S.jsx("span",{children:N.label})]},N.value))]}):null]}),S.jsxs("div",{className:"section-menu",children:[S.jsx("button",{type:"button",className:`section-icon ${P?"active":""}`,"aria-label":`Filter ${a}: ${w}`,"aria-haspopup":"menu","aria-expanded":P,onClick:()=>x(N=>N==="tasks-filter"?null:"tasks-filter"),children:S.jsx(BW,{size:14})}),P?S.jsx("div",{className:"section-menu-popover",role:"menu","aria-label":`Filter ${a}`,children:Cx.map(N=>S.jsxs(y.Fragment,{children:[N.value==="tasksets"?S.jsxs("button",{type:"button",role:"menuitem","aria-expanded":O,onClick:()=>$(z=>!z),children:[S.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:O?S.jsx(Go,{size:13}):S.jsx(Jo,{size:13})}),S.jsx("span",{children:N.label})]}):S.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":e===N.value,onClick:()=>{o(N.value),x(null)},children:[S.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e===N.value?S.jsx(Ai,{size:13}):null}),S.jsx("span",{children:N.label})]}),N.value==="tasksets"&&O?S.jsxs(S.Fragment,{children:[S.jsxs("button",{className:"section-menu-taskset-option",type:"button",role:"menuitemradio","aria-checked":e==="tasksets"&&!R,onClick:()=>{m(null),x(null)},children:[S.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&!R?S.jsx(Ai,{size:13}):null}),S.jsx("span",{children:"All Tasksets"})]}),E.map(z=>S.jsxs("button",{className:"section-menu-taskset-option",type:"button",role:"menuitemradio","aria-checked":e==="tasksets"&&R===z.id,onClick:()=>{m(z.id),x(null)},children:[S.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&R===z.id?S.jsx(Ai,{size:13}):null}),S.jsx("span",{children:z.name}),S.jsx("span",{className:"section-menu-option-count","aria-hidden":"true",children:z.chatCount})]},z.id))]}):null]},N.value))}):null]})]})}function o7({onAddProject:e,onViewProjects:t}){const[n,a]=y.useState(!1),o=y.useRef(null),r=y.useRef(null);return y.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]),S.jsxs(S.Fragment,{children:[S.jsxs("div",{className:"section-menu",ref:o,onKeyDown:s=>{s.key==="Escape"&&(s.stopPropagation(),a(!1),r.current?.focus())},children:[S.jsx("button",{ref:r,type:"button",className:`section-icon${n?" active":""}`,"aria-label":"Project options","aria-haspopup":"menu","aria-expanded":n,onClick:()=>a(s=>!s),children:S.jsx(yd,{size:14})}),n?S.jsxs("div",{className:"section-menu-popover",role:"menu","aria-label":"Project options",children:[S.jsx("button",{type:"button",role:"menuitem",onClick:()=>{a(!1),t()},children:"View all projects"}),S.jsx("button",{type:"button",role:"menuitem",onClick:()=>{a(!1),e()},children:"Add project"})]}):null]}),S.jsx("button",{type:"button",className:"section-icon",onClick:e,"aria-label":"Add project",title:"Add project",children:"+"})]})}const r7=240,s7=36;function l7(e,t,n=!1){const a=Math.max(12,t.width-r7-12),o=Math.max(12,t.height-s7-(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 c7({detail:e,onClose:t}){if(y.useEffect(()=>{if(!e||typeof window>"u")return;const o=l=>{l.key==="Escape"&&t()};let r=!1;const s=window.requestAnimationFrame(()=>{window.addEventListener("scroll",t,!0),r=!0});return window.addEventListener("keydown",o),()=>{window.cancelAnimationFrame(s),window.removeEventListener("keydown",o),r&&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 S.jsxs("aside",{id:e.descriptionId,className:"sidebar-task-detail-popover",style:e.style,role:"tooltip","aria-label":`Last updated for ${e.title}`,children:[S.jsx("time",{dateTime:e.updatedAt,children:a}),e.folderName?S.jsxs("div",{className:"sidebar-task-detail-folder",children:[S.jsx(hP,{size:13,"aria-hidden":"true"}),S.jsx("span",{children:e.folderName})]}):null]})}function d7({children:e,expanded:t,groupKey:n,kind:a,label:o,onToggle:r,onNewTask:s,onOpenProject:l,onRemoveProject:m,project:d}){const f=`sidebar-task-group-${n.replace(/[^a-zA-Z0-9_-]/g,"-")}`,g=a==="draft"?ry:mp,[x,k]=y.useState(!1),C=!!(s||l||m);return S.jsxs("section",{className:"sidebar-task-project-group",children:[S.jsxs("div",{className:`sidebar-task-project-group-header-shell${x?" menu-open":""}`,children:[S.jsxs("button",{type:"button",className:"sidebar-task-project-group-header","aria-controls":f,"aria-expanded":t,onClick:()=>{k(!1),r()},children:[d?S.jsx(WP,{kind:d.kind,linkedCloud:!!(d.kind==="local"&&d.project.linkedSandboxProject?.projectId),open:d.kind==="local"&&t,className:"sidebar-task-project-group-icon",baseSize:14}):S.jsx(g,{className:"sidebar-task-project-group-icon",size:14,"aria-hidden":"true"}),S.jsx("span",{className:"sidebar-task-project-group-name",children:o}),S.jsx("span",{className:"sidebar-task-project-group-caret","aria-hidden":"true",children:t?S.jsx(Go,{size:13}):S.jsx(Jo,{size:13})})]}),d&&C?S.jsxs("div",{className:"sidebar-task-project-group-actions",children:[l||m?S.jsx("button",{type:"button",className:`sidebar-row-action${x?" active":""}`,"data-tooltip":"More project actions","aria-label":"More project actions","aria-expanded":x,"aria-haspopup":"menu",onClick:()=>k(R=>!R),children:S.jsx(yd,{size:13})}):null,s?S.jsx("button",{type:"button",className:"sidebar-row-action","data-tooltip":"New task","aria-label":"New task",onClick:s,children:S.jsx(pp,{size:13})}):null]}):null,x?S.jsxs(S.Fragment,{children:[S.jsx("button",{type:"button",className:"sidebar-task-project-group-menu-backdrop","aria-label":"Close project actions",onClick:()=>k(!1)}),S.jsxs("div",{className:"section-menu-popover sidebar-task-project-group-menu",role:"menu",children:[l?S.jsx("button",{type:"button",role:"menuitem",onClick:()=>{k(!1),l()},children:S.jsx("span",{children:"Open project"})}):null,m?S.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{k(!1),m()},children:[S.jsx(Sd,{size:13}),S.jsx("span",{children:"Remove from Projects"})]}):null]})]}):null]}),t?S.jsx("div",{id:f,className:"sidebar-task-project-group-content",children:e}):null]})}const u7={},m7=new Map,p7=new Map;function f7(e,t){return Math.min(Math.max(e,Bn)+Bg,t)}function h7(e,t){const n=Math.max(Bn,Math.min(e,t));if(n<=Bn)return Bn;const a=Math.ceil((n-Bn)/Bg);return Math.max(Bn,Bn+(a-1)*Bg)}function g7(e,t){const n=new Map;for(const a of e){const o=t(a),r=n.get(o.key);r?r.sessions.push(a):n.set(o.key,{...o,sessions:[a]})}return[...n.values()]}function v7({activeSessions:e,activityTimes:t={},onSelectSession:n,archiveSession:a,archivedSessions:o,chatRowsVisibleCount:r,childSessionRowsByParentId:s={},cloudProjectRows:l,beginProjectChat:m,onAddProject:d,commitTaskDrop:f,commitTaskPreviewDrop:g,dockSessionRight:x,experience:k="work",goalRuntimeBySessionId:C=m7,localProjectRows:R,openSidebarFile:E,pinnedCollapsed:A,pinnedRows:O,previewTaskDrop:$,previewPinnedDrop:M,projectRows:w,renameSession:P,restoreSession:j,runningSessionIds:N,sectionMenuOpen:z,selectedProjectId:D,selectedSessionId:F,setChatRowsVisibleCount:te,setSectionMenuOpen:ve,setSelectedAppId:re,setSelectedProjectId:K,setSelectedSessionId:L,setView:de,sidebarProjectIdBySessionId:X,startTaskDrag:Z,startPinnedDrag:pe,subagentRuntimeBySessionId:ee=p7,taskDragSessionId:me,taskPreviewSessionIds:be,terminalSummaries:je=u7,toggleSessionPinned:ke,toggleSessionSavedForLater:ue,view:Ie,clearTaskDrag:Le,removeProject:Fe,toggleProjectPinned:Xe,onTogglePinnedCollapsed:Ze,setSidebarFileStatus:Be,commitPinnedDrop:Ge,commitPinnedPreviewDrop:Ve,clearSidebarDrag:U,dragItem:J}){const[q,oe]=y.useState(()=>Vo.getItem("openpond.sidebar.presentation.v1")==="inbox"?"inbox":"grouped");al(()=>oe(Vo.getItem("openpond.sidebar.presentation.v1")==="inbox"?"inbox":"grouped"));const he=q==="inbox",[Re,qe]=y.useState("active"),[Je,et]=y.useState("recent"),[dt,_t]=y.useState(!0);y.useEffect(()=>{k!=="chat"&&_t(!0)},[k]);const[Ne,Ye]=y.useState({work:!1,chat:!0}),[h,V]=y.useState({work:!1,chat:!1}),ae=k==="chat"?"chat":"work",we=Ne[ae],[fe,Y]=y.useState(Ex);al(()=>Y(Ex()));const{onlyRunningTasks:_,showCodexChats:G}=fe,[se,ne]=y.useState(null),[ge,Se]=y.useState(()=>new Set),[xe,Oe]=y.useState(()=>new Map),[Te,Ue]=y.useState(null);y.useEffect(()=>{D&&Ye(Q=>Q[ae]?{...Q,[ae]:!1}:Q)},[ae,D]);const Ee=k==="chat"?"chats":"tasks",tt=w??[...R,...l],ht=y.useMemo(()=>new Map(tt.map(Q=>[Q.id,Q.project.name])),[tt]),xn=y.useMemo(()=>new Map(tt.map(Q=>[Q.id,Q])),[tt]),xt=y.useMemo(()=>{const Q=new Set(N);for(const Ae of[...e,...Object.values(s).flat()]){const De=C.get(Ae.id),pt=ee.get(Ae.id);(De?.tone==="active"&&De.status!=="queued"||(pt?.activeCount??0)>0||ea(Ae.id)?.status==="running")&&Q.add(Ae.id)}return Q},[e,s,C,N,ee,je]),Xn=y.useMemo(()=>Th({activeSessions:e,doneSessions:o,filter:"all",inProgressSessionIds:xt,sort:"manual"}),[e,o,xt]),kn=y.useMemo(()=>Th({activeSessions:e,doneSessions:o,filter:Re,inProgressSessionIds:xt,onlyRunningTasks:_,selectedTasksetId:se,previewSessionIds:be,showCodexChats:G,sort:Je}),[e,o,xt,_,se,G,Re,be,Je]),Pn=y.useMemo(()=>{const Q=new Map;for(const Ae of[...e,...o]){if(!$u(Ae,{inProgressSessionIds:xt,onlyRunningTasks:_,showCodexChats:G}))continue;const De=Ms(Ae);if(!De)continue;const pt=Q.get(De.id);pt?pt.chatCount+=1:Q.set(De.id,{...De,chatCount:1})}return[...Q.values()].sort((Ae,De)=>Ae.name.localeCompare(De.name))},[e,o,xt,_,G]),Zt=y.useMemo(()=>O.filter(Q=>Q.type!=="session"||$u(Q.session,{inProgressSessionIds:xt,onlyRunningTasks:_,showCodexChats:G})),[xt,_,O,G]),Dn=y.useMemo(()=>kn.filter(Q=>!vc(Q)),[kn]),An=y.useMemo(()=>Dn.slice(0,Math.max(Bn,r)),[r,Dn]),Hn=y.useMemo(()=>{const Q=g7(An,Ae=>{if(zc(Ae))return{key:"draft",label:"Drafts",projectId:null,project:null,kind:"draft"};const De=X[Ae.id],pt=$t(Ae)??"Work";return{key:De?`project:${De}`:`projectless:${pt}`,label:pt,projectId:De??null,project:De?xn.get(De)??null:null,kind:De?"project":"projectless"}});for(const Ae of tt)Q.some(De=>De.projectId===Ae.id)||Q.push({key:`project:${Ae.id}`,label:Ae.project.name,projectId:Ae.id,project:Ae,kind:"project",sessions:[]});return Q},[tt,ht,xn,X,An]),Un=An.length<Dn.length,Wt=An.length>Bn,Ct=y.useMemo(()=>new Set(Hn.filter(Q=>Q.sessions.some(Ae=>Ae.id===F||xt.has(Ae.id))).map(Q=>Q.key)),[Hn,xt,F]),Ln=Xn.filter(Q=>!vc(Q)).map(Q=>Q.id),mt=An.map(Q=>Q.id),Nt=JSON.stringify(Object.entries(s).filter(([Q,Ae])=>Ae.some(De=>!De.archived)&&(ee.get(Q)?.activeCount??0)>0).flatMap(([Q,Ae])=>Ae.filter(De=>!De.archived).map(De=>[Q,De.id])).sort(([Q,Ae],[De,pt])=>Q.localeCompare(De)||Ae.localeCompare(pt)));y.useEffect(()=>{const Q=JSON.parse(Nt);if(Q.length===0)return;const Ae=new Set(Q.map(([De])=>De));Se(De=>[...Ae].every(pt=>De.has(pt))?De:new Set([...De,...Ae]))},[Nt]);function ea(Q){return dG(je[BP({kind:"session",id:Q})])}function $t(Q){if(zc(Q))return"Draft";const Ae=X[Q.id];return Ae?ht.get(Ae)??Q.workspaceName??"Project":Y8(Q)}function Tn(Q){if(n){n(Q);return}Vt({kind:"chat",sessionId:Q.id}),L(Q.id);const Ae=X[Q.id]??null;re(Ae?null:Q.appId),K(Ae),de("chat")}function st(Q){return(s[Q.id]??[]).filter(Ae=>!Ae.archived&&$u(Ae,{inProgressSessionIds:xt,onlyRunningTasks:_,showCodexChats:G}))}function En(Q,Ae){return ge.has(Q.id)||Ae.some(De=>De.id===F)}function gi(Q){Se(Ae=>{const De=new Set(Ae);return De.has(Q)?De.delete(Q):De.add(Q),De})}function vi(Q){const Ae=st(Q);return Ae.length===0||!En(Q,Ae)?null:S.jsx("div",{className:"sidebar-child-session-group",children:Ae.map(De=>S.jsx(Mh,{session:De,selected:Ie==="chat"&&F===De.id,nested:!0,running:xt.has(De.id),goalRuntime:C.get(De.id)??null,subagentRuntime:ee.get(De.id)??null,terminalIndicator:ea(De.id),projectLabel:$t(Q),onSelect:()=>Tn(De),onTogglePin:()=>ke(De),onToggleSaveForLater:()=>ue(De),onDockRight:()=>x(De),onArchive:()=>De.archived?j(De):a(De),onRename:P},De.id))})}function Wn(Q,Ae){if(typeof window>"u")return;const De=vc(Q)?$t(Q):null;Ue({descriptionId:`sidebar-task-detail-${Q.id}`,sessionId:Q.id,title:Q.title,updatedAt:Q.updatedAt,folderName:De,style:l7(Ae.getBoundingClientRect(),{width:window.innerWidth,height:window.innerHeight},!!De)})}function da(Q,Ae={}){const De=Q.archived,pt=me===Q.id,Yt=st(Q),ua="sidebar-session-group",bi=!he&&Je==="manual"?{onDragStart:In=>Z(In,{allSessionIds:Ln,visibleSessionIds:mt,sessionId:Q.id}),onDragEnd:Le,onDragOver:In=>{pt||$(In,Q.id)},onDrop:In=>{pt?g():f(In,Q.id)}}:{};return S.jsxs("div",{className:ua,onPointerEnter:In=>Wn(Q,In.currentTarget),onPointerLeave:()=>Ue(null),onFocusCapture:In=>Wn(Q,In.currentTarget),onBlurCapture:In=>{In.currentTarget.contains(In.relatedTarget)||Ue(null)},children:[S.jsx(Mh,{session:Q,selected:!De&&Ie==="chat"&&F===Q.id,archived:De,inbox:he,activityAt:Fu(Q,t),placeholder:pt,running:xt.has(Q.id),goalRuntime:C.get(Q.id)??null,subagentRuntime:ee.get(Q.id)??null,terminalIndicator:ea(Q.id),projectLabel:Ae.projectLabel===void 0?$t(Q):Ae.projectLabel,metadataPresentation:Ae.metadataPresentation,ariaDescribedBy:Te?.sessionId===Q.id?Te.descriptionId:void 0,childSessionCount:Yt.length,childSessionsExpanded:En(Q,Yt),onToggleChildSessions:()=>gi(Q.id),onSelect:()=>{Ue(null),De&&j(Q),Tn(Q)},onTogglePin:()=>ke(Q),onToggleSaveForLater:()=>ue(Q),onDockRight:()=>x(Q),onArchive:()=>De?j(Q):a(Q),onRename:P,...bi}),!he&&!pt?vi(Q):null]},Q.id)}function Gn(Q){Q!=="tasksets"&&ne(null),qe(Q),te(Bn)}function Vi(Q){ne(Q),qe("tasksets"),te(Bn)}function ei(Q){et(Q),te(Bn)}function wt(){te(Q=>f7(Q,Dn.length))}function pn(){te(Q=>h7(Q,Dn.length))}function Rt(Q){const Ae={id:Q.id,type:Q.type};return{onDragStart:De=>pe(De,Ae),onDragEnd:U,onDragOver:De=>M(De,Ae),onDrop:De=>{J?.id===Q.id&&J.type===Q.type?Ve():Ge(De,Ae)}}}function ut(Q){const Ae=Rt(Q),De=J?.id===Q.id&&J.type===Q.type;if(Q.type==="project"){const Yt=Q.item;return S.jsx(BG,{kind:Yt.kind,project:Yt.project,pinned:!0,selected:Ie==="chat"&&D===Yt.id,expanded:!1,disclosure:!1,placeholder:De,onSelect:()=>{re(null),K(Yt.id),L(null),de("chat")},onNewChat:()=>m(Yt.id),onTogglePin:()=>Xe(Yt),onRemove:()=>Fe(Yt),...Ae},Q.key)}if(Q.type==="file")return S.jsx(UG,{file:Q.file,placeholder:De,onSelect:()=>E(Q.file),onTogglePin:()=>Be(Q.file,"none"),onToggleSaveForLater:()=>Be(Q.file,"saved_for_later"),...Ae},Q.key);const pt=Q.session;return S.jsx("div",{onPointerEnter:Yt=>Wn(pt,Yt.currentTarget),onPointerLeave:()=>Ue(null),onFocusCapture:Yt=>Wn(pt,Yt.currentTarget),onBlurCapture:Yt=>{Yt.currentTarget.contains(Yt.relatedTarget)||Ue(null)},children:S.jsx(Mh,{ariaDescribedBy:Te?.sessionId===pt.id?Te.descriptionId:void 0,session:pt,selected:Ie==="chat"&&F===pt.id,placeholder:De,running:xt.has(pt.id),goalRuntime:C.get(pt.id)??null,subagentRuntime:ee.get(pt.id)??null,terminalIndicator:ea(pt.id),projectLabel:$t(pt),metadataPresentation:"flyout",onSelect:()=>{Ue(null),Tn(pt)},onTogglePin:()=>ke(pt),onToggleSaveForLater:()=>ue(pt),onDockRight:()=>x(pt),onArchive:()=>a(pt),onRename:P,...Ae})},Q.key)}function ln(Q){const Ae=Ct.has(Q.key)||xe.get(Q.key)!==!1;return S.jsx(d7,{expanded:Ae,groupKey:Q.key,kind:Q.kind,label:Q.label,onToggle:()=>{Oe(De=>{const pt=new Map(De);return pt.set(Q.key,!Ae),pt})},onNewTask:Q.project?()=>m(Q.project.id):void 0,onOpenProject:Q.project?()=>{re(null),K(Q.project.id),L(null),de("chat")}:void 0,onRemoveProject:Q.project?()=>Fe(Q.project):void 0,project:Q.project,children:Q.sessions.map(De=>da(De,{metadataPresentation:"flyout",projectLabel:Q.label}))},Q.key)}const ta=S.jsx(i7,{activityOrder:he,filter:Re,groupByProject:dt,noun:Ee,onFilterChange:Gn,onGroupByProjectChange:_t,onOnlyRunningTasksChange:Q=>{Y(Ae=>{const De={...Ae,onlyRunningTasks:Q};return Mx(De),De}),te(Bn)},onShowCodexChatsChange:Q=>{Y(Ae=>{const De={...Ae,showCodexChats:Q};return Mx(De),De}),te(Bn)},onTasksetChange:Vi,onSortChange:ei,onlyRunningTasks:_,openMenu:z,setOpenMenu:ve,showCodexChats:G,sort:Je,selectedTasksetId:se,tasksets:Pn}),wn=Th({activeSessions:Object.values(s).flat().filter(Q=>!Q.archived),doneSessions:Object.values(s).flat().filter(Q=>Q.archived),filter:Re,inProgressSessionIds:xt,onlyRunningTasks:_,selectedTasksetId:se,showCodexChats:G,sort:"recent"}),nt=PE([...kn,...wn],t,xt);return S.jsxs("div",{className:"sidebar-sections",children:[S.jsxs("div",{className:"sidebar-threads-header",children:[S.jsx("span",{children:"Threads"}),S.jsxs("div",{className:"sidebar-threads-header-actions",children:[he?ta:null,S.jsx("button",{type:"button",className:`sidebar-icon${he?" active":""}`,"aria-label":he?"Show grouped threads":"Show thread inbox",title:he?"Grouped threads":"Thread inbox","aria-pressed":he,onClick:()=>{const Q=he?"grouped":"inbox";oe(Q),Vo.setItem("openpond.sidebar.presentation.v1",Q)},children:he?S.jsx(b8,{size:16}):S.jsx(my,{size:16})})]})]}),he?S.jsxs("section",{className:"sidebar-thread-inbox","aria-label":"Thread inbox",children:[AE(nt,t,xt).map(Q=>S.jsxs("div",{children:[Q.label?S.jsx("h3",{className:"sidebar-inbox-date",children:Q.label}):null,Q.sessions.map(Ae=>da(Ae,{projectLabel:X[Ae.id]?$t(Ae):null}))]},Q.key)),nt.length===0?S.jsx("div",{className:"empty-row",children:Px(Re,Ee)}):null]}):S.jsxs(S.Fragment,{children:[Zt.length>0?S.jsx(Eh,{label:"Pinned",className:"sidebar-pinned-section",collapsed:A,onToggleCollapsed:Ze,children:Zt.map(ut)}):null,S.jsx(Eh,{label:"Projects",className:`sidebar-projects-section${k!=="chat"?" development":""}`,collapsed:we,onToggleCollapsed:()=>Ye(Q=>({...Q,[ae]:!Q[ae]})),actions:S.jsx(o7,{onAddProject:d,onViewProjects:()=>{(async()=>await Vt({kind:"view",view:"projects"})&&(re(null),K(null),L(null),de("projects")))()}}),children:Hn.filter(Q=>Q.kind==="project").map(Q=>ln(k==="chat"||!dt?{...Q,sessions:[]}:Q))}),S.jsxs(Eh,{label:k==="chat"?"Chat":"Work",className:"sidebar-task-section sidebar-ordinary-section",collapsed:h[ae],onToggleCollapsed:()=>V(Q=>({...Q,[ae]:!Q[ae]})),actionsVisible:z==="chats"||z==="tasks-filter"||Re!=="active"||_||!G,actions:ta,children:[(k==="chat"||!dt?An:An.filter(Q=>!X[Q.id])).map(Q=>da(Q)),Dn.length===0&&Zt.length===0?S.jsx("div",{className:"empty-row",children:Px(Re,Ee)}):null,Dn.length>Bn&&(Un||Wt)?S.jsxs("div",{className:"sidebar-pagination-controls","aria-label":`Showing ${An.length} of ${Dn.length} ${Ee}`,children:[Un?S.jsx(Dx,{onClick:wt,children:"Show more"}):null,Wt?S.jsx(Dx,{onClick:pn,children:"Show less"}):null]}):null]})]}),S.jsx(c7,{detail:Te,onClose:()=>Ue(null)})]})}const b7=y.lazy(()=>Zo(()=>import("./TerminalOverlay-Ck43Qri3.js"),__vite__mapDeps([0,1,2,3])).then(e=>({default:e.TerminalOverlay})));function y7({connection:e,command:t,onClose:n,onComplete:a}){const[o,r]=y.useState([]),[s]=y.useState(()=>({kind:"draft",id:`native-setup-${crypto.randomUUID()}`})),l=y.useRef(!1),[m]=y.useState(()=>({id:Date.now(),scope:s,command:t}));return y.useEffect(()=>{!l.current&&o.some(d=>d.lastExitCode!==null&&(d.commandStatus==="success"||d.commandStatus==="failed"))&&(l.current=!0,a?.())},[o,a]),vm.createPortal(S.jsx("div",{className:"native-setup-terminal",children:S.jsx(y.Suspense,{fallback:S.jsx("p",{role:"status",children:"Opening setup terminal…"}),children:S.jsx(b7,{open:!0,disposeOnUnmount:!0,connection:e,scope:s,tabs:o,onTabsChange:r,cwd:null,appId:null,workspaceName:"Agent setup",queuedCommand:m,onClose:n})})}),document.body)}const uu={codex:"Codex",claude_code:"Claude Code",opencode:"OpenCode",grok_build:"Grok Build",hermes:"Hermes",pi:"Pi",oh_my_pi:"Oh My Pi",openclaw:"OpenClaw"};function S7({status:e,busy:t,onControl:n,onConnectionControl:a,onReconnect:o}){const r=e.desiredState==="stopped",s=r?"Importer stopped":e.running?"Importer running":"Importer offline";return S.jsxs("div",{className:"sidebar-section native-importer-status",children:[S.jsx("strong",{children:s}),e.connections.map(l=>{const m=l.backfill,d=m.stage==="complete",f=m.admitted+m.skipped;return S.jsxs("div",{className:"native-importer-connection",children:[S.jsxs("span",{children:[l.error?S.jsx(mm,{size:12}):d?S.jsx(Ai,{size:12}):S.jsx(ly,{size:12}),uu[l.source]??l.source]}),S.jsx("small",{children:l.state==="paused"?"Paused":l.state==="disconnected"?"Disconnected":d?e.running&&!r?"Watching for new conversations":`${m.admitted} conversations imported`:m.stage==="discovering"?"Finding conversations":`${f} of ${m.total} conversations processed`}),S.jsxs("small",{children:[l.admitted," tasks admitted",m.skipped>0?`, ${m.skipped} conversations skipped`:"",m.failed>0?`, ${m.failed} failed`:""]}),!d&&m.total>0?S.jsx("progress",{"aria-label":`${uu[l.source]??l.source} import progress`,value:f,max:m.total}):null,l.queued>0?S.jsxs("small",{children:[l.queued," updates waiting to upload (",new Intl.NumberFormat(void 0,{notation:"compact"}).format(l.pendingBytes)," bytes)"]}):null,l.lastAdmissionAt?S.jsxs("small",{children:["Last synced ",S.jsx("time",{dateTime:l.lastAdmissionAt,children:new Date(l.lastAdmissionAt).toLocaleString()})]}):S.jsx("small",{children:"No uploads acknowledged yet"}),l.destinationLinks?.tasks?S.jsx("a",{href:l.destinationLinks.tasks,target:"_blank",rel:"noopener noreferrer",children:"View tasks"}):null,l.destinationLinks?.conversations?S.jsx("a",{href:l.destinationLinks.conversations,target:"_blank",rel:"noopener noreferrer",children:"View conversations"}):null,l.error?S.jsx("small",{role:"status",children:l.error}):null,l.state==="disconnected"?S.jsx("button",{type:"button",disabled:t,onClick:()=>o(l.id),children:"Reconnect source"}):S.jsxs("div",{children:[S.jsxs("button",{type:"button",disabled:t,onClick:()=>a(l.state==="paused"?"resume":"pause",l.id),children:[l.state==="paused"?"Resume":"Pause"," ",uu[l.source]??l.source]}),S.jsxs("button",{type:"button",disabled:t,onClick:()=>a("disconnect",l.id),children:["Disconnect ",uu[l.source]??l.source]})]})]},l.id)}),S.jsx("button",{type:"button",disabled:t||r,onClick:()=>n("sync"),children:"Sync now"}),S.jsxs("button",{type:"button",disabled:t,onClick:()=>n(r||!e.running?"start":"stop"),children:[r?"Start":e.running?"Stop":"Restart"," importer"]}),!e.running&&!r?S.jsx("button",{type:"button",disabled:t,onClick:()=>n("stop"),children:"Stop importer"}):null,!e.running&&!r?S.jsx("button",{type:"button",disabled:t,onClick:()=>n("install"),children:"Reinstall background service"}):null]})}function x7({title:e,inspection:t,busy:n,onSelect:a,onRefresh:o,onClose:r}){return S.jsxs("section",{className:"native-branch-picker","aria-label":"Choose Claude conversation branch",children:[S.jsx("strong",{children:e||"Claude conversation"}),S.jsx("p",{children:"This conversation has multiple branches. Choose the history to view. Each branch opens as a read-only snapshot."}),t.branches.map(s=>S.jsxs("button",{type:"button",disabled:n,onClick:()=>a({leafId:s.leafId,revision:t.revision}),children:[S.jsx("span",{children:s.title||"Branch without a text message"}),S.jsxs("small",{children:[s.messages," messages · ",s.updatedAt?new Date(s.updatedAt).toLocaleString():"Date unavailable"]}),S.jsx("code",{children:s.leafId})]},s.leafId)),S.jsxs("div",{children:[S.jsx("button",{type:"button",disabled:n,onClick:o,children:"Refresh branches"}),S.jsx("button",{type:"button",disabled:n,onClick:r,children:"Cancel"})]})]})}function k7({connection:e,selectedSessionId:t,selectedSession:n,active:a=!0,onOpen:o}){const r=y.useRef({selectedSessionId:t,active:a});r.current={selectedSessionId:t,active:a};const s=y.useRef(null),l=y.useRef(0),m=y.useRef(null);y.useEffect(()=>(l.current++,s.current=null,O(null),C(null),E(null),x(null),P(null),f(null),()=>{l.current++}),[e]);const[d,f]=y.useState(null),[g,x]=y.useState(null),[k,C]=y.useState(null),[R,E]=y.useState(null),[A,O]=y.useState(null),[$,M]=y.useState(!1),[w,P]=y.useState(null),j=y.useCallback(async()=>{if(!e||m.current===l.current)return;const re=l.current;m.current=re,O("refresh");try{const K=await B(e,"/v1/native-history/list",{method:"POST",body:JSON.stringify({retain:!0})});re===l.current&&(C(K),E(null))}catch(K){re===l.current&&E(K instanceof Error?K.message:"Local history is unavailable.")}finally{m.current===re&&(m.current=null),re===l.current&&O(null)}},[e]);y.useEffect(()=>{j()},[j]),y.useEffect(()=>{const re=window.setInterval(()=>{document.hidden||j()},3e4);return()=>window.clearInterval(re)},[j]),y.useEffect(()=>{if(!a||!e||!d||d.sessionId!==t)return;const re=l.current,K=window.setInterval(()=>{document.hidden||B(e,"/v1/native-history/open",{method:"POST",body:JSON.stringify({id:d.id})}).catch(L=>{re===l.current&&E(L.message)})},1e4);return()=>window.clearInterval(K)},[a,e,d,t]);async function N(){const re=l.current;if(!(!e||!k)){O("more");try{const K=await B(e,"/v1/native-history/list",{method:"POST",body:JSON.stringify({cursors:k.nextCursors,retain:!0})});if(re!==l.current)return;C(L=>({...K,items:[...new Map([...L?.items??[],...K.items].map(de=>[de.id,de])).values()]}))}catch(K){re===l.current&&E(K instanceof Error?K.message:"Could not load more conversations.")}finally{re===l.current&&O(null)}}}async function z(re,K,L=r.current.selectedSessionId){const de=l.current;if(e&&A===null){O(re);try{if(!K){const Z=await B(e,"/v1/native-history/branches",{method:"POST",body:JSON.stringify({id:re})});if(de!==l.current)return;if(Z.branches.length>1){r.current.active&&r.current.selectedSessionId===L&&P({id:re,inspection:Z,originSessionId:L}),E(null);return}}const X=await B(e,"/v1/native-history/open",{method:"POST",body:JSON.stringify({id:re,branch:K})});if(de!==l.current)return;f(K?null:{id:re,sessionId:X.id}),P(null),E(X.metadata?.nativeHistoryProjection&&!X.nativeAgent?typeof X.metadata.nativeReadOnlyReason=="string"?X.metadata.nativeReadOnlyReason:"Read-only history: the native source does not report its original working directory.":null),r.current.active&&r.current.selectedSessionId===L&&await o(X)}catch(X){de===l.current&&E(X instanceof Error?X.message:"Could not read this conversation.")}finally{de===l.current&&O(null)}}}y.useEffect(()=>{if(!a||!e||A!==null||!n||n.metadata?.nativeHistoryLoaded!==!1||n.metadata.nativeBranch)return;const re=n.metadata.nativeHistoryId;if(typeof re!="string")return;const K=`${l.current}:${n.id}`;s.current!==K&&(s.current=K,z(re,void 0,n.id))},[e,n,A,a]);async function D(re){const K=l.current;if(e){O(re);try{await B(e,"/v1/native-history/collector",{method:"POST",body:JSON.stringify({command:re})}),K===l.current&&await j()}catch(L){K===l.current&&E(L instanceof Error?L.message:"Collector action failed.")}finally{K===l.current&&O(null)}}}async function F(re,K){const L=l.current;if(e){O(re);try{const de=await B(e,"/v1/native-history/collector",{method:"POST",body:JSON.stringify({command:re,connectionId:K})});if(L!==l.current)return;x(de.command),E(null)}catch(de){L===l.current&&E(de instanceof Error?de.message:"Could not change Importer connection.")}finally{L===l.current&&O(null)}}}async function te(re){const K=l.current;if(e){O("connect");try{const L=await B(e,"/v1/native-history/collector",{method:"POST",body:JSON.stringify({command:re?"reconnect":"connect",connectionId:re})});if(K!==l.current)return;x(L.command),E(null)}catch(L){K===l.current&&E(L instanceof Error?L.message:"Could not open Importer setup.")}finally{K===l.current&&O(null)}}}async function ve(re){const K=re.metadata?.nativeHistoryId;await o(re)&&re.metadata?.nativeHistoryProjection&&!re.metadata.nativeBranch&&typeof K=="string"&&z(K,void 0,re.id)}return{connection:e,history:k,error:R,busy:A,command:g,expanded:$,branchSelection:w,setCommand:x,setExpanded:M,setBranchSelection:P,refresh:j,more:N,open:z,control:D,connectionControl:F,connect:te,select:ve}}function w7({history:e}){const{connection:t,history:n,error:a,busy:o,command:r,expanded:s,branchSelection:l,setCommand:m,setExpanded:d,setBranchSelection:f,refresh:g,more:x,open:k,control:C,connectionControl:R,connect:E}=e;return t?S.jsxs("section",{className:"sidebar-section native-conversations","aria-label":"Conversation import controls",children:[S.jsxs("div",{className:"sidebar-section-heading",children:[S.jsx("button",{type:"button",onClick:()=>d(A=>!A),"aria-expanded":s,children:"Import conversations"}),S.jsx("button",{type:"button",className:"sidebar-icon","aria-label":"Refresh saved conversation history",disabled:o!==null,onClick:()=>{g()},children:o==="refresh"?S.jsx(ly,{size:14}):S.jsx(i8,{size:14})})]}),r?S.jsx(y7,{connection:t,command:r,onClose:()=>{m(null),g()}}):null,l?S.jsx(x7,{title:n?.items.find(A=>A.id===l.id)?.title??"",inspection:l.inspection,busy:o!==null,onSelect:A=>{k(l.id,A,l.originSessionId??null)},onRefresh:()=>{k(l.id,void 0,l.originSessionId??null)},onClose:()=>f(null)}):null,s?S.jsxs(S.Fragment,{children:[S.jsx("button",{type:"button",disabled:o!==null,onClick:()=>{E()},children:"Connect an import source"}),n&&Object.keys(n.nextCursors).length?S.jsx("button",{type:"button",disabled:o!==null,onClick:()=>{x()},children:"Load more saved conversations"}):null,n&&n.items.length===0?S.jsx("p",{children:"No saved conversations found in configured source locations."}):null,n?.warnings.map(A=>S.jsxs("p",{children:[S.jsx(mm,{size:12,"aria-hidden":"true"})," ",A]},A)),n?.collector.connections.length?S.jsx(S7,{status:n.collector,busy:o!==null,onControl:A=>{C(A)},onConnectionControl:(A,O)=>{R(A,O)},onReconnect:A=>{E(A)}}):S.jsx("p",{children:"Connect an import source to upload conversations. Local history remains available without cloud sync."})]}):null,a?S.jsxs("p",{role:"status",children:[S.jsx(mm,{size:12,"aria-hidden":"true"})," ",a]}):null]}):null}function Hx(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 I7(e,t){const n=Hx(e),a=Hx(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 YP(e){const t=e?.toLowerCase()??"";return t==="darwin"||t.includes("mac")?"mac":t==="linux"||t.includes("linux")?"linux":null}function _7(e){const t=e?.toLowerCase()??"";return t==="arm64"||t==="aarch64"?"arm64":t==="x64"||t==="x86_64"||t==="amd64"?"x64":null}function C7(e,t,n){const a=YP(t),o=_7(n);if(a==="mac"){const r=e.filter(s=>/-mac-.*\.zip$/i.test(s.name));return o==="arm64"?r.find(s=>/-mac-arm64\.zip$/i.test(s.name))??null:o==="x64"?r.find(s=>/-mac-x64\.zip$/i.test(s.name))??r.find(s=>/-mac-universal\.zip$/i.test(s.name))??null:r.find(s=>/-mac-universal\.zip$/i.test(s.name))??r.find(s=>/-mac-arm64\.zip$/i.test(s.name))??r[0]??null}if(a==="linux"){const r=e.filter(s=>/\.AppImage$/i.test(s.name));return o==="arm64"?r.find(s=>/(?:arm64|aarch64).*\.AppImage$/i.test(s.name))??null:o==="x64"?r.find(s=>/(?:x86_64|x64|amd64).*\.AppImage$/i.test(s.name))??r[0]??null:r[0]??null}return null}function R7(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(!I7(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=C7(s,e.platform,e.arch);return!l||!o?null:{version:a,releaseUrl:o,assetName:l.name,downloadUrl:l.downloadUrl}}const P7=3600*1e3,A7="https://api.github.com/repos/openpond/openpond/releases/latest";function T7(e){const[t,n]=y.useState({status:"idle",update:null,lastCheckedAt:null}),a=e.currentVersion?.trim()??"",o=e.platform??"",r=e.arch??"",s=e.enabled&&!!a&&!!YP(o);return y.useEffect(()=>{if(!s){n({status:"idle",update:null,lastCheckedAt:null});return}let l=!1;async function m(){n(f=>({...f,status:f.update?"available":"checking"}));try{const f=await fetch(A7,{headers:{Accept:"application/vnd.github+json"}});if(!f.ok)throw new Error(`GitHub release check failed: ${f.status}`);const g=await f.json(),x=R7({payload:g,currentVersion:a,platform:o,arch:r});if(l)return;n({status:x?"available":"current",update:x,lastCheckedAt:Date.now()})}catch{if(l)return;n(f=>({status:f.update?"available":"error",update:f.update,lastCheckedAt:Date.now()}))}}m();const d=window.setInterval(()=>{m()},P7);return()=>{l=!0,window.clearInterval(d)}},[r,a,s,o]),t}const QP="openpond.sidebar.continuous-learning.dismissed.v1";function Lx(e=XP()){if(!e)return!1;try{return e.getItem(QP)==="true"}catch{return!1}}function E7(e=XP()){if(e)try{e.setItem(QP,"true")}catch{}}function XP(){return typeof window>"u"?null:Vo}function M7({connection:e,onOpenSettings:t}){const[n,a]=y.useState(null),[o,r]=y.useState(Lx);al(()=>r(Lx()));const s=y.useCallback(async()=>{if(!e){a(null);return}try{a(await ie.harnessHistory(e))}catch{a(null)}},[e]);if(y.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 S.jsxs("section",{className:"sidebar-learning-notice","aria-label":"Continuous learning",children:[S.jsxs("header",{children:[S.jsx("strong",{children:"Continuous learning"}),S.jsxs("div",{className:"sidebar-learning-notice-actions",children:[S.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Open Continuous learning settings",onClick:t,type:"button",children:S.jsx(bP,{size:14})}),S.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Close continuous learning",onClick:()=>{r(!0),E7()},type:"button",children:S.jsx(Sd,{size:14})})]})]}),S.jsxs("div",{className:"sidebar-learning-status",children:[S.jsx("strong",{children:"Refiner"}),S.jsx("span",{children:n.backgroundReview.enabled?"On":"Off"})]}),S.jsxs("div",{className:"sidebar-learning-status",children:[S.jsx("strong",{children:"Continuous Review"}),S.jsx("span",{children:m})]})]})}function j7(e){const{arch:t,currentVersion:n,productArea:a,platform:o,setSectionMenuOpen:r,setSelectedAppId:s,setSelectedProjectId:l,setSelectedSessionId:m,setSidebarOpen:d,setView:f,view:g,modelProjects:x,modelTrainingActivityByProjectId:k}=e,C=y.useCallback($=>{r($)},[r]),R=T7({currentVersion:n,platform:o,arch:t,enabled:py()}),E=R.status==="available"?R.update:null,A=y.useCallback(async $=>{if(!await Vt({kind:"chat",sessionId:$.id}))return!1;m($.id);const M=e.sidebarProjectIdBySessionId[$.id]??null;return l(M),s(M?null:$.appId),f("chat"),!0},[m,l,s,f,e.sidebarProjectIdBySessionId]),O=k7({connection:a==="chat"?e.connection:null,active:g==="chat",selectedSessionId:e.selectedSessionId,selectedSession:[...e.activeSessions,...e.archivedSessions,...Object.values(e.childSessionRowsByParentId??{}).flat()].find($=>$.id===e.selectedSessionId)??null,onOpen:A});return S.jsxs("aside",{className:"sidebar",inert:e.open===!1,children:[S.jsxs("div",{className:"sidebar-toolbar",children:[S.jsx("button",{className:"sidebar-icon","aria-label":"Hide sidebar",onClick:()=>d(!1),children:S.jsx(vP,{size:16})}),S.jsx("div",{className:"sidebar-brand",children:S.jsx("img",{className:"sidebar-wordmark",src:_G,alt:"OpenPond"})}),E&&S.jsxs("button",{type:"button",className:"sidebar-update-pill",title:`Download OpenPond ${E.version}: ${E.assetName}`,"aria-label":`Download OpenPond ${E.version}`,onClick:()=>{O7(E.downloadUrl)},children:[S.jsx(AW,{size:14}),S.jsx("span",{children:"Update"})]})]}),a==="chat"?S.jsxs("div",{className:"sidebar-fixed-actions",children:[S.jsx(j8,{experience:e.experience,beginNewChat:e.beginNewChat}),a==="chat"&&g==="chat"&&e.account?.activeProfile&&e.onOpenPonder?S.jsx("div",{className:"sidebar-ponder-fixed",children:S.jsxs("button",{type:"button",className:"sidebar-row sidebar-task-row sidebar-ponder-entry",onClick:e.onOpenPonder,children:[S.jsx("span",{className:"conversation-source-icon","aria-hidden":"true",children:S.jsx("img",{src:Ay,alt:""})}),S.jsx("span",{children:"Ponder Pal"})]})}):null]}):null,S.jsxs("div",{className:"sidebar-scroll",children:[a!=="chat"?S.jsx(O8,{productArea:a,setSectionMenuOpen:C,setSelectedAppId:s,setSelectedProjectId:l,setSelectedSessionId:m,setView:f,view:g,modelProjects:x,modelTrainingActivityByProjectId:k}):null,a!=="chat"||g!=="chat"?null:S.jsx(v7,{...e,onSelectSession:O.select,setSectionMenuOpen:C}),a==="chat"&&g==="chat"?S.jsx(w7,{history:O}):null]}),S.jsx("div",{className:"sidebar-bottom-stack",children:a!=="chat"?null:S.jsx(M7,{connection:e.connection,onOpenSettings:()=>{r(null),Vt({kind:"settings",section:"harness"})}})})]})}async function O7(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-update",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const $7=[{destination:"walkthroughs",icon:bx,label:"Walkthroughs"},{destination:"external",icon:bx,label:"Docs",url:"https://openpond.ai/docs"},{destination:"external",icon:ry,label:"Blog",url:"https://openpond.ai/blog"},{destination:"external",icon:RW,label:"Pricing",url:"https://openpond.ai/pricing"},{destination:"external",icon:gP,label:"Web app",url:"https://openpond.ai/sandboxes"},{destination:"external",icon:HW,label:"GitHub",url:"https://github.com/openpond/openpond"},{destination:"external",icon:mp,label:"Submit issue",url:"https://github.com/openpond/openpond/issues/new/choose"}];function N7({onOpenWalkthroughs:e,onCloseAccount:t,walkthroughsActive:n}){const[a,o]=y.useState(!1),r=y.useRef(null),s=y.useRef(null);y.useLayoutEffect(()=>{a&&s.current?.querySelector('[role="menuitem"]')?.focus()},[a]);function l(){o(!0)}function m(){o(!1),r.current?.focus()}return S.jsxs("div",{className:"user-auth-help",onKeyDown:d=>{a&&(d.key==="Escape"||d.key==="ArrowLeft")&&(d.preventDefault(),d.stopPropagation(),m())},children:[S.jsxs("button",{ref:r,type:"button",className:"user-auth-menu-link",role:"menuitem","aria-haspopup":"menu","aria-expanded":a,onClick:()=>a?m():l(),onKeyDown:d=>{d.key==="ArrowRight"&&(d.preventDefault(),l())},children:[S.jsx(UW,{size:15}),S.jsx("span",{children:"Help"}),S.jsx(Jo,{className:"user-auth-help-chevron",size:14})]}),a?S.jsx("div",{ref:s,className:"user-auth-help-submenu",role:"menu","aria-label":"Help",onKeyDown:d=>{if(!["ArrowDown","ArrowUp","Home","End"].includes(d.key))return;d.preventDefault();const f=Array.from(s.current?.querySelectorAll('[role="menuitem"]')??[]),g=f.indexOf(document.activeElement),x=d.key==="Home"?0:d.key==="End"?f.length-1:(g+(d.key==="ArrowDown"?1:-1)+f.length)%f.length;f[x]?.focus()},children:$7.map(d=>{const f=d.icon,g=S.jsxs(S.Fragment,{children:[S.jsx(f,{size:15}),S.jsx("span",{children:d.label})]});return d.destination==="walkthroughs"?S.jsx("button",{type:"button",role:"menuitem",className:"user-auth-menu-link","aria-current":n?"page":void 0,onClick:()=>{t(),e()},children:g},d.label):S.jsx("a",{className:"user-auth-menu-link",role:"menuitem",href:d.url,target:"_blank",rel:"noreferrer",onClick:x=>{x.preventDefault(),t(),D7(d.url)},children:g},d.label)})}):null]})}async function D7(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-help",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}function H7(...e){for(const t of e){const n=t?.trim();if(n)return n}return null}function L7(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"?H7(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 q7({account:e,open:t,organizations:n,selectedTeamId:a,onOpenActivity:o,onOpenChange:r,onOpenSettings:s,onOpenWalkthroughs:l,walkthroughsActive:m,onSelectTeam:d,onLogOut:f,railTooltip:g}){const[x,k]=y.useState(null),[C,R]=y.useState(!1),E=y.useRef(null),A=y.useMemo(()=>L7(e),[e]),O=A.label.trim().slice(0,1).toUpperCase(),$=n.find(M=>M.teamId===a)??n[0]??null;return y.useEffect(()=>{if(!t)return;function M(P){E.current?.contains(P.target)||r(!1)}function w(P){P.key==="Escape"&&r(!1)}return document.addEventListener("pointerdown",M),document.addEventListener("keydown",w),()=>{document.removeEventListener("pointerdown",M),document.removeEventListener("keydown",w)}},[r,t]),S.jsxs("div",{className:"user-auth-footer",ref:E,children:[S.jsxs("button",{type:"button",className:`user-auth-trigger ${t?"active":""}`,"aria-haspopup":"menu","aria-expanded":t,"aria-label":`${A.label} account menu`,"data-rail-tooltip":g,onClick:()=>r(!t),children:[S.jsx("span",{className:"user-auth-avatar","aria-hidden":"true",children:A.image?S.jsx("img",{src:A.image,alt:""}):O?S.jsx("span",{children:O}):S.jsx(yx,{size:16})}),S.jsx("span",{className:"user-auth-name",children:A.label})]}),t?S.jsxs("div",{className:"user-auth-menu",role:"menu","aria-label":"Account",children:[S.jsxs("div",{className:"user-auth-menu-header",children:[S.jsx("span",{className:"user-auth-menu-avatar","aria-hidden":"true",children:A.image?S.jsx("img",{src:A.image,alt:""}):O?S.jsx("span",{children:O}):S.jsx(yx,{size:17})}),S.jsx("span",{className:"user-auth-menu-identity",children:S.jsx("strong",{children:A.label})})]}),n.length>0&&d?S.jsxs("label",{className:"user-auth-team-picker",children:[S.jsx(uy,{size:15,"aria-hidden":"true"}),S.jsx("span",{className:"user-auth-team-picker-label",children:"Team"}),S.jsx("select",{"aria-label":"Active team",disabled:x!==null,value:$?.teamId??"",onChange:async M=>{const w=M.currentTarget.value;k(w);try{await d(w)}catch{}finally{k(null)}},children:n.map(M=>S.jsx("option",{value:M.teamId,children:M.displayName},M.teamId))})]}):null,S.jsx("div",{className:"user-auth-menu-divider"}),o?S.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",onClick:()=>{r(!1),o()},children:[S.jsx(pP,{size:15}),S.jsx("span",{children:"Activity"})]}):null,S.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",onClick:()=>{r(!1),s()},children:[S.jsx(bP,{size:15}),S.jsx("span",{children:"Settings"})]}),S.jsx(N7,{onOpenWalkthroughs:l,walkthroughsActive:m,onCloseAccount:()=>r(!1)}),e?.state==="signed_in"&&f?S.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",disabled:C,onClick:async()=>{R(!0);try{await f(),r(!1)}catch{}finally{R(!1)}},children:[S.jsx(n8,{size:15}),S.jsx("span",{children:C?"Logging out…":"Log out"})]}):null]}):null]})}function U7({sidebar:e,open:t}){const[n,a]=y.useState(!1),o=[{view:"chat",label:"Home",Icon:xP},{view:"scheduled",label:"Workflows",Icon:mP},{view:"apps",label:"Apps",Icon:uy},{view:"outputs",label:"Outputs",Icon:fP},{view:"projects",label:"Projects",Icon:sy}];async function r(l){if(a(!1),e.productArea==="chat"&&e.view===l){l==="chat"&&e.setSidebarOpen(!t);return}const m=l==="chat"?{kind:"chat",sessionId:e.selectedSessionId}:{kind:"view",view:l};await Vt(m)&&(e.setSectionMenuOpen(null),e.setView(l),l==="chat"&&e.setSidebarOpen(!0))}async function s(){await Vt({kind:"view",view:"get-started"})&&(e.setSelectedAppId(null),e.setSelectedProjectId(null),e.setSelectedSessionId(null),e.setSectionMenuOpen(null),e.setView("get-started"))}return S.jsxs("nav",{className:"desktop-navigation-rail","aria-label":"Desktop destinations",children:[S.jsxs("div",{className:"desktop-rail-destinations",children:[o.map(({view:l,label:m,Icon:d})=>{const f=e.productArea==="chat"&&e.view===l;return S.jsx("button",{type:"button","data-rail-tooltip":m,"aria-label":m,"aria-current":f?"page":void 0,"aria-expanded":l==="chat"?f&&t:void 0,className:`desktop-rail-button${f?" active":""}`,onClick:()=>{r(l)},children:S.jsx(d,{size:19})},l)}),S.jsx("button",{type:"button","data-rail-tooltip":"Console","aria-label":"Console",className:`desktop-rail-button${e.productArea==="console"?" active":""}`,"aria-expanded":e.productArea==="console"&&t,onClick:()=>{e.productArea==="console"?e.setSidebarOpen(!t):(e.onProductAreaChange("console"),e.setSidebarOpen(!0))},children:S.jsx($g,{size:19})}),[{view:"team",label:"Team chat",Icon:mp,onOpen:e.onOpenTeamChat},{view:"community",label:"Discover communities",Icon:gP,onOpen:e.discoverCommunities}].map(({view:l,label:m,Icon:d,onOpen:f})=>S.jsx("button",{type:"button","data-rail-tooltip":m,"aria-label":m,className:`desktop-rail-button${e.productArea==="chat"&&e.view===l?" active":""}`,"aria-current":e.productArea==="chat"&&e.view===l?"page":void 0,onClick:()=>{a(!1),(e.productArea!=="chat"||e.view!==l)&&f()},children:S.jsx(d,{size:19})},l))]}),S.jsx("div",{className:"desktop-rail-account",children:S.jsx(q7,{account:e.account,open:n,onOpenChange:a,railTooltip:n?void 0:"Account",organizations:e.organizations,selectedTeamId:e.teamChatOrganization?.teamId??null,onSelectTeam:e.onSelectTeam,onLogOut:e.onLogOut,walkthroughsActive:e.view==="get-started",onOpenWalkthroughs:()=>{s()},onOpenActivity:()=>{Vt({kind:"settings",section:"usage"})},onOpenSettings:()=>{Vt({kind:"settings",section:"account"})}})})]})}const z7=[/^(?:(?:type)?error:\s*)?failed to fetch\.?$/i,/^networkerror when attempting to fetch resource\.?$/i,/^load failed\.?$/i];function eA(e,t="Something went wrong."){const a=(e instanceof Error?e.message:String(e??"")).trim();return a?tA(a)?"Couldn’t connect to OpenPond.":a:t}function tA(e){const t=e.trim();return z7.some(n=>n.test(t))}const nA=y.createContext(null);function qx({children:e,showToast:t}){return S.jsx(nA.Provider,{value:t,children:e})}function B7(){return y.useContext(nA)}function Ux(e,t={}){const n=B7(),a=y.useRef(null),o=t.enabled??!0,r=t.fallback??"Something went wrong.",s=t.prefix?.trim()??"",l=e==null||e===""?null:`${s}${s?": ":""}${eA(e,r)}`;y.useEffect(()=>{if(!o||!l){a.current=null;return}a.current!==l&&(a.current=l,n?.(l,"error"))},[o,l,n])}function F7({state:e,onClose:t,onOpenBrowserUrl:n,onStart:a}){if(Ux(e?.previewError,{prefix:"Upload preview"}),Ux(e?.error,{prefix:"Cloud setup"}),!e)return null;const o=e.status==="uploading",r=e.status==="ready",s=e.status==="error",l=e.projectKind==="cloud",m=e.preview??null;return S.jsx("div",{className:"git-dialog-backdrop",role:"presentation",children:S.jsxs("section",{className:"git-dialog cloud-setup-dialog",role:"dialog","aria-modal":"true","aria-label":"Set up Cloud coding",children:[S.jsx("button",{className:"git-dialog-close",disabled:o,type:"button",onClick:t,"aria-label":"Close Cloud setup",title:"Close",children:S.jsx(Sd,{size:14})}),S.jsx("div",{className:"git-dialog-icon",children:r?S.jsx(Tu,{size:18}):S.jsx(up,{size:18})}),S.jsx("h2",{children:r?"Cloud repo ready":"Set up Cloud coding"}),S.jsx("p",{children:r?"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."}),S.jsxs("div",{className:"cloud-setup-summary",children:[S.jsxs("div",{className:"git-dialog-row",children:[S.jsx("span",{children:"Project"}),S.jsx("strong",{children:e.projectName})]}),S.jsxs("div",{className:"git-dialog-row",children:[S.jsx("span",{children:"Source"}),S.jsx("strong",{children:l?"OpenPond Git":"Local project upload"})]}),S.jsxs("div",{className:"git-dialog-row",children:[S.jsx("span",{children:"Branch"}),S.jsx("strong",{children:m?.branch??e.branch??"main"})]}),!l&&S.jsxs("div",{className:"git-dialog-row",children:[S.jsx("span",{children:"Cloud project"}),S.jsx("strong",{children:m?.targetProjectId??e.cloudProjectId??"New on upload"})]})]}),!r&&!l&&S.jsx("div",{className:"cloud-setup-upload-preview",role:"status","aria-live":"polite",children:e.previewLoading?S.jsxs(S.Fragment,{children:[S.jsx("strong",{children:"Calculating upload preview"}),S.jsx("span",{children:"Checking tracked and unignored files before anything is pushed."})]}):e.previewError?S.jsxs(S.Fragment,{children:[S.jsx("strong",{children:"Preview unavailable"}),S.jsx("span",{children:"Close and reopen setup to try the preview again."})]}):m?S.jsxs(S.Fragment,{children:[S.jsx("strong",{children:m.initializedEmptyProject?"Will initialize an empty project":`Will upload ${m.fileCount} files`}),S.jsx("span",{children:zx({byteCount:m.byteCount,skippedCount:m.skippedCount,headCommit:m.headCommit,targetProjectName:m.targetProjectName})})]}):S.jsxs(S.Fragment,{children:[S.jsx("strong",{children:"Upload preview pending"}),S.jsx("span",{children:"File count, byte count, and skipped files will appear here before upload."})]})}),o&&S.jsxs("div",{className:"cloud-setup-progress",role:"status","aria-live":"polite",children:[S.jsx(ly,{className:"cloud-setup-spinner",size:16}),S.jsx("span",{children:"Uploading source to OpenPond Git..."})]}),r&&e.upload&&S.jsxs("div",{className:"cloud-setup-upload-result",children:[S.jsx("strong",{children:e.upload.initializedEmptyProject?"Initialized empty project":`Uploaded ${e.upload.fileCount} files`}),S.jsx("span",{children:zx({byteCount:e.upload.byteCount,skippedCount:e.upload.skippedCount,headCommit:e.upload.headCommit,targetProjectName:e.upload.branch})})]}),r&&e.setupUrl&&S.jsxs("div",{className:"cloud-setup-next",children:[e.projectUrl?S.jsxs("span",{children:["Your repo is ready here:"," ",S.jsxs("a",{href:e.projectUrl,target:"_blank",rel:"noreferrer",onClick:d=>jh(d,e.projectUrl,n,{newTab:!0}),children:["Project page",S.jsx(Ih,{size:13})]})]}):S.jsx("span",{children:"Your repo is ready. Next step:"}),S.jsxs("a",{href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:d=>jh(d,e.setupUrl,n),children:["Setup the Cloud sandbox",S.jsx(Ih,{size:13})]})]}),S.jsxs("div",{className:"git-dialog-footer",children:[S.jsx("button",{className:"git-dialog-secondary",disabled:o,type:"button",onClick:t,children:r?"Done":"Cancel"}),r?e.setupUrl?S.jsxs("a",{className:"git-dialog-primary cloud-setup-primary-link",href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:d=>jh(d,e.setupUrl,n),children:["Open setup",S.jsx(Ih,{size:13})]}):null:S.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 jh(e,t,n,a={}){!t||!n||(e.preventDefault(),n(t,a))}function V7(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 zx({byteCount:e,skippedCount:t,headCommit:n,targetProjectName:a}){const o=[V7(e),`${t} skipped`],r=K7(n);return r&&o.push(`local ${r}`),o.push(a),o.join(" · ")}function K7(e){const t=e?.trim();return t?t.slice(0,7):null}const W7=y.lazy(()=>Zo(()=>import("./CommandMenu-CUNGtHwS.js"),__vite__mapDeps([4,1,2,5])).then(e=>({default:e.CommandMenu}))),G7=y.lazy(()=>Zo(()=>import("./SettingsView-BB7wCdbr.js"),__vite__mapDeps([6,1,2,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25])).then(e=>({default:e.SettingsView}))),J7=y.lazy(()=>Zo(()=>import("./NewProjectDialog-gDzX_ZIJ.js"),__vite__mapDeps([26,1,2,11,17,27])).then(e=>({default:e.NewProjectDialog}))),Z7=y.lazy(()=>Zo(()=>import("./WorkspaceGitDialogs-BJVFx_L3.js"),__vite__mapDeps([28,1,2,14,15,29,25])).then(e=>({default:e.CommitDialog}))),Y7=y.lazy(()=>Zo(()=>import("./WorkspaceGitDialogs-BJVFx_L3.js"),__vite__mapDeps([28,1,2,14,15,29,25])).then(e=>({default:e.BranchDialog})));function Q7({payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:o,onError:r,onToast:s,onBack:l,onOpenSourceSession:m,onStartRefinerAuthoring:d,onAcceptEvaluationReview:f,onOpenSkill:g,onOpenExtension:x,teamChatCurrentUserId:k,teamChatEnabled:C,teamChatNotificationMode:R,teamChatThreads:E,onTeamChatNotificationModeChange:A,onTeamChatThreadMuteChange:O,diffPanelWidth:$,diffPanelResizing:M,diffPanelExpanded:w,onDiffPanelResizeStart:P,onDiffPanelExpandedChange:j}){return S.jsx(y.Suspense,{fallback:null,children:S.jsx(G7,{payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:o,onError:r,onToast:s,onBack:l,onOpenSourceSession:m,onStartRefinerAuthoring:d,onAcceptEvaluationReview:f,onOpenSkill:g,onOpenExtension:x,teamChatCurrentUserId:k,teamChatEnabled:C,teamChatNotificationMode:R,teamChatThreads:E,onTeamChatNotificationModeChange:A,onTeamChatThreadMuteChange:O,diffPanelWidth:$,diffPanelResizing:M,diffPanelExpanded:w,onDiffPanelResizeStart:P,onDiffPanelExpandedChange:j})})}function X7({activeSessions:e,branchDialogName:t,branchDialogOpen:n,commitDialogOpen:a,commitDraft:o,commitIncludeUnstaged:r,commitMessage:s,commitNextStep:l,canPublishOpenPondProject:m,expandProject:d,newProjectBusy:f,newProjectDialogOpen:g,newProjectDirectory:x,newProjectMode:k,newProjectName:C,newProjectPath:R,projectRows:E,query:A,searchOpen:O,visibleWorkspaceDiff:$,visibleWorkspaceState:M,workspaceBusy:w,appDispatch:P,beginNewChat:j,openDefaultsSettingsFromBranchDialog:N,setBranchDialogName:z,setBranchDialogOpen:D,setCommitDialogOpen:F,setCommitDraft:te,setCommitIncludeUnstaged:ve,setCommitMessage:re,setCommitNextStep:K,setNewProjectDialogOpen:L,setNewProjectName:de,setNewProjectPath:X,setQuery:Z,setSearchOpen:pe,submitCommitDialog:ee,submitCreateWorkspaceBranch:me,submitNewProjectDialog:be}){return S.jsxs(S.Fragment,{children:[O&&S.jsx(y.Suspense,{fallback:null,children:S.jsx(W7,{open:O,query:A,projects:E,sessions:e,onQueryChange:Z,onClose:()=>{pe(!1),Z("")},onNewChat:()=>{pe(!1),Z(""),j()},onOpenProject:je=>{P({type:"selectProject",projectId:je.id}),P({type:"patch",patch:{searchOpen:!1,query:""}}),d(je.id)},onOpenSession:je=>{P({type:"selectSession",sessionId:je.id,appId:je.appId,projectId:je.workspaceKind==="local_project"&&je.workspaceId?kt("local",je.workspaceId):null}),P({type:"patch",patch:{searchOpen:!1,query:""}})}})}),g&&S.jsx(y.Suspense,{fallback:null,children:S.jsx(J7,{open:g,mode:k,name:C,path:R,directory:x,busy:f,onNameChange:de,onPathChange:X,onClose:()=>{f||L(!1)},onSubmit:be})}),a&&S.jsx(y.Suspense,{fallback:null,children:S.jsx(Z7,{open:a,branch:M?.currentBranch??null,filesChanged:$?.filesChanged??M?.changedFilesCount??0,additions:$?.additions??0,deletions:$?.deletions??0,message:s,includeUnstaged:r,nextStep:l,draft:o,busy:w,canPush:!!M?.remoteUrl,canPublish:m,onMessageChange:re,onIncludeUnstagedChange:ve,onNextStepChange:K,onDraftChange:te,onClose:()=>{w||F(!1)},onSubmit:ee})}),n&&S.jsx(y.Suspense,{fallback:null,children:S.jsx(Y7,{open:n,branchName:t,busy:w,onBranchNameChange:z,onSetPrefix:N,onClose:()=>{w||D(!1)},onSubmit:me})})]})}function aA({toast:e,onDismiss:t}){if(!e)return null;const n=!!(e.actionLabel&&e.onAction);return S.jsxs("div",{className:`app-toast ${e.tone} ${e.placement??"bottom-right"}`,role:e.tone==="error"?"alert":"status","aria-live":"polite",children:[S.jsx("span",{className:"app-toast-message",children:e.message}),n&&S.jsx("div",{className:"app-toast-actions",children:S.jsx("button",{type:"button","aria-label":e.actionLabel,onClick:()=>{t(),e.onAction?.()},children:e.actionLabel})})]})}async function mu(e,t,n){if(t.scope!==e.scope)throw new Error("Review workspace changed. Reload the assignment.");return B(e.connection,`/v1/human-review?location=${e.location}`,{method:"POST",body:JSON.stringify(Cz.parse(t)),signal:n})}function Bx(e,t,n){const a=p_.parse(e);if(a.scope!==t.scope||a.id!==n)throw new Error("Review response identity differs from the requested assignment.");return a}const eJ={inbox:async(e,t,n)=>tJ(await mu(e,{...t,endpoint:"inbox",scope:e.scope},n),e),get:async(e,t,n)=>Bx(await mu(e,{endpoint:"get",scope:e.scope,id:t},n),e,t),inspect:async(e,t,n,a,o)=>nJ(await mu(e,{endpoint:"inspect",scope:e.scope,id:t,...n===void 0?{}:{slot:n},...a?{afterId:a}:{}},o),t),command:async(e,t)=>Bx(await mu(e,{endpoint:"command",scope:e.scope,command:t}),e,t.id)};function tJ(e,t){const n=pz.parse(e);if(n.items.some(a=>a.scope!==t.scope))throw new Error("Inbox response belongs to another workspace.");return n}function nJ(e,t){const n=Rz.parse(e);if(n.some(a=>a.reviewId!==t))throw new Error("Evidence response belongs to another assignment.");return n}function aJ({context:e,onOpen:t}){const[n,a]=y.useState(null);return y.useEffect(()=>{const o=new AbortController;let r=0;async function s(){const m=++r;try{const d=await eJ.inbox(e,{view:"mine",status:"active",limit:1},o.signal);!o.signal.aborted&&m===r&&a(d.actionCount)}catch{!o.signal.aborted&&m===r&&a(null)}}a(null),s();const l=window.setInterval(()=>{document.visibilityState==="visible"&&s()},15e3);return window.addEventListener("human-review-changed",s),()=>{o.abort(),window.clearInterval(l),window.removeEventListener("human-review-changed",s)}},[e.scope,e.actorId,e.location,e.connection]),S.jsxs("button",{type:"button",className:"titlebar-icon human-review-inbox-control",title:n?`Inbox · ${n} actions`:"Inbox","aria-label":n?`Inbox, ${n} actions`:"Inbox",onClick:t,children:[S.jsx(my,{size:17,"aria-hidden":"true"}),n?S.jsx("span",{className:"human-review-inbox-count","aria-hidden":"true",children:n>99?"99+":n}):null]})}function iJ({connection:e,teamId:t,actorId:n,projectId:a}){if(!e||!t||!n)return null;const o=()=>{Ar(Fa("inbox",null,{area:"console",projectId:a}))};return S.jsx(aJ,{context:{connection:e,scope:t,actorId:n,location:"hosted"},onOpen:o})}const kd=y.createContext(null);function oJ({children:e}){const[t,n]=y.useState(null),[a,o]=y.useState(null),[r,s]=y.useState(null),l=y.useMemo(()=>({title:t,actions:a,activity:r,setTitle:n,setActions:o,setActivity:s}),[t,a,r]);return S.jsx(kd.Provider,{value:l,children:e})}function Eoe({children:e}){return S.jsx(kd.Provider,{value:null,children:e})}function rJ({children:e,className:t=""}){const n=y.useContext(kd);return S.jsx("div",{ref:n?.setTitle,className:`page-chrome-title-target ${t}`,children:e?S.jsx("div",{className:"page-chrome-fallback",children:e}):null})}function sJ({className:e=""}){const t=y.useContext(kd);return S.jsx("div",{ref:t?.setActions,className:e})}function Moe({title:e,actions:t,fallback:n,children:a}){const o=y.useContext(kd);return o?S.jsxs(S.Fragment,{children:[o.title?vm.createPortal(S.jsx("div",{className:"page-chrome-title",children:e}),o.title):null,o.actions&&t?vm.createPortal(t,o.actions):null,a]}):n??S.jsxs("header",{children:[e,t]})}const lJ=y.lazy(()=>Zo(()=>import("./WorkspaceEnvironmentMenu-B-K9XgFB.js"),__vite__mapDeps([30,1,2,21,27,12,15,31,29,32])).then(e=>({default:e.WorkspaceEnvironmentMenu})));function cJ({sidebarOpen:e,sidebarAvailable:t=!0,title:n,breadcrumbs:a,backAction:o,workspaceName:r,workspaceId:s,busy:l,workspaceState:m,workspaceKind:d,selectedApp:f,selectedProject:g,workspaceDiff:x,managedWorkspace:k,workspaceBusy:C,defaultTeamId:R,activityActorId:E,activityProjectId:A,showDiffControls:O,diffPanelOpen:$,terminalOpen:M,rightSidebarAvailable:w=!1,rightSidebarOpen:P=!1,onToggleDiffPanel:j,onToggleRightSidebar:N,onOpenSearch:z,onToggleTerminal:D,onRunTerminalCommand:F,onWorkspaceToolAction:te,onOpenCommitDialog:ve,onWorkspaceBranchChange:re,onWorkspaceBranchCreate:K,connection:L,onBootstrap:de,onOpenSandboxWorkspace:X,onShowSidebar:Z,platform:pe,showWorkspaceControls:ee=!0}){const me=x?.filesChanged??0;return S.jsxs("header",{className:"app-titlebar",children:[S.jsxs("div",{className:"titlebar-left",children:[t&&!e&&S.jsx("button",{className:"titlebar-icon",title:"Show sidebar",onClick:Z,children:S.jsx(vP,{size:16})}),o?S.jsx("button",{className:"titlebar-icon",type:"button","aria-label":o.label,title:o.label,onClick:o.onSelect,children:S.jsx(uW,{size:16})}):null,S.jsx(rJ,{children:a?.length?S.jsx("nav",{className:"titlebar-breadcrumbs","aria-label":"Breadcrumb",children:a.map((be,je)=>{const ke=je===a.length-1;return S.jsxs("div",{className:"titlebar-breadcrumb-item",children:[be.onSelect&&!ke?S.jsx("button",{type:"button",onClick:be.onSelect,children:be.label}):S.jsx("strong",{children:be.label}),!ke&&S.jsx(Jo,{size:14})]},`${be.label}-${je}`)})}):S.jsxs("div",{className:"titlebar-title",children:[S.jsx("strong",{children:n}),r&&S.jsx("span",{children:r})]})})]}),S.jsxs("div",{className:"titlebar-right",children:[S.jsx(sJ,{className:"page-chrome-actions"}),S.jsx(iJ,{connection:L,teamId:R??null,actorId:E??null,projectId:A??null}),ee&&S.jsxs("div",{className:"titlebar-actions",children:[S.jsx(y.Suspense,{fallback:null,children:S.jsx(lJ,{mode:"topbar",busy:l,workspaceState:m,workspaceId:s,workspaceKind:d,selectedApp:f,selectedProject:g,workspaceBusy:C,defaultTeamId:R,workspaceDiff:x,managedWorkspace:k,showDiffControls:O,diffPanelOpen:$,onToggleDiffPanel:j,onRunTerminalCommand:F,onWorkspaceToolAction:te,onOpenCommitDialog:ve,onWorkspaceBranchChange:re,onWorkspaceBranchCreate:K,connection:L,onBootstrap:de,onOpenSandboxWorkspace:X})}),S.jsx("button",{type:"button",className:"titlebar-icon",title:"Search chats and projects","aria-label":"Search chats and projects",onClick:z,children:S.jsx(l8,{size:16})}),S.jsx("button",{type:"button",className:`titlebar-icon ${M?"active":""}`,title:`${M?"Hide":"Show"} terminal`,"aria-label":`${M?"Hide":"Show"} terminal`,"aria-pressed":M,onClick:D,children:S.jsx(yP,{size:16})}),O&&S.jsx("button",{type:"button",className:`topbar-diff-button ${P?"active":""}`,title:`${P?"Hide":"Show"} sidebar${me?`, ${me} changed files`:""}`,"aria-label":`${P?"Hide":"Show"} sidebar`,"aria-pressed":P,onClick:j,children:S.jsx(Og,{size:16})})]}),w&&N&&!O?S.jsx("div",{className:"titlebar-actions",children:S.jsx("button",{type:"button",className:`topbar-diff-button ${P?"active":""}`,title:`${P?"Hide":"Show"} sidebar`,"aria-label":`${P?"Hide":"Show"} sidebar`,"aria-pressed":P,onClick:N,children:S.jsx(Og,{size:16})})}):null,S.jsx(x8,{platform:pe})]})]})}function dJ(){const[e,t]=y.useState(null),n=y.useRef(null),a=y.useCallback(r=>new Promise(s=>{n.current?.resolve(!1);const l={...r,cancelLabel:r.cancelLabel??"Cancel",tone:r.tone??"default",resolve:s};n.current=l,t(l)}),[]),o=y.useCallback(r=>{const s=n.current;n.current=null,t(null),s?.resolve(r)},[]);return{confirmAction:a,confirmDialog:e,resolveConfirmDialog:o}}function uJ({state:e,onResolve:t}){const n=y.useId(),a=y.useId();if(y.useEffect(()=>{if(!e)return;function r(s){s.key==="Escape"&&t(!1)}return document.addEventListener("keydown",r),()=>document.removeEventListener("keydown",r)},[t,e]),!e)return null;const o=e.tone==="danger"?"git-dialog-primary danger":"git-dialog-primary";return S.jsx("div",{className:"git-dialog-backdrop",role:"presentation",onMouseDown:()=>t(!1),children:S.jsxs("section",{className:"git-dialog project-confirm-dialog",role:"alertdialog","aria-modal":"true","aria-labelledby":n,"aria-describedby":a,onMouseDown:r=>r.stopPropagation(),children:[S.jsx("h2",{id:n,children:e.title}),S.jsx("p",{id:a,children:e.body}),S.jsxs("div",{className:"git-dialog-footer",children:[S.jsx("button",{type:"button",className:"git-dialog-secondary",onClick:()=>t(!1),children:e.cancelLabel}),S.jsx("button",{type:"button",className:o,autoFocus:!0,onClick:()=>t(!0),children:e.confirmLabel})]})]})})}function mJ(){const{confirmAction:e,confirmDialog:t,resolveConfirmDialog:n}=dJ();return{confirmProjectAction:y.useCallback(o=>e({tone:"danger",...o}),[e]),projectConfirmDialog:t,resolveProjectConfirmDialog:n}}function pJ({state:e,onResolve:t}){return S.jsx(uJ,{state:e,onResolve:t})}const ym=new Map,fJ=(e,t,n)=>{const a=ym.get(e)??{commits:0,maxActualDurationMs:0,totalActualDurationMs:0};a.commits+=1,a.maxActualDurationMs=Math.max(a.maxActualDurationMs,n),a.totalActualDurationMs+=n,ym.set(e,a)};function hJ({children:e,id:t}){return S.jsx(y.Profiler,{id:t,onRender:fJ,children:e})}typeof window<"u"&&(window.__OPENPOND_RENDER_COMMITS__={get:()=>Object.fromEntries([...ym.entries()].map(([e,t])=>[e,{...t}])),reset:()=>ym.clear()});const gJ=y.lazy(()=>Zo(()=>import("./MainPane-LaEtxydD.js").then(e=>e.q),__vite__mapDeps([33,1,2,14,34,9,31,11,12,35])).then(e=>({default:e.MainPane})));function vJ({className:e,style:t,sidebar:n,topBar:a,mainPane:o,cloudSetup:r,projectConfirm:s,lazyPanels:l,toast:m}){return S.jsx(oJ,{children:S.jsxs("div",{className:e,style:t,children:[S.jsx(U7,{sidebar:n,open:a.sidebarOpen}),a.sidebarAvailable!==!1?S.jsxs(hJ,{id:"sidebar",children:[S.jsx(j7,{...n,open:a.sidebarOpen}),a.sidebarOpen?S.jsx("div",{className:"sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",onPointerDown:n.onSidebarResizeStart}):null]}):null,S.jsxs("div",{className:"content-shell",children:[S.jsx(cJ,{...a}),S.jsx(y.Suspense,{fallback:S.jsx("main",{className:"main-pane","aria-busy":"true","aria-label":"Loading workspace"}),children:S.jsx(gJ,{...o})})]}),S.jsx(F7,{...r}),S.jsx(pJ,{...s}),S.jsx(X7,{...l}),S.jsx(aA,{...m})]})})}function bJ({settings:e,toast:t}){return S.jsxs(S.Fragment,{children:[S.jsx(Q7,{...e}),S.jsx(aA,{...t})]})}const Hu="OpenPond".split("");function yJ({visibleLetterCount:e=Hu.length}){const t=Hu.slice(0,Math.max(0,Math.min(e,Hu.length)));return S.jsxs("div",{className:"app-splash-lockup",children:[S.jsx("div",{className:"app-splash-mark",children:S.jsx("img",{alt:"OpenPond",className:"app-splash-logo",decoding:"async",src:Ay})}),S.jsx("span",{"aria-hidden":"true",className:`app-splash-wordmark${t.length>0?" is-visible":""}`,children:t.map((n,a)=>S.jsx("span",{className:"app-splash-letter",children:n},`${n}-${a}`))})]})}const Oh=Hu.length,SJ=520,xJ=240;function Fx(){return typeof window>"u"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function kJ({startup:e}){const[t,n]=y.useState(()=>Fx()?Oh:0);return y.useEffect(()=>{if(Fx()){n(Oh);return}const a=Array.from({length:Oh},(o,r)=>window.setTimeout(()=>n(r+1),SJ+xJ*r));return()=>{a.forEach(o=>window.clearTimeout(o))}},[]),S.jsxs("main",{className:"app-splash","aria-busy":"true","aria-label":e.label,role:"status",children:[S.jsx(yJ,{visibleLetterCount:t}),S.jsx("span",{className:"app-splash-status",children:e.label})]})}const Ey=5e3;function io(e,t){if(e.length===0)return t;if(t.length===0)return e;const n=new Set,a=[];for(const o of[...e,...t])n.has(o.id)||(n.add(o.id),a.push(o));return a}function ao(e,t,n=Ey){return Lu(io(e,t),n)}function Lu(e,t=Ey){return e.length<=t?e:e.slice(e.length-t)}function wJ(e,t,n){return n.length===0?e:{...e,[t]:io(e[t]??[],n)}}function IJ(e,t){if(t.length===0)return Lu(e);if(e.length===0)return Lu(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 Lu([...n.values()].sort((o,r)=>CJ(o,r)).map(({event:o})=>o))}function Sm(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 _J(e){let t=null;for(const n of e)n.sequence!==void 0&&(t===null||n.sequence<t)&&(t=n.sequence);return t}function CJ(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),r=Date.parse(t.event.timestamp);if(Number.isFinite(o)&&Number.isFinite(r)){const s=o-r;if(s!==0)return s}return e.index-t.index}function Vx(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 RJ(e){return e===null?"unknown":e>=85?"high":e>=65?"medium":"low"}function Kx(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 PJ(e){return e==="codex"}function AJ(e){return e==="openpond"}function iA(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="session.context.updated")continue;const a=ND.safeParse(n.data);if(a.success)return a.data}return null}function oA(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)),r=`${o}% full`,s=`${Vx(n)} / ${Vx(a)} tokens used`;return{usedTokens:n,maxTokens:a,percent:o,summary:r,tokensLabel:s,detail:Kx(e.preferences,o),tooltip:`Context window: ${r} ${s}. ${Kx(e.preferences,o)}`,tone:RJ(o)}}if(PJ(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(!AJ(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 My(e){let t=!1;const n=rA(e);for(let a=e.length-1;a>=0;a-=1){const o=e[a];if(TJ(o)){t=!0;continue}const r=il(o?.data);if(!(o?.name!=="diagnostic"||!r)){if(r.kind==="thread_goal_cleared")return null;if(r.kind==="thread_goal"){const s=jy(il(r.goal),ga(r.provider),n);if(s){const l=Fc(s);return t&&l.tone==="active"?null:l}}if(r.kind==="goal_context"){const s=lA(o.output??"",ga(r.provider)??"codex",n);if(s){const l=Fc(s);return t&&l.tone==="active"?null:l}}}}return null}function xm(e){const t=rA(e);for(let n=e.length-1;n>=0;n-=1){const a=e[n],o=il(a?.data);if(!(a?.name!=="diagnostic"||!o)){if(o.kind==="thread_goal_cleared"&&o.synthetic!==!0)return null;if(o.kind==="thread_goal"){const r=jy(il(o.goal),ga(o.provider),t);if(!r)continue;const s=Fc(r);return s.tone==="active"?s:null}if(o.kind==="goal_context"){const r=lA(a.output??"",ga(o.provider)??"codex",t);if(!r)continue;const s=Fc(r);return s.tone==="active"?s:null}}}return null}function $h(e){const t=il(il(e)?.codexGoalRuntime),n=jy(t,ga(t?.provider)??"codex");if(!n)return null;const a=Fc(n);return a.tone==="active"?a:null}function TJ(e){return e?.name==="turn.completed"||e?.name==="turn.interrupted"||e?.name==="turn.failed"}function Fc(e){const t=cA(e.status),n=mA(e.timeUsedSeconds),a=`Goal ${n}`,o=e.tokensUsed===null?null:e.tokenBudget===null?`${Nh(e.tokensUsed)} tokens`:`${Nh(e.tokensUsed)} / ${Nh(e.tokenBudget)} tokens`,r=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:r,tooltip:`Goal runtime: ${pA(e.timeUsedSeconds)}. ${r}. ${e.objective}`,tone:t.tone,observedAt:e.observedAt}}function EJ(e,t){if(!e||e.tone!=="active"||!e.observedAt)return e;const n=sA(e.observedAt,t);if(n<=0)return e;const a=e.timeUsedSeconds+n,o=mA(a);return{...e,timeUsedSeconds:a,timeLabel:o,label:`Goal ${o}`,tooltip:`Goal runtime: ${pA(a)}. ${e.detail}. ${e.objective}`,observedAt:t}}function jy(e,t=null,n=null){if(!e)return null;const a=ga(e.objective)??"Active goal",o=ga(e.status)??"active";if((Wg(t)??Wg(ga(e.provider)))!=="codex")return null;const s=n??ga(e.updatedAt)??ga(e.updated_at)??null,l=bs(e.timeUsedSeconds)??bs(e.time_used_seconds)??0,m=ga(e.activeSinceAt)??ga(e.active_since_at),d=cA(o).tone==="active"?sA(m??ga(e.createdAt)??ga(e.created_at),s):0,f=m?l+d:Math.max(l,d),g=bs(e.tokensUsed)??bs(e.tokens_used),x=bs(e.tokenBudget)??bs(e.token_budget);return{objective:a,status:o,statusLabel:uA(o),timeUsedSeconds:Math.max(0,Math.floor(f)),tokensUsed:g===null?null:Math.max(0,Math.floor(g)),tokenBudget:x===null?null:Math.max(0,Math.floor(x)),observedAt:s}}function rA(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 sA(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 lA(e,t=null,n=null){if(!e.trim()||Wg(t)!=="codex")return null;const a=dA(e,"Status")??"active",o=Wl(e,"Tokens used"),r=Wl(e,"Token budget"),s=Wl(e,"Time used seconds")??Wl(e,"Time spent pursuing goal")??Wl(e,"Elapsed seconds")??0;return{objective:Wx(e,"objective")??Wx(e,"untrusted_objective")??"Active goal",status:a,statusLabel:uA(a),timeUsedSeconds:Math.max(0,Math.floor(s)),tokensUsed:o,tokenBudget:r,observedAt:n}}function cA(e){switch(MJ(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 MJ(e){return e.trim().toLowerCase().replace(/[-\s]+/g,"_")}function dA(e,t){const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^\\s*-?\\s*${n}:\\s*(.+?)\\s*$`,"im").exec(e)?.[1]?.trim()||null}function Wl(e,t){const n=dA(e,t);if(!n)return null;const a=n.replace(/,/g,""),o=/-?\d+(?:\.\d+)?/.exec(a);if(!o)return null;const r=Number(o[0]);return Number.isFinite(r)?r:null}function Wx(e,t){return new RegExp(`<${t}>\\s*([\\s\\S]*?)\\s*<\\/${t}>`,"i").exec(e)?.[1]?.trim()||null}function uA(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function mA(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 pA(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 Nh(e){if(e<1e3)return String(e);if(e>=1e6){const n=e/1e6;return n<10?`${Gx(n,2)}M`:n<100?`${Gx(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 Gx(e,t){return e.toFixed(t).replace(/\.?0+$/,"")}function il(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ga(e){return typeof e=="string"&&e.trim()?e.trim():null}function Wg(e){return e?.trim().toLowerCase()||null}function bs(e){return typeof e=="number"&&Number.isFinite(e)?e:null}const jJ=new Set(["planning","applying_source","running_checks","evaluating","pushing_hosted","running_hosted_checks"]),OJ=new Set(["awaiting_questions","awaiting_plan_approval","paused"]);function Gg(e){const t=fA(e);return t?HJ(t):null}function fA(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="create_improve.updated")continue;const a=DJ(BJ(n.data));if(a)return a}return null}function $J(e){if(e.events)return fA(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 NJ(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 DJ(e){const t=Qc.safeParse(e?.createImproveRun);return t.success?t.data:null}function HJ(e){const t=LJ(e);if(!t)return null;const n=qJ(e.createdAt,e.updatedAt),a=e.blockedReason??UJ(e.state);return{objective:e.objective,status:e.state,timeUsedSeconds:n,tokensUsed:null,tokenBudget:null,actionLabel:t.actionLabel,timeLabel:zJ(n),label:t.actionLabel,detail:a,tooltip:`${t.actionLabel}: ${a}. ${e.objective}`,tone:t.tone}}function LJ(e){const t=e.state,n=e.target.kind==="agent"?"Agent":"Work";return jJ.has(t)?{tone:"active",actionLabel:`${n} running`}:OJ.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 qJ(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 UJ(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function zJ(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 BJ(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function hA(e,t){if(!t)return null;const n=new Map,a=[];for(const M of e){if(!M.name.startsWith("subagent."))continue;const w=KJ(M);w&&a.push(w);const P=VJ(M);P?.parentSessionId===t&&n.set(P.id,P)}if(n.size===0)return null;const o=[...n.values()].sort((M,w)=>Ss(w).localeCompare(Ss(M))),r=o.filter(M=>M.status==="queued"||M.status==="running"),s=o.filter(M=>M.status==="completed"),l=o.filter(M=>M.status==="failed"),m=o.filter(M=>M.status==="cancelled"),d=o.filter(M=>M.status==="needs_resume"),f=[...s,...l,...m].sort((M,w)=>Ss(w).localeCompare(Ss(M))),g=o.reduce((M,w)=>{const P=ol(w.metadata?.usage);return M.totalTokens+=fu(P?.totalTokens),M.promptTokens+=fu(P?.promptTokens),M.completionTokens+=fu(P?.completionTokens),M.requestCount+=fu(P?.requestCount),M},{totalTokens:0,promptTokens:0,completionTokens:0,requestCount:0}),x=o.flatMap(M=>gA([...M.report?.blockers??[],M.error,M.progress.currentBlocker]).map(w=>({runId:M.id,roleId:M.roleId,status:M.status,message:w}))),k=o.flatMap(M=>vA([...M.report?.artifacts??[],M.report?.patchRef,M.report?.diffRef,...M.progress.patchRefs]).map(w=>({...w,runId:M.id,roleId:M.roleId}))),C=f.map(M=>FJ(M,a)),R=o[0]??null,E=R?{runId:R.id,roleId:R.roleId,status:R.status,message:R.progress.latestMeaningfulActivity||R.report?.summary||R.objective,updatedAt:Ss(R)}:null,A=r.length>0?`${r.length} ${r.length===1?"child":"children"} running`:`${f.length} ${f.length===1?"child":"children"} finished`,O=[r.length?`${r.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(" · "),$=E?`${JJ(E.roleId)}: ${E.message}`:"";return{sessionId:t,runs:o,activeRuns:r,completedRuns:s,failedRuns:l,cancelledRuns:m,needsResumeRuns:d,terminalRuns:f,latestRun:R,latestMeaningfulUpdate:E,activeCount:r.length,completedCount:s.length,failedCount:l.length,cancelledCount:m.length,needsResumeCount:d.length,terminalCount:f.length,usage:g,blockers:x,evidenceRefs:k,finalResults:C,testsRunCount:o.reduce((M,w)=>M+w.progress.validationAttempts.length,0),label:A,tooltip:[O,$].filter(Boolean).join(". ")}}function FJ(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:vA([...e.report?.artifacts??[],e.report?.patchRef,e.report?.diffRef]),testsRun:e.report?.testsRun??[],validationAttempts:e.progress.validationAttempts.map(n=>n.command),blockers:gA([...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:WJ(e),updatedAt:Ss(e)}}function VJ(e){const t=ol(e.data),n=[t?.run,ol(t?.message)?.run];for(const a of n){const o=pw.safeParse(a);if(o.success)return o.data}return null}function KJ(e){const t=nN.safeParse(ol(e.data)?.message);return t.success?t.data:null}function WJ(e){const t=ol(ol(e.metadata?.workspaceHandoff)?.workspaceRetention);return t?.status!=="retained"?null:{status:"retained",reason:pu(t.reason),retainedAt:pu(t.retainedAt),expiresAt:pu(t.expiresAt),retentionDays:GJ(t.retentionDays),trigger:pu(t.trigger),cleanupAfterExpiry:t.cleanupAfterExpiry===!0}}function Ss(e){return e.updatedAt??e.completedAt??e.startedAt??e.createdAt}function gA(e){return[...new Set(e.map(t=>t?.trim()).filter(t=>!!t))]}function vA(e){const t=new Map;for(const n of e)n&&t.set(`${n.kind}:${n.id}`,n);return[...t.values()]}function ol(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function pu(e){return typeof e=="string"&&e.trim()?e.trim():null}function fu(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function GJ(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function JJ(e){return e.slice(0,1).toUpperCase()+e.slice(1).replace(/[-_]+/g," ")}const Jg=[];function Zg(e,t){return bA(e,t,null)}function bA(e,t,n){const a=n&&eZ(n.events,e)?YJ(n.indexes,n.events.length,e):ZJ(e),o=XJ(t);return{...a,...o}}function ZJ(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 QJ(t)}function YJ(e,t,n){const a=new Map(e.eventsBySessionId),o=new Map(e.latestContextUsageBySessionId),r=new Map(e.latestGoalRuntimeBySessionId),s=new Map(e.latestSubagentRuntimeBySessionId),l=new Set(e.activeGoalSessionIds),m=new Set(e.activeSubagentSessionIds),d=new Set;for(let f=t;f<n.length;f+=1){const g=n[f];if(!g.sessionId)continue;if(d.has(g.sessionId)){a.get(g.sessionId).push(g);continue}const x=a.get(g.sessionId);a.set(g.sessionId,x?[...x,g]:[g]),d.add(g.sessionId)}for(const f of d){const g=a.get(f)??Jg,x=iA(g);x?o.set(f,x):o.delete(f);const k=SA(g);k?(r.set(f,k),k.tone==="active"?l.add(f):l.delete(f)):(r.delete(f),l.delete(f));const C=hA(g,f);C?(s.set(f,C),yA({sessionEvents:g,sessionId:f,latestGoalRuntimeBySessionId:r,activeGoalSessionIds:l}),C.activeCount>0?m.add(f):m.delete(f)):(s.delete(f),m.delete(f))}return{eventsBySessionId:a,latestContextUsageBySessionId:o,latestGoalRuntimeBySessionId:r,latestSubagentRuntimeBySessionId:s,activeGoalSessionIds:l,activeSubagentSessionIds:m}}function QJ(e){const t=new Map,n=new Map,a=new Map,o=new Set,r=new Set;for(const[s,l]of e){const m=iA(l);m&&t.set(s,m);const d=SA(l);d&&(n.set(s,d),d.tone==="active"&&o.add(s))}for(const[s,l]of e){const m=hA(l,s);m&&(a.set(s,m),yA({sessionEvents:l,sessionId:s,latestGoalRuntimeBySessionId:n,activeGoalSessionIds:o}),m.activeCount>0&&r.add(s))}return{eventsBySessionId:e,latestContextUsageBySessionId:t,latestGoalRuntimeBySessionId:n,latestSubagentRuntimeBySessionId:a,activeGoalSessionIds:o,activeSubagentSessionIds:r}}function yA(e){if(e.latestGoalRuntimeBySessionId.has(e.sessionId))return;const t=xm(e.sessionEvents);t&&(e.latestGoalRuntimeBySessionId.set(e.sessionId,t),t.tone==="active"&&e.activeGoalSessionIds.add(e.sessionId))}function SA(e){return Gg(e)??My(e)??xm(e)}function XJ(e){const t=new Map,n=new Map,a=new Map,o=new Map;for(const r of e){t.set(r.id,r);const s=n.get(r.status);if(s?s.push(r):n.set(r.status,[r]),r.status!=="pending")continue;const l=a.get(r.sessionId);l?l.push(r):a.set(r.sessionId,[r]);const m=o.get(r.sessionId);(!m||Jx(r.createdAt)>Jx(m.createdAt))&&o.set(r.sessionId,r)}return{approvalsById:t,approvalsByStatus:n,pendingApprovalsBySessionId:a,latestPendingApprovalBySessionId:o}}function eZ(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 wd(e,t){return t?e.eventsBySessionId.get(t)??Jg:Jg}function xA(e,t){return t?e.latestContextUsageBySessionId.get(t)??null:null}function kA(e,t){return t?e.latestGoalRuntimeBySessionId.get(t)??null:null}function tZ(e,t){return t?e.latestSubagentRuntimeBySessionId.get(t)??null:null}function nZ(e,t){return t?e.latestPendingApprovalBySessionId.get(t)??null:null}function Jx(e){const t=Date.parse(e);return Number.isFinite(t)?t:Number.NEGATIVE_INFINITY}function aZ(e,t){return e?.conversationId===t}function iZ(e,t){return e?.id===t?null:e}function oZ(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 r of n.resourceFiles)t.add(o?`${o}/${r}`:r)}return{name:`${e.owner}/${e.repo}`,description:`${e.skills.length} installed skill${e.skills.length===1?"":"s"} from GitHub.`,scope:"extension",packagePath:e.sourcePath,files:[...t]}}function rZ(e){return JSON.stringify([e.source,e.repositoryId,e.profileId])}function joe(e,t){return e.profiles.find(n=>rZ(n.ref)===t)?.ref??null}function sZ(e,t){return!!(e&&t&&e.source===t.source&&e.repositoryId===t.repositoryId&&e.profileId===t.profileId)}function Ooe(e,t){return e.profiles.find(n=>sZ(n.ref,t))?.state??null}function lZ(e,t){const n=new Map(Rq.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 cZ(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 $oe(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 wA="openpond:last-chat-task-mode";function dZ(e,t){return e==="labs"?"models":"chat"}function uZ(e){try{return e.getItem(wA)==="work"?"work":"chat"}catch{return"chat"}}function Oy(){if(typeof window>"u")return"chat";try{return uZ(Vo)}catch{return"chat"}}function mZ(e,t){try{e.setItem(wA,t==="chat"?"chat":"work")}catch{}}function pZ(e){if(!(typeof window>"u"))try{mZ(Vo,e)}catch{}}const fZ="uploaded to a different account";function IA(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 Ga(e,t){const n=IA(e,t);return n.state==="confirmed"?n.cloudProject:null}function hZ(e,t){return IA(e,t).state==="different_account"?fZ:null}function Ui(e){return e==="sandbox"||e==="sandbox_template"||e==="sandbox_app"}function _A(e={}){return{...e,workspaceTarget:"hybrid"}}function gZ(e={}){return{...e,workspaceTarget:"local"}}function zi(e){return e?.metadata?.workspaceTarget==="hybrid"}function vZ(e){return!!(e&&e.provider==="openpond"&&e.workspaceKind==="local_project"&&e.cloudProjectId&&e.title.trim().endsWith(" Cloud"))}function CA({cloudProjects:e,selectedCloudProject:t,selectedProject:n}){const a=n?.linkedSandboxProject??null,o=e?Ga(n,e):null,r=t?.id??o?.id??(e?null:a?.projectId??null),s=t?.teamId??o?.teamId??(e?null:a?.teamId??null);return!r||!s?{kind:"missing_cloud_project",message:"Upload/sync this Project to Cloud before using Hybrid."}:{kind:"ready",cloudProjectId:r,cloudTeamId:s,cwd:n?.workspacePath??null,localProjectId:n?.id??null,workspaceName:t?.name??o?.name??a?.projectName??n?.name??"Hybrid workspace"}}function RA({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:_A(),cwd:n.cwd,title:a}}function bZ(e){return y.useEffect(()=>{const t=DP(e.selectedSession);!t||e.composerDraftStore.getSnapshot()||e.composerDraftStore.set(t)},[e.composerDraftStore,e.selectedSession?.id]),y.useCallback(async t=>{const n=t.trim();if(!e.connection||!n||e.activeExperience==="chat")return!1;const a=Q8(n);try{let o;const r=e.selectedSession;if(r&&zc(r))o=await ie.patchSession(e.connection,r.id,{title:a,metadata:Ah(r.metadata,n)}),e.setSessions(s=>s.map(l=>l.id===o.id?o:l));else{const s=r?.metadata?.workspaceTarget==="hybrid"?"hybrid":r?.metadata?.workspaceTarget==="local"?"local":null,l=r?.provider??(e.selectedCloudProject?"openpond":e.activeProvider),m=r?.modelRef??(l==="openpond"?{providerId:"openpond",modelId:Ws}:{providerId:l,modelId:e.activeModel}),d=s?{workspaceTarget:s}:!r&&e.workspaceTarget==="local"?{workspaceTarget:"local"}:{};let f;if(!r&&e.workspaceTarget==="hybrid"){const g=CA({cloudProjects:e.cloudProjects,selectedCloudProject:e.selectedCloudProject,selectedProject:e.selectedProject});if(g.kind!=="ready")throw new Error(g.message);const x=RA({modelRef:m,provider:l,target:g,title:a});f={...x,experience:"work",metadata:Ah(x.metadata,n)}}else f={experience:"work",provider:l,modelRef:m,openPondCommandAccessMode:r?.openPondCommandAccessMode??e.activeOpenPondCommandAccessMode,appId:r?.appId??null,appName:r?.appName??null,workspaceKind:r?.workspaceKind??(e.selectedCloudProject?"sandbox":e.selectedProject?"local_project":void 0),workspaceId:r?.workspaceId??e.selectedCloudProject?.id??e.selectedProject?.id??null,workspaceName:r?.workspaceName??e.selectedCloudProject?.name??e.selectedProject?.name??null,localProjectId:r?.localProjectId??e.selectedProject?.id??null,cloudProjectId:r?.cloudProjectId??e.selectedCloudProject?.id??null,cloudTeamId:r?.cloudTeamId??e.selectedCloudProject?.teamId??null,cwd:r?.cwd??e.selectedProject?.workspacePath??null,metadata:Ah(d,n),title:a};o=await ie.createSession(e.connection,f),e.setSessions(g=>[o,...g])}return e.composerDraftStore.set(""),e.setMentionedAppId(null),e.setSelectedSessionId(null),e.setView("chat"),e.requestComposerFocus(),e.showToast("Task draft saved.","success"),!0}catch(o){return e.showToast(o instanceof Error?o.message:"Could not save task draft.","error"),!1}},[e.activeExperience,e.activeModel,e.activeOpenPondCommandAccessMode,e.activeProvider,e.cloudProjects,e.composerDraftStore,e.connection,e.requestComposerFocus,e.selectedCloudProject,e.selectedProject,e.selectedSession,e.setMentionedAppId,e.setSelectedSessionId,e.setSessions,e.setView,e.showToast,e.workspaceTarget])}const yZ=[];function SZ({primary:e,secondary:t}){const[n,a]=y.useState(null),o=y.useRef(new Set),[r,s]=y.useState(!1),[l,m]=y.useState(null),d=M8(),f=d?.kind==="models"&&["home","inbox","datasets","graders","experiments"].includes(d.route.page),{composerDraftStore:g,appDispatch:x,pendingTerminalCommand:k,setPendingTerminalCommand:C,terminalTabs:R,setTerminalTabs:E,trainingDetailTasksetId:A,setTrainingDetailTasksetId:O,mentionedAppId:$,setMentionedAppId:M,cloudSetupDialog:w,setCloudSetupDialog:P,rightPanelTabRequest:j,workspaceDiffPanelViewState:N,mainComposerFocusRequestId:z,requestMainComposerFocus:D,projectConfirmDialog:F,resolveProjectConfirmDialog:te,query:ve,searchOpen:re,archivedChatsOpen:K,sectionMenuOpen:L,cloudProjectsExpanded:de,sidebarOpen:X,view:Z,selectedAppId:pe,selectedProjectId:ee,selectedSessionId:me,codexPermissionMode:be,codexReasoningEffort:je,busy:ke,diffPanelOpen:ue,diffPanelExpanded:Ie,rightPanelMode:Le,activeExperience:Fe,changeNewExperience:Xe,terminalOpen:Ze,settingsSection:Be,newProjectDialogOpen:Ge,newProjectMode:Ve,newProjectName:U,newProjectPath:J,newProjectBusy:q,commitDialogOpen:oe,commitMessage:he,commitIncludeUnstaged:Re,commitNextStep:qe,commitDraft:Je,branchDialogOpen:et,branchDialogName:dt,toast:_t,labDetailNavigation:Ne,setQuery:Ye,setSearchOpen:h,setArchivedChatsOpen:V,setSectionMenuOpen:ae,setCloudProjectsExpanded:we,setChatRowsVisibleCount:fe,setSidebarOpen:Y,setView:_,setSelectedAppId:G,setSelectedProjectId:se,setSelectedSessionId:ne,setPrompt:ge,setDraftProvider:Se,setDraftModel:xe,setDraftExperience:Oe,setDiffPanelOpen:Te,setDiffPanelExpanded:Ue,setRightPanelMode:Ee,setTerminalOpen:tt,setSettingsSection:ht,setNewProjectDialogOpen:xn,setNewProjectName:xt,setNewProjectPath:Xn,setCommitDialogOpen:kn,setCommitMessage:Pn,setCommitIncludeUnstaged:Zt,setCommitNextStep:Dn,setCommitDraft:An,setBranchDialogOpen:Hn,setBranchDialogName:Un,setError:Wt,showToast:Ct,applyBootstrapPayload:Ln,bootstrap:mt,connection:Nt,startup:ea,training:$t,pinnedCollapsed:Tn,cloudProjectsCollapsed:st,chatsCollapsed:En,savedForLaterCollapsed:gi,sidebarWidth:vi,sidebarResizing:Wn,diffPanelWidth:da,diffPanelResizing:Gn,togglePinnedCollapsed:Vi,toggleCloudProjectsCollapsed:ei,toggleChatsCollapsed:wt,toggleSavedForLaterCollapsed:pn,startSidebarResize:Rt,startDiffPanelResize:ut,selectedApp:ln,selectedCloudProject:ta,selectedProject:wn,selectedProjectLinkedApp:nt,selectedSession:Q,sidebarSessions:Ae,runtimeIndexes:De,runtimeEventStore:pt,chatMentionApps:Yt,connectedAppMentions:ua,pendingApproval:bi,pendingChatUserMessages:In,account:Ki,activeModel:Jn,activeProvider:ja,appDefaults:ma,startMessage:ko,organizations:ir,teamChatOrganization:wo,teamChatTeamId:Io,teamChat:It,publishTeamProfileAgent:bl,communitySidebar:or,communityView:yl,teamAiThreadId:zr,toggleTeamAiSidebar:Sl,activeOpenPondCommandAccessMode:Wi,viewWorkspaceAppId:xl,viewWorkspaceId:Br,viewWorkspaceKind:Fr,viewWorkspaceName:Vr,selectedActionCatalog:kl,expandedProjectIds:wl,expandProject:yi,toggleProjectExpanded:Il,changeCodexPermissionMode:Kr,changeCodexReasoningEffort:Wr,changeOpenPondCommandAccessMode:_o,resolveApproval:Gr,beginNewChat:wa,beginNewChatWithTrainingModel:_l,dismissTrainingChatHandoff:rr,trainingChatHandoff:Gi,selectTrainingChatTaskForComposer:pa,chatHistoryLoadStates:Cl,loadMoreSelectedChatHistory:Rl,selectedPagedSessionEvents:Mn,activeSessions:Co,archivedSessions:Oa,pinnedSessions:ti,savedForLaterSessions:sr,savedForLaterFiles:Ro,sidebarFileBookmarks:Pl,setSidebarFileStatus:Jr,setSessions:lr,projectRows:Ji,localProjectRows:Po,cloudProjectRows:Ao,projectSessionRowsByProjectId:Zr,childSessionRowsByParentId:Yr,sidebarProjectIdBySessionId:$a,chatRows:Na,visibleChatRows:Qr,chatRowsVisibleCount:cr,sessionEvents:Si,goalRuntime:dr,subagentRuntime:Zi,visibleChatMessages:Xr,activeTerminalScope:es,terminalSummaries:ts,runningSessionIds:Al,selectedSessionRunning:ns,sidebarGoalRuntimeBySessionId:as,sidebarSubagentRuntimeBySessionId:Tl,taskDragSessionId:To,taskPreviewSessionIds:is,startTaskDrag:ur,clearTaskDrag:xi,previewTaskDrop:El,commitTaskDrop:Ml,commitTaskPreviewDrop:jl,dragItem:Ol,startPinnedDrag:ki,clearSidebarDrag:os,previewPinnedDrop:$l,commitPinnedDrop:Nl,commitPinnedPreviewDrop:Dl,commandProjectRows:Ia,contextWindowStatus:rs,pinnedRows:Hl,workspaceBusy:gt,diffBusy:cn,visibleWorkspaceState:fa,visibleWorkspaceDiff:vn,refreshVisibleWorkspaceDiff:zn,managedWorkspace:_a,canSyncActiveWorkspace:wp,canPublishOpenPondProject:Ip,projectTarget:_p,workspaceTarget:_d}=e,{title:Cp,browserConversationId:mr,handleWorkspaceDiffPanelViewStateChange:Cd,openSessionInChat:ss,changeProjectTarget:Rp,submitNewProjectDialog:Pp,changeWorkspaceBranch:Ap,openCommitDialog:Tp,openCreateWorkspaceBranchDialog:Ep,openDefaultsSettingsFromBranchDialog:Mp,runWorkspaceTool:jp,submitCommitDialog:Op,submitCreateWorkspaceBranch:$p,syncWorkspaceLocally:Np,answerCreateImproveQuestion:Rd,applyCreateImproveCandidate:Dp,approveCreateImproveRun:Hp,cancelCreateImproveRun:Lp,changeDraftProvider:Ll,openCreateImprovePullRequest:Pd,reconcileCreateImprovePullRequest:qp,rejectCreateImproveCandidate:Up,pauseCreateImproveRun:Ad,resumeCreateImproveRun:Td,reviseCreateImproveRun:zp,stopTurn:ls,archiveSession:Bp,restoreSession:Ed,renameSession:Fp,toggleSessionPinned:ql,toggleProjectPinned:Md,toggleSessionSavedForLater:jd,moveProjectToCloud:Vp,startCloudSetupUpload:Od,changeWorkspaceTarget:Kp,sendPromptFromMainComposer:Wp,openSandboxWorkspace:$d,openCloudProjectDialog:Gp,openExistingProjectPathDialog:Nd,openUrlInBrowserPanel:Jp,showBrowserPanel:Zp,showChangesPanel:Yp,showGoalSidebarTab:Eo,rightChatTrainingLaunchRequest:Dd,setRightChatTrainingLaunchRequest:Qp,closeRightChatPanel:Xp,openRightChatPanel:Ul,rightChatPanelViews:ef,showRightChatPanel:tf,showRightPanelDiffTab:nf,submitRightChatPrompt:af,activateRightChatPanel:of,updateRightChatModel:rf,updateRightChatPrompt:sf,updateRightChatProvider:lf,updateRightChatScrollState:cf,openProfileSettings:df,diagnosticEvents:uf,toggleRightSidebar:Hd,removeProject:mf}=t;qE(Nt,mt?.account.activeProfile&&mt.preferences.defaultTeamId?JSON.stringify([mt.account.baseUrl,mt.account.activeProfile,mt.account.profile?.id,mt.account.state,mt.preferences.defaultTeamId]):null,()=>{Vt({kind:"chat",sessionId:null}).then(Me=>{Me&&(ne(null),_("chat"),a("activity"))})});const ni=mt?.account.activeProfile&&mt?.preferences.defaultTeamId?`${mt.account.activeProfile.handle}:${mt.preferences.defaultTeamId}`:null;y.useEffect(()=>{if(!(!ni||Z!=="chat"||d?.kind!=="chat"||d.sessionId||me||o.current.has(ni))){o.current.add(ni);try{const Me=localStorage.getItem(`openpond:ponder-mode:v1:${ni}`);(Me==="clean"||Me==="activity")&&a(Me)}catch{}}},[ni,d,Z,me]),y.useEffect(()=>{if(!(!ni||!o.current.has(ni)))try{localStorage.setItem(`openpond:ponder-mode:v1:${ni}`,n??"off")}catch{}},[ni,n]);const cs=y.useCallback(Me=>{G(null),se(Me),ne(null),_("chat"),yi(Me),D()},[yi,D,G,se,ne,_]),pf=y.useCallback((Me=null)=>{a(null);const ft=me?$a[me]??null:null;if(!Me&&ft){cs(ft);return}wa(Me)},[wa,cs,me,$a]),ff=y.useCallback(async Me=>{if(!(!Nt||!mt))try{const ft=await ie.savePreferences(Nt,{defaultTeamId:Me});Ln({...mt,preferences:ft.preferences})}catch(ft){const Ut=ft instanceof Error?ft.message:String(ft);throw Wt(Ut),Ct("Could not switch teams","error"),ft}},[Ln,mt,Nt,Wt,Ct]),hf=y.useCallback(async()=>{if(Nt)try{const Me=await ie.signOutOpenPondAccount(Nt);Ln(Me);const ft=await ie.savePreferences(Nt,{defaultTeamId:null});Ln({...Me,preferences:ft.preferences}),Ct("Logged out","success")}catch(Me){const ft=Me instanceof Error?Me.message:String(Me);throw Wt(ft),Ct("Could not log out","error"),Me}},[Ln,Nt,Wt,Ct]),zl=Io??ma.defaultTeamId??null,gf=y.useMemo(()=>Ji.filter(Me=>Me.kind==="local"||zl!==null&&Me.project.teamId===zl),[Ji,zl]),vf=y.useMemo(()=>{const Me={};for(const ft of Co){const Ut=$a[ft.id];Ut&&(Me[Ut]=(Me[Ut]??0)+1)}for(const ft of Po){if(ft.kind!=="local")continue;const Ut=ft.project.linkedSandboxProject?.projectId;if(!Ut||!ft.cloudLinkTrusted)continue;const Da=kt("cloud",Ut);Me[ft.id]=(Me[ft.id]??0)+(Me[Da]??0)}return Me},[Co,Po,$a]),[Ld,Yi]=y.useState(null),[ds,us]=y.useState(null),bf=lZ(mt?.profile,mt?.extensionCatalog),[pr,Bl]=y.useState(null),[ms,Fl]=y.useState(null),[wi,qd]=y.useState(null),yf=y.useCallback(async()=>{await Vt({kind:"view",view:"team"})&&(G(null),se(null),ne(null),ae(null),_("team"))},[ae,G,se,ne,_]),Sf=y.useCallback(async()=>{await Vt({kind:"view",view:"community"})&&(G(null),se(null),ne(null),ae(null),or.discoverCommunities())},[or.discoverCommunities,ae,G,se,ne]),xf=bZ({activeExperience:Fe,activeModel:Jn,activeOpenPondCommandAccessMode:Wi,activeProvider:ja,cloudProjects:mt?.cloudProjects??yZ,composerDraftStore:g,connection:Nt,requestComposerFocus:D,selectedCloudProject:ta,selectedProject:wn,selectedSession:Q,setMentionedAppId:M,setSelectedSessionId:ne,setSessions:lr,setView:_,showToast:Ct,workspaceTarget:_d.value}),kf=y.useCallback(async Me=>{if(!Nt)throw new Error("OpenPond is not connected.");let ft=ja,Ut=Jn;ft==="codex"&&(ft=Vg(mt?.providers,{enabledOnly:!0}).find(jn=>jn.value!=="codex")?.value??Tr,Ut=gm(ft,mt?.providers)??wc);const Da=Ae.find(jn=>jn.id===Me.sourceSessionId),Qi=await ie.createSession(Nt,{experience:Me.target,provider:ft,modelRef:{providerId:ft,modelId:Ut},openPondCommandAccessMode:Wi,appId:null,appName:null,workspaceId:null,workspaceName:null,localProjectId:null,cloudProjectId:null,cloudTeamId:null,cwd:null,title:`Continue ${Da?.title??"task"}`.slice(0,120),metadata:{experienceHandoff:cZ({sourceTaskId:Me.sourceSessionId,sourceExperience:Da?.experience??null,targetExperience:Me.target,sourceMessageIds:Me.sourceMessageIds??[],sourceContext:Me.sourceContext,output:Me.output})}});return lr(jn=>[Qi,...jn]),Oe(Me.target),Se(ft),xe(Ut),g.set(Me.prompt),Vt({kind:"chat",sessionId:Qi.id}),x({type:"selectSession",sessionId:Qi.id,appId:null,projectId:null}),G(null),se(null),tt(!1),_("chat"),Ee("home"),Te(Me.target==="work"),Ue(!1),Qi},[Jn,Wi,ja,x,mt?.providers,g,Nt,Ue,Te,Oe,xe,Se,Ee,G,se,lr,tt,_,Ae]),wf=y.useCallback(Me=>{Bl(Me),Fl(null),wa(null),Y(!0)},[wa,Y]),If=y.useCallback(Me=>{wa(null),Oe("work"),g.set(`$openpond-refiner-authoring ${Me}`),_("chat"),Y(!0)},[wa,g,Oe,Y,_]),Ud=y.useCallback(Me=>{Fl(oZ(Me)),Bl(null),wa(null),Y(!0)},[wa,Y]);y.useEffect(()=>{!pr&&!ms||Z!=="chat"||me||ee||pe||(Yi(pr),us(ms),Bl(null),Fl(null),Ee("home"),Ue(!1),Te(!0))},[pr,ms,pe,ee,me,Ue,Te,Ee,Z]),y.useEffect(()=>{!Ld&&!ds||Z==="chat"&&ue&&Le==="home"||(Yi(null),us(null))},[ue,ds,Ld,Le,Z]);const zd=y.useCallback(()=>{Yi(null),us(null),Ue(!1),Te(!1)},[Ue,Te]),_f=y.useCallback(Me=>{let ft;if(Me.workspaceKind==="local"){const Ut=kt("local",Me.workspaceId);ft=`draft:${Ut}`,G(null),se(Ut),ne(null),yi(Ut),_("chat")}else{const Ut=Ae.find(Da=>Da.id===Me.sourceSessionId||Da.workspaceId===Me.workspaceId);if(!Ut){Ct("This saved file's cloud chat is no longer available.","error");return}ft=Ut.id,ss(Ut.id)}Ee("changes"),Te(!0),qd({id:Date.now(),conversationId:ft,file:Me}),Me.available||Ct(`File unavailable: ${Me.path}`,"error")},[yi,ss,Te,Ee,G,se,ne,_,Ct,Ae]);y.useEffect(()=>{if(!aZ(wi,mr))return;const Me=window.setTimeout(()=>{Ee("changes"),Te(!0),qd(ft=>iZ(ft,wi.id))},0);return()=>window.clearTimeout(Me)},[mr,Te,Ee,wi]);const Bd=d?.kind==="models"&&d.route.area==="console"?"console":dZ(Z);y.useEffect(()=>{if(d){if(d.kind==="models"||d.kind==="models_unavailable"){Z!=="labs"&&_("labs");return}if(d.kind==="settings"){G(null),se(null),ne(null),ht(d.section),Z!=="settings"&&_("settings");return}if(d.kind==="view"){G(null),se(null),ne(null),Z!==d.view&&_(d.view);return}d.sessionId!==null&&(a(null),G(null),se(null)),ne(d.sessionId),Z!=="chat"&&_("chat")}},[d,G,se,ne,ht,_,Z]);const Cf=y.useCallback(Me=>{if(ae(null),G(null),se(null),ne(null),Me==="models"||Me==="console"){Ar(Me==="console"?Fa("datasets",null,{area:"console"}):Fa()),_("labs");return}Me==="chat"&&Vt({kind:"chat",sessionId:null}),Xe(Oy())},[Xe,Vt,ae,G,se,ne,_]),Rf=y.useCallback(async(Me,ft)=>{const Ut=await $t.actions.acceptHarnessReview(Me,ft,{providerId:ja,modelId:Jn},je);return Ut?(O(Ut.materializedTasksetId??null),Ar(Fa()),_("labs"),!0):(Ct("Taskset review could not be opened.","error"),!1)},[Jn,ja,je,Ar,Fa,O,_,Ct,$t.actions]),it=y.useMemo(()=>RE([...De.eventsBySessionId.values()].flat()),[De.eventsBySessionId]);if(!ea.ready)return S.jsx(kJ,{startup:ea});if(Z==="settings")return S.jsx(qx,{showToast:Ct,children:S.jsx(bJ,{settings:{payload:mt,connection:Nt,diagnostics:uf,initialSection:Be,onPayload:Ln,onError:Wt,onToast:Ct,onOpenSourceSession:ss,onStartRefinerAuthoring:If,onAcceptEvaluationReview:Rf,onOpenSkill:wf,onOpenExtension:Ud,teamChatCurrentUserId:It.currentUserId,teamChatEnabled:Io!==null,teamChatNotificationMode:It.notificationMode,teamChatThreads:It.threads,onTeamChatNotificationModeChange:It.setNotificationMode,onTeamChatThreadMuteChange:It.setThreadMuted,diffPanelWidth:da,diffPanelResizing:Gn,diffPanelExpanded:Ie,onDiffPanelResizeStart:ut,onDiffPanelExpandedChange:Ue,onBack:()=>{const Me=A8(d);Vt(Me),_(Me.kind==="models"?"labs":"chat"),Y(!0)}},toast:{toast:_t,onDismiss:()=>x({type:"field",key:"toast",value:null})}})});const dn=py(),Gt=Bd==="console"||Z==="chat",Qt=Gt&&X,Ca=Nt?.platform??navigator.platform,Pf=dn&&SP(Ca),Gy=es,ET=fa?.initialized?fa.repoPath:Q?.cwd??null,MT={"--sidebar-width":`${vi}px`,"--diff-panel-width":`${da}px`},jT=Z==="chat"&&Fe!=="chat"||Z==="labs"||Z==="scheduled"&&r||Z==="team"&&!!zr,OT=["app-shell",Pf?"platform-macos":"",Qt?"sidebar-open":"sidebar-closed",Wn?"sidebar-resizing":"",Gn?"diff-panel-resizing":""].filter(Boolean).join(" "),Af=me?Cl[me]:null,$T=me?Af?.cursorSequence??_J(ao(Mn,wd(De,me))):null,NT=!!me&&!!Nt&&(Jt(me)?!0:!!mt?.eventWindow?.hasMoreBefore&&!!$T)&&(Af?.hasMore??!0),DT=!!Af?.loading,HT=(()=>{const Me=$t.payload;if(!Me)return{};const ft=new Map(Me.plans.map(jn=>[jn.id,jn])),Ut=new Set(["queued","starting","running","cancelling","reconciling"]),Da={queued:"Queued",starting:"Starting",running:"Running",cancelling:"Cancelling",reconciling:"Reconciling"},Qi={};for(const jn of[...Me.modelRuns].sort((ai,ps)=>ps.updatedAt.localeCompare(ai.updatedAt))){if(jn.kind==="evaluation"||!["prepared","running"].includes(jn.status))continue;const ai=Me.jobs.filter(Tf=>Tf.metadata.modelRunId===jn.id).sort((Tf,LT)=>LT.updatedAt.localeCompare(Tf.updatedAt))[0];if(ai&&!Ut.has(ai.status))continue;const ps=ai?.status??(jn.status==="prepared"?"starting":"running");Qi[jn.modelId]={label:Da[ps]??"Running",status:ps}}for(const jn of[...Me.jobs].sort((ai,ps)=>ps.updatedAt.localeCompare(ai.updatedAt))){if(!Ut.has(jn.status))continue;const ai=ft.get(jn.planId)?.modelId;!ai||Qi[ai]||(Qi[ai]={label:Da[jn.status]??"Active",status:jn.status})}return Qi})();return S.jsx(qx,{showToast:Ct,children:S.jsx(vJ,{className:OT,style:MT,sidebar:{activityTimes:it,onOpenPonder:()=>{Vt({kind:"chat",sessionId:null}),ne(null),_("chat"),a("activity")},productArea:Bd,modelProjects:($t.payload?.modelProjects??[]).filter(Me=>Me.hosted===null||Me.hosted.teamId===(ma.defaultTeamId?.trim()??null)),modelTrainingActivityByProjectId:HT,onProductAreaChange:Cf,experience:Fe,view:Z,selectedAppId:pe,selectedProjectId:ee,selectedSessionId:me,selectedTeamThreadId:It.selectedThreadId,teamChatEnabled:Io!==null,organizations:ir,teamChatOrganization:wo,teamChatLoading:It.loading,currentUserId:It.currentUserId,teamMembers:It.members,teamThreads:It.threads,...or,onOpenTeamChat:yf,discoverCommunities:Sf,account:Ki,connection:Nt,profile:mt?.profile,pinnedCollapsed:Tn,cloudProjectsCollapsed:st,chatsCollapsed:En,savedForLaterCollapsed:gi,archivedChatsOpen:K,cloudProjectsExpanded:de,sectionMenuOpen:L,dragItem:Ol,taskDragSessionId:To,taskPreviewSessionIds:is,activeSessions:Co,archivedSessions:Oa,pinnedRows:Hl,pinnedSessions:ti,savedForLaterSessions:sr,savedForLaterFiles:Ro,projectRows:Ji,localProjectRows:Po,cloudProjectRows:Ao,projectSessionRowsByProjectId:Zr,childSessionRowsByParentId:Yr,sidebarProjectIdBySessionId:$a,terminalSummaries:ts,runningSessionIds:Al,goalRuntimeBySessionId:as,subagentRuntimeBySessionId:Tl,visibleChatRows:Qr,chatRows:Na,chatRowsVisibleCount:cr,expandedProjectIds:wl,currentVersion:mt?.server.version??null,platform:Ca,arch:Nt?.arch??null,onSidebarResizeStart:Rt,setSidebarOpen:Y,setView:_,setSelectedAppId:G,setSelectedProjectId:se,setSelectedSessionId:ne,setSearchOpen:h,setSectionMenuOpen:ae,setSettingsSection:ht,onSelectTeam:ff,onLogOut:hf,onTogglePinnedCollapsed:Vi,onToggleCloudProjectsCollapsed:ei,onToggleChatsCollapsed:wt,onToggleSavedForLaterCollapsed:pn,setArchivedChatsOpen:V,setCloudProjectsExpanded:we,setChatRowsVisibleCount:fe,beginNewChat:pf,beginProjectChat:cs,onAddProject:Nd,dockSessionRight:Ul,selectTeamThread:Me=>{_("team"),It.selectThread(Me)},openTeamDm:Me=>{_("team"),It.openDm(Me)},toggleSessionPinned:ql,toggleProjectPinned:Md,toggleSessionSavedForLater:jd,openSidebarFile:_f,setSidebarFileStatus:(Me,ft)=>{Jr(Me,ft)},archiveSession:Bp,restoreSession:Ed,renameSession:Fp,removeProject:mf,expandProject:yi,toggleProjectExpanded:Il,startPinnedDrag:ki,clearSidebarDrag:os,previewPinnedDrop:$l,commitPinnedDrop:Nl,commitPinnedPreviewDrop:Dl,startTaskDrag:ur,clearTaskDrag:xi,previewTaskDrop:El,commitTaskDrop:Ml,commitTaskPreviewDrop:jl},topBar:{sidebarOpen:Qt,sidebarAvailable:Gt,title:Z==="chat"&&n?"Ponder Pal":Cp,backAction:Ne.backAction,breadcrumbs:Ne.breadcrumbs,workspaceName:Vr,workspaceId:Br,busy:ke,workspaceState:fa,workspaceKind:Fr,selectedApp:nt??ln,selectedProject:wn,workspaceDiff:vn,managedWorkspace:_a,workspaceBusy:gt,defaultTeamId:ma.defaultTeamId,activityActorId:mt?.account.profile?.id??null,activityProjectId:d?.kind==="models"?d.route.projectId??null:null,showDiffControls:Z==="chat"&&Fe==="development",diffPanelOpen:ue,terminalOpen:Ze,rightSidebarAvailable:jT,rightSidebarOpen:Z==="labs"&&f?l?.open??!1:Z==="scheduled"?r:ue,onToggleDiffPanel:Hd,onToggleRightSidebar:Z==="labs"&&f?l?.toggle:Z==="scheduled"?()=>s(Me=>!Me):Z==="team"&&zr?Sl:Hd,onOpenSearch:()=>{ae(null),h(!0)},onToggleTerminal:()=>tt(Me=>!Me),onRunTerminalCommand:Me=>{C({id:Date.now(),scope:Gy,command:Me}),tt(!0)},onWorkspaceToolAction:jp,onOpenCommitDialog:Tp,onWorkspaceBranchChange:Ap,onWorkspaceBranchCreate:Ep,connection:Nt,onBootstrap:Ln,onOpenSandboxWorkspace:$d,onShowSidebar:()=>Y(!0),platform:Ca,showWorkspaceControls:Z!=="team"&&Z!=="community"&&Z!=="labs"&&Z!=="scheduled"&&Z!=="outputs"&&Z!=="projects"&&(Fe==="development"||Fe==="work"&&!!(wn||Q?.localProjectId||Q?.cloudProjectId||Q?.workspaceKind==="local_project"))},mainPane:{ponderMode:n,onPonderModeChange:a,experience:Fe,onNewExperienceChange:Xe,view:Z,teamChat:{currentUserId:It.currentUserId,members:It.members,agents:It.agents,profile:mt?.profile??null,teamId:Io,teamName:wo?.displayName??null,detail:It.detail,aiThread:It.aiThread,agentConversation:It.agentConversation,loading:It.loading,busy:It.busy,error:It.error,connection:Nt,providerSettings:mt?.providers??null,provider:ja,model:Jn,codexPermissionMode:be,codexReasoningEffort:je,openPondCommandAccessMode:Wi,contextWindowStatus:rs,showToast:Ct,onProviderChange:Ll,onModelChange:xe,onCodexPermissionModeChange:Kr,onCodexReasoningEffortChange:Wr,onOpenPondCommandAccessModeChange:_o,onOpenProviderSettings:()=>{Vt({kind:"view",view:"apps"})},onSendMessage:It.sendMessage,onPublishProfileAgent:bl,onOpenAiThread:async Me=>{await It.openAiThread(Me),Ee("chat"),Te(!0)},onOpenAgentConversation:async Me=>{await It.openAgentConversation(Me),Ee("chat"),Te(!0)},onCloseAiThread:()=>Te(!1),onCloseAgentConversation:()=>{It.closeAgentConversation(),Te(!1)},onSendAgentTurn:It.sendAgentTurn,onSendAiTurn:It.sendAiTurn,onStopAiTurn:It.stopAiTurn,onEditMessage:It.editMessage,onDeleteMessage:It.deleteMessage,onRetryMessage:It.retryMessage,onDismissFailedMessage:It.dismissFailedMessage,onLoadMoreMessages:It.loadMoreMessages,onRetryLoad:It.refresh},community:yl,bootstrap:mt,runtimeEvents:Si,chatMessages:Xr,pendingUserMessage:me?In[me]??null:null,contextWindowStatus:rs,goalRuntime:dr,subagentRuntime:Zi,selectedSessionId:me,composerDraftStore:g,mainComposerFocusRequestId:z,labCloseDetailRequestId:Ne.closeDetailRequestId,labCloseDetailKind:Ne.closeDetailKind,sideChatTrainingLaunchRequest:Dd,onSideChatTrainingLaunchHandled:Me=>Qp(ft=>ft?.id===Me?null:ft),mentionApps:Yt,connectedAppMentions:ua,profileSkills:bf,selectedMentionAppId:$,busy:ke,turnRunning:ns,activeProvider:ja,activeModel:Jn,codexPermissionMode:be,codexReasoningEffort:je,openPondCommandAccessMode:Wi,pendingApproval:bi,activeWorkspaceAppId:xl,activeWorkspaceId:Br,activeWorkspaceKind:Fr,projectTarget:_p,actionCatalog:kl,workspaceTarget:_d,connection:Nt,workspaceName:Vr,workspaceState:fa,workspaceDiff:vn,workspaceBusy:gt,diffBusy:cn,forceChatThread:!!me,diffPanelOpen:ue,diffPanelExpanded:Ie,rightPanelMode:Le,rightPanelTabRequest:j,rightChatPanels:ef,runtimeEventStore:pt,nativeSkillSidebar:Ld,extensionSkillSidebar:ds,workspaceDiffPanelViewState:N,sidebarFileOpenRequest:wi,sidebarFileBookmarks:Pl,onSetSidebarFileStatus:(Me,ft)=>{Jr(Me,ft)},browserConversationId:mr,terminalScope:Gy,terminalTabs:R,terminalCwd:ET,pendingTerminalCommand:k,terminalOpen:Ze,onToggleTerminal:()=>tt(Me=>!Me),onWorkspaceDiffPanelViewStateChange:Cd,training:$t,trainingSessions:Ae,trainingChatHandoff:Gi,trainingDetailTasksetId:A,onTrainingDetailTasksetIdChange:O,onTrainingChatTaskSelect:pa,onTrainingChatHandoffDismiss:rr,onOpenSession:ss,onExperienceHandoff:kf,cloudProjects:mt?.cloudProjects??[],projects:gf,projectsAccountBaseUrl:Ki?.baseUrl??Ki?.activeProfile?.baseUrl??null,projectsTeamName:wo?.displayName??null,projectTaskCounts:vf,onNewCloudProject:Gp,onNewLocalProject:Nd,onNewProjectTask:Me=>cs(Me.id),onToggleProjectPinned:Md,onUploadLocalProject:Vp,chatHistoryHasMore:NT,chatHistoryLoading:DT,onDiffPanelResizeStart:ut,onToggleDiffPanelExpanded:()=>Ue(Me=>!Me),onShowDiffPanel:Yp,onShowBrowserPanel:Zp,onShowFilesPanel:()=>nf("files"),onShowGoalSidebarTab:Eo,onShowTrainingDraftPanel:()=>{Ee("training"),Te(!0)},onShowRightChatPanel:tf,onAddRightChat:()=>Ul(null),onOpenRightChatForSession:(Me,ft)=>{const Ut=ft??Ae.find(Da=>Da.id===Me)??null;Ut&&Ul(Ut,{preserveView:!0})},onLabDetailOpenChange:Ne.onDetailOpenChange,evaluationSidebarActive:Z==="labs"&&f,onEvaluationSidebarControl:m,scheduledDetailOpen:r,onScheduledDetailOpenChange:s,onTerminalTabsChange:E,onCloseRightChatPanel:Xp,onCloseNativeSkillSidebar:zd,onActivateRightChatPanel:of,onRightChatModelChange:rf,onRightChatPromptChange:sf,onRightChatScrollStateChange:cf,onRightChatProviderChange:lf,onSubmitRightChat:af,onStopRightChat:Me=>ls(Me),onCloseTerminal:()=>tt(!1),onLoadMoreChatHistory:Rl,canSyncWorkspace:wp,startMessage:ko,onPayload:Ln,onError:Wt,setView:_,onOpenProfileSettings:df,onOpenProviderSettings:()=>{Vt({kind:"view",view:"apps"})},onOpenTrainingSettings:()=>{Vt({kind:"settings",section:"training"})},onOpenDatasetStorageSettings:()=>{Vt({kind:"settings",section:"dataset-storage"})},changeDraftProvider:Ll,changeProjectTarget:Rp,changeWorkspaceTarget:Kp,setDraftProvider:Se,setDraftModel:xe,onBeginNewChatWithModel:_l,changeCodexPermissionMode:Kr,changeCodexReasoningEffort:Wr,changeOpenPondCommandAccessMode:_o,resolveApproval:Gr,answerCreateImproveQuestion:Rd,applyCreateImproveCandidate:Dp,approveCreateImproveRun:Hp,cancelCreateImproveRun:Lp,openCreateImprovePullRequest:Pd,reconcileCreateImprovePullRequest:qp,rejectCreateImproveCandidate:Up,pauseCreateImproveRun:Ad,resumeCreateImproveRun:Td,reviseCreateImproveRun:zp,setMentionedAppId:M,showToast:Ct,onSaveTaskDraft:xf,sendPrompt:Wp,stopTurn:Me=>ls(void 0,Me),syncWorkspaceLocally:Np,refreshWorkspaceDiff:zn},cloudSetup:{state:w,onClose:()=>P(null),onOpenBrowserUrl:Jp,onStart:()=>{Od()}},projectConfirm:{state:F,onResolve:te},lazyPanels:{activeSessions:Co,branchDialogName:dt,branchDialogOpen:et,commitDialogOpen:oe,commitDraft:Je,commitIncludeUnstaged:Re,commitMessage:he,commitNextStep:qe,canPublishOpenPondProject:Ip,connection:Nt,expandProject:yi,newProjectBusy:q,newProjectDialogOpen:Ge,newProjectDirectory:ma.defaultNewProjectDirectory,newProjectMode:Ve,newProjectName:U,newProjectPath:J,projectRows:Ia,query:ve,searchOpen:re,visibleWorkspaceDiff:vn,visibleWorkspaceState:fa,workspaceBusy:gt,appDispatch:x,beginNewChat:()=>wa(null),openDefaultsSettingsFromBranchDialog:Mp,setBranchDialogName:Un,setBranchDialogOpen:Hn,setCommitDialogOpen:kn,setCommitDraft:An,setCommitIncludeUnstaged:Zt,setCommitMessage:Pn,setCommitNextStep:Dn,setNewProjectDialogOpen:xn,setNewProjectName:xt,setNewProjectPath:Xn,setPrompt:ge,setQuery:Ye,setSearchOpen:h,submitCommitDialog:Op,submitCreateWorkspaceBranch:$p,submitNewProjectDialog:Pp},toast:{toast:_t,onDismiss:()=>x({type:"field",key:"toast",value:null})}})})}const js=new Map,qu=new Map;function Yg(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 xZ(e){const t=e?.trim();if(!t)return null;const n=js.get(t);return n?.updatedAt?n.organizations:null}function kZ(e,t){const n=e?.trim();if(n){js.set(n,{organizations:t,promise:null,updatedAt:Date.now()});for(const a of qu.get(n)??[])a()}}function wZ(e,t){const n=e?.trim();if(!n)return()=>{};const a=qu.get(n)??new Set;return a.add(t),qu.set(n,a),()=>{a.delete(t),a.size===0&&qu.delete(n)}}function Zx(e){const t=e.accountKey?.trim();if(!t)return Promise.resolve([]);const n=js.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=>(kZ(t,o),o)).catch(o=>{const r=js.get(t);throw r?.promise===a&&js.set(t,{organizations:r.organizations,promise:null,updatedAt:r.updatedAt}),o});return js.set(t,{organizations:n?.organizations??[],promise:a,updatedAt:n?.updatedAt??0}),a}const Noe="openpond.config.json";function Doe(e,t,n){return t<=0?-1:n==="Home"?0:n==="End"?t-1:n==="ArrowRight"?(e+1)%t:(e-1+t)%t}function PA(){return{activeTab:"files",openFilePaths:[],selectedPath:null}}function Dh(e){return{activeTab:e.activeTab,openFilePaths:[...e.openFilePaths],selectedPath:e.selectedPath}}function Hoe(e,t=null){const n=_Z(e.openFilePaths.map(o=>Qx(o,t)).filter(Boolean)),a=e.selectedPath&&Qx(e.selectedPath,t)||null;return{activeTab:e.activeTab==="file"&&!a?"files":e.activeTab,openFilePaths:n,selectedPath:a}}function Yx(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 Qx(e,t=null){let n=IZ(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 Loe(e){return e.startsWith("/")||/^[A-Za-z]:\//.test(e)}function qoe(e){return{path:e,status:"unchanged",additions:0,deletions:0,patch:"",content:null}}function Uoe(e,t){const n=Xx(e.path);return!n||e.path.endsWith("/")||e.content==null&&/Could not access .+\/null['"]?/.test(e.patch)?!0:t.some(a=>{const o=Xx(a);return!!(o&&o.startsWith(`${n}/`))})}function zoe(e){return/\.(?:md|markdown|mdx)$/i.test(e)||/(?:^|\/)readme$/i.test(e)}function Boe(e){return/\.(?:doc|docx|pdf)$/i.test(e)}function IZ(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 _Z(e){return Array.from(new Set(e))}function Xx(e){const n=e.replace(/\\/g,"/").replace(/^\.\/+/,"").split("/").filter(Boolean);return n.length===0?null:n.join("/")}function CZ(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??"",r=e.apiBaseUrl??t?.apiBaseUrl??"",s=e.chatApiBaseUrl??t?.chatApiBaseUrl??"";return[n?`profile:${n}`:"profile:unknown",a,o,r,s].join("|")}function AA(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"cloud-project"}function RZ(e){const t=new TextEncoder().encode(e);let n="";for(const a of t)n+=String.fromCharCode(a);return btoa(n)}function gp(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||AA(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 PZ(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 AZ(e,t){const n=e.filter(o=>o.status==="active"&&o.workspaceKind==="shared"),a=t?.trim()??"";if(a){const o=n.find(r=>r.teamId===a);if(o)return o}return n.find(o=>o.role==="owner")??n.find(o=>o.role==="admin")??n[0]??null}function TZ(...e){for(const t of e){const n=t?.trim();if(n)return n}return""}function EZ({draftProvider:e,hasSelectedCloudProject:t,selectedSessionHybridWorkspace:n}){return t&&!n?"openpond":e}const MZ=[{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 jZ(...e){return TZ(...e.map(t=>{const n=t?.trim();return n&&!n.includes("@")?n:null}))}function OZ(e){if(e?.state!=="signed_in")return"";const t=e.accounts.find(n=>n.isActive)??null;return jZ(e.profile?.name,e.label,t?.displayLabel,e.profile?.handle,t?.handle,e.activeProfile?.handle)}function $Z({bootstrap:e,draftModel:t,draftProvider:n,selectedApp:a,selectedAppId:o,selectedCloudProject:r,selectedProject:s,selectedSession:l,selectedSessionId:m,selectedSessionLinkedProject:d}){const f=l?.workspaceKind==="local_project"?l.workspaceId??null:d?.id??null,g=Jt(m)&&!l,x=l?Ui(l.workspaceKind):!1,k=zi(l),C=l?vZ(l):!1,R=l?.cwd&&(!x||k)?qw(l.cwd):null,E=e?.providers??null,A=Ga(s,e?.cloudProjects??[]),O=EZ({draftProvider:n,hasSelectedCloudProject:!!r,selectedSessionHybridWorkspace:k}),$=nr(O,t,E),M=La(e?.preferences),w=g?null:l?x?l.workspaceKind??"sandbox":C?"sandbox":f?"local_project":l.workspaceKind??(l.appId?"sandbox_app":R?"local_project":null):r?"sandbox":s?"local_project":o?"sandbox_app":null,P=g?null:l?x&&!k||C?null:f||(l.workspaceId??l.appId??R):r?null:s?.id??o,j=g?null:l?x?l.workspaceId??null:C?null:f??l.workspaceId??l.appId??R:r?null:s?.id??o,N=e?.account??null,z=!e||N?.state==="loading"||N?.state==="switching",D=!z&&N?.state==="signed_out",F=z?null:D?"Sign in":N?.label??N?.activeProfile?.handle??"Account",te=OZ(N),ve=te?`Welcome, ${te}`:"Welcome",re=l?.workspaceName??l?.appName??r?.name??s?.name??a?.name??null,K=Ui(w)?"cloud":"local",L=s?.name??d?.name??(l?.workspaceKind==="local_project"?l.workspaceName:null)??"Local workspace",de=(K==="cloud"?re:null)??r?.name??A?.name??s?.name??"Cloud workspace",X=!!(r?.id||A?.id||l?.cloudProjectId||K==="cloud");return{account:N,accountLabel:F,accountPending:z,accountSignedOut:D,activeModel:$,activeProvider:O,activeWorkspaceAppId:P,activeWorkspaceId:j,activeWorkspaceKind:w,activeWorkspaceLocation:K,appDefaults:M,cloudLinked:X,cloudTargetName:de,localTargetName:L,selectedCodexHistoryPending:g,selectedSessionCloudWorkspace:x,selectedSessionLocalPathWorkspaceId:R,selectedSessionPendingCloudStart:C,selectedSessionProjectId:f,startMessage:ve,workspaceName:re}}function NZ({accountPending:e,accountSignedOut:t,activeWorkspaceLocation:n,bootstrap:a,busy:o,cloudLinked:r,selectedCloudProject:s,selectedProject:l,selectedSession:m,pendingWorkspaceTarget:d,workspaceStates:f,workspaceBusy:g}){const x=Ga(l,a?.cloudProjects??[]),C=!!!l?.linkedSandboxProject?.projectId||!!x,R=y.useMemo(()=>{const j=(a?.localProjects??[]).map(F=>({value:`local:${F.id}`,label:F.name,detail:F.workspacePath,kind:"local"})),N=(a?.cloudProjects??[]).map(F=>({value:`cloud:${F.id}`,label:F.name,detail:F.organizationName??F.sourceLabel??"OpenPond Cloud",kind:"cloud"})),z=l?`local:${l.id}`:s?`cloud:${s.id}`:"none",D=[...j,...N].find(F=>F.value===z)??null;return{value:z,label:D?.label??"Select Project",detail:D?.detail??"Choose a project for local or cloud work",busy:g||o,options:[...j,...N,...MZ,{value:"none",label:"Don't work in a project",detail:"General chat without project files",kind:"none"}]}},[a?.cloudProjects,a?.localProjects,o,s,l,g]),E=!!(r||l),A=!!(s?.id||x?.id||m?.cloudProjectId||zi(m)),O=l?f[l.id]??null:null,$=FP(O,{branch:l?.linkedSandboxProject?.defaultBranch??null,path:l?.workspacePath??m?.cwd??null,linkedCloudSourceKnown:l?.linkedSandboxProject?.projectId&&C?!!l.linkedSandboxProject.lastUploadedCommit||!O?.headCommit:!0}),M=VP(l,s??x,O,{cloudLinkTrusted:C}),w=mG(l,O,{cloudLinkTrusted:C}),P=y.useMemo(()=>{const j={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},N={value:"hybrid",label:"Hybrid",detail:"Use your selected model with hosted sandbox edits.",stateNote:A?M:"upload required",disabled:e||t||!A,disabledReason:t?"Add an OpenPond account before using Hybrid.":"Upload/sync this Project to Cloud before using Hybrid."},z={value:"cloud",label:"Hosted",detail:"Run with hosted compute, with or without a Project.",stateNote:l||s?M:"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:w,disabled:e||t||!l,disabledReason:t?"Add an OpenPond account before uploading source.":"Select a local Project before uploading source."},F=n==="cloud"?"local":"cloud",te=F==="local"?j:z;let ve=n==="cloud"?z:j;return d==="cloud"?ve=z:d==="local"?ve=j:(zi(m)||d==="hybrid")&&(ve=N),{value:ve.value,label:ve.label,detail:ve.stateNote||ve.detail,busy:g,action:{...te,label:F==="cloud"?"Hosted":l?"Local checkout":"Check out locally"},uploadAction:l?D:null,options:[j,N,z]}},[n,e,t,r,E,M,A,$,d,l,m,w,g]);return{projectTarget:R,workspaceTarget:P}}function Qn(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")}function TA(e){return Qn(e.name||e.gitRepo||e.id)}function Foe(e){return`@${TA(e)}`}function EA(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>Qn(t[1]??"")).filter(Boolean)}function DZ(e,t){const n=EA(e);if(n.length===0)return!1;const a=new Set([Qn(t.id),TA(t),t.gitRepo?Qn(t.gitRepo):""].filter(Boolean));return n.some(o=>a.has(o))}function MA(e){return e.filter(t=>t.sandbox)}function HZ(e,t){const n=EA(e);if(n.length===0)return null;const a=new Map;for(const o of n){const r=t.find(s=>{const l=Qn(s.id),m=Qn(s.name),d=s.gitRepo?Qn(s.gitRepo):"";return o===l||o===m||o===d});r&&a.set(r.id,r)}return a.size===1?Array.from(a.values())[0]??null:null}function Voe(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:Qn(a[1]??""),start:a.index+o}}function LZ(e){return new Set(e.map(t=>t.id))}function ek(e,t){const n=e?.linkedOpenPondApp??null;return n?.appId&&t.has(n.appId)?n:null}function qZ({bootstrap:e,codexHistorySessions:t,selectedProjectId:n,selectedSessionId:a,selectedAppId:o,sessions:r}){const s=y.useMemo(()=>e?.apps.find(D=>D.id===o)??null,[e?.apps,o]),l=y.useMemo(()=>new Map((e?.localProjects??[]).map(D=>[D.id,D])),[e?.localProjects]),m=y.useMemo(()=>new Map((e?.cloudProjects??[]).map(D=>[D.id,D])),[e?.cloudProjects]),d=y.useMemo(()=>MP(n),[n]),f=y.useMemo(()=>d?.kind==="local"?l.get(d.id)??null:null,[l,d]),g=y.useMemo(()=>d?.kind==="cloud"?m.get(d.id)??null:null,[m,d]),x=y.useMemo(()=>LZ(e?.apps??[]),[e?.apps]),k=y.useMemo(()=>MA(e?.apps??[]),[e?.apps]),C=y.useMemo(()=>{const D=[];for(const F of e?.localProjects??[]){const te=ek(F,x);te&&D.push([te.appId,F.id])}return new Map(D)},[e?.localProjects,x]),R=y.useMemo(()=>new Set((e?.localProjects??[]).map(D=>D.id)),[e?.localProjects]),E=y.useMemo(()=>HP(e?.localProjects??[]),[e?.localProjects]),A=y.useRef([]),O=y.useMemo(()=>UZ(r,t,A.current),[t,r]),$=y.useMemo(()=>O.find(D=>D.id===a)??null,[O,a]),M=y.useMemo(()=>{if(!$)return null;if($.localProjectId)return l.get($.localProjectId)??null;if($.workspaceKind==="local_project")return $.workspaceId?l.get($.workspaceId)??null:null;const D=nG($,R,E);if(D)return l.get(D)??null;if(!$.appId)return null;const F=C.get($.appId);return F?l.get(F)??null:null},[C,l,R,E,$]),w=y.useMemo(()=>$?.cloudProjectId?m.get($.cloudProjectId)??null:null,[m,$]),P=f??M,j=g??w,N=y.useMemo(()=>ek(P,x),[x,P]),z=y.useMemo(()=>N?e?.apps.find(D=>D.id===N.appId)??null:null,[e?.apps,N]);return{cloudProjectById:m,currentAppIds:x,linkedProjectByAppId:C,localProjectById:l,mentionableSandboxApps:k,selectedApp:s,selectedCloudProject:j,selectedProject:P,selectedProjectLinkedApp:z,selectedProjectLinkedOpenPondApp:N,selectedSession:$,selectedSessionLinkedProject:M,sidebarSessions:O}}function UZ(e,t,n){const a=new Map;for(const d of e){const f=tk(d);a.set(f,d)}for(const d of t){const f=tk(d),g=a.get(f);a.set(f,g?zZ(g,d):d)}const o=Array.from(a.entries());if(!n)return o.sort((d,f)=>nk(d[1],f[1])).map(d=>d[1]);const r=[],s=new Set;for(const d of n){const f=a.get(d);f&&(r.push([d,f]),s.add(d))}const m=[...o.filter(([d])=>!s.has(d)).sort((d,f)=>nk(d[1],f[1])),...r];return n.splice(0,n.length,...m.map(([d])=>d)),m.map(d=>d[1])}function zZ(e,t){return{...e,metadata:BZ(e.metadata,t.metadata),status:e.status==="active"||t.status==="active"?"active":e.status,updatedAt:FZ(e.updatedAt,t.updatedAt)}}function tk(e){return e.codexThreadId?`codex:${e.codexThreadId}`:`session:${e.id}`}function nk(e,t){const n=ak(t)-ak(e);return n!==0?n:e.title.localeCompare(t.title)}function BZ(e,t){const n={...e??{},...t??{}};return Object.keys(n).length>0?n:void 0}function FZ(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 ak(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 VZ(e){return!!(e&&Ui(e.workspaceKind)&&!zi(e)&&e.provider!=="openpond")}function KZ(e,t){const n=$P(e,t);return`${e.id}\0${n.provider}\0${n.model}`}function WZ({activeWorkspaceId:e,activeWorkspaceKind:t,appDispatch:n,connection:a,expandProject:o,linkedProjectByAppId:r,providerSettings:s,selectedAppId:l,selectedSession:m,selectedSessionId:d,selectedSessionProjectId:f,setDiffPanelExpanded:g,setDraftModel:x,setDraftProvider:k,setError:C,setSelectedAppId:R,setSelectedProjectId:E,setSessions:A,setTerminalOpen:O,toast:$}){const M=y.useRef(null);y.useEffect(()=>{if(!l)return;const w=f??(d?null:r.get(l)??null);if(!w)return;const P=kt("local",w);R(null),E(P),o(P)},[o,r,l,d,f,R,E]),y.useEffect(()=>{if(!$||$.persistent)return;const w=window.setTimeout(()=>{n({type:"clearToast",toastId:$.id})},$.durationMs??($.tone==="error"?7e3:3500));return()=>window.clearTimeout(w)},[n,$]),y.useEffect(()=>{function w(P){(P.metaKey||P.ctrlKey)&&P.key==="`"&&(P.preventDefault(),O(j=>!j))}return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[O]),y.useEffect(()=>{g(!1)},[e,t,g]),y.useEffect(()=>{if(!d){M.current=null;return}if(!m||m.id!==d)return;const w=KZ(m,s);if(M.current===w)return;M.current=w;const P=$P(m,s);k(P.provider),x(P.model)},[s,m,d,x,k]),y.useEffect(()=>{!a||!m||!VZ(m)||ie.patchSession(a,m.id,{provider:"openpond"}).then(w=>{A(P=>P.map(j=>j.id===w.id?w:j)),k("openpond"),x(P=>nr("openpond",P))}).catch(w=>{C(w instanceof Error?w.message:String(w))})},[a,m,x,k,C,A])}function GZ({connection:e,setError:t}){return y.useCallback(async(n,a,o)=>{if(!e){const r=new Error("OpenPond App server is not connected.");throw t(r.message),r}t(null);try{await ie.resolveApproval(e,n,{decision:a,answers:o})}catch(r){const s=r instanceof Error?r.message:String(r);throw t(s),r}},[e,t])}function JZ({activeProvider:e,contextCompaction:t,contextUsage:n,pinnedItems:a,pinnedPreviewKeys:o,pinnedProjects:r,projectRows:s,visibleProjectRows:l}){const m=y.useMemo(()=>B8(a,o),[a,o]),d=y.useMemo(()=>oA({provider:e,snapshot:n,preferences:t}),[e,t,n]),f=y.useMemo(()=>Array.from(new Set([...r,...l].filter(wy).map(x=>x.project.id))),[r,l]);return{commandProjectRows:y.useMemo(()=>s,[s]),contextWindowStatus:d,pinnedRows:m,sidebarWorkspaceAppIds:f}}function ZZ({appDispatch:e,expandProject:t,linkedProjectByAppId:n,requestComposerFocus:a,onBeginNewChat:o,setMentionedAppId:r}){return y.useCallback((s=null)=>{o?.();const l=s?.id?n.get(s.id)??null:null;if(l){const m=kt("local",l);r(null),e({type:"selectProject",projectId:m}),t(m),a();return}r(null),e({type:"beginNewChat",appId:s?.id??null}),a()},[e,t,n,o,a,r])}const jA={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 Koe(e){return`@${e.token}`}function YZ(e){return`@${nY(e)}`}function QZ(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],r=xs(a.flatMap(g=>g.capabilities.map(x=>x.id))),s=xs(a.flatMap(g=>g.capabilityLabels)),l=xs(a.flatMap(g=>g.connections.map(x=>x.id).filter(iY))),m=xs(a.map(g=>g.id)),d=xs(a.map(g=>g.setupSurface)),f=tY(n);return{provider:n,label:o.providerLabel,detail:s.length>0?s.slice(0,4).join(", "):o.description,token:f,tokens:eY(a),ref:{kind:"integration",provider:n,appIds:m,setupSurfaces:d,...l.length>0?{connectionIds:l}:{},...r.length>0?{capabilities:r}:{}}}})}function Woe(e,t){const n=Qn(t);return e.filter(a=>n?a.tokens.some(o=>o.includes(n)):!0).slice(0,8)}function XZ(e,t){const n=aY(e);if(n.length===0)return[];const a=new Map;for(const o of n){const r=t.find(s=>s.tokens.includes(o));r&&a.set(r.provider,r)}return Array.from(a.values())}function Goe(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]??"",r=Qn(o);if(!r)continue;const s=t.find(g=>g.tokens.includes(r));if(!s)continue;const m=(a[0]??"").indexOf("@");if(m<0||typeof a.index!="number")continue;const d=a.index+m,f=`@${o}`;n.push({detail:s.detail,displayText:YZ(s),end:d+f.length,label:s.label,provider:s.provider,start:d,text:f})}return n}function eY(e){return xs(e.flatMap(t=>[...jA[t.providerFamily],t.providerFamily,t.id,t.label,t.shortLabel]).map(Qn).filter(Boolean))}function tY(e){return Qn(jA[e][0]??e)}function nY(e){return e.provider==="github"?"GitHub":e.provider==="x"?"X":e.provider==="mcp"?"MCP":e.label}function aY(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>Qn(t[1]??"")).filter(Boolean)}function xs(e){return Array.from(new Set(e))}function iY(e){return typeof e=="string"&&e.length>0}function oY({bootstrap:e,connectedAppRows:t,mentionableSandboxApps:n,runtimeIndexes:a,selectedApp:o,selectedCloudProject:r,selectedProject:s,selectedSession:l,selectedSessionId:m}){const d=y.useMemo(()=>{const C=new Map;for(const R of e?.cloudProjects??[]){const E=C.get(R.teamId)??[];E.push(R.id),C.set(R.teamId,E)}return C},[e?.cloudProjects]),g=!!(l||o||s||r)?[]:n,x=y.useMemo(()=>QZ(t),[t]),k=y.useMemo(()=>nZ(a,m),[a,m]);return{chatMentionApps:g,cloudProjectIdsByTeam:d,connectedAppMentions:x,pendingApproval:k}}function rY({connection:e,setBootstrap:t,setCodexPermissionMode:n,setCodexReasoningEffort:a,setError:o}){const r=y.useCallback(l=>{if(!e){o("Connect to OpenPond before saving preferences.");return}ie.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=y.useCallback(l=>{if(!e){o("Connect to OpenPond before saving preferences.");return}ie.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:r,changeCodexReasoningEffort:s}}const sY=6e4;function $y(e,t){if(!e)return t;const n=cY(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 $A(e,n)?e:n}function lY(e,t){const n=$y(e,t),a=e?{...n,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order,updatedAt:e.updatedAt}:n;return e&&$A(e,a)?e:a}function rc(e,t){let n=!1,a=!1;const o=e.map(r=>{if(r.id!==t.id)return r;n=!0;const s=$y(r,t);return s!==r&&(a=!0),s});return n?a?o:e:[t,...e]}function vp(e,t){let n=!1,a=!1;const o=e.map(r=>{if(r.id!==t.id)return r;n=!0;const s=lY(r,t);return s!==r&&(a=!0),s});return n?a?o:e:[t,...e]}function Qg(e,t,n,a=Date.now()){const o=new Map(e.map(r=>[r.id,r]));return t.map(r=>{const s=o.get(r.id);if(s&&n){const l=uY(s,r,n,a);if(l)return l}return $y(s,r)})}function ik(e,t,n,a=Date.now()){const o=new Map(e.map(d=>[d.id,d])),r=new Map(Qg(e,t,n,a).map(d=>[d.id,d])),s=new Set(o.keys()),l=t.filter(d=>!s.has(d.id)).map(d=>r.get(d.id)??d),m=e.map(d=>{const f=r.get(d.id);return f||(OA(d,t)?d:null)}).filter(d=>!!d);return[...l,...m]}function OA(e,t){const n=Date.parse(e.updatedAt);if(!Number.isFinite(n))return!1;const a=dY(t);return a===null||n>=a}function ok(e,t,n,a=Date.now()){const o=new Map(t.map(r=>[r.id,r]));for(const r of n){const s=o.get(r.id);s&&(NA(s,r)||(e[r.id]=a))}}function cY(e,t){const n=Date.parse(e),a=Date.parse(t);return Number.isFinite(n)&&Number.isFinite(a)&&n>a}function $A(e,t){return JSON.stringify(e)===JSON.stringify(t)}function dY(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 uY(e,t,n,a){const o=n[t.id];return o===void 0?null:a-o>sY||NA(e,t)?(delete n[t.id],null):{...t,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order}}function NA(e,t){return e.pinned===t.pinned&&e.savedForLater===t.savedForLater&&e.archived===t.archived&&e.order===t.order}const DA=800,mY=5e3,rk=5e4,pY=16,fY=3e4,ba=new Map;function hY(e,t){return ba.get(LA(e,t))?.payload??null}async function HA(e,t,n={}){const a=LA(e,t),o=ba.get(a),r=n.limit??DA,s=n.tail??!0;if(o?.promise)return o.promise;if(!n.force&&s&&o?.payload&&Date.now()-o.fetchedAt<=fY)return sk(a,o),o.payload;const l=!!(n.force&&s&&o?.payload),m=l?o?.payload?.events.at(-1)?.id:void 0,d=ie.codexHistoryThreadIncremental(e,t,{afterEventId:m,limit:r,revision:l?o?.revision:void 0,tail:s}).then(f=>{const g=ba.get(a)?.payload??o?.payload;if(f.unchanged){if(!g)throw new Error("Codex history revision matched without a cached thread.");return ba.set(a,{fetchedAt:Date.now(),payload:g,revision:f.revision}),sk(a,ba.get(a)),g}const x={session:f.session,events:f.events},k=s&&g&&!f.reset?{...x,events:gY(g.events,x.events)}:x;return ba.set(a,{fetchedAt:Date.now(),payload:k,revision:f.revision}),lk(),k}).catch(f=>{throw ba.get(a)?.promise===d&&ba.delete(a),f});return ba.set(a,{fetchedAt:o?.fetchedAt??0,payload:o?.payload,promise:d,revision:o?.revision}),lk(),d}function LA(e,t){return`${e.serverUrl}
|
|
192
|
-
${e.token}
|
|
193
|
-
${t}`}function sk(e,t){ba.delete(e),ba.set(e,t)}function lk(){for(;ba.size>pY;){const e=ba.keys().next().value;if(!e)return;ba.delete(e)}}function gY(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 vY=500,bY=2500,yY=15e3;function SY(e){return e.active?vY:e.surface==="thread"?bY:yY}function Ny(e,t){return!t||e.session.status==="active"?e:{...e,session:{...e.session,status:"active"}}}function xY(e={}){const t={cachedPayload:e.cachedPayload??hY,clearTimer:e.clearTimer??(d=>globalThis.clearTimeout(d)),loadPayload:e.loadPayload??HA,now:e.now??Date.now,setTimer:e.setTimer??((d,f)=>globalThis.setTimeout(d,f))},n=new Map;let a=1;function o(d){const f=wY(d.connection,d.sessionId);let g=n.get(f);g||(g={connection:d.connection,disposed:!1,inFlight:null,latestPayload:t.cachedPayload(d.connection,d.sessionId),nextRefreshAt:null,sessionId:d.sessionId,subscribers:new Map,timer:null},n.set(f,g));const x=a++;return g.subscribers.set(x,d),g.latestPayload&&d.onPayload(g.latestPayload),r(g,0),()=>{const k=n.get(f);if(k){if(k.subscribers.delete(x),k.subscribers.size>0){r(k,l(k));return}k.disposed=!0,m(k),n.delete(f)}}}function r(d,f){if(d.disposed||d.subscribers.size===0||d.inFlight)return;const g=t.now()+Math.max(0,f);d.timer&&d.nextRefreshAt!==null&&d.nextRefreshAt<=g||(m(d),d.nextRefreshAt=g,d.timer=t.setTimer(()=>{d.timer=null,d.nextRefreshAt=null,s(d)},Math.max(0,f)))}async function s(d){if(d.disposed||d.subscribers.size===0||d.inFlight)return;const f=t.loadPayload(d.connection,d.sessionId,{force:!!d.latestPayload});d.inFlight=f;try{const g=await f;if(d.disposed||g===d.latestPayload)return;d.latestPayload=g;for(const x of d.subscribers.values())x.onPayload(g)}catch(g){if(d.disposed)return;for(const x of d.subscribers.values())x.onError?.(g)}finally{d.inFlight===f&&(d.inFlight=null),d.disposed||r(d,l(d))}}function l(d){const f=[...d.subscribers.values()],g=f.some(k=>k.locallyActive||k.reportedActive)||d.latestPayload?.session.status==="active"||My(d.latestPayload?.events??[])?.tone==="active",x=f.some(k=>k.surface==="thread")?"thread":"sidebar";return SY({active:g,surface:x})}function m(d){d.timer&&t.clearTimer(d.timer),d.timer=null,d.nextRefreshAt=null}return{subscribe:o}}const kY=xY();function Dy(e){return kY.subscribe(e)}function wY(e,t){return`${e.serverUrl}
|
|
194
|
-
${e.token}
|
|
195
|
-
${t}`}function IY({connection:e,selectedSessionId:t,selectedSessionLocallyActive:n,selectedSessionStatus:a,setCodexHistorySessions:o,setError:r}){const[s,l]=y.useState({events:[],sessionId:null}),m=Jt(t)?t:null,d=m&&s.sessionId===m?s.events:[],f=y.useCallback(g=>{l(x=>{if(!m)return{events:[],sessionId:null};const k=x.sessionId===m?x.events:[];return{events:typeof g=="function"?g(k):g,sessionId:m}})},[m]);return y.useEffect(()=>{if(!e||!m){l(k=>k.sessionId===null&&k.events.length===0?k:{events:[],sessionId:null});return}r(k=>k==="Session not found"?null:k);const g=n;return Dy({connection:e,locallyActive:g,onError:k=>r(k instanceof Error?k.message:String(k)),onPayload:k=>{const C=Ny(k,g);l(R=>R.sessionId!==m?{events:C.events,sessionId:m}:{events:ao(R.events,C.events),sessionId:m}),r(R=>R==="Session not found"?null:R),o(R=>vp(R,C.session))},reportedActive:a==="active",sessionId:m,surface:"thread"})},[e,m,n,a,o,r]),{codexHistoryEvents:d,setCodexHistoryEvents:f}}function qA(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 _Y({connection:e,appPreferences:t,sessions:n,pinnedItems:a,setAppPreferences:o,setCodexHistorySessions:r,setSessions:s,sidebarFileBookmarks:l,setSidebarFileBookmarks:m,setError:d}){const[f,g]=y.useState(null),[x,k]=y.useState(null),C=y.useRef(null),R=y.useRef(null);function E(P,j){P.dataTransfer.effectAllowed="move",P.dataTransfer.setData("text/plain",`${j.type}:${j.id}`),qA(P);const N=a.map(z=>z.key);C.current=j,R.current=N,g(j),k(N)}function A(){C.current=null,R.current=null,g(null),k(null)}function O(P,j){const N=C.current;if(!N)return;const z=fm(P),D=R.current??a.map(te=>te.key),F=hm(D,_r(N),_r(j),z);kx(D,F)||(R.current=F,k(F))}function $(P){if(!e)return;const j=a.map(K=>K.key),N=new Set(j),z=[...P.filter(K=>N.has(K)),...j.filter(K=>!P.includes(K))];if(kx(j,z))return;const D=t,F=new Map(n.map(K=>[K.id,K])),te=l,ve=new Map(a.map(K=>[K.key,K]));o(K=>{const L={...K};return z.forEach((de,X)=>{const Z=ve.get(de);Z?.type==="project"&&(L[Z.id]={...L[Z.id]??{},pinned:!0,archived:!1,order:X})}),L});const re=K=>{const L=new Map(K.map(Z=>[Z.id,Z])),de=z.map((Z,pe)=>{const ee=ve.get(Z),me=ee?.type==="session"?L.get(ee.id):null;return me?{...me,order:pe}:null}).filter(Z=>!!Z),X=new Map(de.map(Z=>[Z.id,Z]));return K.map(Z=>X.get(Z.id)??Z)};s(re),r(re),m(K=>{const L=new Map;return z.forEach((de,X)=>{const Z=ve.get(de);Z?.type==="file"&&L.set(Z.id,X)}),K.map(de=>{const X=L.get(de.id);return X===void 0?de:{...de,order:X}})}),Promise.all(z.map((K,L)=>{const de=ve.get(K);return de?de.type==="project"?ie.patchSidebarAppPreference(e,de.id,{pinned:!0,archived:!1,order:L}):de.type==="session"?ie.patchSession(e,de.id,{order:L}):ie.patchSidebarFile(e,{workspaceKind:de.file.workspaceKind,workspaceId:de.file.workspaceId,workspaceName:de.file.workspaceName,path:de.file.path,status:"pinned",order:L,sourceSessionId:de.file.sourceSessionId}):Promise.resolve(null)})).catch(K=>{d(K instanceof Error?K.message:String(K)),o(D);const L=de=>de.map(X=>F.get(X.id)??X);s(L),r(L),m(te)})}function M(P,j){const N=C.current;if(N){const z=R.current??a.map(F=>F.key),D=hm(z,_r(N),_r(j),fm(P));$(D)}A()}function w(){C.current&&$(R.current??a.map(j=>j.key)),A()}return{dragItem:f,pinnedPreviewKeys:x,startPinnedDrag:E,clearSidebarDrag:A,previewPinnedDrop:O,commitPinnedDrop:M,commitPinnedPreviewDrop:w}}function CY({connection:e,sessions:t,setCodexHistorySessions:n,setError:a,setSessions:o}){const[r,s]=y.useState(null),[l,m]=y.useState(null),d=y.useRef(null),f=y.useRef(null);function g(A,O){A.dataTransfer.effectAllowed="move",A.dataTransfer.setData("text/plain",`session:${O.sessionId}`),qA(A),d.current=O,f.current=O.visibleSessionIds,s(O.sessionId),m(O.visibleSessionIds)}function x(A,O){const $=d.current;if(!$)return;const M=f.current??$.visibleSessionIds,w=hm(M,$.sessionId,O,fm(A));RY(M,w)||(f.current=w,m(w))}function k(){d.current=null,f.current=null,s(null),m(null)}function C(A,O){const $=d.current;if(!$){k();return}const M=f.current??$.visibleSessionIds,w=hm(M,$.sessionId,O,fm(A));E(Ax($.allSessionIds,$.visibleSessionIds,w)),k()}function R(){const A=d.current;A&&E(Ax(A.allSessionIds,A.visibleSessionIds,f.current??A.visibleSessionIds)),k()}function E(A){const O=new Map(A.map((P,j)=>[P,j])),$=new Map(t.map(P=>[P.id,P.order])),M=A.filter((P,j)=>$.get(P)!==j);if(M.length===0)return;const w=P=>P.map(j=>{const N=O.get(j.id);return N===void 0||N===j.order?j:{...j,order:N}});o(w),n(w),e&&Promise.all(M.map(P=>ie.patchSession(e,P,{order:O.get(P)}))).catch(P=>{const j=N=>N.map(z=>{const D=$.get(z.id);return D===void 0||D===z.order?z:{...z,order:D}});o(j),n(j),a(P instanceof Error?P.message:String(P))})}return{clearTaskDrag:k,commitTaskDrop:C,commitTaskPreviewDrop:R,previewTaskDrop:x,startTaskDrag:g,taskDragSessionId:r,taskPreviewSessionIds:l}}function RY(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function ck({afterMessageId:e=null,attachments:t,content:n,sessionId:a}){const o=new Date().toISOString(),r=`pending_user_${a}_${o}_${Math.random().toString(36).slice(2,8)}`,s=PY(t);return{id:r,role:"user",content:n,sessionId:a,afterMessageId:e,timestamp:o,turnId:r,...s.length>0?{attachments:s}:{}}}function UA(e,t){return!t||zA(e,t)?e:[...e,t]}function zA(e,t){const n=t.afterMessageId?e.findIndex(r=>r.id===t.afterMessageId):-1,a=n>=0?n+1:0,o=Date.parse(t.timestamp);for(let r=a;r<e.length;r+=1){const s=e[r];if(s.role!=="user"||s.content!==t.content)continue;if(n>=0||!t.afterMessageId)return!0;const l=Date.parse(s.timestamp);if(!Number.isFinite(o)||!Number.isFinite(l)||l>=o)return!0}return!1}function PY(e){return e.map(({contentsBase64:t,text:n,...a})=>a)}function Ce(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 ar(e){const t=e.trim();if(!t||!t.startsWith("{")&&!t.startsWith("["))return null;try{return JSON.parse(t)}catch{return null}}function Pe(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function bo(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];if(t(a))return a}return null}function AY(e,t,n){if(t.name==="workspace_action_result"){const a=bo(e,o=>o.role==="assistant"&&o.turnId===t.turnId&&o.actionRun?.actionName===n.actionName);if(a?.actionRun){a.id=t.id,a.timestamp=t.timestamp,a.actionRun={...a.actionRun,...n,refs:Xg([...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 TY(e){if(e.name!=="workspace_action"&&e.name!=="workspace_action_result")return null;const t=Pe(e.data),n=Pe(e.args),a=Ce(n,["actionName"])??Ce(Pe(n?.input),["actionName"])??Hh(t)??Hh(Pe(t?.run))??Hh(Pe(t?.agentRun));if(!(e.action==="sandbox_run_action"||e.action==="profile_run_action"||!!a||t?.openPondActionRun===!0||t?.openPondProfileActionRun===!0)||!a)return null;const r=Pe(t?.run)??Pe(t?.agentRun),s=Pe(r?.metadata),l=Pe(t?.actionSummary)??Pe(r?.actionSummary)??Pe(s?.actionSummary),m=Pe(t?.action)??l??Pe(s?.selectedAction)??null,d=Pe(t?.responseSummary)??Pe(r?.responseSummary)??Pe(s?.responseSummary),f=Pe(t?.sourceSummary)??Pe(r?.sourceSummary)??Pe(s?.sourceSummary),g=Pe(t?.traceSummary)??Pe(r?.traceSummary)??Pe(s?.traceSummary),x=Pe(t?.evalSummary)??Pe(r?.evalSummary)??Pe(s?.evalSummary),k=Xg([...to("artifact",t?.artifactRefs,"Artifact"),...to("artifact",m?.artifactRefs,"Artifact"),...to("artifact",l?.artifactRefs,"Artifact"),...to("artifact",d?.artifactRefs,"Artifact"),...to("trace",t?.traceArtifactRefs,"Trace"),...to("trace",g?.artifactRefs,"Trace"),...to("eval",t?.evalResultArtifactRefs,"Eval"),...to("eval",x?.artifactRefs,"Eval"),...to("output",t?.outputRefs,"Output")]),C=Ce(f,["sourceRef","ref"]);return C&&k.push({id:ev("source",C),kind:"source",label:"Source",target:C}),{actionName:a,title:Ce(m,["label","title","name"])??Ce(s,["selectedActionLabel"])??NY(a),status:EY(e,d,r),responseText:Ce(d,["text","summary","message"])??(e.name==="workspace_action_result"&&e.output?.trim()||null),runId:Ce(r,["id","runId"])??Ce(t,["runId","agentRunId"])??null,projectId:Ce(r,["projectId"])??Ce(t,["projectId"])??Ce(n,["projectId"])??null,agentId:Ce(r,["agentId"])??Ce(t,["agentId"])??Ce(n,["agentId"])??null,agentName:Ce(Pe(m?.implementation),["agentName"])??Ce(m,["agentName"])??Ce(s,["selectedAgentName"])??null,sandboxId:Ce(r,["sandboxId"])??Ce(t,["sandboxId"])??Ce(Pe(t?.sandbox),["id"])??Ce(Pe(t?.createdSandbox),["id"])??Ce(n,["sandboxId"])??null,runtimeId:Ce(r,["runtimeId"])??Ce(t,["runtimeId"])??null,implementationType:Ce(t,["implementationType"])??Ce(m,["implementationType","type","kind"])??Ce(Pe(m?.implementation),["type","kind"])??Ce(s,["implementationType"])??(e.action==="profile_run_action"||t?.openPondProfileActionRun===!0?"openpond-profile-action":null),sourceRef:C,manifestHash:Ce(f,["manifestHash"])??Ce(t,["manifestHash"])??Ce(s,["manifestHash"])??null,refs:Xg(k),childCalls:jY(t,r,s)}}function Hh(e){return e?Ce(e,["actionName","name"])??Ce(Pe(e.action),["actionName","name"])??Ce(Pe(e.actionSummary),["actionName","name"])??Ce(Pe(e.selectedEntrypoint),["name"]):null}function EY(e,t,n){if(e.status==="failed")return"failed";const a=Ce(t,["status"]);if(a==="failed")return"failed";if(a==="running"||a==="pending")return a;if(a==="available"||e.status==="completed")return"completed";const o=Ce(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 to(e,t,n){return(Array.isArray(t)?t:t?[t]:[]).flatMap(o=>{const r=MY(e,o,n);return r?[r]:[]})}function MY(e,t,n){if(typeof t=="string"&&t.trim()){const s=t.trim();return{id:ev(e,s),kind:e,label:n,target:s}}const a=Pe(t);if(!a)return null;const o=Ce(a,["url","webUrl","artifactPath","path","ref"])??Ce(Pe(a.artifact),["url","webUrl","path","ref"]);if(!o)return null;const r=Ce(a,["label","title","name","type","kind"])??n;return{id:ev(e,o),kind:e,label:r,target:o}}function Xg(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 ev(e,t){return`${e}:${t}`}function jY(e,t,n){return[e?.childCalls,e?.childRuns,e?.implementationCalls,t?.childCalls,t?.childRuns,n?.childCalls,n?.childRuns].flatMap(o=>OY(o)).slice(0,6)}function OY(e){return(Array.isArray(e)?e:e?[e]:[]).flatMap((n,a)=>{const o=Pe(n);if(!o)return[];const r=Ce(o,["id","runId","callId"])??`child_${a+1}`,s=Ce(o,["label","title","actionName","name","tool"])??Ce(Pe(o.action),["label","name"])??"Implementation call",l=Ce(o,["detail","summary","runId","sandboxId","runtimeId"])??null;return[{id:r,label:s,status:$Y(o),detail:l}]})}function $Y(e){const t=Ce(e,["status","state"]);return t==="running"||t==="completed"||t==="failed"||t==="pending"?t:t==="succeeded"?"completed":"unknown"}function NY(e){const t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e}const DY=new Set([".avif",".gif",".jpeg",".jpg",".png",".webp"]);function BA(e){if(!e)return!1;const t=e.split("?")[0]?.split("#")[0]??e,n=t.lastIndexOf(".");return n<0?!1:DY.has(t.slice(n).toLowerCase())}function FA(e){return e.split("/").filter(Boolean).pop()??e}function HY(e){if(!nv(e))return;const t=Pe(e.data),a=(typeof t?.openpondImagePreviewPath=="string"?t.openpondImagePreviewPath:null)??Cr(e.data)??Cr(e.args)??Cr(e.output);if(!(!a||!BA(a)))return{path:a,appId:e.appId??null,title:FA(a)}}function LY(e){if(e.name!=="tool.completed"&&e.name!=="workspace_action_result")return[];const t=[],n=new Set;return tv(e.data,t,n),t.slice(0,12)}function tv(e,t,n,a=0){if(a>7||e==null)return;if(Array.isArray(e)){for(const l of e)tv(l,t,n,a+1);return}const o=Pe(e);if(!o)return;const r=Ce(o,["path","artifactRef"]),s=Ce(o,["contentType","mimeType"]);r&&s&&!n.has(r)&&(n.add(r),t.push({path:r,title:Ce(o,["title","name"])??FA(r),contentType:s,sizeBytes:typeof o.sizeBytes=="number"?o.sizeBytes:null}));for(const l of Object.values(o))tv(l,t,n,a+1)}function nv(e){if(e.name!=="tool.started"&&e.name!=="tool.completed")return!1;const t=Pe(e.data);return typeof t?.openpondImagePreviewPath=="string"&&t.openpondImagePreviewPath.trim()?!0:[e.output,e.action,Ce(t,["tool","toolName","tool_name","name","functionName","function_name","command"]),Ce(Pe(t?.input),["tool","toolName","tool_name","name"]),Ce(Pe(t?.arguments),["tool","toolName","tool_name","name"]),Ce(Pe(t?.args),["tool","toolName","tool_name","name"])].filter(a=>!!a).some(a=>a.toLowerCase().includes("view_image"))}function Cr(e,t=0,n=""){if(t>5||e==null)return null;if(typeof e=="string"){if(Lh(n)&&BA(e.trim()))return e.trim();const o=ar(e);if(o!==null){const r=Cr(o,t+1,n);if(r)return r}return qY(e)}if(Array.isArray(e)){for(const o of e){const r=Cr(o,t+1,n);if(r)return r}return null}const a=Pe(e);if(!a)return null;for(const[o,r]of Object.entries(a)){if(!Lh(o))continue;const s=Cr(r,t+1,o);if(s)return s}for(const[o,r]of Object.entries(a)){if(Lh(o))continue;const s=Cr(r,t+1,o);if(s)return s}return null}function Lh(e){return/^(path|filePath|filepath|imagePath|image|localPath|uri|url)$/i.test(e)}function qY(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 UY(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=BY(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 zY(e){if(e.action!=="connected_app_search"&&e.action!=="connected_app_read"&&e.action!=="connected_app_write")return null;const t=VA(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 BY(e){return VA(e).providerLabel}function VA(e){const t=Pe(e.args),n=Pe(e.data),a=Pe(n?.result),o=jm(Ce(t,["provider"])??Ce(a,["provider"])??Ce(n,["provider"])??void 0),r=Ce(a,["providerLabel"])??Ce(n,["providerLabel"])??(o?Ov(o)?.label:null)??"connected app",s=Ce(t,["operation"]),l=Ce(a,["operation"])??Ce(n,["operation"]),m=qh(t?.capabilityIds)||qh(a?.capabilityIds)||qh(n?.capabilityIds);return{providerLabel:r,providerOperation:s,operation:l,capabilityCount:m}}function qh(e){return Array.isArray(e)?e.length:0}function KA(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()||Uh(a)}}return t==="<turn_aborted>"?{kind:"turn_aborted",text:Uh("turn_aborted")}:t==="<goal_context>"?{kind:"goal_context",text:Uh("goal_context")}:null}function Uh(e){return e==="turn_aborted"?"The previous turn was interrupted.":"Goal context updated."}function bp(e){return e.name==="diagnostic"&&Pe(e.data)?.kind==="goal_context"}const FY="Steered by user";function VY(e){return e?.trim().toLowerCase()===FY.toLowerCase()}function KY(e,t){if(!t.turnId)return;YY(e,t.turnId);const n=WY(t);if(!n)return;const a=ZY(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},r=e.findIndex(s=>s.role==="assistant"&&s.turnId===t.turnId);r>=0?e.splice(r,0,o):e.push(o)}function WY(e){const t=Pe(e.data),n=Pe(t?.activity);return n?GY(n,e):JY(e,t)}function Joe(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 · ${tQ(e.route??"external")} issue routed`;const t=e.result==="applied"?"Applied":"Needs review";return`Refiner · ${e.summary} — ${t}`}function GY(e,t){const n=Ei(e.state,["running","completed","failed"]);if(!n)return null;const a=n==="failed"?"failed":Ei(e.result,["no_action","routed","applied","retained"]),o=ia(e.reason)??t.output??t.error??null;return{state:n,visibility:Ei(e.visibility,["always","material_only"])??"material_only",result:n==="running"?null:a,workspaceId:ia(e.workspaceId),decision:Ei(e.decision,["no_action","route","propose"]),route:ia(e.route),operation:Ei(e.operation,["create","update","delete"]),target:ia(e.target),summary:ia(e.summary)??WA(n,a),expectedOutcome:ia(e.expectedOutcome),reason:o,evidenceBasis:QY(e.evidenceBasis),critiqueStatus:Ei(e.critiqueStatus,["not_applicable","pending","passed","rejected","failed"])??(n==="running"?"pending":"not_applicable"),validationStatus:Ei(e.validationStatus,["not_applicable","pending","passed","failed"])??(n==="running"?"pending":"not_applicable"),validations:XY(e.validationReceipts),edits:eQ(e.edits),refs:{trigger:Ti(e.trigger),outcome:Ti(e.outcome),proposal:Ti(e.proposal),applyReceipt:Ti(e.applyReceipt),advanceReceipt:Ti(e.advanceReceipt),inputHarness:Ti(e.inputHarness),outputHarness:Ti(e.outputHarness)}}}function JY(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=Pe(t?.outcome),r=Pe(t?.proposal),s=o?.routed===!0,l=ia(t?.workspaceAdvance),m=n?"failed":a?r?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:r?"propose":s?"route":a?"no_action":null,route:ia(o?.route),operation:null,target:null,summary:WA(n?"failed":a?"completed":"running",m),expectedOutcome:null,reason:e.output??e.error??null,evidenceBasis:null,critiqueStatus:r?"passed":"not_applicable",validationStatus:r?"pending":"not_applicable",validations:[],edits:[],refs:{trigger:Ti(t?.trigger),outcome:Ti(o),proposal:Ti(r),applyReceipt:null,advanceReceipt:null,inputHarness:null,outputHarness:null}}}function ZY(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 YY(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 QY(e){const t=Pe(e),n=Ei(t?.kind,["single_deterministic","recurrent_independent"]);return!t||!n?null:{kind:n,supportingEvidenceIds:dk(t.supportingEvidenceIds),counterevidence:dk(t.counterevidence)}}function XY(e){return Array.isArray(e)?e.flatMap(t=>{const n=Pe(t),a=ia(n?.id),o=Ei(n?.status,["passed","failed","blocked","skipped"]),r=ia(n?.summary);return a&&o&&r?[{id:a,status:o,summary:r}]:[]}):[]}function eQ(e){return Array.isArray(e)?e.flatMap(t=>{const n=Pe(t),a=ia(n?.id),o=Ei(n?.operation,["create","update","delete"]),r=ia(n?.target),s=ia(n?.summary);return!a||!o||!r||!s?[]:[{id:a,operation:o,target:r,summary:s,content:typeof n?.content=="string"?n.content:null}]}):[]}function Ti(e){const t=Pe(e),n=ia(t?.id),a=ia(t?.contentHash);return n&&a?`${n} · ${a.slice(0,12)}`:null}function dk(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()):[]}function ia(e){return typeof e=="string"&&e.trim()?e.trim():null}function Ei(e,t){return typeof e=="string"&&t.includes(e)?e:null}function WA(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 tQ(e){return e.length>0?`${e[0].toUpperCase()}${e.slice(1)}`:e}const uk=64*1024,mk=8*1024;function pk(e,t){const n=GA(t);if(n.subagentMessage){e.push({id:t.id,role:"activity_group",activities:[n],timestamp:t.timestamp,turnId:t.turnId});return}const a=nQ(e,t.turnId);if(a){a.activities=oQ(a.activities??[],t,n),a.timestamp=t.timestamp;return}Uu(e,t),e.push({id:t.id,role:"activity_group",activities:[n],timestamp:t.timestamp,turnId:t.turnId,traceState:"running",traceStartedAt:t.timestamp})}function Uu(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 nQ(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 av(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"),r=o.length>0?o:a.length>0?[a[a.length-1]]:[];for(const l of r)l.traceState=n;const s=r.at(-1);s&&(s.traceCompletedAt=t.timestamp,s.timestamp=t.timestamp)}function aQ(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(r=>r.controlKind!=="turn_aborted")??[];o.length!==a.activities?.length&&(o.length===0?e.splice(n,1):a.activities=o)}av(e,t,"interrupted"),!VY(t.output)&&e.push({id:t.id,role:"status_divider",content:iQ(t),timestamp:t.timestamp,turnId:t.turnId,statusKind:"interruption",statusState:"failed",statusTone:"danger"})}function iQ(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 oQ(e,t,n=GA(t)){const a=[...e];return hQ(a,t,n)||mQ(a,t,n)||pQ(a,t,n)||fQ(a,t,n)?a:[...a,n]}function rQ(e){return e.name==="session.compaction.started"||e.name==="session.compaction.completed"||e.name==="session.compaction.failed"}function sQ(e,t){const n={id:t.id,role:"status_divider",content:lQ(t),timestamp:t.timestamp,turnId:t.turnId,statusKind:"compaction",statusState:cQ(t),statusTone:dQ(t)};if(t.name!=="session.compaction.started"){const a=bo(e,o=>o.role==="status_divider"&&o.statusKind==="compaction"&&o.statusState==="running"&&o.turnId===t.turnId);if(a){a.id=n.id,a.content=n.content,a.timestamp=n.timestamp,a.statusState=n.statusState,a.statusTone=n.statusTone;return}}e.push(n)}function lQ(e){const t=uQ(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 cQ(e){return e.name==="session.compaction.started"?"running":e.name==="session.compaction.completed"?"completed":"failed"}function dQ(e){return e.name==="session.compaction.failed"?"danger":e.name==="session.compaction.completed"?"success":"info"}function uQ(e){return Pe(e.data)?.reason==="auto"?"auto":"manual"}function GA(e){const t=HY(e),n=e.name==="assistant.reasoning.delta"?"reasoning":_Q(e),a=CQ(e),o=AQ(e),r=PQ(e),s=TQ(e),l=EQ(e),m=LY(e);return{id:e.id,label:l?l.direction==="received"?"Child message received":"Child message sent":bQ(e),content:l?.summary??SQ(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:Hy(e)??void 0}:{},...n&&e.name==="command.output"?{detail:iv(e)}:{},...n==="command"?{terminal:DQ(e)}:{},...r?{meta:r}:{},...o?{receipt:o}:{},...s?{openSession:s}:{},...l?{subagentMessage:l}:{},state:vQ(e),...t?{imagePreview:t}:{},...m.length>0?{artifacts:m}:{}}}function mQ(e,t,n){if(t.name==="tool.completed"){const a=fk(e,t);if(!a)return!1;const o=HQ(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 r=iv(t);return r&&r!==a.content&&(a.detail=km(a.detail,r)),!0}if(t.name==="command.output"){const a=fk(e,t);if(!a)return!1;const o=iv(t);return o&&(a.detail=km(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 pQ(e,t,n){if(t.name!=="tool.completed"||n.kind==="command")return!1;const a=Hy(t),o=bo(e,s=>s.state==="running"&&s.kind!=="command"&&(a?s.callId===a:!!t.action&&s.action===t.action));if(!o)return!1;const r=n.content.trim();return o.id=n.id,o.label=n.label,o.timestamp=n.timestamp,o.state=n.state,r&&r!==o.content.trim()&&(o.content.trim()===o.action?o.content=r:o.detail=km(o.detail,r)),n.detail&&(o.detail=km(o.detail,n.detail)),o.meta=n.meta,o.receipt=n.receipt,o.imagePreview=n.imagePreview??o.imagePreview,o.artifacts=n.artifacts,!0}function fQ(e,t,n){if(t.name!=="workspace_action_result")return!1;const a=gQ(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 hQ(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 fk(e,t){const n=Hy(t);if(n){const a=bo(e,o=>o.kind==="command"&&o.callId===n);if(a)return a}return bo(e,a=>a.kind==="command")}function gQ(e,t){const n=t.action??"",a=JA[n]??{started:"Running workspace action"};return bo(e,o=>o.state==="running"&&o.label===a.started&&o.kind!=="command"&&!o.controlKind)}function vQ(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 bQ(e){if(e.name==="assistant.reasoning.delta")return Ce(Pe(e.data),["kind"])==="commentary"?"Update":"Reasoning";if(bp(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(nv(e)&&e.name==="tool.started")return"Reading image";if(nv(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=UY(e);if(t)return t;const n=kQ(e);if(n)return n;const a=xQ(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"?yQ(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 JA={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 yQ(e){const t=e.action??"",n=JA[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 SQ(e,t){if(e.name==="assistant.reasoning.delta")return e.output??"";if(t)return t.path;const n=KA(e.output??"");if(n)return n.text;if(bp(e)||e.name==="turn.interrupted")return e.output??e.error??"";const a=wQ(e);if(a)return a;const o=IQ(e);if(o)return o;const r=zY(e);if(r)return r;const s=ZA(e);if(s)return s;if(e.name==="command.output")return QA(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 f=l.type;if(typeof f=="string"&&f.trim())return f}}return e.name==="session.compaction.started"||e.name==="session.compaction.completed"||e.name==="session.compaction.failed"?e.error??e.output??"":e.output??e.action??""}function xQ(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 kQ(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 wQ(e){if(!e.action?.startsWith("openpond_browser_"))return null;const t=Pe(Pe(e.data)?.result),n=Ce(t,["output"]);if(n)return n;const a=Pe(ar(e.output??"")),o=Ce(a,["output"]);if(o)return o;const r=Pe(e.args),s=Ce(r,["url"]);return s||(e.action==="openpond_browser_type"?"Text redacted":e.error??e.output??e.action)}function IQ(e){if(e.action!=="openpond_create_improve")return null;const t=Pe(Pe(e.data)?.result),n=Ce(t,["nextStep"]);if(n)return n;const a=Pe(ar(e.output??"")),o=Ce(a,["output"]);if(o)return o;const r=Pe(e.args),s=Ce(r,["reason"]);if(s)return s;const l=Ce(r,["objective"]);return l||(e.error??null)}function _Q(e){if(e.name==="command.output")return"command";if(e.name!=="tool.started"&&e.name!=="tool.completed")return;const t=Pe(e.data),n=Ce(t,["type"]),a=Ce(t,["tool","toolName","tool_name","name","functionName","function_name"]);if(e.action==="commandExecution"||n==="commandExecution"||ZA(e)||a&&/(^|[._-])exec_command$/i.test(a))return"command"}function CQ(e){if(e.name==="turn.interrupted")return"turn_aborted";if(bp(e))return"goal_context"}function ZA(e){const t=Pe(e.data),n=Ce(t,["type"]),a=Ce(t,["tool","toolName","tool_name","name","functionName","function_name"]),o=Pe(t?.result),r=Pe(ar(e.output??"")),s=Pe(r?.data),l=Ce(t,["command","cmd"])??Ce(Pe(t?.input),["command","cmd"])??Ce(Pe(t?.arguments),["command","cmd"])??Ce(Pe(t?.args),["command","cmd"])??RQ(Ce(t,["arguments","args","input"]))??Ce(Pe(e.args),["command","cmd"])??Ce(o,["command","cmd"])??Ce(s,["command","cmd"]);return l||e.name==="tool.started"&&(e.action==="commandExecution"||n==="commandExecution"||/(^|[._-])exec_command$/i.test(a??""))&&e.output?.trim()||null}function RQ(e){if(!e)return null;const t=ar(e),n=Pe(t);return Ce(n,["command","cmd"])}function Hy(e){const t=Pe(e.data);return Ce(t,["callId","call_id","toolCallId","tool_call_id","id","itemId","item_id"])}function PQ(e){const t=Pe(e.data);if(!t)return null;const n=[],a=Pe(t.workspaceToolTiming),o=typeof a?.durationMs=="number"?a.durationMs:null;o!==null&&n.push(OQ(o));const r=Pe(t.workspaceExecutionTarget),s=Ce(r,["target"]);if(s==="sandbox"){const d=r?.hybrid===!0,f=Ce(r,["sandboxId","workspaceId"]);n.push(`${d?"Hybrid ":""}sandbox${f?` ${hk(f)}`:""}`)}else s==="local"&&n.push("local workspace");const l=Pe(t.sourcePreservation);if(l?.attempted===!0)if(l.ok!==!0)n.push("checkpoint failed");else if(l.preserved===!0){const d=Ce(l,["preservedSha"]);n.push(d?`checkpoint ${NQ(d)}`:"checkpoint saved")}else n.push("checkpoint clean");const m=YA(t);return m&&(n.push(`receipt ${hk(m.id)}`),n.push(`${$Q(m.totalUsd)} ${m.status}`)),n.length>0?n.join(" · "):null}function AQ(e){const t=YA(Pe(e.data));return t?{id:t.id,status:t.status,totalUsd:t.totalUsd}:void 0}function TQ(e){if(!e.name.startsWith("subagent."))return;const t=Pe(e.data),n=Pe(t?.run),a=Ce(t,["childSessionId"])??Ce(n,["childSessionId"]);if(!a)return;const o=Ce(n,["roleId"])??Ce(t,["roleId"]),r=Ce(n,["status"])??Ce(t,["status"]);return{sessionId:a,label:"Open conversation",...o?{roleId:o}:{},...r?{status:r}:{}}}function EQ(e){if(e.name!=="subagent.message")return;const t=Pe(e.data),n=Pe(t?.message);if(!n)return;const a=Ce(n,["id"]),o=Ce(n,["kind"]),r=Ce(n,["fromRunId"]),s=Ce(n,["body"]);if(!a||!o||!r||!s)return;const l=Pe(t?.delivery??n.delivery),m=Pe(t?.modelRef),d=Ce(m,["providerId"]),f=Ce(m,["modelId"]),x=Ce(l,["deliveredParentSessionId"])===e.sessionId&&!r.startsWith("parent:")?"received":"sent",k=Array.isArray(n.refs)?n.refs.flatMap(C=>{const R=Pe(C),E=Ce(R,["kind"]),A=Ce(R,["id"]),O=Ce(R,["label"]);return E&&A&&O?[{kind:E,id:A,label:O}]:[]}):[];return{direction:x,summary:MQ(s),body:s,messageId:a,kind:o,fromRunId:r,toRunId:Ce(n,["toRunId"]),toRole:Ce(n,["toRole"]),childSessionId:Ce(t,["childSessionId"]),roleId:Ce(t,["roleId"]),modelRef:d&&f?{providerId:d,modelId:f}:null,deliveryStatus:Ce(l,["status"]),wakeReason:Ce(l,["wakeParentReason"]),createdAt:Ce(n,["createdAt"]),refs:k}}function MQ(e){const t=e.replace(/\s+/g," ").trim();if(!t)return"No message body";const n=/^(.*?[.!?])(?:\s|$)/.exec(t)?.[1]??t;return jQ(n,96)}function jQ(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 YA(e){const t=Pe(e?.sandbox),n=Array.isArray(t?.receipts)?t.receipts:[];for(let a=n.length-1;a>=0;a-=1){const o=Pe(n[a]),r=Ce(o,["id"]),s=Ce(o,["status"]),l=Ce(o,["totalUsd","retailTotalUsd"]);if(r&&s&&l)return{id:r,status:s,totalUsd:l}}return null}function OQ(e){return e<1e3?`${Math.max(0,Math.round(e))} ms`:e<1e4?`${(e/1e3).toFixed(1)} s`:`${Math.round(e/1e3)} s`}function $Q(e){const t=e.trim();return t.startsWith("$")?t:`$${t}`}function NQ(e){return e.length>12?e.slice(0,12):e}function hk(e){const t=e.trim();return t.length<=14?t:`${t.slice(0,6)}...${t.slice(-4)}`}function QA(e){let t=e.replace(/\r\n/g,`
|
|
196
|
-
`).trim();if(!t)return"";const n=LQ(t);if(n!==null)return Bs(n);const a=`
|
|
197
|
-
Output:
|
|
198
|
-
`,o=t.indexOf(a);return o>=0&&qQ(t.slice(0,o))&&(t=t.slice(o+a.length).trim()),t=t.replace(/^Total output lines: \d+\n\n/,""),Bs(t.trim())}function iv(e){const t=QA(e.output??"");if(t)return t;const n=Pe(Pe(e.data)?.result);return n?Bs(XA(n)):""}function DQ(e){const t=Pe(e.data),n=Pe(t?.result),a=Pe(ar(e.output??"")),o=Pe(a?.data),r=Pe(t?.workspaceToolTiming),s=[n?.exitCode,o?.exitCode,t?.exitCode].find(m=>typeof m=="number"),l=r?.durationMs;return{...typeof s=="number"?{exitCode:s}:{},...typeof l=="number"?{durationMs:l}:{}}}function HQ(e,t){const n=Date.parse(t)-Date.parse(e);return Number.isFinite(n)&&n>0?n:null}function LQ(e){const t=Pe(ar(e)),n=typeof t?.action=="string"?t.action:"";if(!t||typeof t.ok!="boolean"||!n||typeof t.output!="string")return null;const a=Pe(t.data);return a?XA(a,Ce(t,["output"])):typeof t.output=="string"?t.output.trim():""}function XA(e,t=null){const n=Ce(e,["stdout"])?.replace(/\r\n/g,`
|
|
199
|
-
`).trimEnd()??"",a=Ce(e,["stderr"])?.replace(/\r\n/g,`
|
|
200
|
-
`).trimEnd()??"",o=[n,a].filter(Boolean);return o.length>0?o.join(`
|
|
201
|
-
`):t?.replace(/\r\n/g,`
|
|
202
|
-
`).trim()??""}function qQ(e){return/^(Chunk ID|Exit code):/m.test(e)&&/Wall time:/m.test(e)}function km(e,t){const n=e??"";if(!n)return Bs(t);if(n===t||n.includes(t))return n;if(t.includes(n))return Bs(t);const a=n.endsWith(`
|
|
203
|
-
`)||t.startsWith(`
|
|
204
|
-
`)?"":`
|
|
205
|
-
`;return Bs(`${n}${a}${t}`)}function Bs(e){if(e.length<=uk)return e;const t=`
|
|
206
|
-
|
|
207
|
-
… output omitted from live view; full output remains in task history …
|
|
208
|
-
|
|
209
|
-
`,n=Math.max(0,uk-mk-t.length);return`${e.slice(0,mk)}${t}${e.slice(-n)}`}const UQ=/\bopenpond\s+opchat\b/i,zQ=/\b(?:50[0-9]|52[0-9]|53[0-9])\b|bad\s+gateway|gateway\s+timeout|service\s+unavailable/i;function eT(e){const t=e?.trim()||"Turn failed";return UQ.test(t)&&zQ.test(t)?"Server connection lost. Retry your message.":t}function BQ(e,t){if((hu(t,"code")??hu(t,"errorCode"))==="opchat_quota_exceeded")return"opchat_quota_exceeded";const a=t&&typeof t=="object"?t.error:null;if(a&&typeof a=="object"&&(hu(a,"code")??hu(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 hu(e,t){if(!e||typeof e!="object")return null;const a=e[t];return typeof a=="string"&&a.trim()?a.trim():null}function FQ(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=VQ(a.activities??[]);if(o.length===0){a.deliverables=void 0;continue}const r=t.get(a.turnId)??"",s=r?KQ(o,r):[];if(s.length>0){a.deliverables=s;continue}a.deliverables=n.has(a.turnId)?[o[o.length-1]]:void 0}}function VQ(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 KQ(e,t){const n=tT(t);return e.filter(a=>WQ(a).some(o=>t.includes(o)||n.includes(o)))}function WQ(e){const t=new Set;for(const n of[e.path,e.title,GQ(e.path)]){const a=n.trim();a&&(t.add(a),t.add(tT(a)))}return[...t]}function GQ(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).at(-1)??e}function tT(e){try{return decodeURIComponent(e)}catch{return e}}const nT=8;function JQ(e){if(e.name!=="tool.completed"||e.status==="failed")return[];if(e.action!=="web_search"&&e.action!=="web_fetch")return[];const t=rv(e.data),n=e.output?rv(ar(e.output)):null;return ZQ(t??n)}function ov(e,t){if(t.length===0)return e;const n=[],a=new Set;for(const o of[...e??[],...t]){const r=aT(o.url);if(!(!r||a.has(r))&&(a.add(r),n.push(o),n.length>=nT))break}return n.length>0?n:void 0}function rv(e,t=0){if(t>5)return null;const n=Pe(e);if(!n)return null;const a=Array.isArray(n.results)?n.results:Array.isArray(n.items)?n.items:Ce(n,["url"])?[n]:null;if(a)return{provider:Ce(n,["provider"]),results:a};for(const o of["result","data","output"]){const r=rv(n[o],t+1);if(r)return r}return null}function ZQ(e){if(!e)return[];const t=[],n=new Set;for(let a=0;a<e.results.length;a+=1){const o=YQ(e.results[a],a,e.provider);if(!o)continue;const r=aT(o.url);if(!(!r||n.has(r))&&(n.add(r),t.push(o),t.length>=nT))break}return t}function YQ(e,t,n){const a=Pe(e);if(!a)return null;const o=Ce(a,["url","href"]);if(!o||!QQ(o))return null;const r=Ce(a,["title"])??gk(o)??`Source ${t+1}`;return{id:Ce(a,["id"])??`source_${t+1}`,title:r,url:o,sourceName:Ce(a,["sourceName","source_name","source"])??gk(o),snippet:Ce(a,["snippet","description"]),provider:n,faviconUrl:XQ(Ce(a,["faviconUrl","favicon_url","iconUrl","icon_url"]))??eX(o),publishedAt:Ce(a,["publishedAt","published_at"]),updatedAt:Ce(a,["updatedAt","updated_at"])}}function QQ(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function aT(e){try{const t=new URL(e);return t.hash="",t.toString()}catch{return null}}function XQ(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 eX(e){try{return new URL("/favicon.ico",e).toString()}catch{return null}}function gk(e){try{return new URL(e).hostname.replace(/^www\./i,"")}catch{return null}}function tX(e){const t=Pe(e.data),n=ty.safeParse(t?.input);if(!n.success||!n.data.senderSessionId||n.data.senderKind==="user")return null;const a=n.data,o=Pe(t?.delivery),r=o?.direction==="sent"&&e.sessionId===a.senderSessionId;if(!r&&e.sessionId!==a.sessionId)return null;const s=r?a.sessionId:a.senderSessionId,l=Pe(o?.peer),m=l?.sessionId===s;return{id:`task-input:${a.id}:${r?"sent":"received"}`,role:"task_message",content:a.body,timestamp:a.createdAt,turnId:r?void 0:a.turnId??void 0,taskMessage:{input:a,direction:r?"sent":"received",peer:{sessionId:s,title:m&&typeof l.title=="string"?l.title:"Another task",provider:m&&typeof l.provider=="string"?l.provider:""}}}}function vk(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.every(n=>typeof Pe(n)?.text=="string")?e.map(n=>Pe(n).text).join(`
|
|
210
|
-
`):JSON.stringify(e);const t=Pe(e);return typeof t?.text=="string"?t.text:e==null?"":JSON.stringify(e)}function nX(e,t){const n=Pe(e.data);if(!n?.retainedHistory||e.action!=="native_tool"||!["tool.started","tool.completed"].includes(e.name))return e;const a=Pe(n.content)??{},o=e.name==="tool.started",r=typeof n.callId=="string"?n.callId:null,s=o&&typeof a.name=="string"?a.name:(r?t.get(r):void 0)??"native_tool";o&&r&&t.set(r,s);let l=a.input??a.arguments;if(typeof l=="string")try{l=JSON.parse(l)}catch{l={input:l}}const m=a.error||(a.is_error===!0?a.content:null);return{...e,action:s,status:o?"started":m!=null||a.status==="error"?"failed":"completed",...o?{args:Pe(l)??{}}:{output:vk(a.output??a.content??n.content),...m!=null?{error:vk(m)}:{}}}}const bk=new WeakMap;function yp(e){const t=bk.get(e);if(t)return t;const n=aX(e);return bk.set(e,n),n}function aX(e){const t=[],n=new Set,a=new Map,o=new Map,r=new Map;for(const s of e){const l=nX(s,r);if(l.name==="task.input"){const m=tX(l);if(m){const f=a.get(m.id);if(!f)a.set(m.id,m),t.push(m);else{const g=m.taskMessage.input,x=f.taskMessage.input;(g.revision>x.revision||g.revision===x.revision&&g.updatedAt>=x.updatedAt)&&Object.assign(f,m)}continue}const d=ty.safeParse(Pe(l.data)?.input);d.success&&d.data.senderKind==="user"&&d.data.kind==="steer"&&!n.has(d.data.id)&&(n.add(d.data.id),t.push({id:`task-input:${d.data.id}`,role:"user",content:d.data.body,timestamp:l.timestamp,turnId:d.data.turnId??void 0}));continue}if(l.name==="turn.started"){Uu(t,l),iX(t,l);const m=lX(l.args);if(m){const d=Pe(l.args)?.taskInputId,f=typeof d=="string"?a.get(`task-input:${d}:received`):null;if(f?.taskMessage?.input.kind==="followup"){f.turnId=l.turnId;continue}const g=KA(m);if(g){pk(t,{...l,name:g.kind==="turn_aborted"?"turn.interrupted":"diagnostic",output:g.text,data:{...Pe(l.data)??{},kind:g.kind}});continue}t.push({id:l.id,role:"user",content:m,attachments:cX(l.args),timestamp:l.timestamp,turnId:l.turnId});const x=Sk(l.args);x&&t.push({id:`${l.id}:create-improve`,role:"assistant",timestamp:l.timestamp,turnId:l.turnId,createImproveRun:x})}continue}if(l.name==="create_improve.updated"){const m=Sk(l.data);if(!m)continue;const d=bo(t,f=>f.turnId===l.turnId&&!!f.createImproveRun);d?(d.createImproveRun=m,d.timestamp=l.timestamp):t.push({id:`${l.id}:create-improve`,role:"assistant",timestamp:l.timestamp,turnId:l.turnId,createImproveRun:m});continue}if(l.name==="assistant.delta"){const m=l.output??"";if(!m)continue;Uu(t,l);const d=Pe(l.data);if(d?.retainedHistory===!0&&typeof d.nativeMessageId=="string"){const g=d.nativeMessageId,x=t.find(k=>k.id===g);x?(x.content=m,x.timestamp=l.timestamp):t.push({id:g,role:"assistant",content:m,timestamp:l.timestamp,turnId:l.turnId});continue}const f=t[t.length-1];if(f?.role==="assistant"&&f.turnId===l.turnId&&!f.createImproveRun)f.content=`${f.content??""}${m}`,f.timestamp=l.timestamp,f.sources=ov(f.sources,yk(o,l.turnId)??[]);else{const g=yk(o,l.turnId);t.push({id:l.id,role:"assistant",content:m,timestamp:l.timestamp,turnId:l.turnId,...g?.length?{sources:g}:{}})}continue}if(l.name==="assistant.reasoning.delta"){const m=l.output??"";if(!m)continue;Uu(t,l);const d=t[t.length-1];d?.role==="assistant"&&d.turnId===l.turnId&&d.reasoningContent!==void 0&&!d.createImproveRun?(d.reasoningContent=`${d.reasoningContent}${m}`,d.timestamp=l.timestamp):d?.role==="assistant"&&d.turnId===l.turnId&&!d.reasoningContent&&!d.createImproveRun?(d.reasoningContent=m,d.timestamp=l.timestamp):t.push({id:l.id,role:"assistant",reasoningContent:m,timestamp:l.timestamp,turnId:l.turnId});continue}if(l.name==="user_question.asked"){const m=Pe(l.data),d=sN.safeParse(m?.question);if(!d.success)continue;t.push({id:l.id,role:"assistant",timestamp:l.timestamp,turnId:l.turnId,userQuestion:d.data});continue}if(l.name==="user_question.answered"||l.name==="user_question.dismissed"){const m=Pe(l.data),d=lN.safeParse(m?.resolution);if(!d.success)continue;const f=bo(t,g=>g.userQuestion?.id===d.data.questionId);if(!f?.userQuestion||f.userQuestion.status!=="pending")continue;f.userQuestion={...f.userQuestion,status:d.data.action==="answer"?"answered":"dismissed",answer:d.data.action==="answer"?{optionId:d.data.optionId,text:d.data.text}:null,answeredAt:l.timestamp},f.timestamp=l.timestamp;continue}if(l.name==="turn.completed"){av(t,l,"completed");continue}if(l.name==="turn.failed"){av(t,l,"failed");const m=l.error??"Turn failed",d=BQ(m,l.data);t.push({id:l.id,role:"error",content:eT(m),...d?{errorKind:d}:{},timestamp:l.timestamp,turnId:l.turnId});continue}if(l.name==="turn.interrupted"){aQ(t,l);continue}if(rQ(l)){sQ(t,l);continue}if(l.name.startsWith("harness.refiner.")){KY(t,l);continue}if(l.name==="tool.started"||l.name==="tool.completed"||l.name==="skill.selected"||l.name==="skill.loaded"||l.name==="skill.load_failed"||l.name==="command.output"||l.name==="workspace_action"||l.name==="workspace_action_result"||l.name==="approval.requested"||l.name.startsWith("subagent.")||bp(l)){if(rX(l))continue;const m=TY(l);if(m){AY(t,l,m);continue}const d=JQ(l);d.length>0&&oX(t,o,l.turnId,d),pk(t,l)}if(l.name==="workspace.diff"){const m=sX(l.data);if(!m||m.filesChanged===0)continue;const d=bo(t,f=>f.role==="assistant"&&f.turnId===l.turnId);d&&(d.changeSummary=m,d.timestamp=l.timestamp)}}return FQ(t),t}function iX(e,t){if(Pe(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 oX(e,t,n,a){if(!n)return;const o=e[e.length-1];if(o?.role!=="assistant"||o.turnId!==n){t.set(n,ov(t.get(n),a));return}o.sources=ov(o.sources,a)}function yk(e,t){if(!t)return;const n=e.get(t);return n&&e.delete(t),n}function rX(e){if(e.name!=="approval.requested")return!1;if(e.action==="create_plan")return!0;const t=Pe(e.data),n=Pe(t?.approval);return t?.kind==="create_plan"||n?.kind==="create_plan"}function sX(e){const t=xD.safeParse(e);return t.success?t.data:null}function lX(e){if(!e||typeof e!="object"||!("prompt"in e))return"";const t=e.prompt;return typeof t=="string"?t:""}function cX(e){if(!e||typeof e!="object"||!("attachments"in e))return;const t=nU.array().safeParse(e.attachments);return t.success&&t.data.length>0?t.data:void 0}function Sk(e){const t=Pe(e);if(!t)return null;const n=Qc.safeParse(t.createImproveRun);return n.success?n.data:null}function Zoe(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 Yoe(e){const t=iT(e);return t?t.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):""}function Qoe(e){const t=iT(e);return t?t.toLocaleString():""}function iT(e){if(!e)return null;const t=new Date(e);return Number.isNaN(t.getTime())?null:t}function dX(e){const{chatMessages:t,runtimeIndexes:n,selectedSessionId:a}=e,[o,r]=y.useState({}),s=y.useCallback(m=>{r(d=>({...d,[m.sessionId]:m}))},[]);y.useEffect(()=>{r(m=>{let d=m;for(const[f,g]of Object.entries(m)){const x=yp(wd(n,f));zA(x,g)&&(d===m&&(d={...m}),delete d[f])}return d})},[n]);const l=y.useMemo(()=>UA(t,a?o[a]:null),[t,o,a]);return{pendingChatUserMessages:o,recordPendingChatUserMessage:s,visibleChatMessages:l}}function uX({connection:e,selectedSession:t,setBootstrap:n,setError:a,setOpenPondCommandAccessMode:o,setSessions:r}){return{changeOpenPondCommandAccessMode:y.useCallback((l,m=t)=>{if(!e){a("Connect to OpenPond before saving preferences.");return}const d=m?.provider==="codex"?null:m;ie.savePreferences(e,{openPondCommandAccessMode:l}).then(f=>{o(f.preferences.openPondCommandAccessMode),n(g=>g&&{...g,preferences:f.preferences})}).catch(f=>{a(f instanceof Error?f.message:String(f))}),d&&ie.patchSession(e,d.id,{openPondCommandAccessMode:l}).then(f=>{r(g=>g.map(x=>x.id===f.id?f:x))}).catch(f=>{a(f instanceof Error?f.message:String(f))})},[e,t,n,a,o,r])}}function mX({localProjects:e,cloudProjects:t,sessions:n,runtimeIndexes:a,appPreferences:o,selectedSessionId:r,selectedProjectId:s,archivedChatsOpen:l,projectsExpanded:m,chatRowsVisibleCount:d,sidebarFileBookmarks:f=[]}){const g=y.useMemo(()=>e.filter(ue=>!ue.hiddenFromDefaultSidebar),[e]),x=y.useMemo(()=>n.filter(ue=>!ue.archived&&xk(ue)),[n]),k=y.useMemo(()=>x.filter(ue=>ue.pinned),[x]),C=y.useMemo(()=>x.filter(ue=>!!ue.savedForLater),[x]),R=y.useMemo(()=>n.filter(ue=>ue.archived&&xk(ue)),[n]),E=y.useMemo(()=>new Set(e.map(ue=>ue.id)),[e]),A=y.useMemo(()=>new Set(t.map(ue=>ue.id)),[t]),O=y.useMemo(()=>HP(e),[e]),$=y.useMemo(()=>{const ue={};for(const Le of n){const Fe=Ix(Le,E,O,A);Fe&&(ue[Le.id]=Fe)}const Ie=new Map(n.map(Le=>[Le.id,Le]));for(const Le of n){if(ue[Le.id])continue;const Fe=new Set([Le.id]);let Xe=Le.parentSessionId;for(;Xe&&!Fe.has(Xe);){if(ue[Xe]){ue[Le.id]=ue[Xe];break}Fe.add(Xe),Xe=Ie.get(Xe)?.parentSessionId}}return ue},[n,A,E,O]),M=y.useMemo(()=>x.filter(ue=>!ue.pinned&&!ue.savedForLater&&!ue.appId&&!$[ue.id]),[x,$]),w=y.useMemo(()=>R.filter(ue=>!ue.appId&&!Ix(ue,E,O,A)),[R,A,E,O]),P=y.useMemo(()=>{const ue={};for(const Ie of x){if(Ie.pinned||Ie.savedForLater)continue;const Le=$[Ie.id];if(!Le)continue;const Fe=ue[Le];Fe?Fe.push(Ie):ue[Le]=[Ie]}return ue},[x,$]),j=y.useMemo(()=>{const ue={};for(const Ie of n){if(!oT(Ie))continue;const Le=ue[Ie.parentSessionId];Le?Le.push(Ie):ue[Ie.parentSessionId]=[Ie]}for(const Ie of Object.values(ue))Ie.sort((Le,Fe)=>Date.parse(Fe.updatedAt)-Date.parse(Le.updatedAt));return ue},[n]),N=y.useMemo(()=>g.map((ue,Ie)=>{const Le=kt("local",ue.id),Fe=hZ(ue,t);return{id:Le,kind:"local",project:ue,pinned:!!o[Le]?.pinned,order:o[Le]?.order??Ie,cloudLinkTrusted:!Fe,cloudLinkWarning:Fe}}).sort(zh),[o,t,g]),z=y.useMemo(()=>t.map((ue,Ie)=>{const Le=kt("cloud",ue.id);return{id:Le,kind:"cloud",project:ue,pinned:!!o[Le]?.pinned,order:o[Le]?.order??Ie,cloudLinkTrusted:!0,cloudLinkWarning:null}}).sort(zh),[o,t]),D=y.useMemo(()=>new Set(g.map(ue=>Ga(ue,t)?.id??null).filter(ue=>!!ue)),[t,g]),F=y.useMemo(()=>z.filter(ue=>!D.has(ue.project.id)),[z,D]),te=y.useMemo(()=>[...N,...F].sort(zh),[F,N]),ve=y.useMemo(()=>te.filter(ue=>ue.pinned),[te]),re=y.useMemo(()=>f.filter(ue=>ue.status==="pinned"),[f]),K=y.useMemo(()=>f.filter(ue=>ue.status==="saved_for_later"),[f]),L=te,de=y.useMemo(()=>pX(L,m,s),[L,m,s]),X=y.useMemo(()=>[...ve.map(ue=>({type:"project",key:_r({type:"project",id:ue.id}),id:ue.id,item:ue,order:ue.order})),...k.map(ue=>({type:"session",key:_r({type:"session",id:ue.id}),id:ue.id,session:ue,order:ue.order})),...re.map((ue,Ie)=>({type:"file",key:_r({type:"file",id:ue.id}),id:ue.id,file:ue,order:ue.order??ve.length+k.length+Ie}))].sort((ue,Ie)=>{if(ue.order!==Ie.order)return ue.order-Ie.order;if(ue.type!==Ie.type){const Xe={project:0,session:1,file:2};return Xe[ue.type]-Xe[Ie.type]}const Le=ue.type==="project"?ue.item.project.name:ue.type==="session"?ue.session.title:ue.file.path,Fe=Ie.type==="project"?Ie.item.project.name:Ie.type==="session"?Ie.session.title:Ie.file.path;return Le.localeCompare(Fe)}),[re,ve,k]),Z=y.useMemo(()=>l?[...M,...w]:M,[l,w,M]),pe=y.useMemo(()=>Z.slice(0,Math.max(Bn,d)),[Z,d]),ee=y.useMemo(()=>wd(a,r),[a,r]),me=y.useMemo(()=>yp(ee),[ee]),be=xA(a,r),je=kA(a,r),ke=tZ(a,r);return{activeSessions:x,pinnedSessions:k,savedForLaterSessions:C,pinnedFiles:re,savedForLaterFiles:K,chatSessions:M,archivedSessions:R,pinnedProjects:ve,pinnedItems:X,projectRows:L,localProjectRows:N,visibleProjectRows:de,cloudProjectRows:F,projectSessionRowsByProjectId:P,childSessionRowsByParentId:j,sidebarProjectIdBySessionId:$,chatRows:Z,visibleChatRows:pe,sessionEvents:ee,chatMessages:me,contextUsage:be,goalRuntime:je,subagentRuntime:ke}}function xk(e){return oT(e)?!1:e.hiddenFromDefaultSidebar?e.metadata?.benchmarkRuntime==="desktop_local_work":!0}function oT(e){return!!(e.parentSessionId&&e.subagentRunId)}function zh(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 pX(e,t,n){if(t||e.length<=Ou)return e;const a=e.slice(0,Ou);if(!n||a.some(r=>r.id===n))return a;const o=e.find(r=>r.id===n);return o?[...a.slice(0,Ou-1),o]:a}function fX(e){return e.name==="turn.completed"||e.name==="turn.failed"||e.name==="turn.interrupted"}function rT(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||!fX(o))&&!(n&&o.turnId&&o.turnId!==n))return o.name==="turn.completed"?"completed":"blocked"}return"pending"}function kk(e,t){if(e.systemKind)return!1;const n=wd(t,e.id);if(n.length===0)return!1;const a=rT(n);return a==="pending"||a==="none"&&sT(n)==="pending"}function wk(e,t){if(e.systemKind||e.status!=="active")return!1;const n=wd(t,e.id);if(n.length===0)return!0;const a=rT(n);return a==="pending"||a==="none"&&sT(n)!=="terminal"}function sT(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 hX({goalRuntime:e,goalRuntimeBySessionId:t,runtimeIndexes:n,selectedSession:a,selectedSessionId:o,sidebarSessions:r,subagentRuntimeBySessionId:s}){const l=y.useMemo(()=>new Map(r.map(x=>[x.id,x])),[r]),m=y.useMemo(()=>{const x=new Set;for(const[k,C]of t??[]){const R=l.get(k);C.tone==="active"&&!R?.systemKind&&x.add(k)}for(const k of n.activeGoalSessionIds)l.get(k)?.systemKind||x.add(k);return o&&!a?.systemKind&&e?.tone==="active"&&x.add(o),x},[e,t,n,a,o,l]),d=y.useMemo(()=>{const x=new Set(m);for(const[k,C]of s??[]){const R=l.get(k);C.activeCount>0&&!R?.systemKind&&x.add(k)}for(const k of n.activeSubagentSessionIds)l.get(k)?.systemKind||x.add(k);for(const k of r)k.systemKind||kk(k,n)&&x.add(k.id);return a&&kk(a,n)&&x.add(a.id),x},[m,n,a,r,l,s]),f=y.useMemo(()=>{const x=new Set(d);for(const k of r)wk(k,n)&&x.add(k.id);return a&&wk(a,n)&&x.add(a.id),x},[d,n,a,r]),g=!!(a&&!a.systemKind&&d.has(a.id));return{runningSessionIds:f,selectedSessionRunning:g}}const gX=1e3;function vX(e){const[t,n]=y.useState(()=>new Date().toISOString());return y.useEffect(()=>{if(!e)return;const a=()=>n(new Date().toISOString());a();const o=window.setInterval(a,gX);return()=>window.clearInterval(o)},[e]),t}function bX(e){const{codexHistoryEvents:t,codexHistorySessions:n,connection:a,expandedProjectIds:o,goalRuntime:r,locallyActiveCodexHistorySessionIds:s,pinnedSessions:l,savedForLaterSessions:m,projectSessionRowsByProjectId:d,rightChatHistoryEvents:f,runtimeIndexes:g,selectedSession:x,selectedSessionId:k,serverId:C,setCodexHistorySessions:R,sidebarSessions:E,subagentRuntime:A,visibleChatRows:O,visibleProjectRows:$}=e,[M,w]=y.useState({});y.useEffect(()=>{w({})},[C]);const P=y.useMemo(()=>{const Z=[],pe=new Set,ee=be=>{!be||be.id===k||!Jt(be.id)||pe.has(be.id)||(pe.add(be.id),Z.push(be.id))};for(const be of n)(be.status==="active"||s.has(be.id))&&ee(be);const me=Z.length;for(const be of $)for(const je of(d[be.id]??[]).slice(0,2))ee(je);for(const be of o)for(const je of(d[be]??[]).slice(0,Ou))ee(je);for(const be of l)ee(be);for(const be of m)ee(be);for(const be of O)ee(be);return[...Z.slice(0,me),...Z.slice(me,me+8)].join(`
|
|
211
|
-
`)},[n,o,s,l,m,d,k,O,$]),j=y.useCallback(Z=>{w(pe=>pe[Z.session.id]===Z.events?pe:{...pe,[Z.session.id]:Z.events}),R(pe=>vp(pe,Z.session))},[R]),N=y.useMemo(()=>{if(!P)return"";const Z=new Set(P.split(`
|
|
212
|
-
`).filter(Boolean));return E.filter(pe=>Z.has(pe.id)&&pe.status==="active").map(pe=>pe.id).join(`
|
|
213
|
-
`)},[P,E]),z=y.useMemo(()=>P?P.split(`
|
|
214
|
-
`).filter(Z=>s.has(Z)).join(`
|
|
215
|
-
`):"",[P,s]);y.useEffect(()=>{!x||!k||!Jt(k)||t.length===0||j({session:x,events:t})},[j,t,x,k]),y.useEffect(()=>{if(!a||!P)return;const Z=a,pe=P.split(`
|
|
216
|
-
`).filter(Boolean),ee=new Set(N.split(`
|
|
217
|
-
`).filter(Boolean)),me=new Set(z.split(`
|
|
218
|
-
`).filter(Boolean)),be=pe.map(je=>Dy({connection:Z,locallyActive:me.has(je),onPayload:ke=>j(Ny(ke,me.has(je))),reportedActive:ee.has(je),sessionId:je,surface:"sidebar"}));return()=>be.forEach(je=>je())},[j,N,z,P,a]);const D=y.useMemo(()=>new Map(E.map(Z=>[Z.id,Z])),[E]),F=y.useMemo(()=>{const Z=new Map(g.latestGoalRuntimeBySessionId);for(const pe of E){const ee=pe.status==="active"?$h(pe.metadata):null;ee&&Z.set(pe.id,ee)}for(const pe of[M,f])for(const[ee,me]of Object.entries(pe)){const be=D.get(ee),je=be?.status==="active"?$h(be.metadata):null,ke=Gg(me)??My(me)??(be?.status==="active"?xm(me)??je:null);ke?Z.set(ee,ke):Z.delete(ee)}if(k)if(r)Z.set(k,r);else if(x?.status==="active"&&t.length>0){const pe=Gg(t)??xm(t)??$h(x.metadata);pe?Z.set(k,pe):Z.delete(k)}else(!Jt(k)||t.length>0)&&Z.delete(k);return Z},[t.length,M,r,f,g.latestGoalRuntimeBySessionId,x?.status,x?.metadata,k,D,E]),te=y.useMemo(()=>[...F.values()].some(Z=>Z.tone==="active"&&!!Z.observedAt),[F]),ve=vX(te),re=y.useMemo(()=>te?new Map([...F].map(([Z,pe])=>[Z,EJ(pe,ve)??pe])):F,[F,ve,te]),K=k?re.get(k)??r:r,L=y.useMemo(()=>{const Z=new Map(g.latestSubagentRuntimeBySessionId);return k&&(A?Z.set(k,A):Z.delete(k)),Z},[g.latestSubagentRuntimeBySessionId,k,A]),{runningSessionIds:de,selectedSessionRunning:X}=hX({goalRuntime:K,goalRuntimeBySessionId:re,runtimeIndexes:g,selectedSession:x,selectedSessionId:k,sidebarSessions:E,subagentRuntimeBySessionId:L});return{goalRuntime:K,runningSessionIds:de,selectedSessionRunning:X,sidebarGoalRuntimeBySessionId:re,sidebarSubagentRuntimeBySessionId:L}}function yX({searchOpen:e,sectionMenuOpen:t,setSectionMenuOpen:n,setSearchOpen:a,setQuery:o}){y.useEffect(()=>{const r=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",r),()=>document.removeEventListener("keydown",r)},[e,t,o,a,n])}function SX({afterSequence:e,appendEvents:t,connection:n,setApprovals:a,setSessions:o,setError:r,onDisconnected:s}){y.useEffect(()=>{if(!n?.token||e===null)return;const l=n;let m=null,d=[],f=null,g=null,x=!1;const k=new Map;let C=0;const R=16;function E(){m!==null&&(window.clearTimeout(m),m=null)}function A(){r(D=>D==="Event stream disconnected"?null:D)}function O(){f=null;const D=d;if(d=[],D.length===0)return;C=Date.now(),t(D);const F=xX(D);F.length>0&&o(te=>F.reduce(rc,te)),a(te=>{let ve=te;for(const re of D)if(re.name==="approval.requested"&&re.data&&(ve=[re.data,...ve]),re.name==="approval.resolved"&&re.data&&typeof re.data=="object"){const K=re.data;K.approvalId&&(ve=ve.filter(L=>L.id!==K.approvalId))}return ve})}function $(){const D=Date.now()-C;if(D>=R){f!==null&&(window.clearTimeout(f),f=null),O();return}f===null&&(f=window.setTimeout(O,R-D))}function M(D){w(D),d.push(D),$()}function w(D){if(!(!D.sessionId||!D.name.startsWith("harness.refiner."))){if(D.name==="harness.refiner.completed"||D.name==="harness.refiner.failed"){k.delete(D.sessionId);return}(D.name==="harness.refiner.queued"||D.name==="harness.refiner.started")&&(k.set(D.sessionId,typeof D.sequence=="number"?D.sequence:0),P())}}function P(){g!==null||k.size===0||(g=window.setTimeout(()=>{g=null,j()},1e3))}async function j(){if(!(x||k.size===0)){x=!0;try{await Promise.all([...k].map(async([D,F])=>{const te=await ie.runtimeEventsPage(l,{sessionId:D,afterSequence:F,limit:100});for(const ve of te.events){const re=ve.event;k.set(D,Math.max(k.get(D)??0,ve.sequence)),M(re)}}))}catch{}finally{x=!1,P()}}}function N(){f!==null&&(window.clearTimeout(f),f=null),O()}document.addEventListener("visibilitychange",N);const z=jE(n,D=>{E(),A(),M(D)},()=>{E(),m=window.setTimeout(()=>{z.isOpen()||(r("Event stream disconnected"),s?.())},2e3)},()=>{E(),A(),window.dispatchEvent(new Event("openpond-runtime-connected"))},{afterSequence:e});return()=>{E(),f!==null&&window.clearTimeout(f),g!==null&&window.clearTimeout(g),f=null,g=null,d=[],document.removeEventListener("visibilitychange",N),z.close()}},[e,t,n,s,a,r,o])}function xX(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.updated"||n.name==="session.title.updated"?"session":n.name==="subagent.started"||n.name==="subagent.failed"?"childSession":null;if(!o)continue;const r=Cc.safeParse(a[o]);r.success&&t.set(r.data.id,r.data)}return[...t.values()]}function Bh(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function kX(e){return typeof e=="string"&&e.trim()?e.trim():null}function wX(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n.name!=="create_improve.updated")continue;const a=Bh(n.data),o=Bh(a?.createImproveRun);if(o?.state!=="ready_local"&&o?.state!=="released"||Bh(o.adapter)?.kind!=="local")continue;const s=kX(o.id)??n.id;return[n.sessionId??"global",n.turnId??"turn",s].join(":")}return null}const IX=332,Ik=244,_k=560,_X=560,Ck=320,Rk=2400,CX=440;function Fh(e){const t=typeof window>"u"?_k:Math.min(_k,Math.max(Ik,window.innerWidth-420));return Math.min(t,Math.max(Ik,Math.round(e)))}function Vh(e){const t=typeof window>"u"?Rk:Math.min(Rk,Math.max(Ck,window.innerWidth-CX));return Math.min(t,Math.max(Ck,Math.round(e)))}function RX(e,t){return!!(e&&e.serverUrl===t.serverUrl&&e.token===t.token&&e.platform===t.platform)}const Os=new Map;function Ly(e,t){const n=e?.trim();return n?`${t?.trim()||"global"}|${n}`:null}function lT(e,t){const n=Ly(e,t);if(!n)return null;const a=Os.get(n);return a?.updatedAt?a.agents:null}function PX(e,t,n){const a=Ly(e,n);a&&Os.set(a,{agents:t,promise:null,updatedAt:Date.now()})}function qy(e){const t=e.teamId?.trim();if(!t)return Promise.resolve([]);const n=Ly(t,e.accountKey);if(!n)return Promise.resolve([]);const a=Os.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(r=>(PX(t,r,e.accountKey),r)).catch(r=>{const s=Os.get(n);throw s?.promise===o&&Os.set(n,{agents:s.agents,promise:null,updatedAt:s.updatedAt}),r});return Os.set(n,{agents:a?.agents??[],promise:o,updatedAt:a?.updatedAt??0}),o}const AX=6e4,TX=6e4,EX=6e4,Uy=["pinned","projects","cloudProjects","chats","savedForLater"];function MX(e,t,n,a=Date.now()){for(const o of NX(t,n))cT(t[o],n[o])||(e[o]=a)}function jX(e,t,n,a=Date.now()){const o={...t};for(const[r,s]of Object.entries(n)){if(a-s>AX){delete n[r];continue}const l=HX(e,r),m=e[r];!l||cT(m,t[r])||(o[r]=m)}return o}function OX(e,t,n,a=Date.now()){for(const o of Uy)t[o]!==n[o]&&(e[o]=a)}function $X(e,t,n,a=Date.now()){const o={...t};for(const r of Uy){const s=n[r];if(s!==void 0){if(a-s>TX){delete n[r];continue}if(e[r]===t[r]){delete n[r];continue}o[r]=e[r]}}return DX(e,o)?e:o}function Pk(e,t,n=Date.now()){return e===t?null:{value:t,changedAt:n}}function Ak(e,t,n=Date.now()){return t?n-t.changedAt>EX?{value:e,localChange:null}:e===t.value?{value:e,localChange:t}:{value:t.value,localChange:t}:{value:e,localChange:null}}function NX(e,t){return new Set([...Object.keys(e),...Object.keys(t)])}function cT(e,t){return e?.pinned===t?.pinned&&e?.archived===t?.archived&&e?.order===t?.order}function DX(e,t){return Uy.every(n=>e[n]===t[n])}function HX(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const LX=5e4,Uo="\0openpond-unscoped-runtime-events",Pi=[];class qX{perSessionLimit;totalLimit;entries=new Map;eventKeyById=new Map;listenersByKey=new Map;allListeners=new Set;summaryListeners=new Set;retainedKeys=new Set;allEventsSnapshot=Pi;summaryEventsSnapshot=Pi;clock=0;eventCount=0;constructor(t={}){if(this.perSessionLimit=Mk(t.perSessionLimit??Ey,"perSessionLimit"),this.totalLimit=Mk(t.totalLimit??LX,"totalLimit"),this.totalLimit<this.perSessionLimit)throw new Error("totalLimit must be greater than or equal to perSessionLimit")}append(t){if(t.length===0)return Ek();const n=new Map;let a=0;for(const d of t){if(this.eventKeyById.has(d.id)){a+=1;continue}const f=d.sessionId||Uo,g=n.get(f);g?g.push(d):n.set(f,[d]),this.eventKeyById.set(d.id,f)}if(n.size===0)return{...Ek(),duplicateEventCount:a};const o=new Set;let r=0,s=0,l=!1;for(const[d,f]of n){f.some(jk)&&(l=!0);const g=this.entries.get(d),x=g?.snapshot.events??Pi,k=Math.max(0,Math.min(x.length,this.perSessionLimit-f.length)),C=f.length>this.perSessionLimit?f.slice(f.length-this.perSessionLimit):f,R=k===x.length?x:x.slice(x.length-k),E=R.length===0?C:[...R,...C],A=x.slice(0,x.length-R.length);A.some(jk)&&(l=!0);for(const M of A)this.eventKeyById.delete(M.id);for(const M of f.slice(0,f.length-C.length))this.eventKeyById.delete(M.id);const $={eventIds:new Set(E.map(M=>M.id)),lastTouched:++this.clock,retained:g?.retained??this.retainedKeys.has(d),snapshot:{events:E,latestSequence:Sm(E),revision:(g?.snapshot.revision??0)+1}};this.entries.set(d,$),this.eventCount+=E.length-x.length,r+=C.length,s+=A.length+f.length-C.length,o.add(d)}const m=this.enforceTotalLimit(o);return s+=m,this.publish(o,l||m>0),zX({acceptedEventCount:r,duplicateEventCount:a,evictedEventCount:s,changedKeys:o})}mergeBootstrap(t){const n=UX(t),a=new Set([...this.entries.keys(),...n.keys()]),o=[];for(const r of a){const s=n.get(r)??Pi,l=this.entries.get(r)?.snapshot.events??Pi;o.push(...IJ(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=Pi,this.summaryEventsSnapshot=Pi;const o=this.append(t);for(const m of this.retainedKeys){const d=this.entries.get(m);d&&(d.retained=!0)}const r=this.eventKeyById;let s=0;for(const m of n)r.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!==Uo)]),unscopedEventsChanged:o.unscopedEventsChanged||l.has(Uo)}}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=Pi,this.summaryEventsSnapshot=Pi,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??Tk:Tk;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(BX),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!==Uo&&a.retained&&(t+=1);return{eventCount:this.eventCount,retainedSessionCount:t,sessionCount:this.entries.size-(this.entries.has(Uo)?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,r]=a,s=this.eventCount-this.totalLimit;if(!r.retained||r.snapshot.events.length<=s){n+=r.snapshot.events.length,this.removeEntry(o),t.add(o);continue}const l=r.snapshot.events.slice(0,s),m=r.snapshot.events.slice(s);for(const d of l)this.eventKeyById.delete(d.id);r.eventIds=new Set(m.map(d=>d.id)),r.snapshot={events:m,latestSequence:Sm(m),revision:r.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 Tk=Object.freeze({events:Pi,latestSequence:null,revision:0});function UX(e){const t=new Map;for(const n of e){const a=n.sessionId||Uo,o=t.get(a);o?o.push(n):t.set(a,[n])}return t}function zX(e){return{acceptedEventCount:e.acceptedEventCount,duplicateEventCount:e.duplicateEventCount,evictedEventCount:e.evictedEventCount,changedSessionIds:new Set([...e.changedKeys].filter(t=>t!==Uo)),unscopedEventsChanged:e.changedKeys.has(Uo)}}function Ek(){return{acceptedEventCount:0,duplicateEventCount:0,evictedEventCount:0,changedSessionIds:new Set,unscopedEventsChanged:!1}}function BX(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 Mk(e,t){if(!Number.isInteger(e)||e<=0)throw new Error(`${t} must be a positive integer`);return e}function jk(e){return e.name!=="assistant.delta"&&e.name!=="assistant.reasoning.delta"&&e.name!=="command.output"}const FX=256,VX=15e3,KX=5e3,WX=3e4;class GX{constructor(t={}){this.options=t}options;entries=new Map;connection=null;accountScope=null;generation=0;activateConnection(t){JX(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,ZX(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(),r=this.entries.get(t);if(r?.state==="loading"&&!this.expired(r,o))return r.promise;if(r?.state==="failed"&&!this.expired(r,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??KX),lastAccessedAt:m}),this.prune(),null});return this.entries.set(t,{state:"loading",promise:l,expiresAt:o+(this.options.loadingTtlMs??WX),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??FX;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??VX:0;return t.expiresAt<=n+a}now(){return(this.options.now??Date.now)()}}const Ok=new GX;function Xoe(e,t,...n){return[t,e.serverUrl,...n].join("\0")}function JX(e,t){return e?.serverUrl===t?.serverUrl&&e?.token===t?.token&&e?.platform===t?.platform}function ZX(e,t,n){e.delete(t),e.set(t,n)}const YX={connecting:"Connecting to OpenPond",account:"Loading account",team:"Loading default team",ready:"Ready"};function QX(e){return{label:YX[e],ready:e==="ready",stage:e}}const XX=650,eee=1200,tee=6e4;function nee(e){const{selectedSessionId:t,setDraftModel:n,setDraftProvider:a,setCodexPermissionMode:o,setCodexReasoningEffort:r,setOpenPondCommandAccessMode:s,setError:l,setSelectedAppId:m,setSelectedProjectId:d,setSelectedSessionId:f}=e,[g,x]=y.useState(null),[k,C]=y.useState(null),[R]=y.useState(()=>new qX),E=y.useSyncExternalStore(R.subscribeSummary,R.getSummaryEvents,R.getSummaryEvents),A=y.useCallback(q=>{const oe=R.getAllEvents(),he=typeof q=="function"?q(oe):q;he!==oe&&R.replace(he)},[R]),O=y.useCallback(q=>{R.append(q)},[R]),[$,M]=y.useState(null),[w,P]=y.useState([]),[j,N]=y.useState([]),[z,D]=y.useState([]),[F,te]=y.useState({}),[ve,re]=y.useState("connecting"),K=Yg(k?.account),L=y.useRef({}),de=y.useRef({}),X=y.useRef({}),Z=y.useRef([]),pe=y.useRef([]),ee=y.useRef(null),me=y.useRef(null),be=y.useRef(!1),je=y.useRef(Date.now()),ke=y.useRef(null),ue=y.useRef(null);y.useEffect(()=>{Ok.activateConnection(g),Ok.activateAccountScope(K)},[g,K]);const Ie=y.useCallback(q=>{be.current||re(q)},[]),Le=y.useCallback(q=>{te(oe=>{const he=typeof q=="function"?q(oe):q;return MX(L.current,oe,he),he})},[]),Fe=y.useCallback(q=>{P(oe=>{const he=typeof q=="function"?q(oe):q;return ok(de.current,oe,he),Z.current=he,he})},[]),Xe=y.useCallback(q=>{N(oe=>{const he=typeof q=="function"?q(oe):q;return ok(X.current,oe,he),pe.current=he,he})},[]),Ze=y.useCallback(()=>{if(be.current||ke.current!==null)return;const q=()=>{ke.current=null,!be.current&&(be.current=!0,re("ready"))},oe=Date.now()-je.current,he=aee(oe);if(he===0){q();return}ke.current=window.setTimeout(q,he)},[]);y.useEffect(()=>()=>{ke.current!==null&&window.clearTimeout(ke.current)},[]);const Be=y.useCallback(q=>{const oe=ee.current,he=!oe||oe===q.server.id;ee.current=q.server.id,M(Re=>Re?.serverId===q.server.id?Re:{afterSequence:q.eventWindow?.latestSequence??Sm(q.events)??0,serverId:q.server.id}),C(q),he?R.mergeBootstrap(q.events):R.replace(q.events),P(Re=>{const qe=he?ik(Re,q.sessions,de.current):Qg(Re,q.sessions,de.current);return Z.current=qe,qe}),N(Re=>{const qe=he?ik(Re,q.codexHistorySessions??[],X.current):Qg(Re,q.codexHistorySessions??[],X.current);return pe.current=qe,qe}),D(q.approvals),te(Re=>jX(Re,q.sidebarAppPreferences,L.current)),m(Re=>Re&&q.apps.some(qe=>qe.id===Re)?Re:null),d(Re=>{if(!Re)return null;const qe=MP(Re);return qe?.kind==="local"&&q.localProjects.some(Je=>Je.id===qe.id)?kt("local",qe.id):qe?.kind==="cloud"&&(q.cloudProjects??[]).some(Je=>Je.id===qe.id)?kt("cloud",qe.id):q.localProjects.some(Je=>Je.id===Re)?kt("local",Re):(q.cloudProjects??[]).some(Je=>Je.id===Re)?kt("cloud",Re):null}),f(Re=>{if(!Re)return null;const qe=[...q.sessions,...q.codexHistorySessions??[]];if(qe.some(et=>et.id===Re&&!et.archived))return Re;if(!he)return null;const Je=Z.current.find(et=>et.id===Re)??pe.current.find(et=>et.id===Re)??null;return Je&&!Je.archived&&OA(Je,qe)?Re:null})},[R,m,d,f]),Ge=y.useCallback(q=>{C(oe=>oe&&{...oe,preferences:q.preferences})},[]);y.useEffect(()=>{if(t)return;const q=La(k?.preferences);a(q.defaultChatProvider),n(q.defaultChatModel)},[t,k?.preferences.defaultChatProvider,k?.preferences.defaultChatModel,n,a]),y.useEffect(()=>{o(La(k?.preferences).codexPermissionMode)},[k?.preferences.codexPermissionMode,o]),y.useEffect(()=>{r(La(k?.preferences).codexReasoningEffort)},[k?.preferences.codexReasoningEffort,r]),y.useEffect(()=>{s(La(k?.preferences).openPondCommandAccessMode)},[k?.preferences.openPondCommandAccessMode,s]),y.useEffect(()=>{if(!g||!k){me.current=null;return}if(k.account.state!=="signed_in"){me.current=null,Ze();return}const q=Yg(k.account);if(!q){me.current=null,Ze();return}Ze(),Ie("team");const oe=k.preferences.defaultTeamId?.trim()??"",he=iee(q,oe,k.accountMeta.asOf??"initial");if(me.current===he)return;me.current=he;let Re=!1;const qe=Je=>qy({teamId:Je,accountKey:q,fetchAgents:async et=>(await ie.listSandboxAgents(g,{teamId:et})).agents}).catch(()=>{!Re&&me.current===he&&(me.current=null)});return Zx({accountKey:q,force:!0,fetchOrganizations:()=>$k(g)}).then(async Je=>{if(Re)return;if(Je.length===0){Ze();return}if(!!oe&&Je.some(_t=>_t.teamId===oe)){await qe(oe),Ze();return}const dt=PZ(Je)?.teamId;if(!dt){Ze();return}if(oe){l("The configured default team is unavailable for this account. Select an available team in account settings."),Ze();return}await qe(dt),Re||Ze()}).catch(Je=>{Re||(me.current=null,l(Je instanceof Error?Je.message:String(Je)),Ze())}),()=>{Re=!0}},[Be,Ge,k?.account,k?.accountMeta.asOf,k?.preferences.defaultTeamId,Ze,g,Ie,l]),y.useEffect(()=>{if(!g||!K)return;let q=!1;const oe=()=>{q||(q=!0,Zx({accountKey:K,force:!0,fetchOrganizations:()=>$k(g)}).catch(()=>{}).finally(()=>{q=!1}))},he=()=>{document.visibilityState==="visible"&&oe()},Re=window.setInterval(oe,tee);return window.addEventListener("focus",oe),document.addEventListener("visibilitychange",he),()=>{window.clearInterval(Re),window.removeEventListener("focus",oe),document.removeEventListener("visibilitychange",he)}},[g,K]),al(()=>{const q=N8();l(q||(oe=>oe?.startsWith("Preference changes have not been saved.")?null:oe))}),y.useEffect(()=>{g&&xx(g).catch(q=>l(String(q)))},[g,K,l]);const Ve=y.useCallback(async()=>{Ie("connecting"),M(null);const q=await eW();x(he=>RX(he,q)?he:q),Ie("account");const oe=await ie.bootstrap(q);await xx(q),Be(oe),Ze(),l(he=>he&&(tA(he)||he==="Event stream disconnected")?null:he)},[Be,Ze,Ie,l]);y.useEffect(()=>{let q=!1,oe=null;const he=async Re=>{try{await Ve()}catch(qe){if(q)return;l(qe instanceof Error?qe.message:String(qe));const Je=Math.min(5e3,750+Re*750);oe=window.setTimeout(()=>{he(Re+1)},Je)}};return he(0),()=>{q=!0,oe!==null&&window.clearTimeout(oe)}},[Ve,l]);const U=y.useCallback(()=>{Ve().catch(()=>{})},[Ve]);SX({afterSequence:$?.afterSequence??null,appendEvents:O,connection:g,setApprovals:D,setSessions:Fe,setError:l,onDisconnected:U}),y.useEffect(()=>{if(!g||!k){ue.current=null;return}const q=wX(E);!q||ue.current===q||(ue.current=q,ie.profileCurrent(g).then(oe=>{C(he=>he&&{...he,profile:oe})}).catch(oe=>{ue.current=null,l(oe instanceof Error?oe.message:String(oe))}))},[k,g,E,l]);const J=y.useCallback(()=>{g&&ie.refreshOpenPondAccount(g).then(({account:q,accountMeta:oe})=>{C(he=>he&&{...he,account:q,accountMeta:oe})}).catch(q=>l(q instanceof Error?q.message:String(q)))},[g,l]);return{appPreferences:F,applyBootstrapPayload:Be,approvals:z,bootstrap:k,codexHistorySessions:j,connection:g,events:E,runtimeEventStore:R,refreshOpenPondAccount:J,sessions:w,startup:QX(ve),setAppPreferences:Le,setBootstrap:C,setCodexHistorySessions:Xe,setEvents:A,setSessions:Fe}}async function $k(e){return(await ie.organizations(e)).organizations.map(gp).filter(n=>!!n).filter(n=>n.status==="active")}function aee(e){return e>=eee?0:Math.max(0,XX-e)}function iee(e,t,n){return`${e}::${t||"none"}::${n}`}function oee({appDispatch:e,error:t,setErrorState:n}){const a=y.useRef(null),o=y.useRef(null),r=y.useRef(null),s=y.useRef(0),l=y.useCallback((d,f="info",g={})=>{const x=Date.now()+ ++s.current;return e({type:"showToast",toast:{id:x,message:d,tone:f,...g}}),x},[e]),m=y.useCallback(d=>{const f=o.current,g=typeof d=="function"?d(f):d;if(Object.is(f,g))return;if(o.current=g,n(g),!g){r.current!==null&&(e({type:"clearToast",toastId:r.current}),r.current=null);return}r.current=l(ree(g),"error");const x=a.current;x&&ie.recordClientDiagnostic(x,{message:g,surface:"app",context:{href:window.location.href}}).catch(k=>{console.warn("Unable to record client diagnostic.",k)})},[e,n,l]);return y.useEffect(()=>{o.current=t,!(t||r.current===null)&&(e({type:"clearToast",toastId:r.current}),r.current=null)},[e,t]),{connectionRef:a,setError:m,showToast:l}}function ree(e){return eA(e)}const see={query:"",searchOpen:!1,archivedChatsOpen:!1,sectionMenuOpen:null,projectsExpanded:!1,cloudProjectsExpanded:!1,chatRowsVisibleCount:Bn,sidebarOpen:!0,view:"chat",selectedAppId:null,selectedProjectId:null,selectedSessionId:null,prompt:"",promptDrafts:{},draftProvider:Tr,draftModel:wc,draftExperience:"chat",codexPermissionMode:Nv,codexReasoningEffort:Dv,openPondCommandAccessMode:Om,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 zy(e){return e.selectedSessionId?`session:${e.selectedSessionId}`:e.selectedProjectId?`project:${e.selectedProjectId}`:e.selectedAppId?`app:${e.selectedAppId}`:`new-${e.draftExperience}`}function wm(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 lee(e){return wm(e.promptDrafts,zy(e),e.prompt)}function Gl(e,t,n={}){const a={...e,...t},o=zy(a),r=lee(e),s=n.clearSelectedDraft?wm(r,o,""):n.preserveCurrentPrompt?wm(r,o,e.prompt):r;return{...e,...t,promptDrafts:s,prompt:n.clearSelectedDraft?"":n.preserveCurrentPrompt?e.prompt:s[o]??""}}function cee(e){return e==="draftExperience"||e==="selectedAppId"||e==="selectedProjectId"||e==="selectedSessionId"}function dee(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:wm(e.promptDrafts,zy(e),o)}}return cee(t.key)?Gl(e,{[t.key]:a}):{...e,[t.key]:a}}case"patch":return{...e,...t.patch};case"selectApp":return Gl(e,{selectedAppId:t.appId,selectedProjectId:null,selectedSessionId:null,view:"chat"});case"selectProject":return Gl(e,{selectedAppId:null,selectedProjectId:t.projectId,selectedSessionId:null,view:"chat"},{preserveCurrentPrompt:!0});case"selectSession":{const n=t.projectId??null;return Gl(e,{selectedSessionId:t.sessionId,selectedAppId:n?null:t.appId??null,selectedProjectId:n,view:"chat"})}case"beginNewChat":return Gl(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 St(e,t){return n=>e({type:"field",key:t,value:n})}function uee(e){return{setQuery:St(e,"query"),setSearchOpen:St(e,"searchOpen"),setArchivedChatsOpen:St(e,"archivedChatsOpen"),setSectionMenuOpen:St(e,"sectionMenuOpen"),setProjectsExpanded:St(e,"projectsExpanded"),setCloudProjectsExpanded:St(e,"cloudProjectsExpanded"),setChatRowsVisibleCount:St(e,"chatRowsVisibleCount"),setSidebarOpen:St(e,"sidebarOpen"),setView:St(e,"view"),setSelectedAppId:St(e,"selectedAppId"),setSelectedProjectId:St(e,"selectedProjectId"),setSelectedSessionId:St(e,"selectedSessionId"),setPrompt:St(e,"prompt"),setDraftProvider:St(e,"draftProvider"),setDraftModel:St(e,"draftModel"),setDraftExperience:St(e,"draftExperience"),setCodexPermissionMode:St(e,"codexPermissionMode"),setCodexReasoningEffort:St(e,"codexReasoningEffort"),setOpenPondCommandAccessMode:St(e,"openPondCommandAccessMode"),setBusy:St(e,"busy"),setDiffPanelOpen:St(e,"diffPanelOpen"),setDiffPanelExpanded:St(e,"diffPanelExpanded"),setRightPanelMode:St(e,"rightPanelMode"),setRightChatPanels:St(e,"rightChatPanels"),setTerminalOpen:St(e,"terminalOpen"),setSyncingWorkspaceAppId:St(e,"syncingWorkspaceAppId"),setSettingsSection:St(e,"settingsSection"),setNewProjectDialogOpen:St(e,"newProjectDialogOpen"),setNewProjectMode:St(e,"newProjectMode"),setNewProjectName:St(e,"newProjectName"),setNewProjectPath:St(e,"newProjectPath"),setNewProjectBusy:St(e,"newProjectBusy"),setCommitDialogOpen:St(e,"commitDialogOpen"),setCommitMessage:St(e,"commitMessage"),setCommitIncludeUnstaged:St(e,"commitIncludeUnstaged"),setCommitNextStep:St(e,"commitNextStep"),setCommitDraft:St(e,"commitDraft"),setBranchDialogOpen:St(e,"branchDialogOpen"),setBranchDialogName:St(e,"branchDialogName"),setToast:St(e,"toast"),setError:St(e,"error")}}function Jl(e){return e.selectedSessionId?`session:${e.selectedSessionId}`:e.selectedProjectId?`project:${e.selectedProjectId}`:e.selectedAppId?`app:${e.selectedAppId}`:"new-chat"}function mee(e={selectedAppId:null,selectedProjectId:null,selectedSessionId:null}){let t=e,n="";const a=new Map,o=new Set,r=d=>{if(!Object.is(n,d)){n=d;for(const f of o)f()}},s=()=>{const d=Jl(t);n?a.set(d,n):a.delete(d)},l=(d,f={})=>{const g=n;s(),t={...t,...d};const x=Jl(t);if(f.clear&&a.delete(x),f.preserveCurrentDraft){g?a.set(x,g):a.delete(x),r(g);return}r(f.clear?"":a.get(x)??"")},m={getScopeKey:()=>Jl(t),getSnapshot:()=>n,subscribe(d){return o.add(d),()=>o.delete(d)},set:d=>m.setForScope(Jl(t),d),setForScope(d,f){const g=Jl(t),x=d===g?n:a.get(d)??"",k=typeof f=="function"?f(x):f;Object.is(x,k)||(k?a.set(d,k):a.delete(d),d===g&&r(k))},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 f=t[d.key],g=typeof d.value=="function"?d.value(f):d.value;Object.is(f,g)||l({[d.key]:g})}return}if(d.type==="patch"){const f={};"selectedAppId"in d.patch&&(f.selectedAppId=d.patch.selectedAppId),"selectedProjectId"in d.patch&&(f.selectedProjectId=d.patch.selectedProjectId),"selectedSessionId"in d.patch&&(f.selectedSessionId=d.patch.selectedSessionId),Object.keys(f).length>0&&l(f),"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 f=d.projectId??null;l({selectedSessionId:d.sessionId,selectedAppId:f?null:d.appId??null,selectedProjectId:f});return}d.type==="beginNewChat"&&l({selectedSessionId:null,selectedAppId:d.appId,selectedProjectId:null})}};return m}function ere(e){return y.useSyncExternalStore(e.subscribe,e.getSnapshot,e.getSnapshot)}function pee(e){return{...e,draftExperience:Oy()}}function fee(){const[e,t]=y.useReducer(dee,see,pee),[n]=y.useState(()=>mee()),a=y.useCallback(r=>{n.applyAppAction(r),t(r)},[n]),o=y.useMemo(()=>({...uee(a),setPrompt:n.set}),[n,a]);return al(()=>o.setDraftExperience(Oy())),{composerDraftStore:n,dispatch:a,setters:o,state:e}}function hee(e){return!!(e&&e.includes("Git is required for OpenPond app workspaces")&&e.includes("Command Line Tools"))}function gee(e){const{connection:t,events:n,showToast:a}=e,o=y.useRef(new Set),r=y.useCallback(async()=>{if(t)try{const l=await ie.installMacOSCommandLineTools(t);a(l.message,"info")}catch(l){a(l instanceof Error?l.message:String(l),"error")}},[t,a]),s=y.useCallback((l="OpenPond needs Git to create and sync local projects.")=>{a(l,"error",{actionLabel:"Install Tools",onAction:()=>{r()},persistent:!0})},[a,r]);y.useEffect(()=>{if(!t)return;let l=!1;return ie.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]),y.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"&&hee(m)&&(o.current.add(l.id),s("OpenPond needs Git before it can update this project."))}},[n,s])}function vee({connection:e,preferences:t,sidebarOpen:n,diffPanelExpanded:a,setBootstrap:o,setError:r}){const[s,l]=y.useState(()=>La().sidebarSectionsCollapsed),m=y.useRef(s),d=y.useRef({}),f=y.useRef(null),g=y.useRef(null),[x,k]=y.useState(IX),[C,R]=y.useState(!1),[E,A]=y.useState(_X),[O,$]=y.useState(!1),{pinned:M,projects:w,cloudProjects:P,chats:j,savedForLater:N}=s;y.useEffect(()=>{if(C)return;const ee=Fh(La(t).sidebarWidth),me=Ak(ee,f.current);f.current=me.localChange,k(me.value)},[t,C]),y.useEffect(()=>{if(O)return;const ee=Vh(La(t).diffPanelWidth),me=Ak(ee,g.current);g.current=me.localChange,A(me.value)},[O,t]),y.useEffect(()=>{const ee=La(t).sidebarSectionsCollapsed;l(me=>{const be=$X(me,ee,d.current);return m.current=be,be})},[t]);const z=y.useCallback(ee=>{o(me=>me&&{...me,preferences:ee.preferences})},[o]),D=y.useCallback(async ee=>{if(e&&Fh(La(t).sidebarWidth)!==ee)try{z(await ie.savePreferences(e,{sidebarWidth:ee}))}catch(me){r(me instanceof Error?me.message:String(me))}},[e,t,r,z]),F=y.useCallback(async ee=>{if(e&&Vh(La(t).diffPanelWidth)!==ee)try{z(await ie.savePreferences(e,{diffPanelWidth:ee}))}catch(me){r(me instanceof Error?me.message:String(me))}},[e,t,r,z]),te=y.useCallback(async ee=>{if(!e)return;const me=La(t).sidebarSectionsCollapsed;if(!bee(me,ee))try{z(await ie.savePreferences(e,{sidebarSectionsCollapsed:ee}))}catch(be){r(be instanceof Error?be.message:String(be))}},[e,t,r,z]),ve=y.useCallback(ee=>{const me=m.current;OX(d.current,me,ee),m.current=ee,l(ee),te(ee)},[te]),re=y.useCallback(()=>{const ee=m.current;ve({...ee,pinned:!ee.pinned})},[ve]),K=y.useCallback(()=>{const ee=m.current;ve({...ee,projects:!ee.projects})},[ve]),L=y.useCallback(()=>{const ee=m.current;ve({...ee,cloudProjects:!ee.cloudProjects})},[ve]),de=y.useCallback(()=>{const ee=m.current;ve({...ee,chats:!ee.chats})},[ve]),X=y.useCallback(()=>{const ee=m.current;ve({...ee,savedForLater:!ee.savedForLater})},[ve]),Z=y.useCallback(ee=>{if(!n)return;ee.preventDefault();const me=ee.clientX,be=x;let je=be;R(!0);function ke(Ie){je=Fh(be+Ie.clientX-me),k(je)}function ue(){window.removeEventListener("pointermove",ke),window.removeEventListener("pointerup",ue);const Ie=Pk(be,je);Ie&&(f.current=Ie),R(!1),D(je)}window.addEventListener("pointermove",ke),window.addEventListener("pointerup",ue,{once:!0})},[D,n,x]),pe=y.useCallback(ee=>{if(a)return;ee.preventDefault();const me=ee.clientX,be=E;let je=be;$(!0);function ke(Ie){je=Vh(be-(Ie.clientX-me)),A(je)}function ue(){window.removeEventListener("pointermove",ke),window.removeEventListener("pointerup",ue);const Ie=Pk(be,je);Ie&&(g.current=Ie),$(!1),F(je)}window.addEventListener("pointermove",ke),window.addEventListener("pointerup",ue,{once:!0})},[a,E,F]);return{pinnedCollapsed:M,projectsCollapsed:w,cloudProjectsCollapsed:P,chatsCollapsed:j,savedForLaterCollapsed:N,sidebarWidth:x,sidebarResizing:C,diffPanelWidth:E,diffPanelResizing:O,togglePinnedCollapsed:re,toggleProjectsCollapsed:K,toggleCloudProjectsCollapsed:L,toggleChatsCollapsed:de,toggleSavedForLaterCollapsed:X,startSidebarResize:Z,startDiffPanelResize:pe}}function bee(e,t){return e.pinned===t.pinned&&e.projects===t.projects&&e.cloudProjects===t.cloudProjects&&e.chats===t.chats&&e.savedForLater===t.savedForLater}function yee(e){const[t,n]=y.useState({id:0,kind:null}),[a,o]=y.useState(null),r=y.useCallback((d=null)=>{n(f=>({id:f.id+1,kind:d}))},[]),s=y.useCallback(d=>{o(d)},[]),l=null,m=y.useMemo(()=>{if(e)return See(a,r)},[e,a,r]);return{backAction:l,breadcrumbs:m,closeDetailKind:t.kind,closeDetailRequestId:t.id,onDetailOpenChange:s}}function See(e,t){return e?[{label:e.rootLabel??"Models",onSelect:()=>t(null)},{label:e.kindLabel,onSelect:e.kindOnSelect??(()=>t(e.kind))},...e.workproductLabel?[{label:e.workproductLabel,onSelect:e.workproductOnSelect}]:[],...e.segments]:[{label:"Models"}]}const Nk=new WeakMap,sv=new WeakMap;function xee(e){if(!e)return"disconnected";let t=Nk.get(e);return(!t||t.serverUrl!==e.serverUrl||t.token!==e.token)&&(t={serverUrl:e.serverUrl,token:e.token,id:crypto.randomUUID()},Nk.set(e,t)),t.id}function tre(e,t){return sv.set(e,t),e}function nre(e){if(!e)return["learning","disconnected"];let t=sv.get(e);return t||(t=["learning",crypto.randomUUID()],sv.set(e,t)),t}function kee(e,t,n){return{inspectModelBatch:async a=>{if(!e)throw new Error("Connect to OpenPond to inspect this batch.");return TK.parse(await ie.trainingRequest(e,"/models/batch-review/inspect",{profileId:t,modelId:a},"POST"))},beginModelBatchReview:async a=>{const o=await n(a);return o?EK.parse(o):null}}}function wee(e,t,n,a){async function o(r,s){if(!e)throw new Error("Connect to OpenPond to load tasks.");const l=y6.parse(s),m=new URLSearchParams({profileId:t});for(const[d,f]of Object.entries(l))f!==void 0&&m.set(d,String(f));return ie.trainingRequest(e,`${r}?${m}`,{},"GET")}return{taskInventory:async(r={})=>x6.parse(await o("/tasks",r)),taskInventoryDetail:async r=>{const s=await o("/tasks/detail",r);return{item:wR.parse(s.item),task:ap.parse(s.task)}},tasksetDraftFiles:async r=>{if(!e)return null;try{return await ie.trainingRequest(e,`/taskset-drafts/${encodeURIComponent(r)}/files?${new URLSearchParams({profileId:t})}`,{},"GET")}catch(s){return a(s),null}},tasksetDraftFile:async(r,s)=>{if(!e)return null;try{return await ie.trainingRequest(e,`/taskset-drafts/${encodeURIComponent(r)}/file?${new URLSearchParams({profileId:t,path:s})}`,{},"GET")}catch(l){return a(l),null}},saveTasksetDraftFile:r=>n("save-taskset-draft-file",`/taskset-drafts/${encodeURIComponent(r.draftId)}/file`,{profileId:t,...r},"PATCH"),inspectTasksetDraftSource:(r,s)=>n("inspect-taskset-draft-source","/taskset-drafts/source",{profileId:t,modelId:r,expectedModelRevision:s}),createTasksetDraftFromSource:r=>n("create-taskset-draft","/taskset-drafts",{profileId:t,sourceRequest:r}),createTasksetDraft:(r="",s)=>n("create-taskset-draft","/taskset-drafts",{profileId:t,name:r,modelId:s??null}),importTasksetDraftPackage:r=>n("import-taskset-draft-package","/taskset-drafts/import",{packagePath:r,profileId:t}),saveTasksetDraft:r=>n("save-taskset-draft",`/taskset-drafts/${encodeURIComponent(r.id)}`,r,"PUT"),tasksetDraftWorkspace:async r=>{if(!e)return null;try{return await ie.trainingRequest(e,`/taskset-drafts/${encodeURIComponent(r)}/workspace`,{},"GET")}catch(s){return a(s),null}},publishTasksetDraft:(r,s)=>n("publish-taskset-draft",`/taskset-drafts/${encodeURIComponent(r)}/publish`,{modelId:s??null}),refreshTasksetDraftModel:(r,s)=>n("refresh-taskset-draft-model",`/taskset-drafts/${encodeURIComponent(r.id)}/model-revision`,{expectedDraftRevision:r.revision,expectedModelRevision:s}),deleteTasksetDraft:r=>n("delete-taskset-draft",`/taskset-drafts/${encodeURIComponent(r)}`,{},"DELETE")}}function dT(e,t){return rB({id:e.id,profileId:e.profileId,name:e.name,objective:e.objective,defaultBaseModel:e.defaultBaseModel,defaultDestinationId:e.defaultDestinationId,trainingSetup:e.trainingSetup},t)}async function Iee(e,t,n){if(!e)throw new Error("Connect to the execution owner to check this configuration.");const a=await dT(t,n);return oC.parse(await ie.trainingRequest(e,"/models/check",a,"POST"))}function _ee(e,t){return{listModelStarters:async(n,a=!1)=>{if(!e)throw new Error("Connect to OpenPond to browse model starters.");return ie.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 ie.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 oC.parse(await ie.trainingRequest(e,"/model-starters/check",n))},createModelFromStarter:n=>t("create-model-from-starter","/model-starters/create",n)}}const Dk=1e4,Hk=3e4;function Cee(e){const{connection:t,profileId:n}=e,a=s1(),o=xee(t),r=y.useMemo(()=>["training",o,n],[o,n]),s=y.useCallback(async()=>Q9.parse(await ie.trainingState(t,n)),[t,n]),l=IE({queryKey:r,queryFn:s,enabled:!!t}),m=l.data??null,d=!!t&&l.isPending,[f,g]=y.useState(null),[x,k]=y.useState(null),C=y.useRef(null);C.current=m?.activityRevision??null;const R=y.useCallback(async()=>{if(!t)return null;try{const w=await a.fetchQuery({queryKey:r,queryFn:s,staleTime:0});return k(null),w}catch(w){return k(no(w)),null}},[t,a,r,s]),E=y.useCallback(async()=>(await a.cancelQueries({queryKey:r,exact:!0}),await a.invalidateQueries({queryKey:r,exact:!0,refetchType:"none"}),await a.invalidateQueries({queryKey:["task-inventory",o,n]}),R()),[a,r,o,n,R]),A=y.useCallback(async(w,P,j,N="POST",z={})=>{if(!t)return null;z.silent||g(w);try{const D=await ie.trainingRequest(t,P,j,N);return await E(),z.silent||k(null),D}catch(D){return z.silent||k(no(D)),null}finally{z.silent||g(null)}},[t,E]),O=m?[m.jobs.some(w=>["queued","starting","running","cancelling","reconciling"].includes(w.status)),m.creations.some(w=>["planning","materializing","validating"].includes(w.state)),m.minerRuns.some(w=>["queued","running","cancelling"].includes(w.status)),m.datasetImports.some(w=>["inspecting","materializing","validating","cancelling"].includes(w.status))].some(Boolean):!1;y.useEffect(()=>{if(!t)return;let w=!0,P=null;const j=O?Dk:Hk,N=async()=>{let z=j;try{const D=await ie.trainingActivity(t,n);z=D.active?Dk:Hk,(C.current===null||C.current!==D.revision)&&await R()}catch(D){k(no(D))}w&&(P=window.setTimeout(()=>{N()},z))};return P=window.setTimeout(()=>{N()},j),()=>{w=!1,P!==null&&window.clearTimeout(P)}},[t,O,n,R]);const $=y.useMemo(()=>({..._ee(t,A),saveComparisonSeries:w=>A("save-comparison-series","/comparison-series",{series:w}),saveContinualBenchIssueReview:w=>A("save-continual-support-issue-review","/continual-support/issue-reviews",{review:w},"PUT"),importContinualLearningDailyBatch:(w,P="json_upload")=>A("import-continual-learning-daily-batch","/continual-learning/daily-batches/import",{manifest:w,source:P}),saveContinualLearningDailyBatch:w=>A("save-continual-learning-daily-batch","/continual-learning/daily-batches",{batch:w},"PUT"),generateContinualLearningResponses:w=>A("generate-continual-learning-responses","/continual-learning/responses",w),sealComparisonSeries:(w,P)=>A("seal-comparison-series",`/comparison-series/${encodeURIComponent(w)}/seal`,{expectedRevision:P}),archiveComparisonSeries:(w,P)=>A("archive-comparison-series",`/comparison-series/${encodeURIComponent(w)}/archive`,{expectedRevision:P}),queueComparisonRelease:w=>A("queue-comparison-release",`/comparison-series/${encodeURIComponent(w.seriesId)}/releases`,w),startComparisonEvaluation:w=>A("start-comparison-evaluation",`/comparison-series-entries/${encodeURIComponent(w.entryId)}/evaluations`,w),loadComparisonAttemptEvidence:w=>t?ie.trainingRequest(t,`/model-runs/${encodeURIComponent(w.runId)}/attempts/${encodeURIComponent(w.attemptId)}/evidence?kind=${w.kind}`,{},"GET"):Promise.resolve(null),linkComparisonRun:w=>A("link-comparison-run",`/comparison-series-entries/${encodeURIComponent(w.entryId)}/run`,w,"PATCH"),decideComparisonEntry:w=>A("decide-comparison-entry",`/comparison-series-entries/${encodeURIComponent(w.entryId)}/decision`,w),recordComparisonPromotion:w=>A("record-comparison-promotion",`/comparison-series-entries/${encodeURIComponent(w.entryId)}/promotion`,w),checkModelProject:(w,P=w.revision)=>Iee(t,w,P),...kee(t,n,w=>A("begin-model-batch-review","/models/batch-review",{profileId:n,request:w})),saveModelProject:async(w,P=w.revision)=>A("save-model-project","/models",await dT(w,P),"PUT"),listHostedModelProjects:async(w={})=>{if(!t)return null;w.silent||g("list-hosted-model-projects");try{const P=await ie.trainingRequest(t,`/hosted-model-projects?profileId=${encodeURIComponent(n)}&refresh=${w.refresh===!0}`,{},"GET");return w.silent||k(null),P}catch(P){return w.silent||k(no(P)),null}finally{w.silent||g(P=>P==="list-hosted-model-projects"?null:P)}},openHostedModelProject:(w,P,j,N={})=>A(`open-hosted-model-project:${w}`,`/hosted-model-projects/${encodeURIComponent(w)}/open`,{profileId:n,teamId:P,apiOrigin:j},"POST",N),pullHostedModelProject:w=>A(`pull-hosted-model-project:${w}`,`/hosted-model-projects/${encodeURIComponent(w)}/pull`,{profileId:n}),syncModelProject:w=>A("sync-model-project",`/models/${encodeURIComponent(w)}/sync`,{}),publishModelProjectTaskset:(w,P)=>A("publish-model-project-taskset",`/models/${encodeURIComponent(w)}/tasksets/${encodeURIComponent(P)}/publish`,{}),createScorer:(w,P,j)=>A("create-scorer","/scorers",{grader:w,tasksetId:P,modelProjectId:j??null}),prepareLearningBatch:w=>A("prepare-learning-batch","/learning-batches/prepare",{profileId:n,batchId:w}),...wee(t,n,A,w=>k(no(w))),tasksetGraderDetails:async w=>{if(!t)return null;try{return await ie.trainingRequest(t,`/tasksets/${encodeURIComponent(w)}/graders`,{},"GET")}catch(P){return k(no(P)),null}},inspectHuggingFaceDataset:w=>A("inspect-huggingface-dataset","/dataset-imports/huggingface/inspect",{profileId:n,url:w}),materializeDatasetImport:(w,P)=>A("materialize-dataset-import",`/dataset-imports/${encodeURIComponent(w)}/materialize`,P),cancelDatasetImport:w=>A("cancel-dataset-import",`/dataset-imports/${encodeURIComponent(w)}/cancel`,{}),datasetRows:(w,P={})=>{if(!t)return Promise.resolve(null);const j=new URLSearchParams;P.split&&j.set("split",P.split),P.cursor&&j.set("cursor",P.cursor),j.set("limit",String(P.limit??25));for(const N of P.columns??[])j.append("column",N);return ie.trainingRequest(t,`/tasksets/${encodeURIComponent(w)}/rows?${j}`,{},"GET")},addSource:(w,P)=>A("add-source","/sources",{profileId:n,sessionId:w,turnIds:P}),addSources:w=>A("add-sources","/sources/batch",{profileId:n,sessionIds:w}),estimateSources:w=>t?ie.trainingRequest(t,"/sources/estimate",{sessionIds:w}):Promise.resolve([]),searchChats:(w,P,j=0,N=20)=>t?ie.trainingRequest(t,"/sources/search",{query:w,candidates:P,offset:j,limit:N}):Promise.resolve({schemaVersion:"openpond.trainingChatSearchResult.v1",query:w,offset:j,limit:N,total:0,hasMore:!1,indexedChats:0,totalChats:0,indexing:!1,entries:[]}),removeSource:w=>A("remove-source",`/sources/${encodeURIComponent(w)}`,{},"DELETE"),deleteTaskset:w=>A("delete-model",`/tasksets/${encodeURIComponent(w)}`,{},"DELETE"),runBenchmark:(w,P,j,N)=>A(`run-benchmark-${P}`,`/tasksets/${encodeURIComponent(w)}/benchmark-runs`,{phase:P,model:j,reasoningEffort:N,seeds:[17],repetitions:1}),startHarnessRefinerBenchmark:(w,P,j)=>A("run-harness-refiner-benchmark",`/models/${encodeURIComponent(w)}/harness-refiner-benchmark`,{profileId:n,model:P,reasoningEffort:j,maximumSpendUsd:10}),acceptHarnessReview:(w,P,j=null,N=null)=>A("accept-harness-review","/harness-reviews/accept",{profileId:n,workspaceId:w,reviewRef:P,analysisModel:j,analysisReasoningEffort:N}),startCreation:(w,P={})=>A("create-taskset","/task-creations",{profileId:n,sourceIds:w,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:(w,P)=>A("create-model","/models/from-taskset",{profileId:n,tasksetId:w,preferredBaseModelId:P.modelId,preferredBaseModel:P}),scanBaseModels:async()=>{if(!t)return null;g("scan-base-models");try{const w=await R();return k(null),w}catch(w){return k(no(w)),null}finally{g(null)}},approveDisclosure:(w,P)=>A("approve-disclosure",`/task-creations/${encodeURIComponent(w)}/disclosure`,{approved:P}),retryCreation:w=>A("retry-creation",`/task-creations/${encodeURIComponent(w)}/retry`,{}),answerQuestions:(w,P)=>A("answer-questions",`/task-creations/${encodeURIComponent(w)}/questions`,{answers:P}),materialize:(w,P)=>A("materialize",`/task-creations/${encodeURIComponent(w)}/materialize`,{approved:P}),chatCreation:(w,P)=>A("task-creator-chat",`/task-creations/${encodeURIComponent(w)}/chat`,{message:P}),renameCreation:(w,P)=>A("rename-creation",`/task-creations/${encodeURIComponent(w)}/name`,{name:P},"PATCH"),cancelCreation:w=>A("cancel-creation",`/task-creations/${encodeURIComponent(w)}/cancel`,{}),runMiner:(w=[],P=[],j)=>A("run-miner","/miner/run",{profileId:n,sourceIds:w,sessionIds:P,config:j}),cancelMinerRun:w=>A("cancel-miner-run",`/miner/runs/${encodeURIComponent(w)}/cancel`,{}),configureMiner:w=>A("configure-miner","/miner/config",{profileId:n,config:w},"PUT"),patchCandidate:(w,P)=>A("candidate",`/candidates/${encodeURIComponent(w)}`,P,"PATCH"),createCandidate:(w,P,j,N)=>A("create-candidate",`/candidates/${encodeURIComponent(w)}/create`,{mode:P,analysisModel:j??null,analysisReasoningEffort:N??null}),auditGraders:w=>A("audit-graders","/audit-graders",{tasksetId:w}),executeTasksetAttempt:(w,P,j)=>A("execute-taskset-attempt",`/tasksets/${encodeURIComponent(w)}/attempts`,{taskId:P,model:j,seed:17,attempt:0,sampling:{maxOutputTokens:4096,temperature:0,topP:1}}),materializeSyntheticPreferenceCollection:w=>A("materialize-synthetic-preference-collection",`/tasksets/${encodeURIComponent(w.tasksetId)}/synthetic-preference-collection`,w),tasksetOperationalState:w=>t?ie.trainingRequest(t,`/tasksets/${encodeURIComponent(w)}/operations`,{},"GET"):Promise.resolve(null),calibrateJudges:w=>A("calibrate-judges","/calibrate-judges",{tasksetId:w}),nextPreferenceComparison:(w,P)=>A("next-preference-comparison",`/tasksets/${encodeURIComponent(w)}/preference-comparisons/next`,{reviewerKey:P}),submitPreferenceComparison:w=>A("submit-preference-comparison",`/tasksets/${encodeURIComponent(w.tasksetId)}/preference-comparisons/${encodeURIComponent(w.assignmentId)}/submit`,w),submitSyntheticFixturePreference:w=>A("submit-synthetic-fixture-preference",`/tasksets/${encodeURIComponent(w.tasksetId)}/preference-comparisons/${encodeURIComponent(w.assignmentId)}/fixture-submit`,{...w,id:crypto.randomUUID()}),listPreferenceDatasets:w=>t?ie.trainingRequest(t,`/tasksets/${encodeURIComponent(w)}/preference-datasets`,{},"GET"):Promise.resolve(null),materializePreferenceDataset:w=>A("materialize-preference-dataset",`/tasksets/${encodeURIComponent(w.tasksetId)}/preference-datasets`,{...w,id:`preference-dataset-${crypto.randomUUID()}`,revision:1}),launchRewardModelRun:w=>A("launch-reward-model-run",`/tasksets/${encodeURIComponent(w.tasksetId)}/reward-model-runs`,{...w,id:`reward-model-run-${crypto.randomUUID()}`}),learnedPreferenceRewardBinding:w=>A("learned-preference-reward-binding",`/tasksets/${encodeURIComponent(w.tasksetId)}/learned-preference-reward-binding`,w),retryRewardModelQualification:w=>A("retry-reward-model-qualification",`/reward-model-runs/${encodeURIComponent(w.runId)}/retry-qualification`,w),cancelRewardModelRun:w=>A("cancel-reward-model-run",`/reward-model-runs/${encodeURIComponent(w)}/cancel`,{}),markPreferenceComparisonUnreviewable:w=>A("mark-preference-comparison-unreviewable",`/tasksets/${encodeURIComponent(w.tasksetId)}/preference-comparisons/${encodeURIComponent(w.assignmentId)}/unreviewable`,w),preferenceCalibrationStatus:(w,P,j)=>{if(!t)return Promise.resolve(null);const N=new URLSearchParams({reviewerKey:P});return j&&N.set("comparisonReleaseId",j),ie.trainingRequest(t,`/tasksets/${encodeURIComponent(w)}/preference-comparisons/calibration/status?${N}`,{},"GET")},startPreferenceCalibrationBatch:w=>A("start-preference-calibration-batch",`/tasksets/${encodeURIComponent(w.tasksetId)}/preference-comparisons/calibration/batches`,{...w,id:crypto.randomUUID()}),syncPreferenceCalibrationBatch:w=>A("sync-preference-calibration-batch",`/tasksets/${encodeURIComponent(w.tasksetId)}/preference-comparisons/calibration/batches/${encodeURIComponent(w.jobId)}/sync`,w),reviewPreferenceComparisonWithModel:w=>A("review-preference-comparison-with-model",`/tasksets/${encodeURIComponent(w.tasksetId)}/preference-comparisons/${encodeURIComponent(w.assignmentId)}/model-review`,{...w,id:crypto.randomUUID()}),runNextPreferenceCalibrationReview:w=>A("run-next-preference-calibration-review",`/tasksets/${encodeURIComponent(w.tasksetId)}/preference-comparisons/calibration/model-reviews/next`,{...w,id:crypto.randomUUID()}),savePreferenceCalibration:w=>A("save-preference-calibration",`/tasksets/${encodeURIComponent(w.tasksetId)}/preference-comparisons/calibration/report`,{...w,id:crypto.randomUUID()}),preferenceArtifactUrl:async w=>{if(!t)return null;const P=await fetch(`${t.serverUrl}/v1/training/artifacts/${encodeURIComponent(w)}/download`,{headers:{Authorization:`Bearer ${t.token}`}});if(!P.ok)throw new Error(await P.text());return URL.createObjectURL(await P.blob())},readiness:w=>A("readiness","/readiness",{tasksetId:w}),previewExpertBootstrap:w=>A("preview-expert-bootstrap",`/tasksets/${encodeURIComponent(w)}/expert-bootstrap/preview`,{}),approveExpertBootstrap:(w,P)=>A("approve-expert-bootstrap",`/tasksets/${encodeURIComponent(w)}/expert-bootstrap/approve`,{previewHash:P}),createPlan:w=>A("create-plan","/plans",{...w,tasksetId:w.tasksetId}),buildBundle:w=>A("build-bundle","/bundles",{planId:w}),approveTraining:(w,P)=>A("approve-training","/approvals",{planId:w,bundleId:P}),launch:(w,P)=>A("launch","/launch",{planId:w,approvalId:P}),prepareTraining:w=>A("prepare-training","/prepare",w),prepareModelRun:(w,P)=>A("prepare-model-run",`/model-projects/${encodeURIComponent(w)}/training/prepare`,P),startModelRun:(w,P)=>A("start-model-run",`/model-projects/${encodeURIComponent(w)}/training/start`,P),startPreparedTraining:w=>A("start-prepared-training","/start/prepared",w),startTraining:w=>A("start-training","/start",w),cancelJob:w=>A("cancel-job",`/jobs/${encodeURIComponent(w)}/cancel`,{}),retryModelRunCollection:w=>A("retry-model-run-collection",`/model-runs/${encodeURIComponent(w)}/retry-collection`,{}),cancelModelRun:w=>A("cancel-model-run",`/model-runs/${encodeURIComponent(w)}/cancel`,{}),rejectModel:(w,P)=>A("reject-model",`/models/${encodeURIComponent(w)}/reject`,{reason:P}),bindModel:(w,P,j)=>A("bind-model",`/models/${encodeURIComponent(w)}/bind`,{profileId:n,role:P,roleTargetId:j,promotedBy:n}),rollbackModelBinding:w=>A("rollback-model-binding",`/bindings/${encodeURIComponent(w)}/rollback`,{rolledBackBy:n}),updateModelConfiguration:(w,P)=>A("update-model-configuration",`/models/${encodeURIComponent(w)}/configuration`,P,"PATCH",{silent:!0}),setModelPinned:(w,P)=>A("pin-model-version",`/models/${encodeURIComponent(w)}/pin`,{pinned:P},"PATCH"),downloadArtifact:async w=>{if(!t)return!1;g("download-artifact");try{const P=await fetch(`${t.serverUrl}/v1/training/artifacts/${encodeURIComponent(w)}/download`,{headers:{Authorization:`Bearer ${t.token}`}});if(!P.ok)throw new Error(await P.text());const j=P.headers.get("content-disposition")??"",N=/filename="([^"]+)"/.exec(j)?.[1]??"openpond-model-artifact",z=URL.createObjectURL(await P.blob()),D=document.createElement("a");return D.href=z,D.download=N,D.click(),URL.revokeObjectURL(z),!0}catch(P){return k(no(P)),!1}finally{g(null)}},downloadModelPackage:async w=>M(`/models/${encodeURIComponent(w)}/download`,`${w}.openpond-lora.tar`),downloadBundle:async w=>M(`/bundles/${encodeURIComponent(w)}/download`,"openpond-model-improvement-bundle.json")}),[t,A,n,R]);async function M(w,P){if(!t)return!1;g("download-bundle");try{const j=await fetch(`${t.serverUrl}/v1/training${w}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!j.ok)throw new Error(await j.text());const N=j.headers.get("content-disposition")??"",z=/filename="([^"]+)"/.exec(N)?.[1]??P,D=URL.createObjectURL(await j.blob()),F=document.createElement("a");return F.href=D,F.download=z,F.click(),URL.revokeObjectURL(D),!0}catch(j){return k(no(j)),!1}finally{g(null)}}return{connection:t,payload:m,loading:d,busyAction:f,error:x??l.error?.message??null,refresh:R,actions:$}}function no(e){return e instanceof Error?e.message:String(e)}function are({modelId:e,taskset:t}){const n=t.metadata.toolContractHash===vd?"cross_system":t.environment.kind==="stateful_harness"&&t.environment.actionBindings?.length?"harness":null,a=n?Tee(t,n):[];return{model:{providerId:"openpond",modelId:e},tasksetId:t.id,tasksetName:t.name,taskRuntime:n,sourceProjectId:Eee(t),tasks:a,selectedTaskIndex:0,sessionId:null}}function ire(e){return{model:{providerId:"openpond",modelId:e.modelId},tasksetId:e.tasksetId,tasksetName:e.modelName,taskRuntime:null,sourceProjectId:null,tasks:[],selectedTaskIndex:0,sessionId:null}}function ks(e){return e?.tasks.length?e.tasks[pT(e,e.selectedTaskIndex)]??null:null}function uT(e,t){return{...e,selectedTaskIndex:pT(e,t)}}function Ree(e){return uT(e,e.selectedTaskIndex+1)}function Pee(e,t,n){if(!e||mT(e,n))return null;const a=ks(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 mT(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 Aee({model:e,connection:t,loadBootstrap:n,applyBootstrap:a}){e.providerId!=="openpond"||!t||a(await n(t))}function Tee(e,t){const n=new Set;return e.tasks.flatMap(a=>{const o=t==="cross_system"?a.metadata.taskId:a.metadata.caseId,r=typeof o=="string"?o.trim():"",s=typeof a.input.prompt=="string"?a.input.prompt.trim():"";return!r||!s||n.has(r)?[]:(n.add(r),[{authoredTaskId:a.id,generatedTaskId:r,prompt:s,split:a.split}])})}function Eee(e){const t=new Set(e.sourceRefs.filter(sR).flatMap(n=>{const a=n.workspaceId?.trim();return a?[a]:[]}));return t.size===1?t.values().next().value??null:null}function pT(e,t){return e.tasks.length?Math.max(0,Math.min(Math.trunc(t),e.tasks.length-1)):0}function Mee({activeModel:e,activeProvider:t,applyBootstrapPayload:n,beginNewChat:a,composerDraftStore:o,connection:r,requestComposerFocus:s,selectedLocalProjectId:l,selectedSessionId:m,selectLocalProject:d,setDraftModel:f,setDraftProvider:g,setError:x,view:k}){const[C,R]=y.useState(null),E=y.useCallback(j=>{j.sourceProjectId?d(j.sourceProjectId):a(null)},[a,d]),A=y.useCallback(j=>{if(!C)return;const N={...uT(C,j),sessionId:C.sessionId?null:C.sessionId},z=ks(N);R(N),z&&(C.sessionId&&E(N),o.set(z.prompt),s())},[E,o,C,s]),O=y.useCallback(()=>{const j=ks(C);j&&o.getSnapshot().trim()===j.prompt.trim()&&o.set(""),R(null)},[o,C]),$=y.useCallback(j=>{const N=j.model;Aee({model:N,connection:r,loadBootstrap:ie.bootstrap,applyBootstrap:n}).then(()=>{const z={...j,selectedTaskIndex:0,sessionId:null};g(N.providerId),f(N.modelId),R(z.tasks.length?z:null),E(z);const D=ks(z);D&&o.set(D.prompt)}).catch(x)},[n,E,o,r,f,g,x]),M=y.useCallback(j=>{const N=!!(C&&C.model.providerId===t&&C.model.modelId===e);return{active:N,error:N?mT(C,l):null,metadata:N?Pee(C,j,l):null}},[e,t,C,l]),w=y.useCallback(j=>{R(N=>N&&{...N,sessionId:j})},[]),P=y.useCallback(()=>{if(!C)return;const j={...Ree(C),sessionId:null},N=ks(j);R(j),N&&(E(j),o.set(N.prompt),s())},[E,o,C,s]);return y.useEffect(()=>{const j=ks(C);!j||k!=="chat"||m||o.set(N=>N.trim()?N:j.prompt)},[o,C,l,m,k]),y.useEffect(()=>{C&&m&&C.sessionId!==m&&R(null)},[C?.sessionId,m]),{advanceAfterTurn:P,begin:$,bindSession:w,dismiss:O,handoff:C,prepareTurn:M,selectTask:A}}const Zl=[],Kh=500;function jee(e){const{approvals:t,codexHistoryEvents:n,connection:a,latestServerSequence:o,runtimeIndexes:r,runtimeEventStore:s,selectedSessionId:l,serverId:m,setCodexHistoryEvents:d,setCodexHistorySessions:f,setError:g}=e,[x,k]=y.useState({}),[C,R]=y.useState({}),E=y.useRef(new Set);y.useEffect(()=>{k({}),R({}),E.current.clear()},[m]);const A=y.useCallback(async()=>{if(!a||!l||E.current.has(l))return!1;const P=C[l];if(P?.hasMore===!1)return!1;if(Jt(l)){const z=Math.max(P?.totalMatchingEvents??0,n.length,DA),D=Math.min(rk,Math.max(mY,z*2));E.current.add(l),R(F=>({...F,[l]:{cursorSequence:null,hasMore:!0,loading:!0,totalMatchingEvents:F[l]?.totalMatchingEvents??n.length}}));try{const F=await HA(a,l,{force:!0,limit:D,tail:!1});return d(F.events),f(te=>vp(te,F.session)),R(te=>({...te,[l]:{cursorSequence:null,hasMore:F.events.length>=D&&D<rk,loading:!1,totalMatchingEvents:D}})),F.events.length>n.length}catch(F){return g(F instanceof Error?F.message:String(F)),R(te=>({...te,[l]:{cursorSequence:null,hasMore:te[l]?.hasMore??!0,loading:!1,totalMatchingEvents:te[l]?.totalMatchingEvents??n.length}})),!1}finally{E.current.delete(l)}}const j=io(x[l]??Zl,s.getSessionEvents(l)),N=P?.cursorSequence??Oee(j);if(!N)return!1;E.current.add(l),R(z=>({...z,[l]:{cursorSequence:z[l]?.cursorSequence??N,hasMore:z[l]?.hasMore??!0,loading:!0,totalMatchingEvents:z[l]?.totalMatchingEvents??null}}));try{const z=await ie.runtimeEventsPage(a,{sessionId:l,beforeSequence:N,limit:Kh}),D=z.events.map(F=>F.event);return k(F=>({...F,[l]:io(D,F[l]??Zl)})),R(F=>({...F,[l]:{cursorSequence:z.previousSequence,hasMore:z.hasMore,loading:!1,totalMatchingEvents:z.totalMatchingEvents}})),D.length>0}catch(z){return g(z instanceof Error?z.message:String(z)),R(D=>({...D,[l]:{cursorSequence:D[l]?.cursorSequence??N,hasMore:D[l]?.hasMore??!0,loading:!1,totalMatchingEvents:D[l]?.totalMatchingEvents??null}})),!1}finally{E.current.delete(l)}},[C,n.length,a,x,s,l,d,f,g]),O=l?x[l]??Zl:Zl,$=y.useMemo(()=>s.getSessionEvents(l).length,[s,l]),M=y.useRef(null);y.useEffect(()=>{if(!a||!l||Jt(l)||E.current.has(l)||O.length>0||$>0)return;const P=o;if(!P)return;const j=l,N=P+1;E.current.add(j),R(z=>({...z,[j]:{cursorSequence:z[j]?.cursorSequence??N,hasMore:z[j]?.hasMore??!0,loading:!0,totalMatchingEvents:z[j]?.totalMatchingEvents??null}})),ie.runtimeEventsPage(a,{sessionId:j,beforeSequence:N,limit:Kh}).then(z=>{const D=z.events.map(F=>F.event);k(F=>({...F,[j]:io(D,F[j]??Zl)})),R(F=>({...F,[j]:{cursorSequence:z.previousSequence,hasMore:z.hasMore,loading:!1,totalMatchingEvents:z.totalMatchingEvents}}))}).catch(z=>{g(z instanceof Error?z.message:String(z)),R(D=>({...D,[j]:{cursorSequence:D[j]?.cursorSequence??N,hasMore:D[j]?.hasMore??!0,loading:!1,totalMatchingEvents:D[j]?.totalMatchingEvents??null}}))}).finally(()=>{E.current.delete(j)})},[o,a,O.length,$,l,g]),y.useEffect(()=>{if(!a||!l||Jt(l)||E.current.has(l)||!o)return;const P=io(O,s.getSessionEvents(l)),j=Sm(P);if(!j||j>=o)return;const N=`${l}:${j}:${o}`;if(M.current===N)return;M.current=N;let z=!1;return ie.runtimeEventsPage(a,{sessionId:l,afterSequence:j,limit:Kh}).then(D=>{if(z)return;const F=D.events.map(te=>te.event);F.length!==0&&k(te=>wJ(te,l,F))}).catch(D=>{z||(M.current=null,g(D instanceof Error?D.message:String(D)))}),()=>{z=!0}},[o,a,s,O,l,g]);const w=y.useMemo(()=>Jt(l)?Zg(n,[]):!l||O.length===0?r:Zg(io(O,s.getSessionEvents(l)),t),[t,n,r,O,l]);return{chatHistoryLoadStates:C,loadMoreSelectedChatHistory:A,selectedPagedSessionEvents:O,selectedRuntimeIndexes:w}}function Oee(e){let t=null;for(const n of e)n.sequence!==void 0&&(t===null||n.sequence<t)&&(t=n.sequence);return t}function $ee(e,t){const n=y.useRef(null);return y.useMemo(()=>{const a=bA(e,t,n.current);return n.current={events:e,indexes:a},a},[t,e])}function $s(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Wh(e){return Array.isArray(e)?e.filter(t=>!!$s(t)):[]}function gr(e){return typeof e=="string"&&e.trim()?e.trim():null}function Lk(e){return gr(e)??$s(e)}function Nee(e){if(!e)return[];const t=$s(e.sandboxActionRegistry),n=$s(e.sandboxManifest),a=new Map;for(const o of[...Wh(n?.actionCatalog),...Wh(t?.actions),...Wh(n?.actions)]){const r=gr(o.id)??gr(o.name);if(!r)continue;const s=a.get(r);a.set(r,{id:r,name:gr(o.name)??s?.name??r,label:gr(o.label)??s?.label??Dee(r),description:gr(o.description)??s?.description??null,visibility:gr(o.visibility)??s?.visibility??"default",inputSchema:Lk(o.inputSchema)??s?.inputSchema??null,outputSchema:Lk(o.outputSchema)??s?.outputSchema??null,implementation:$s(o.implementation)??s?.implementation??null,mcp:$s(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 Dee(e){const t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e}function fT(e){if(e.selectedCloudProject)return{id:e.selectedCloudProject.id,teamId:e.selectedCloudProject.teamId,name:e.selectedCloudProject.name,selectionKey:kt("cloud",e.selectedCloudProject.id),localProjectId:null};const t=e.selectedProject?.linkedSandboxProject??null;if(!t?.projectId||!t.teamId)return null;const n=e.cloudProjects?Ga(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:kt("cloud",n?.id??t.projectId),localProjectId:e.selectedProject?.id??null}}const hT="openpond-agent",gT="openpond-profile-action";function Sp(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function oo(e){return typeof e=="string"&&e.trim()?e.trim():null}function By(e){return e.displayPrompt&&/(?:^|\s)@[A-Za-z0-9_-]+/.test(e.displayPrompt)?"mention":"slash"}function Hee(e){const t=Sp(e),n=oo(t?.scope);return n!=="entire_manifest"&&n!=="start"&&n!=="action"&&n!=="service"&&n!=="schedule"?null:{scope:n,name:oo(t?.name)}}function Lee(e){const t=oo(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 qee(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:hT,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 Uee(e){const t=Sp(e.implementation);if(t?.type!==hT)return null;const n=oo(t.agentId),a=oo(t.teamId),o=oo(t.projectId),r=Hee(t.selectedEntrypoint),s=Lee(t.workflowMode);return!n||!a||!o||!r||!s?null:{agentId:n,agentName:oo(t.agentName)??e.label??e.name??e.id,teamId:a,projectId:o,projectName:oo(t.projectName),selectedEntrypoint:r,workflowMode:s}}function zee(e,t={}){const n=t.agentName?.trim()||null;return{...e,implementation:{...Sp(e.implementation)??{},type:gT,actionId:e.id,...n?{agentName:n}:{}},invokesModel:e.invokesModel??!0}}function Bee(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=>zee(n,{agentName:n.agentId?t.get(n.agentId):null}))}function ore(e){return!!(e&&Fy(e))}function rre(e){return!!(e&&Fy(e)&&e.sourceActionId==="chat")}function Fy(e){const t=Sp(e.implementation);if(t?.type!==gT)return null;const n=oo(t.actionId)??e.id;return n?{actionId:n,actionLabel:e.label??e.name??n}:null}function Fee({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:By({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{},...o?{sessionId:o}:{}}}}function Vee({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:By({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{}}}}function Kee({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:By({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{}},workflowMode:e.workflowMode}}const Ns=new Map;function Vy(e,t){const n=e?.trim();return n?`${t?.trim()||"global"}|${n}`:null}function Wee(e,t){const n=Vy(e,t);if(!n)return null;const a=Ns.get(n);return a?.updatedAt?a.projects:null}function Gee(e,t,n){const a=Vy(e,n);a&&Ns.set(a,{projects:t,promise:null,updatedAt:Date.now()})}function Jee(e){const t=e.teamId?.trim();if(!t)return Promise.resolve([]);const n=Vy(t,e.accountKey);if(!n)return Promise.resolve([]);const a=Ns.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(r=>(Gee(t,r,e.accountKey),r)).catch(r=>{const s=Ns.get(n);throw s?.promise===o&&Ns.set(n,{projects:s.projects,promise:null,updatedAt:s.updatedAt}),r});return Ns.set(n,{projects:a?.projects??[],promise:o,updatedAt:a?.updatedAt??0}),o}function Gh(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 Zee({cloudProjectById:e,cloudProjects:t,connection:n,defaultTeamId:a,accountScopeKey:o,localProjects:r,profile:s,selectedCloudProject:l,selectedProject:m,reportError:d}){const[f,g]=y.useState(null),[x,k]=y.useState([]),[C,R]=y.useState([]),E=y.useMemo(()=>{const j=new Set;a&&j.add(a);for(const N of t)j.add(N.teamId);for(const N of r){const z=t.find(D=>D.id===N.linkedSandboxProject?.projectId&&D.teamId===N.linkedSandboxProject?.teamId);z?.teamId&&j.add(z.teamId)}return[...j].sort()},[t,a,r]),A=E.join("\0"),O=y.useMemo(()=>fT({cloudProjects:t,selectedCloudProject:l,selectedProject:m}),[t,l,m]);y.useEffect(()=>{if(!n||E.length===0){R([]);return}let j=!1;const N=E.flatMap(z=>lT(z,o)??[]);return R(Gh(N)),Promise.all(E.map(z=>qy({teamId:z,accountKey:o,fetchAgents:async D=>(await ie.listSandboxAgents(n,{teamId:D})).agents}))).then(z=>{j||R(Gh(z.flat()))}).catch(()=>{j||R(Gh(N))}),()=>{j=!0}},[o,n,A]),y.useEffect(()=>{if(!n||!O){g(null);return}const j=Wee(O.teamId,o);j&&g(j.find(z=>z.id===O.id)??null);let N=!1;return Jee({teamId:O.teamId,accountKey:o,fetchProjects:async z=>(await ie.listSandboxProjects(n,{teamId:z})).projects}).then(z=>{N||g(z.find(D=>D.id===O.id)??null)}).catch(()=>{N||g(null)}),()=>{N=!0}},[o,n,O?.id,O?.teamId]),y.useEffect(()=>{if(!n||!m){k([]);return}let j=!1;return ie.localProjectActions(n,m.id).then(N=>{j||k(N.actions)}).catch(N=>{j||(k([]),d?.(`Could not load Project Actions for ${m.name}: ${N instanceof Error?N.message:String(N)}`))}),()=>{j=!0}},[n,d,m?.id,m?.name,m?.updatedAt]);const $=y.useMemo(()=>{const j=new Map;for(const N of Nee(f))j.set(N.id,N);for(const N of x)j.set(N.id,N);return[...j.values()]},[x,f]),M=y.useMemo(()=>Bee(s),[s]),w=y.useMemo(()=>[...C.map(j=>qee(j,e.get(j.projectId)?.name??null)),...M,...$],[e,M,$,C]);return{openPondActionCatalog:y.useMemo(()=>[...M,...$],[M,$]),selectedActionCatalog:w,selectedProjectActionCatalog:$}}function Yee({selectedProjectId:e}){const[t,n]=y.useState(()=>new Set),a=y.useCallback(r=>{n(s=>{if(s.has(r))return s;const l=new Set(s);return l.add(r),l})},[]),o=y.useCallback(r=>{n(s=>{const l=new Set(s);return l.has(r)?l.delete(r):l.add(r),l})},[]);return y.useEffect(()=>{e&&a(e)},[a,e]),{expandedProjectIds:t,expandProject:a,toggleProjectExpanded:o,setExpandedProjectIds:n}}function Qee(){const e=new Map;function t(o,r){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(()=>r(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,r,s){let l=!1;return{key:o,promise:r.promise,shared:s,release:()=>{l||(l=!0,r.consumers=Math.max(0,r.consumers-1),r.consumers===0&&!r.settled&&r.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 Jh(e,t,n){return`workspace-status:${e.serverUrl}:${t}:${n?"ensure":"read"}`}function Xee(e,t){return`workspace-diff:${e.serverUrl}:${t}`}function Zh(e){return e instanceof Error&&e.name==="AbortError"}function ete({connection:e,activeWorkspaceAppId:t,view:n,shouldLoadWorkspaceDiff:a,sidebarWorkspaceAppIds:o,setError:r}){const[s,l]=y.useState(null),[m,d]=y.useState({}),[f,g]=y.useState(null),[x,k]=y.useState(!1),[C,R]=y.useState(!1),E=y.useRef(new Set),A=y.useRef(new Set),O=y.useRef(Qee()),$=t?m[t]??(s?.appId===t?s:null):null,M=f?.appId===t?f:null,w=n==="chat"||n==="labs",P=y.useCallback(z=>{E.current.add(z.appId),l(z),d(D=>({...D,[z.appId]:z}))},[]),j=y.useCallback(async(z,D=!1)=>{if(!e||!z)return l(null),null;k(!0);const F=O.current.request(Jh(e,z,D),te=>ie.workspaceStatus(e,z,D,{signal:te}));try{const te=await F.promise;return P(te),D&&te.error?r(`Workspace sync failed: ${te.error}`):D&&r(null),te}catch(te){return Zh(te)||(l(null),r(te instanceof Error?te.message:String(te))),null}finally{F.release(),k(!1)}},[e,P,r]),N=y.useCallback(async(z=t,D={})=>{if(!e||!z)return g(null),null;D.silent||R(!0);const F=O.current.request(Xee(e,z),te=>ie.workspaceDiff(e,z,{signal:te}));try{const te=await F.promise;return g(te),te}catch(te){return Zh(te)||(g(null),r(te instanceof Error?te.message:String(te))),null}finally{F.release(),D.silent||R(!1)}},[t,e,r]);return y.useEffect(()=>{if(!e||!t||!w){l(null),g(null),k(!1);return}let z=!1;const D=O.current.request(Jh(e,t,!1),F=>ie.workspaceStatus(e,t,!1,{signal:F}));return k(!0),D.promise.then(F=>{z||(P(F),F.initialized||g(te=>te?.appId===F.appId?null:te))}).catch(F=>{Zh(F)||z||(l(null),r(F instanceof Error?F.message:String(F)))}).finally(()=>{D.release(),z||k(!1)}),()=>{z=!0,D.release()}},[t,e,P,r,w]),y.useEffect(()=>{if(!e||!t||!w){g(null);return}if(!$?.initialized){$&&!$.initialized&&g(z=>z?.appId===t?null:z);return}a&&N(t)},[t,e,N,a,w,$?.dirty,$?.initialized]),y.useEffect(()=>{if(!e||o.length===0)return;const z=o.filter(te=>!E.current.has(te)&&!A.current.has(te));if(z.length===0)return;z.forEach(te=>A.current.add(te));let D=!1;const F=z.map(te=>({appId:te,request:O.current.request(Jh(e,te,!1),ve=>ie.workspaceStatus(e,te,!1,{signal:ve}))}));return Promise.all(F.map(({appId:te,request:ve})=>ve.promise.then(re=>({appId:te,state:re})).catch(()=>({appId:te,state:null})).finally(()=>{ve.release(),A.current.delete(te)}))).then(te=>{if(!D)for(const ve of te)ve.state&&P(ve.state)}),()=>{D=!0,F.forEach(({appId:te,request:ve})=>{ve.release(),A.current.delete(te)})}},[e,P,o]),y.useEffect(()=>()=>O.current.cancelAll(),[]),{workspaceState:s,workspaceStates:m,workspaceDiff:f,workspaceBusy:x,diffBusy:C,visibleWorkspaceState:$,visibleWorkspaceDiff:M,rememberWorkspaceState:P,refreshWorkspace:j,refreshWorkspaceDiff:N,setWorkspaceBusy:k}}const tte=1,nte=15e3,ate=15e3,vT=5*6e4,ite=5e3,ote=1e4;function bT(e,t=(a,o)=>new WebSocket(a,o),n={}){const a=new rte(e,t,n.reconnectDelayMs??ste);return a.open(),{close:()=>a.close()}}class rte{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=vT;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===tte)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-${lte(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."))},nte))},n.onmessage=a=>{this.isCurrent(n,t)&&this.handleMessage(n,a)},n.onerror=()=>{this.isCurrent(n,t)&&this.failConnection(new Error("Team chat realtime socket failed."),!1)},n.onclose=a=>{this.isCurrent(n,t)&&(this.socket=null,this.clearConnectionTimers(),this.closed||((a.code===4401||a.code===4403)&&this.reportError(new Error("Team chat realtime authorization expired.")),this.scheduleReconnect()))}}handleMessage(t,n){if(typeof n.data!="string")return;let a;try{const r=JSON.parse(n.data);if(!r||typeof r!="object"||Array.isArray(r))return;a=r}catch{this.reportError(new Error("Team chat realtime returned an invalid frame."));return}const o=typeof a.type=="string"?a.type:"";if(o==="connection_ack"){this.connectionAckTimer&&clearTimeout(this.connectionAckTimer),this.connectionAckTimer=null,this.keepAliveTimeoutMs=dte(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 r=typeof a.id=="string"?a.id:"";if(!this.subscriptionChannels.has(r))return;this.acknowledgedSubscriptions.add(r),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 r=ute(a);if(this.reportError(r),o==="connection_error")this.failConnection(r,!1);else{const s=typeof a.id=="string"?a.id:"";this.subscriptionChannels.delete(s),this.acknowledgedSubscriptions.delete(s),this.markReadyWhenSubscribed()}}}subscribe(t){const n={Authorization:this.input.authorizationToken,host:new URL(this.input.httpUrl).host};for(const a of Array.from(new Set(this.input.channels))){const o=cte();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."))},ate)}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."))},ite)}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 ste(e){const t=Math.min(ote,500*2**Math.min(e,5));return Math.max(100,Math.floor(Math.random()*t))}function lte(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 cte(){return globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random().toString(36).slice(2)}`}function dte(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:vT}function ute(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",r=typeof a.message=="string"?a.message:"Request failed";return new Error(`${o}: ${r}`)}return new Error("Team chat realtime request failed.")}function mte(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 bT({realtimeUrl:e.session.realtimeUrl,httpUrl:e.session.httpUrl,authorizationToken:e.session.token,channels:a,onEvent:o=>{const r=YI.safeParse(o);r.success&&e.onEvent(r.data)},onReady:e.onReady,onError:e.onError},t,n)}function pte(e){return e.refs.find(t=>t.refType==="message_reply")??null}function fte(e){return{id:e.id,authorType:e.authorType,authorUserId:e.authorUserId,authorAgentId:e.authorAgentId,body:e.body,deleted:!!e.deletedAt}}function sre(e,t){const n=pte(e);if(!n)return null;const a=t.get(n.refId);return a?fte(a):gte(n)}function hte(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 lre(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 cre(e){return e.deleted?"Message deleted":e.body.replace(/\s+/g," ").trim()||"Attachment"}function gte(e){const t=e.preview;return{id:e.refId,authorType:vte(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 vte(e){return e==="agent"||e==="system"?e:"user"}function qk(e,t,n){return n===t.conversationId?{...e,aiThread:t}:e}function bte(e,t){return!e||e.thread.id!==t.thread.id?t:{...t,messages:Id([...e.messages,...t.messages]),hasMoreBefore:e.messages.length>t.messages.length?e.hasMoreBefore:t.hasMoreBefore}}function Yh(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=rl(a,o,"message.created",!0,o.authorUserId);return{...e,thread:a,messages:Id([...e.messages,...n])}}function yte(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 r=a.get(o.threadId)??[];r.push(o),a.set(o.threadId,r)}return e.map(o=>{let r=o;for(const s of a.get(o.id)??[])r=rl(r,s,"message.created",!0,s.authorUserId);return r}).sort((o,r)=>r.lastMessageAt.localeCompare(o.lastMessageAt))}function Qh(e,t,n){for(const a of e)!a.clientRequestId||a.id.startsWith("pending:")||(t.delete(a.clientRequestId),n.delete(a.clientRequestId))}function Xh(e,t,n){const a=e.get(t);a&&e.set(t,{...a,metadata:{...a.metadata,deliveryStatus:n}})}function Uk(e,t,n){const a=e.get(t);a&&e.set(t,{...a,metadata:{...a.metadata,uploadProgress:n}})}function Id(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 yT(e){return e.type!=="message.created"&&e.type!=="message.updated"&&e.type!=="message.deleted"?null:rb.safeParse(e.payload.message).data??null}function ST(e,t,n){const a=yT(t);if(a){const o=e.selectedThreadId===a.threadId,r=e.detail?.thread.id===a.threadId?{...e.detail,thread:rl(e.detail.thread,a,t.type,o,n),messages:Id([...e.detail.messages,a])}:e.detail,l=e.threads.some(m=>m.id===a.threadId)?e.threads.map(m=>m.id===a.threadId?rl(m,a,t.type,o,n):m).sort((m,d)=>d.lastMessageAt.localeCompare(m.lastMessageAt)):e.threads;return{...e,detail:r,threads:l,error:null}}if(t.type==="read.updated"){const o=typeof t.payload.userId=="string"?t.payload.userId:null,r=Number(t.payload.sequence);if(!o||!Number.isSafeInteger(r)||r<0)return e;const s=l=>({...l,participants:l.participants.map(m=>m.userId===o?{...m,lastReadSequence:Math.max(m.lastReadSequence,r)}: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 rl(e,t,n,a,o){const r=n==="message.created",s=t.sequence>=e.lastMessageSequence;return{...e,lastMessageId:s?t.id:e.lastMessageId,lastMessageSequence:Math.max(e.lastMessageSequence,t.sequence),lastMessageAt:s?t.createdAt:e.lastMessageAt,updatedAt:s?t.createdAt:e.updatedAt,lastMessage:s?t:e.lastMessage,unreadCount:a||t.authorUserId===o?0:r?e.unreadCount+1:e.unreadCount}}function Ste(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:hte(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 xte(e,t){const n=e.detail?.thread.id===t.threadId?{...e.detail,thread:rl(e.detail.thread,t,"message.created",!0,t.authorUserId),messages:Id([...e.detail.messages,t])}:e.detail;return{...e,detail:n,threads:e.threads.map(a=>a.id===t.threadId?rl(a,t,"message.created",!0,t.authorUserId):a).sort((a,o)=>o.lastMessageAt.localeCompare(a.lastMessageAt)),error:null}}function zk(e,t,n){return ST(e,{teamId:t.teamId,threadId:t.threadId,type:"message.created",payload:{message:t},createdAt:t.createdAt},n)}function kte(e,t){return lv(e,t,"failed")}function lv(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 Bk(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 wte(e,t){const n=e.detail?.messages.filter(r=>r.id!==t)??[],a=n.at(-1)??null,o=e.detail?{...e.detail,thread:e.detail.thread.lastMessageId===t?Fk(e.detail.thread,a):e.detail.thread,messages:n}:null;return{...e,detail:o,threads:e.threads.map(r=>r.lastMessageId===t?Fk(r,a):r)}}function Ite(e){if(e.length>xr.maxAttachments)return null;const t=[];for(const n of e){if(n.kind!=="image"||!_te(n.mediaType)||!n.contentsBase64||n.sizeBytes<=0||n.sizeBytes>xr.maxAttachmentBytes)return null;t.push({...n,kind:"image",mediaType:n.mediaType,contentsBase64:n.contentsBase64})}return t}function Fk(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 _te(e){return e==="image/png"||e==="image/jpeg"||e==="image/webp"||e==="image/gif"}const Cte={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 Rte(e){const t=e instanceof Error?e.message:String(e),n=t.trim().toLowerCase();for(const[a,o]of Object.entries(Cte))if(n.includes(a))return o;return n.includes("event stream ended")?"Team chat realtime disconnected. Messages will continue to refresh automatically.":eT(t)}const xT="openpond.team-chat.notification-mode";function kT(){try{return typeof window>"u"?null:Vo}catch{return null}}function Vk(e=kT()){const t=e?.getItem(xT);return t==="direct_mentions"||t==="none"?t:"all"}function Pte(e,t=kT()){try{t?.setItem(xT,e)}catch{}}function Ate(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 Tte(e){const t=e.message.authorUserId?e.members.find(s=>s.userId===e.message.authorUserId)?.name??"Team member":e.message.authorType==="agent"?"Agent":"Team",n=e.thread.title?.trim()||(e.thread.kind==="general"?"general":"conversation"),a=e.thread.kind==="dm"?t:`${t} in #${n}`,r=e.message.body.replace(/\s+/g," ").trim()||(e.message.attachments.length===1?"Sent an image":e.message.attachments.length>1?`Sent ${e.message.attachments.length} images`:"New message");return{eventId:e.eventId,threadId:e.message.threadId,title:a,body:r.length>160?`${r.slice(0,157)}…`:r}}const Kk={members:[],agents:[],threads:[],selectedThreadId:null,detail:null,aiThread:null,agentConversation:null,loading:!1,busy:!1,error:null};function gu(e,t){return e.map(n=>n.id===t&&n.unreadCount!==0?{...n,unreadCount:0}:n)}function vu(e){return!e||e.thread.unreadCount===0?e:{...e,thread:{...e.thread,unreadCount:0}}}function Ete(e){return{teamId:e.teamId,body:e.body.trim(),clientRequestId:e.clientRequestId,selectedAgentId:e.conversation.agent.id,conversationId:e.conversation.conversationId}}function Mte(e){return{teamId:e.teamId,body:e.body.trim(),clientRequestId:e.clientRequestId,selectedActionKey:e.selectedActionKey,approvalId:e.approvalId??null}}async function Wk(e,t=ie.markTeamChatRead){return e.lastMessageSequence<=0?!1:t(e.connection,e.threadId,e.teamId,e.lastMessageSequence).then(()=>!0,()=>!1)}function jte(e){const[t,n]=y.useState(Kk),a=y.useRef(t);a.current=t;const[o,r]=y.useState(Vk);al(()=>r(Vk()));const[s,l]=y.useState(null),m=y.useRef(null),d=y.useRef(null),f=y.useRef(0),g=y.useRef(new Map),x=y.useRef(new Map),k=y.useRef(0),C=y.useRef(null),R=y.useRef(0),E=y.useRef(new Set),A=y.useRef(0),O=y.useRef(!1),$=y.useRef(new Map),M=y.useRef(new Map),[w,P]=y.useState(null),[j,N]=y.useState(null),z=y.useCallback(U=>{r(U),Pte(U)},[]),D=y.useCallback(U=>{l(J=>J?.eventId===U?null:J)},[]),F=y.useCallback(async()=>{if(!e.connection||!e.teamId)return[];const U=await ie.teamChatThreads(e.connection,e.teamId),J=yte(U.threads,$.current);return n(q=>({...q,threads:J})),J},[e.connection,e.teamId]),te=y.useCallback(async()=>{if(!e.connection||!e.teamId)return{members:[],agents:[]};const[U,J]=await Promise.all([ie.teamChatMembers(e.connection,e.teamId),ie.teamChatAgents(e.connection,e.teamId)]);return n(q=>({...q,members:U.members,agents:J.agents})),{members:U.members,agents:J.agents}},[e.connection,e.teamId]),ve=y.useCallback(async U=>{const J=U??m.current;if(!e.connection||!e.teamId||!J)return null;const q=(x.current.get(J)??0)+1;x.current.set(J,q);const oe=await ie.teamChatThread(e.connection,e.teamId,J);Qh(oe.messages,$.current,M.current);const he=Yh(oe,$.current);return x.current.get(J)!==q||(n(Re=>Re.selectedThreadId===J?{...Re,threads:gu(Re.threads,J),detail:vu(bte(Re.detail,he))}:Re),m.current===J&&he.thread.lastMessageSequence>0&&await ie.markTeamChatRead(e.connection,J,e.teamId,he.thread.lastMessageSequence).catch(()=>{})),he},[e.connection,e.teamId]),re=y.useCallback(async U=>{const J=U??d.current;if(!e.connection||!e.teamId||!J)return null;const q=(g.current.get(J)??0)+1;g.current.set(J,q);const oe=await ie.teamChatAiThread(e.connection,e.teamId,J);return g.current.get(J)===q&&d.current===J&&n(he=>qk(he,oe,d.current)),oe},[e.connection,e.teamId]),K=y.useCallback(async U=>{const J=U??C.current;if(!e.connection||!e.teamId||!J)return null;const q=await ie.teamChatAgentConversation(e.connection,e.teamId,J);return n(oe=>oe.agentConversation?.run.id===J?{...oe,agentConversation:q}:oe),q},[e.connection,e.teamId]);y.useEffect(()=>{m.current=t.selectedThreadId},[t.selectedThreadId]),y.useEffect(()=>{C.current=t.agentConversation?.run.id??null},[t.agentConversation?.run.id]),y.useEffect(()=>{const U=t.agentConversation?.run.status;if(!U||!["pending","queued","running"].includes(U))return;const J=window.setInterval(()=>{K().catch(q=>{n(oe=>({...oe,error:_n(q)}))})},2500);return()=>window.clearInterval(J)},[K,t.agentConversation?.run.status]),y.useEffect(()=>{if(!e.connection||!e.teamId||!e.currentUserId){n(Kk),P(null),N(null),M.current.clear(),$.current.clear(),x.current.clear(),g.current.clear(),k.current+=1,l(null),E.current.clear(),A.current=0,R.current=0;return}let U=!1;return d.current=null,f.current+=1,k.current+=1,P(null),N(null),M.current.clear(),$.current.clear(),E.current.clear(),A.current=0,n(J=>({...J,aiThread:null,agentConversation:null,loading:!0,error:null})),(async()=>{try{const J=await ie.teamChatEvents(e.connection,e.teamId);if(U)return;R.current=J.cursor;const q=ie.teamChatMembers(e.connection,e.teamId),oe=ie.teamChatAgents(e.connection,e.teamId),he=await ie.teamChatGeneral(e.connection,e.teamId),[Re,qe,Je]=await Promise.all([q,oe,ie.teamChatThreads(e.connection,e.teamId)]);if(U)return;const et=m.current&&Je.threads.some(Ne=>Ne.id===m.current)?m.current:he.thread.id,dt=et===he.thread.id?he:await ie.teamChatThread(e.connection,e.teamId,et);if(U)return;const _t=vu(dt);n(Ne=>({...Ne,members:Re.members,agents:qe.agents,threads:gu(Je.threads,et),selectedThreadId:et,detail:_t,loading:!1,error:null})),Wk({connection:e.connection,teamId:e.teamId,threadId:et,lastMessageSequence:_t?.thread.lastMessageSequence??0}),N(e.teamId)}catch(J){if(U)return;n(q=>({...q,loading:!1,error:_n(J)}))}})(),()=>{U=!0}},[e.connection,e.currentUserId,e.refreshToken,e.teamId]);const L=y.useCallback(U=>{if(E.current.has(U.id))return;if(E.current.add(U.id),E.current.size>2e3){const q=E.current.values().next().value;typeof q=="number"&&E.current.delete(q)}const J=yT(U);if(J&&U.type==="message.created"){const q=a.current,oe=q.threads.find(Re=>Re.id===J.threadId)??(q.detail?.thread.id===J.threadId?q.detail.thread:null),he=Re=>{U.id<=A.current||Ate({mode:o,currentUserId:e.currentUserId,message:J,thread:Re})&&(A.current=U.id,l(Tte({eventId:U.id,message:J,thread:Re,members:q.members})))};oe?he(oe):F().then(Re=>{const qe=Re.find(Je=>Je.id===J.threadId);qe&&he(qe)}).catch(()=>{})}J?.clientRequestId&&!J.id.startsWith("pending:")&&($.current.delete(J.clientRequestId),M.current.delete(J.clientRequestId)),n(q=>ST(q,U,e.currentUserId)),U.type==="thread.created"&&F().catch(q=>{n(oe=>({...oe,error:_n(q)}))}),(U.type==="ai_thread.created"||U.type==="ai_turn.updated")&&(ve(U.threadId).catch(q=>{n(oe=>({...oe,error:_n(q)}))}),U.conversationId===d.current&&re(U.conversationId).catch(q=>{n(oe=>({...oe,error:_n(q)}))})),J&&U.type==="message.created"&&m.current===J.threadId&&J.authorUserId!==e.currentUserId&&e.connection&&e.teamId&&ie.markTeamChatRead(e.connection,J.threadId,e.teamId,J.sequence).catch(()=>{})},[e.connection,e.currentUserId,e.teamId,o,re,ve,F]),de=y.useCallback(async()=>{if(!(!e.connection||!e.teamId||O.current)){O.current=!0;try{let U=!0;for(;U;){const J=await ie.teamChatEvents(e.connection,e.teamId,{after:R.current,limit:250});for(const q of J.events)L(q);R.current=J.cursor,U=J.hasMore}}finally{O.current=!1}}},[L,e.connection,e.teamId]);y.useEffect(()=>{if(!e.connection||!e.teamId||j!==e.teamId)return;let U=!1,J=null;const q=async()=>{try{const oe=await ie.teamChatRealtimeSession(e.connection,e.teamId);if(U||(await de(),U))return;P(oe);const he=Math.max(3e4,new Date(oe.expiresAt).getTime()-Date.now()-3e4);J=window.setTimeout(()=>{q()},he)}catch{U||(de().catch(()=>{}),J=window.setTimeout(()=>{q()},1e4))}};return q(),()=>{U=!0,J!==null&&window.clearTimeout(J),P(null)}},[de,e.connection,e.teamId,j]);const X=t.threads.map(U=>U.id).sort().join(",");y.useEffect(()=>{if(!w)return;const U=mte({session:w,threadIds:X?X.split(","):[],onEvent:L,onReady:()=>{de().catch(J=>{n(q=>({...q,error:_n(J)}))})},onError:()=>{de().catch(()=>{})}});return()=>{U.close()}},[L,de,w,X]),y.useEffect(()=>{if(!e.connection||!e.teamId||j!==e.teamId)return;const U=window.setInterval(()=>{de().catch(()=>{})},15e3);return()=>window.clearInterval(U)},[de,e.connection,e.teamId,j]);const Z=y.useCallback(async U=>{if(!e.connection||!e.teamId)return;const J=k.current+1;k.current=J;const q=m.current!==U;m.current=U,q&&(f.current+=1,d.current=null),n(oe=>({...oe,threads:gu(oe.threads,U),selectedThreadId:U,detail:oe.detail?.thread.id===U?vu(oe.detail):null,aiThread:q?null:oe.aiThread,agentConversation:q?null:oe.agentConversation,loading:!0,error:null}));try{const oe=await ie.teamChatThread(e.connection,e.teamId,U);if(k.current!==J||m.current!==U)return;Qh(oe.messages,$.current,M.current);const he=Yh(oe,$.current);n(Re=>({...Re,threads:gu(Re.threads,U),detail:vu(he),loading:!1})),await ie.markTeamChatRead(e.connection,U,e.teamId,he.thread.lastMessageSequence).catch(()=>{})}catch(oe){if(k.current!==J)return;n(he=>({...he,loading:!1,error:_n(oe)}))}},[e.connection,e.teamId]),pe=y.useCallback(async U=>{if(!e.connection||!e.teamId)return null;const J=k.current+1;k.current=J,n(q=>({...q,busy:!0,error:null}));try{const q=await ie.teamChatDm(e.connection,e.teamId,U);if(k.current!==J)return null;Qh(q.messages,$.current,M.current);const oe=Yh(q,$.current),he=m.current!==oe.thread.id;return m.current=oe.thread.id,he&&(f.current+=1,d.current=null),n(Re=>({...Re,selectedThreadId:oe.thread.id,detail:oe,aiThread:he?null:Re.aiThread,agentConversation:he?null:Re.agentConversation,busy:!1})),await Wk({connection:e.connection,teamId:e.teamId,threadId:oe.thread.id,lastMessageSequence:oe.thread.lastMessageSequence}),await F(),oe}catch(q){return k.current!==J||n(oe=>({...oe,busy:!1,error:_n(q)})),null}},[e.connection,e.teamId,F]),ee=y.useCallback(async()=>{const U=t.detail,J=U?.messages[0]?.sequence;if(!e.connection||!e.teamId||!U||!U.hasMoreBefore||J==null)return!1;n(q=>({...q,loading:!0,error:null}));try{const q=await ie.teamChatThread(e.connection,e.teamId,U.thread.id,{beforeSequence:J,limit:50});return n(oe=>{if(oe.detail?.thread.id!==U.thread.id)return oe;const he=[...q.messages,...oe.detail.messages];return{...oe,loading:!1,detail:{...oe.detail,messages:Id(he),hasMoreBefore:q.hasMoreBefore}}}),!0}catch(q){return n(oe=>({...oe,loading:!1,error:_n(q)})),!1}},[e.connection,e.teamId,t.detail]),me=y.useCallback(async U=>{const J=m.current,q=Ite(U.attachments??[]);if(!q)return n(Re=>({...Re,error:"Team chat supports up to 10 PNG, JPEG, WebP, or GIF images per message."})),!1;if(!e.connection||!e.teamId||!J||!U.body.trim()&&q.length===0)return!1;if(U.replyToMessage&&(U.replyToMessage.threadId!==J||U.replyToMessage.teamId!==e.teamId||U.replyToMessage.id.startsWith("pending:")||U.replyToMessage.deletedAt))return n(Re=>({...Re,error:"That message is no longer available to reply to."})),!1;if(U.useModel){if(q.length>0)return n(qe=>({...qe,error:"Images can be sent to the team thread with Use model turned off."})),!1;const Re=f.current;n(qe=>({...qe,busy:!0,error:null}));try{const qe=await ie.createTeamChatAiThread(e.connection,J,{teamId:e.teamId,body:U.body.trim(),clientRequestId:crypto.randomUUID(),providerId:U.providerId,modelId:U.modelId}),Je=f.current===Re&&m.current===J;return Je&&(f.current+=1,d.current=qe.conversationId),n(et=>({...et,aiThread:Je?qe:et.aiThread})),qe.activeTurn&&await ie.executeTeamChatAiTurn(e.connection,qe.activeTurn.id,e.teamId),await Promise.all([ve(J),F()]),n(et=>({...et,busy:!1})),!0}catch(qe){return n(Je=>({...Je,busy:!1,error:_n(qe)})),!1}}const oe=crypto.randomUUID();if(U.selectedActionKey){if(q.length>0)return n(Re=>({...Re,error:"Agent invocations do not support image attachments yet."})),!1;n(Re=>({...Re,busy:!0,error:null}));try{return await ie.createTeamChatAgentRun(e.connection,J,Mte({teamId:e.teamId,body:U.body,clientRequestId:oe,selectedActionKey:U.selectedActionKey,approvalId:U.approvalId})),await Promise.all([ve(J),F()]),n(Re=>({...Re,busy:!1})),!0}catch(Re){return n(qe=>({...qe,busy:!1,error:_n(Re)})),!1}}M.current.set(oe,{inputs:q,uploaded:null});const he=Ste({clientRequestId:oe,threadId:J,teamId:e.teamId,userId:e.currentUserId,body:U.body.trim(),mentionUserIds:U.mentionUserIds??[],attachments:q,replyToMessage:U.replyToMessage,sequence:(t.detail?.thread.lastMessageSequence??0)+1});$.current.set(oe,he),n(Re=>xte(Re,he));try{const Re=[];for(const[et,dt]of q.entries())Re.push(await ie.uploadTeamChatAttachment(e.connection,J,{teamId:e.teamId,attachment:dt})),Uk($.current,oe,`${et+1} of ${q.length}`),n(_t=>Bk(_t,oe,`${et+1} of ${q.length}`));const qe=M.current.get(oe);qe&&(qe.uploaded=Re);const Je=await ie.sendTeamChatMessage(e.connection,J,{teamId:e.teamId,body:U.body.trim(),clientRequestId:oe,mentionUserIds:U.mentionUserIds,attachmentIds:Re.map(et=>et.id),replyToMessageId:U.replyToMessage?.id??null});return M.current.delete(oe),$.current.delete(oe),n(et=>zk(et,Je,e.currentUserId)),!0}catch(Re){return Xh($.current,oe,"failed"),n(qe=>({...kte(qe,oe),error:_n(Re)})),!1}},[e.connection,e.currentUserId,e.teamId,ve,F,t.detail?.thread.lastMessageSequence]),be=y.useCallback(async U=>{if(!(!e.connection||!e.teamId)){f.current+=1,d.current=U,n(J=>({...J,aiThread:J.aiThread?.conversationId===U?J.aiThread:null,busy:!0,error:null}));try{const J=await ie.teamChatAiThread(e.connection,e.teamId,U);if(d.current!==U)return;n(q=>({...q,aiThread:J,busy:!1}))}catch(J){if(d.current!==U)return;n(q=>({...q,busy:!1,error:_n(J)}))}}},[e.connection,e.teamId]),je=y.useCallback(async U=>{if(!(!e.connection||!e.teamId)){C.current=U,n(J=>({...J,busy:!0,error:null}));try{const J=await ie.teamChatAgentConversation(e.connection,e.teamId,U);n(q=>({...q,agentConversation:J,busy:!1}))}catch(J){n(q=>({...q,busy:!1,error:_n(J)}))}}},[e.connection,e.teamId]),ke=y.useCallback(()=>{C.current=null,n(U=>({...U,agentConversation:null}))},[]),ue=y.useCallback(async U=>{const J=m.current,q=t.agentConversation;if(!e.connection||!e.teamId||!J||!q||!U.body.trim())return!1;n(oe=>({...oe,busy:!0,error:null}));try{const oe=await ie.createTeamChatAgentRun(e.connection,J,Ete({teamId:e.teamId,body:U.body,clientRequestId:U.clientRequestId,conversation:q}));C.current=oe.run.id;const[he]=await Promise.all([ie.teamChatAgentConversation(e.connection,e.teamId,oe.run.id),ve(J),F()]);return n(Re=>({...Re,agentConversation:he,busy:!1})),!0}catch(oe){return n(he=>({...he,busy:!1,error:_n(oe)})),!1}},[e.connection,e.teamId,ve,F,t.agentConversation]),Ie=y.useCallback(()=>{f.current+=1,d.current=null,n(U=>({...U,aiThread:null}))},[]),Le=y.useCallback(async U=>{const J=d.current;if(!e.connection||!e.teamId||!J||!U.body.trim())return!1;n(q=>({...q,busy:!0,error:null}));try{const q=await ie.sendTeamChatAiTurn(e.connection,J,{teamId:e.teamId,body:U.body.trim(),clientRequestId:crypto.randomUUID(),providerId:U.providerId,modelId:U.modelId});return n(oe=>({...qk(oe,q,d.current),busy:!1})),q.activeTurn&&await ie.executeTeamChatAiTurn(e.connection,q.activeTurn.id,e.teamId),!0}catch(q){return n(oe=>({...oe,busy:!1,error:_n(q)})),!1}},[e.connection,e.teamId]),Fe=y.useCallback(async()=>{const U=t.aiThread?.activeTurn?.id;return!e.connection||!e.teamId||!U?!1:(await ie.cancelTeamChatAiTurnExecution(e.connection,U,e.teamId)).cancelled},[e.connection,e.teamId,t.aiThread?.activeTurn?.id]),Xe=y.useCallback(async(U,J)=>{if(!e.connection||!e.teamId)return!1;try{return await ie.editTeamChatMessage(e.connection,U.threadId,U.id,{teamId:e.teamId,body:J}),await ve(U.threadId),!0}catch(q){return n(oe=>({...oe,error:_n(q)})),!1}},[e.connection,e.teamId,ve]),Ze=y.useCallback(async U=>{if(!e.connection||!e.teamId)return!1;try{return await ie.deleteTeamChatMessage(e.connection,U.threadId,U.id,e.teamId),await ve(U.threadId),!0}catch(J){return n(q=>({...q,error:_n(J)})),!1}},[e.connection,e.teamId,ve]),Be=y.useCallback(async U=>{if(!e.connection||!e.teamId||!U.clientRequestId||!U.id.startsWith("pending:"))return!1;const J=Array.isArray(U.metadata.mentionUserIds)?U.metadata.mentionUserIds.filter(he=>typeof he=="string"):[],q=M.current.get(U.clientRequestId),oe=U.refs.find(he=>he.refType==="message_reply");Xh($.current,U.clientRequestId,"sending"),n(he=>lv(he,U.clientRequestId,"sending"));try{let he=q?.uploaded??[];if(q&&!q.uploaded){he=[];for(const[qe,Je]of q.inputs.entries())he.push(await ie.uploadTeamChatAttachment(e.connection,U.threadId,{teamId:e.teamId,attachment:Je})),Uk($.current,U.clientRequestId,`${qe+1} of ${q.inputs.length}`),n(et=>Bk(et,U.clientRequestId,`${qe+1} of ${q.inputs.length}`));q.uploaded=he}const Re=await ie.sendTeamChatMessage(e.connection,U.threadId,{teamId:e.teamId,body:U.body,clientRequestId:U.clientRequestId,mentionUserIds:J,attachmentIds:he.map(qe=>qe.id),replyToMessageId:oe?.refId??null});return M.current.delete(U.clientRequestId),$.current.delete(U.clientRequestId),n(qe=>zk(qe,Re,e.currentUserId)),!0}catch(he){return Xh($.current,U.clientRequestId,"failed"),n(Re=>({...lv(Re,U.clientRequestId,"failed"),error:_n(he)})),!1}},[e.connection,e.currentUserId,e.teamId]),Ge=y.useCallback(U=>{U.id.startsWith("pending:")&&(U.clientRequestId&&M.current.delete(U.clientRequestId),U.clientRequestId&&$.current.delete(U.clientRequestId),n(J=>wte(J,U.id)))},[]),Ve=y.useCallback(async(U,J)=>{if(!e.connection||!e.teamId)return!1;try{const q=await ie.setTeamChatThreadMuted(e.connection,U,e.teamId,J),oe=he=>he.id===q.threadId?{...he,mutedAt:q.mutedAt}:he;return n(he=>({...he,threads:he.threads.map(oe),detail:he.detail?.thread.id===q.threadId?{...he.detail,thread:oe(he.detail.thread)}:he.detail,error:null})),!0}catch(q){return n(oe=>({...oe,error:_n(q)})),!1}},[e.connection,e.teamId]);return{...t,currentUserId:e.currentUserId,notificationMode:o,incomingNotification:s,setNotificationMode:z,dismissIncomingNotification:D,setThreadMuted:Ve,selectThread:Z,openDm:pe,loadMoreMessages:ee,sendMessage:me,openAiThread:be,openAgentConversation:je,closeAgentConversation:ke,sendAgentTurn:ue,closeAiThread:Ie,sendAiTurn:Le,stopAiTurn:Fe,editMessage:Xe,deleteMessage:Ze,retryMessage:Be,dismissFailedMessage:Ge,refreshDirectory:te,refresh:async()=>{await Promise.all([te(),F(),ve(),re(),K()])}}}function _n(e){return Rte(e)}const wT="local-profile-agent";function dre(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?[]:[vr(l.agentName),vr(s.name),vr(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")),r=t.agents.flatMap(s=>s.enabled?a?.agentId===s.id&&!!(a.runtimeAgentId&&o.has(a.runtimeAgentId))||n.has(vr(s.name))||n.has(vr(s.id))?[]:[Nte(t,s)]:[]);return[...e.hostedActions,...r]}function ure(e){return e?.implementation?.type===wT}function mre(e){const t=e.implementation?.profileAgentId;return typeof t=="string"&&t.trim()?t.trim():null}function Ote(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 $te(e,t){const n=t.runtimeAgentId?.trim()??"",a=t.profileName?.trim()??"",o=vr(t.agentName);return e.find(r=>{const s=r.implementation;return s?.type!=="openpond-agent"?!1:n&&typeof s.agentId=="string"&&s.agentId===n?!0:!!(a&&s.profileName===a&&o&&[s.agentName,r.name,r.label].some(l=>vr(l)===o))})??null}function Nte(e,t){return{id:`local-profile:${e.activeProfile??"default"}:${t.id}:chat`,name:t.name,label:t.name,description:Dte(e),approvalPolicy:{required:!1,risk:"write"},setupRequirements:e.setupGate.blockingRequirements,invokesModel:!0,implementation:{type:wT,profileAgentId:t.id,profileName:e.activeProfile??"default"}}}function Dte(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 vr(e){return typeof e=="string"?e.trim().toLowerCase().replace(/[^a-z0-9]+/g,""):""}const Gk=5;function Hte(e){return y.useCallback(async t=>{if(!e.connection||!e.teamId)throw new Error("Connect OpenPond to a Team before publishing an agent.");const n=await ie.profileCheck(e.connection,{kind:"all"}),a=Ote(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 ie.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 ie.bootstrap(e.connection));let m=null;for(let d=0;d<Gk;d+=1){const f=await e.refreshDirectory();if(m=$te(f.agents,{runtimeAgentId:l,profileName:n.activeProfile,agentName:o.name}),m)break;d<Gk-1&&await Lte(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 Lte(e){return new Promise(t=>{setTimeout(t,e)})}function qte(e){y.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 Ute(e){const{connection:t,refreshToken:n=null}=e,[a,o]=y.useState([]),[r,s]=y.useState(null),[l,m]=y.useState(null),[d,f]=y.useState(null),[g,x]=y.useState(!1),[k,C]=y.useState(!1),[R,E]=y.useState(!1),[A,O]=y.useState(null),[$,M]=y.useState(null),[w,P]=y.useState(null),[j,N]=y.useState(0),z=y.useRef(0),D=y.useMemo(()=>a.find(ee=>ee.id===l)??null,[a,l]),F=y.useCallback(async()=>{if(!t)return!1;x(!0),O(null);try{const ee=await ie.communities(t);return o(ee.items),s(ee.nextCursor),m(me=>me&&ee.items.some(be=>be.id===me)?me:null),!0}catch(ee){return O(zu(ee)),!1}finally{x(!1)}},[t]),te=y.useCallback(async()=>{if(!t||!r||g)return!1;x(!0),O(null);try{const ee=await ie.communities(t,r);return o(me=>zte(me,ee.items)),s(ee.nextCursor),!0}catch(ee){return O(zu(ee)),!1}finally{x(!1)}},[t,g,r]),ve=y.useCallback(async ee=>{if(!t)return null;const me=++z.current;C(!0),M(null);try{const be=await ie.communityPreview(t,ee.slug);return z.current===me&&f(be),be}catch(be){return z.current===me&&M(zu(be)),null}finally{z.current===me&&C(!1)}},[t]),re=y.useCallback(ee=>{const me=a.find(be=>be.id===ee);me&&(m(me.id),f(be=>be?.id===me.id?be:null),P(null),ve(me))},[a,ve]),K=y.useCallback(()=>{z.current+=1,m(null),f(null),M(null),P(null)},[]);y.useEffect(()=>{if(!t){o([]),f(null),m(null);return}F()},[t,F,n]),y.useEffect(()=>{!D||d?.id===D.id||k||ve(D)},[ve,d?.id,k,D]);const L=y.useCallback(async()=>{const ee=D;await F(),ee&&await ve(ee)},[ve,F,D]),de=y.useCallback(async()=>{if(!t||!d?.currentRules||R)return!1;E(!0),P(null);try{return await ie.joinCommunity(t,d.id,d.currentRules.id),N(ee=>ee+1),await L(),!0}catch(ee){const me=bu(ee);return P(me),me.kind==="rules_stale"&&await L(),!1}finally{E(!1)}},[t,R,d,L]),X=y.useCallback(async()=>{if(!t||!d?.currentRules||R)return!1;E(!0),P(null);try{return await ie.acceptCommunityRules(t,d.id,d.currentRules.id),N(ee=>ee+1),await L(),!0}catch(ee){const me=bu(ee);return P(me),me.kind==="rules_stale"&&await L(),!1}finally{E(!1)}},[t,R,d,L]),Z=y.useCallback(async()=>{if(!t||!d||R)return!1;E(!0),P(null);try{return await ie.leaveCommunity(t,d.id),N(ee=>ee+1),await L(),!0}catch(ee){return P(bu(ee)),!1}finally{E(!1)}},[t,R,d,L]),pe=y.useCallback(async ee=>{if(!t||!d||R)return!1;E(!0),P(null);try{return await ie.updateCommunityNotifications(t,d.id,ee),o(me=>me.map(be=>be.id===d.id&&be.membership?{...be,membership:{...be.membership,notificationMode:ee}}:be)),f(me=>me?.id===d.id&&me.membership?{...me,membership:{...me.membership,notificationMode:ee}}:me),!0}catch(me){return P(bu(me)),!1}finally{E(!1)}},[t,R,d]);return{items:a,nextCursor:r,selectedCommunityId:l,selectedSummary:D,preview:d,discoveryLoading:g,previewLoading:k,membershipBusy:R,discoveryError:A,previewError:$,membershipError:w,membershipVersion:j,refresh:F,loadMore:te,showDiscovery:K,selectCommunity:re,join:de,acceptRules:X,leave:Z,updateNotifications:pe,clearMembershipError:()=>P(null)}}function zte(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 zu(e){return e instanceof Error?e.message:String(e)}function bu(e){const t=zu(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 Bte(e,t,n){return bT({realtimeUrl:e.session.realtimeUrl,httpUrl:e.session.httpUrl,authorizationToken:e.session.token,channels:[e.session.channel],onEvent:a=>{const o=r_.safeParse(a);o.success&&e.onEvent(o.data)},onReady:e.onReady,onError:e.onError},t,n)}function Fte(e){const{connection:t,preview:n,currentUserId:a,membershipVersion:o}=e,r=n?.id??null,s=n?.membership?.status==="active",l=!n?.capabilities.requiresRulesAcceptance,[m,d]=y.useState([]),[f,g]=y.useState(null),[x,k]=y.useState({}),[C,R]=y.useState([]),[E,A]=y.useState(!1),[O,$]=y.useState(!1),[M,w]=y.useState(!1),[P,j]=y.useState(!1),[N,z]=y.useState(null),[D,F]=y.useState(null),[te,ve]=y.useState(null),[re,K]=y.useState(null),[L,de]=y.useState(!1),[X,Z]=y.useState(null),[pe,ee]=y.useState(null),me=y.useRef(null),be=y.useRef([]),je=y.useRef("mentions"),ke=y.useRef(0),ue=y.useRef({}),Ie=y.useRef(new Set),Le=y.useMemo(()=>m.find(Ne=>Ne.id===f)??null,[m,f]),Fe=f?x[f]??null:null;y.useEffect(()=>{me.current=f},[f]),y.useEffect(()=>{be.current=m},[m]),y.useEffect(()=>{je.current=n?.membership?.notificationMode??"mentions"},[n?.membership?.notificationMode]);const Xe=y.useCallback(async()=>{if(!t||!r)return!1;A(!0),z(null);try{const Ne=await ie.communityChannels(t,r);return d(Ne.channels),g(Ye=>Ye&&Ne.channels.some(h=>h.id===Ye)?Ye:Ne.channels.find(h=>h.isDefault)?.id??Ne.channels[0]?.id??null),de(!1),!0}catch(Ne){const Ye=Ra(Ne);return z(Ye),Yl(Ye)&&de(!0),!1}finally{A(!1)}},[r,t]),Ze=y.useCallback(async Ne=>{if(!t||!r)return!1;const Ye=++ke.current;$(!0),F(null);try{const h=await ie.communityMessages(t,r,Ne,{limit:50});return Ye!==ke.current?!1:(k(V=>({...V,[Ne]:{items:h.messages,hasMoreBefore:h.hasMoreBefore,preview:h.preview}})),de(!1),!0)}catch(h){if(Ye!==ke.current)return!1;const V=Ra(h);return F(V),Yl(V)&&de(!0),!1}finally{Ye===ke.current&&$(!1)}},[r,t]);y.useEffect(()=>{d(n?.channels??[]),k({}),g(n?.channels.find(Ne=>Ne.isDefault)?.id??n?.channels[0]?.id??null),z(null),F(null),ve(null),de(!1),Ie.current.clear(),r&&Xe()},[r,Xe,o]),y.useEffect(()=>{f&&Ze(f)},[Ze,f]);const Be=y.useCallback(async(Ne,Ye)=>{if(!t||!r||!s||!l||Ye<=0)return!1;if((ue.current[Ne]??0)>=Ye)return!0;ue.current[Ne]=Ye;try{const h=await ie.markCommunityRead(t,r,Ne,Ye);return d(V=>V.map(ae=>ae.id===Ne?{...ae,unreadCount:0,readState:ae.readState?{...ae.readState,lastReadSequence:h.sequence,lastReadAt:new Date().toISOString()}:{lastReadSequence:h.sequence,lastReadAt:new Date().toISOString(),mutedAt:null,pinnedAt:null}}:ae)),!0}catch(h){const V=Ra(h);return Yl(V)&&de(!0),!1}},[r,t,s,l]);y.useEffect(()=>{const Ne=Fe?.items.at(-1)?.sequence??0;f&&Ne>0&&Be(f,Ne)},[Be,f,Fe?.items]);const Ge=y.useCallback(Ne=>{if(Ne.communityId!==r||Ie.current.has(Ne.id))return;Ie.current.add(Ne.id);const Ye=o_.safeParse(Ne.payload.message);if(Ye.success&&Ne.type!=="read.updated"){const h=Ye.data;if(k(V=>{const ae=V[Ne.channelId];if(!ae)return V;const fe=ae.items.some(Y=>Y.id===h.id)?ae.items.map(Y=>Y.id===h.id?h:Y):[...ae.items,h].sort((Y,_)=>Y.sequence-_.sequence);return{...V,[Ne.channelId]:{...ae,items:fe}}}),d(V=>V.map(ae=>ae.id===Ne.channelId?{...ae,lastMessageSequence:Math.max(ae.lastMessageSequence,h.sequence),unreadCount:me.current===Ne.channelId||h.authorUserId===a?0:Math.max(ae.unreadCount+(Ne.type==="message.created"?1:0),0)}:ae)),Ne.type==="message.created"&&h.authorUserId!==a){const V=be.current.find(fe=>fe.id===Ne.channelId),ae=Vte(h).includes(a??""),we=je.current;!V?.readState?.mutedAt&&(we==="all"||we==="mentions"&&ae)&&ee({communityId:Ne.communityId,channelId:Ne.channelId,message:h})}me.current===Ne.channelId&&Be(Ne.channelId,h.sequence);return}Ne.type==="read.updated"&&Ne.payload.userId===a&&Xe()},[r,a,Xe,Be]);y.useEffect(()=>{if(!t||!r||!s||!l)return;let Ne=!1,Ye=null;return ve(null),Promise.all([ie.communityRealtimeSession(t,r),ie.communityEvents(t,r)]).then(async([h,V])=>{if(Ne)return;const ae=async()=>{let fe=V.cursor;for(;;){const Y=await ie.communityEvents(t,r,{after:fe,limit:200});if(Ne)return;for(const _ of Y.events)Ge(_);if(fe=Y.cursor,!Y.hasMore)return}},we=Bte({session:h,onEvent:Ge,onReady:()=>{ve(null),ae().catch(fe=>ve(Ra(fe)))},onError:fe=>ve(Ra(fe))});Ye=()=>we.close(),await ae()}).catch(h=>{if(!Ne){const V=Ra(h);ve(V),Yl(V)&&de(!0)}}),()=>{Ne=!0,Ye?.()}},[Ge,r,t,s,o,l]);const Ve=y.useCallback(async()=>{if(!t||!r||!f||M)return!1;const Ne=x[f],Ye=Ne?.items[0]?.sequence;if(!Ne?.hasMoreBefore||Ye==null)return!1;w(!0),F(null);try{const h=await ie.communityMessages(t,r,f,{beforeSequence:Ye,limit:50});return k(V=>{const ae=V[f]??Ne,we=new Set(ae.items.map(fe=>fe.id));return{...V,[f]:{...ae,items:[...h.messages.filter(fe=>!we.has(fe.id)),...ae.items],hasMoreBefore:h.hasMoreBefore}}}),!0}catch(h){return F(Ra(h)),!1}finally{w(!1)}},[r,t,x,M,f]),U=y.useCallback(async Ne=>{if(!t||!r||!f||P)return!1;j(!0),K(null),Z(null);try{const Ye=await Promise.all(Ne.attachments.map(V=>ie.uploadCommunityAttachment(t,r,f,V))),h=await ie.sendCommunityMessage(t,r,f,{body:Ne.body,clientRequestId:Ne.clientRequestId,mentionUserIds:Ne.mentionUserIds,attachmentIds:Ye.map(V=>V.id),replyToMessageId:Ne.replyToMessageId});return k(V=>{const ae=V[f]??{items:[],hasMoreBefore:!1,preview:!1};return ae.items.some(we=>we.id===h.id)?V:{...V,[f]:{...ae,items:[...ae.items,h]}}}),await Be(f,h.sequence),!0}catch(Ye){const h=Ra(Ye);return K(h),Z({...Ne,message:h}),Yl(h)&&de(!0),!1}finally{j(!1)}},[r,t,Be,f,P]),J=y.useCallback(Ne=>U({body:Ne.body,clientRequestId:crypto.randomUUID(),mentionUserIds:Ne.mentionUserIds??[],attachments:Ne.attachments??[],replyToMessageId:Ne.replyToMessageId??null}),[U]),q=y.useCallback(async(Ne,Ye)=>{if(!t||!r||!f)return!1;K(null);try{const h=await ie.editCommunityMessage(t,r,f,Ne,Ye);return Jk(k,f,h),!0}catch(h){return K(Ra(h)),!1}},[r,t,f]),oe=y.useCallback(async Ne=>{if(!t||!r||!f)return!1;K(null);try{const Ye=await ie.deleteCommunityMessage(t,r,f,Ne);return Jk(k,f,Ye),!0}catch(Ye){return K(Ra(Ye)),!1}},[r,t,f]),he=y.useCallback(async(Ne,Ye)=>{if(!t||!r)return!1;K(null);try{const h=await ie.setCommunityChannelMuted(t,r,Ne,Ye);return d(V=>V.map(ae=>ae.id===Ne&&ae.readState?{...ae,readState:{...ae.readState,mutedAt:h.mutedAt}}:ae)),!0}catch(h){return K(Ra(h)),!1}},[r,t]),Re=y.useCallback(async(Ne="")=>{if(!t||!r||!s)return[];try{const Ye=await ie.searchCommunityMembers(t,r,{query:Ne,limit:50});return R(h=>Kte(h,Ye.items)),Ye.items}catch(Ye){return K(Ra(Ye)),[]}},[r,t,s]);y.useEffect(()=>{s&&l?Re():R([])},[s,l,Re]);const qe=y.useCallback(async Ne=>{if(!t||!r||!f)return!1;try{const Ye=await ie.communityAttachmentDownload(t,r,f,Ne);return window.open(Ye.url,"_blank","noopener,noreferrer"),!0}catch(Ye){return K(Ra(Ye)),!1}},[r,t,f]),Je=y.useCallback(()=>f?Ze(f):Promise.resolve(!1),[Ze,f]),et=y.useCallback(()=>X?U(X):Promise.resolve(!1),[X,U]),dt=y.useCallback(()=>Z(null),[]),_t=y.useCallback(()=>ee(null),[]);return{channels:m,selectedChannelId:f,selectedChannel:Le,messages:Fe?.items??[],hasMoreBefore:Fe?.hasMoreBefore??!1,previewMode:Fe?.preview??!s,members:C,channelsLoading:E,messagesLoading:O,olderMessagesLoading:M,sending:P,channelsError:N,messagesError:D,realtimeError:te,actionError:re,lostMembership:L,failedSend:X,incomingNotification:pe,selectChannel:g,loadChannels:Xe,loadMessages:Je,loadOlder:Ve,sendMessage:J,retrySend:et,dismissFailedSend:dt,editMessage:q,deleteMessage:oe,setMuted:he,searchMembers:Re,downloadAttachment:qe,dismissIncomingNotification:_t}}function Jk(e,t,n){e(a=>{const o=a[t];return o?{...a,[t]:{...o,items:o.items.map(r=>r.id===n.id?n:r)}}:a})}function Vte(e){const t=e.metadata.mentionUserIds;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function Kte(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 Yl(e){return e.includes("community_membership_required")||e.includes("community_rules")}function Ra(e){return e instanceof Error?e.message:String(e)}function Wte(e){const t=Ute({connection:e.connection,refreshToken:e.refreshToken}),n=Fte({connection:e.connection,preview:t.preview,currentUserId:e.currentUserId,membershipVersion:t.membershipVersion}),a=n.incomingNotification,o=t.items,r=n.channels,s=t.selectCommunity,l=n.selectChannel,m=n.dismissIncomingNotification,{setView:d,showToast:f}=e,g=y.useCallback(()=>{t.showDiscovery(),d("community")},[t.showDiscovery,d]),x=y.useCallback(C=>{t.selectCommunity(C),d("community")},[t.selectCommunity,d]),k=y.useCallback(C=>{n.selectChannel(C),d("community")},[n.selectChannel,d]);return y.useEffect(()=>{if(!a)return;const C=o.find(E=>E.id===a.communityId),R=r.find(E=>E.id===a.channelId);f(`${C?.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()},[r,o,m,a,l,s,d,f]),{communities:t,chat:n,sidebar:{communityItems:t.items,communityChannels:n.channels,communityLoading:t.discoveryLoading,communityError:t.discoveryError,selectedCommunityId:t.selectedCommunityId,selectedCommunityChannelId:n.selectedChannelId,discoverCommunities:g,selectCommunity:x,selectCommunityChannel:k},view:{communities:t,chat:n,currentUserId:e.currentUserId}}}const Gte=[];function Jte(e){const t=y.useCallback(a=>wZ(e,a),[e]),n=y.useCallback(()=>xZ(e)??Gte,[e]);return y.useSyncExternalStore(t,n,n)}function Zte(e){const[t,n]=y.useState(()=>ch());return y.useEffect(()=>{let a=!0;return e?(ie.connectedAppStatus(e,{status:"all"}).then(o=>{a&&n(o.apps)}).catch(o=>{console.warn("Unable to load connected app mention status.",o),a&&n(ch())}),()=>{a=!1}):(n(ch()),()=>{a=!1})},[e]),t}function Yte(){const{composerDraftStore:e,dispatch:t,setters:n,state:a}=fee(),[o,r]=y.useState(null),[s,l]=y.useState([]),[m,d]=y.useState(null),[f,g]=y.useState(null),[x,k]=y.useState([]),[C,R]=y.useState(null),[E,A]=y.useState(null),[O,$]=y.useState(PA),[M,w]=y.useState({}),[P,j]=y.useState(()=>new Set),N=y.useCallback((it,dn)=>{j(Gt=>{if(Gt.has(it)===dn)return Gt;const Qt=new Set(Gt);return dn?Qt.add(it):Qt.delete(it),Qt})},[]),[z,D]=y.useState(0),[F,te]=y.useState(null),ve=y.useRef(null),{confirmProjectAction:re,projectConfirmDialog:K,resolveProjectConfirmDialog:L}=mJ(),{query:de,searchOpen:X,archivedChatsOpen:Z,sectionMenuOpen:pe,projectsExpanded:ee,cloudProjectsExpanded:me,chatRowsVisibleCount:be,sidebarOpen:je,view:ke,selectedAppId:ue,selectedProjectId:Ie,selectedSessionId:Le,draftProvider:Fe,draftModel:Xe,draftExperience:Ze,codexPermissionMode:Be,codexReasoningEffort:Ge,openPondCommandAccessMode:Ve,busy:U,diffPanelOpen:J,diffPanelExpanded:q,rightPanelMode:oe,rightChatPanels:he,terminalOpen:Re,settingsSection:qe,newProjectDialogOpen:Je,newProjectMode:et,newProjectName:dt,newProjectPath:_t,newProjectBusy:Ne,commitDialogOpen:Ye,commitMessage:h,commitIncludeUnstaged:V,commitNextStep:ae,commitDraft:we,branchDialogOpen:fe,branchDialogName:Y,toast:_,error:G}=a,se=yee(ke==="labs"),{setQuery:ne,setSearchOpen:ge,setArchivedChatsOpen:Se,setSectionMenuOpen:xe,setProjectsExpanded:Oe,setCloudProjectsExpanded:Te,setChatRowsVisibleCount:Ue,setSidebarOpen:Ee,setView:tt,setSelectedAppId:ht,setSelectedProjectId:xn,setSelectedSessionId:xt,setPrompt:Xn,setDraftProvider:kn,setDraftModel:Pn,setDraftExperience:Zt,setCodexPermissionMode:Dn,setCodexReasoningEffort:An,setOpenPondCommandAccessMode:Hn,setDiffPanelOpen:Un,setDiffPanelExpanded:Wt,setRightPanelMode:Ct,setRightChatPanels:Ln,setTerminalOpen:mt,setSyncingWorkspaceAppId:Nt,setSettingsSection:ea,setNewProjectDialogOpen:$t,setNewProjectMode:Tn,setNewProjectName:st,setNewProjectPath:En,setNewProjectBusy:gi,setCommitDialogOpen:vi,setCommitMessage:Wn,setCommitIncludeUnstaged:da,setCommitNextStep:Gn,setCommitDraft:Vi,setBranchDialogOpen:ei,setBranchDialogName:wt,setError:pn}=n,{connectionRef:Rt,setError:ut,showToast:ln}=oee({appDispatch:t,error:G,setErrorState:pn}),{appPreferences:ta,applyBootstrapPayload:wn,bootstrap:nt,codexHistorySessions:Q,connection:Ae,events:De,runtimeEventStore:pt,approvals:Yt,sessions:ua,startup:bi,setAppPreferences:In,setBootstrap:Ki,setCodexHistorySessions:Jn,setEvents:ja,setSessions:ma}=nee({selectedSessionId:Le,setDraftModel:Pn,setDraftProvider:kn,setCodexPermissionMode:Dn,setCodexReasoningEffort:An,setOpenPondCommandAccessMode:Hn,setError:ut,setSelectedAppId:ht,setSelectedProjectId:xn,setSelectedSessionId:xt});Rt.current=Ae,y.useEffect(()=>{nt&&k(nt.sidebarFileBookmarks??[])},[nt?.sidebarFileBookmarks]);const ko=y.useMemo(()=>[...De].reverse().find(it=>it.name==="tool.completed"&&it.action==="manage_sidebar_file")??null,[De]),ir=y.useRef(null);y.useEffect(()=>{!Ae||!ko||ir.current===ko.id||(ir.current=ko.id,ie.sidebarFiles(Ae).then(it=>k(it.items)).catch(it=>ut(it instanceof Error?it.message:String(it))))},[Ae,ko,ut]);const wo=y.useCallback(async(it,dn)=>{if(!Ae)return;const Gt=x;k(Qt=>dn==="none"?Qt.filter(Ca=>Ca.id!==it.id):Qt.some(Ca=>Ca.id===it.id)?Qt.map(Ca=>Ca.id===it.id?{...Ca,status:dn}:Ca):[...Qt,{...it,status:dn}]);try{const Qt=await ie.patchSidebarFile(Ae,{workspaceKind:it.workspaceKind,workspaceId:it.workspaceId,workspaceName:it.workspaceName,path:it.path,status:dn,sourceSessionId:it.sourceSessionId});k(Qt.items)}catch(Qt){k(Gt),ut(Qt instanceof Error?Qt.message:String(Qt))}},[Ae,ut,x]),Io=Zte(Ae),It=Cee({connection:Ae,profileId:nt?.profile?.activeProfile??"default"}),{pinnedCollapsed:bl,projectsCollapsed:or,cloudProjectsCollapsed:yl,chatsCollapsed:zr,savedForLaterCollapsed:Sl,sidebarWidth:Wi,sidebarResizing:xl,diffPanelWidth:Br,diffPanelResizing:Fr,togglePinnedCollapsed:Vr,toggleProjectsCollapsed:kl,toggleCloudProjectsCollapsed:wl,toggleChatsCollapsed:yi,toggleSavedForLaterCollapsed:Il,startSidebarResize:Kr,startDiffPanelResize:Wr}=vee({connection:Ae,preferences:nt?.preferences,sidebarOpen:je,diffPanelExpanded:q,setBootstrap:Ki,setError:ut}),{cloudProjectById:_o,linkedProjectByAppId:Gr,localProjectById:wa,mentionableSandboxApps:_l,selectedApp:rr,selectedCloudProject:Gi,selectedProject:pa,selectedProjectLinkedApp:Cl,selectedProjectLinkedOpenPondApp:Rl,selectedSession:Mn,selectedSessionLinkedProject:Co,sidebarSessions:Oa}=qZ({bootstrap:nt,codexHistorySessions:Q,selectedAppId:ue,selectedProjectId:Ie,selectedSessionId:Le,sessions:ua}),ti=Mn?.experience??Ze;y.useEffect(()=>{pZ(ti)},[ti]);const sr=y.useMemo(()=>Z8(Oa,ti),[ti,Oa]),Ro=$ee(De,Yt),{chatMentionApps:Pl,connectedAppMentions:Jr,pendingApproval:lr}=oY({bootstrap:nt,connectedAppRows:Io,mentionableSandboxApps:_l,runtimeIndexes:Ro,selectedApp:rr,selectedCloudProject:Gi,selectedProject:pa,selectedSession:Mn,selectedSessionId:Le}),{codexHistoryEvents:Ji,setCodexHistoryEvents:Po}=IY({connection:Ae,selectedSessionId:Le,selectedSessionLocallyActive:!!(Le&&P.has(Le)),selectedSessionStatus:Mn?.status,setCodexHistorySessions:Jn,setError:ut}),{account:Ao,accountPending:Zr,accountSignedOut:Yr,activeModel:$a,activeProvider:Na,activeWorkspaceAppId:Qr,activeWorkspaceId:cr,activeWorkspaceKind:Si,activeWorkspaceLocation:dr,appDefaults:Zi,cloudLinked:Xr,selectedCodexHistoryPending:es,selectedSessionProjectId:ts,startMessage:Al,workspaceName:ns}=$Z({bootstrap:nt,draftModel:Xe,draftProvider:Fe,selectedApp:rr,selectedAppId:ue,selectedCloudProject:Gi,selectedProject:pa,selectedSession:Mn,selectedSessionId:Le,selectedSessionLinkedProject:Co}),as=y.useMemo(()=>CZ(nt?.account??null),[nt?.account]),Tl=y.useMemo(()=>Yg(nt?.account??null),[nt?.account]),To=Jte(Tl),is=y.useMemo(()=>AZ(To,Zi.defaultTeamId),[Zi.defaultTeamId,To]),ur=is?.teamId??null,xi=jte({connection:Ae,teamId:ur,currentUserId:Ao?.profile?.id??null,refreshToken:nt?.accountMeta.asOf??null}),El=Hte({connection:Ae,teamId:ur,applyBootstrapPayload:wn,refreshDirectory:xi.refreshDirectory});qte({notification:xi.incomingNotification,dismiss:xi.dismissIncomingNotification,selectThread:xi.selectThread,setView:tt,showToast:ln});const{communities:Ml,sidebar:jl,view:Ol}=Wte({connection:Ae,currentUserId:Ao?.profile?.id??null,refreshToken:nt?.accountMeta.asOf??null,setView:tt,showToast:ln}),ki=xi.aiThread?.conversationId??null,os=ke==="team"&&!!ki&&J&&oe==="chat";y.useEffect(()=>{if(ke==="team"){if(ki){Ct("chat"),Un(!0);return}oe==="chat"&&Un(!1)}},[oe,Un,Ct,ki,ke]);const $l=y.useCallback(()=>{if(ki){if(os){Un(!1);return}Ct("chat"),Un(!0)}},[Un,Ct,os,ki]),Nl=y.useMemo(()=>Ga(pa,nt?.cloudProjects??[]),[nt?.cloudProjects,pa]),Dl=Mn?.provider==="codex"?Ve:Mn?.openPondCommandAccessMode??Ve,Ia=Qr,rs=cr,Hl=Si,gt=ns,{openPondActionCatalog:cn,selectedActionCatalog:fa}=Zee({cloudProjectById:_o,cloudProjects:nt?.cloudProjects??[],connection:Ae,defaultTeamId:Zi.defaultTeamId,accountScopeKey:as,localProjects:nt?.localProjects??[],profile:nt?.profile,selectedCloudProject:Gi,selectedProject:pa,reportError:ut}),{expandedProjectIds:vn,expandProject:zn,toggleProjectExpanded:_a,setExpandedProjectIds:wp}=Yee({selectedProjectId:Ie});WZ({activeWorkspaceId:cr,activeWorkspaceKind:Si,appDispatch:t,connection:Ae,expandProject:zn,linkedProjectByAppId:Gr,providerSettings:nt?.providers??null,selectedAppId:ue,selectedSession:Mn,selectedSessionId:Le,selectedSessionProjectId:ts,setDiffPanelExpanded:Wt,setDraftModel:Pn,setDraftProvider:kn,setError:ut,setSelectedAppId:ht,setSelectedProjectId:xn,setSessions:ma,setTerminalOpen:mt,toast:_});const{changeCodexPermissionMode:Ip,changeCodexReasoningEffort:_p}=rY({connection:Ae,setBootstrap:Ki,setCodexPermissionMode:Dn,setCodexReasoningEffort:An,setError:ut}),{changeOpenPondCommandAccessMode:_d}=uX({connection:Ae,selectedSession:Mn,setBootstrap:Ki,setError:ut,setOpenPondCommandAccessMode:Hn,setSessions:ma}),Cp=GZ({connection:Ae,setError:ut}),mr=y.useCallback(()=>{D(it=>it+1)},[]),Cd=ZZ({appDispatch:t,expandProject:zn,linkedProjectByAppId:Gr,requestComposerFocus:mr,onBeginNewChat:()=>{Vt({kind:"chat",sessionId:null}),te(null),Zt(it=>it==="development"?"work":it)},setMentionedAppId:g}),ss=y.useCallback(it=>{const dn=kt("local",it);t({type:"selectProject",projectId:dn}),zn(dn)},[t,zn]),{advanceAfterTurn:Rp,begin:Pp,bindSession:Ap,dismiss:Tp,handoff:Ep,prepareTurn:Mp,selectTask:jp}=Mee({activeModel:$a,activeProvider:Na,applyBootstrapPayload:wn,beginNewChat:Cd,composerDraftStore:e,connection:Ae,requestComposerFocus:mr,selectedLocalProjectId:pa?.id??null,selectedSessionId:Le,selectLocalProject:ss,setDraftModel:Pn,setDraftProvider:kn,setError:ut,view:ke});gee({connection:Ae,events:De,showToast:ln}),yX({searchOpen:X,sectionMenuOpen:pe,setSectionMenuOpen:xe,setSearchOpen:ge,setQuery:ne}),y.useEffect(()=>{w({})},[nt?.server.id]);const{chatHistoryLoadStates:Op,loadMoreSelectedChatHistory:$p,selectedPagedSessionEvents:Np,selectedRuntimeIndexes:Rd}=jee({approvals:Yt,codexHistoryEvents:Ji,connection:Ae,latestServerSequence:nt?.eventWindow?.latestSequence,runtimeIndexes:Ro,runtimeEventStore:pt,selectedSessionId:Le,serverId:nt?.server.id,setCodexHistoryEvents:Po,setCodexHistorySessions:Jn,setError:ut}),{activeSessions:Dp,archivedSessions:Hp,pinnedProjects:Lp,pinnedSessions:Ll,savedForLaterSessions:Pd,pinnedFiles:qp,savedForLaterFiles:Up,pinnedItems:Ad,projectRows:Td,localProjectRows:zp,visibleProjectRows:ls,cloudProjectRows:Bp,projectSessionRowsByProjectId:Ed,childSessionRowsByParentId:Fp,sidebarProjectIdBySessionId:ql,chatRows:Md,visibleChatRows:jd,sessionEvents:Vp,chatMessages:Od,contextUsage:Kp,goalRuntime:Wp,subagentRuntime:$d}=mX({localProjects:nt?.localProjects??[],cloudProjects:nt?.cloudProjects??[],sessions:sr,runtimeIndexes:Rd,appPreferences:ta,selectedSessionId:Le,selectedProjectId:Ie,archivedChatsOpen:Z,projectsExpanded:ee,chatRowsVisibleCount:be,sidebarFileBookmarks:x}),Gp=y.useCallback(it=>{Zt(it);const dn=[...sr].filter(Gt=>it==="work"?Gt.experience==="work"||Gt.experience==="development":Gt.experience===it).sort((Gt,Qt)=>Qt.updatedAt.localeCompare(Gt.updatedAt))[0]??[...Oa].filter(Gt=>Gt.experience===it).sort((Gt,Qt)=>Qt.updatedAt.localeCompare(Gt.updatedAt))[0]??null;if(dn)t({type:"selectSession",sessionId:dn.id,appId:it!=="chat"?dn.appId:null,projectId:it!=="chat"?ql[dn.id]??null:null});else if(t({type:"beginNewChat",appId:null}),it==="chat"&&Na==="codex"){const Gt=Vg(nt?.providers,{enabledOnly:!0}).find(Qt=>Qt.value!=="codex")?.value??Tr;kn(Gt),Pn(gm(Gt,nt?.providers)??wc)}it==="chat"&&(mt(!1),Wt(!1),Ct("home")),tt("chat")},[t,Na,nt?.providers,sr,Wt,Zt,Pn,kn,Ct,mt,tt,ql,Oa]),Nd=y.useCallback(it=>{const dn=e.getSnapshot();if(Zt(it),(Le||ue||Ie)&&(t({type:"beginNewChat",appId:null}),dn&&e.set(dn)),it==="chat"&&Na==="codex"){const Gt=Vg(nt?.providers,{enabledOnly:!0}).find(Qt=>Qt.value!=="codex")?.value??Tr;kn(Gt),Pn(gm(Gt,nt?.providers)??wc)}it==="chat"&&(mt(!1),Wt(!1),Ct("home")),tt("chat")},[Na,t,nt?.providers,e,ue,Ie,Le,Wt,Zt,Pn,kn,Ct,mt,tt]),{pendingChatUserMessages:Jp,recordPendingChatUserMessage:Zp,visibleChatMessages:Yp}=dX({chatMessages:Od,runtimeIndexes:Rd,selectedSessionId:Le}),Eo=y.useMemo(()=>sG({selectedAppId:ue,selectedProjectId:Ie,selectedSessionId:Le}),[ue,Ie,Le]),Dd=y.useRef(null);y.useEffect(()=>{const it=Dd.current;Dd.current=Eo,!(!it||it.kind!=="draft"||Eo.kind!=="session")&&(Bc(it,Eo)||l(dn=>{const Gt=lG({tabs:dn,previousScope:it,activeScope:Eo});return Gt.some((Ca,Pf)=>Ca!==dn[Pf])?Gt:dn}))},[Eo]);const Qp=y.useMemo(()=>cG(s),[s]),{goalRuntime:Xp,runningSessionIds:Ul,selectedSessionRunning:ef,sidebarGoalRuntimeBySessionId:tf,sidebarSubagentRuntimeBySessionId:nf}=bX({codexHistoryEvents:Ji,codexHistorySessions:Q,connection:Ae,expandedProjectIds:vn,goalRuntime:Wp,locallyActiveCodexHistorySessionIds:P,pinnedSessions:Ll,savedForLaterSessions:Pd,projectSessionRowsByProjectId:Ed,rightChatHistoryEvents:M,runtimeIndexes:Ro,selectedSession:Mn,selectedSessionId:Le,serverId:nt?.server.id,setCodexHistorySessions:Jn,sidebarSessions:Oa,subagentRuntime:$d,visibleChatRows:jd,visibleProjectRows:ls}),{dragItem:af,pinnedPreviewKeys:of,startPinnedDrag:rf,clearSidebarDrag:sf,previewPinnedDrop:lf,commitPinnedDrop:cf,commitPinnedPreviewDrop:df}=_Y({connection:Ae,appPreferences:ta,sessions:Oa,pinnedItems:Ad,setAppPreferences:In,setCodexHistorySessions:Jn,setSessions:ma,sidebarFileBookmarks:x,setSidebarFileBookmarks:k,setError:ut}),{clearTaskDrag:uf,commitTaskDrop:Hd,commitTaskPreviewDrop:mf,previewTaskDrop:ni,startTaskDrag:cs,taskDragSessionId:pf,taskPreviewSessionIds:ff}=CY({connection:Ae,sessions:Oa,setCodexHistorySessions:Jn,setError:ut,setSessions:ma}),{commandProjectRows:hf,contextWindowStatus:zl,pinnedRows:gf,sidebarWorkspaceAppIds:vf}=JZ({activeProvider:Na,contextCompaction:Zi.contextCompaction,contextUsage:Kp,pinnedItems:Ad,pinnedPreviewKeys:of??[],pinnedProjects:Lp,projectRows:Td,visibleProjectRows:ls}),Yi=!!(Ia&&(ke==="chat"||ke==="labs")&&(Ye||J&&(oe==="changes"||oe==="goal"))),{workspaceStates:ds,workspaceBusy:us,diffBusy:bf,visibleWorkspaceState:pr,visibleWorkspaceDiff:Bl,rememberWorkspaceState:ms,refreshWorkspace:Fl,refreshWorkspaceDiff:wi,setWorkspaceBusy:qd}=ete({connection:Ae,activeWorkspaceAppId:Ia,view:ke,shouldLoadWorkspaceDiff:Yi,sidebarWorkspaceAppIds:vf,setError:ut});ve.current=ms;const yf=y.useCallback((it=Ia)=>!it||it!==Ia||!Yi?Promise.resolve(null):wi(it),[wi,Yi,Ia]),Sf=y.useCallback(async(it={})=>{!Ia||!Yi||await wi(Ia,it)},[wi,Yi,Ia]),xf=!1,kf=!!(Mn?.provider==="codex"&&Mn.cwd&&!Ui(Mn.workspaceKind)),wf=!!(pr&&!pr.initialized&&Si!=="local_project"&&Na!=="codex"&&!kf&&!es),If=Si==="local_project"&&!!pa?.sandboxTemplate?.detected&&!pa?.linkedOpenPondApp?.appId,[Ud,zd]=y.useState(null),[_f,Bd]=y.useState(null),{projectTarget:Cf,workspaceTarget:Rf}=NZ({accountPending:Zr,accountSignedOut:Yr,activeWorkspaceLocation:dr,bootstrap:nt,busy:U,cloudLinked:Xr,selectedCloudProject:Gi,selectedProject:pa,selectedSession:Mn,pendingWorkspaceTarget:Ud,workspaceStates:ds,workspaceBusy:us});return y.useEffect(()=>{zd(null)},[Mn?.id]),{composerDraftStore:e,appDispatch:t,pendingTerminalCommand:o,setPendingTerminalCommand:r,terminalTabs:s,setTerminalTabs:l,trainingDetailTasksetId:m,setTrainingDetailTasksetId:d,mentionedAppId:f,setMentionedAppId:g,cloudSetupDialog:C,setCloudSetupDialog:R,rightPanelTabRequest:E,setRightPanelTabRequest:A,workspaceDiffPanelViewState:O,setWorkspaceDiffPanelViewState:$,rightChatHistoryEvents:M,setRightChatHistoryEvents:w,locallyActiveCodexHistorySessionIds:P,setCodexHistoryTurnLocallyActive:N,mainComposerFocusRequestId:z,requestMainComposerFocus:mr,draftSubagentDelegationMode:F,setDraftSubagentDelegationMode:te,confirmProjectAction:re,projectConfirmDialog:K,resolveProjectConfirmDialog:L,query:de,searchOpen:X,archivedChatsOpen:Z,sectionMenuOpen:pe,projectsExpanded:ee,cloudProjectsExpanded:me,sidebarOpen:je,view:ke,selectedAppId:ue,selectedProjectId:Ie,selectedSessionId:Le,draftProvider:Fe,draftModel:Xe,draftExperience:Ze,activeExperience:ti,changeExperience:Gp,changeNewExperience:Nd,codexPermissionMode:Be,codexReasoningEffort:Ge,openPondCommandAccessMode:Ve,busy:U,diffPanelOpen:J,diffPanelExpanded:q,rightPanelMode:oe,rightChatPanels:he,terminalOpen:Re,settingsSection:qe,newProjectDialogOpen:Je,newProjectMode:et,newProjectName:dt,newProjectPath:_t,newProjectBusy:Ne,commitDialogOpen:Ye,commitMessage:h,commitIncludeUnstaged:V,commitNextStep:ae,commitDraft:we,branchDialogOpen:fe,branchDialogName:Y,toast:_,error:G,labDetailNavigation:se,setQuery:ne,setSearchOpen:ge,setArchivedChatsOpen:Se,setSectionMenuOpen:xe,setProjectsExpanded:Oe,setCloudProjectsExpanded:Te,setChatRowsVisibleCount:Ue,setSidebarOpen:Ee,setView:tt,setSelectedAppId:ht,setSelectedProjectId:xn,setSelectedSessionId:xt,setPrompt:Xn,setDraftProvider:kn,setDraftModel:Pn,setDraftExperience:Zt,setDiffPanelOpen:Un,setDiffPanelExpanded:Wt,setRightPanelMode:Ct,setRightChatPanels:Ln,setTerminalOpen:mt,setSyncingWorkspaceAppId:Nt,setSettingsSection:ea,setNewProjectDialogOpen:$t,setNewProjectMode:Tn,setNewProjectName:st,setNewProjectPath:En,setNewProjectBusy:gi,setCommitDialogOpen:vi,setCommitMessage:Wn,setCommitIncludeUnstaged:da,setCommitNextStep:Gn,setCommitDraft:Vi,setBranchDialogOpen:ei,setBranchDialogName:wt,setError:ut,showToast:ln,appPreferences:ta,applyBootstrapPayload:wn,approvals:Yt,bootstrap:nt,connection:Ae,events:De,runtimeEventStore:pt,sessions:ua,startup:bi,setAppPreferences:In,setCodexHistorySessions:Jn,setEvents:ja,setSessions:ma,training:It,pinnedCollapsed:bl,projectsCollapsed:or,cloudProjectsCollapsed:yl,chatsCollapsed:zr,savedForLaterCollapsed:Sl,sidebarWidth:Wi,sidebarResizing:xl,diffPanelWidth:Br,diffPanelResizing:Fr,togglePinnedCollapsed:Vr,toggleProjectsCollapsed:kl,toggleCloudProjectsCollapsed:wl,toggleChatsCollapsed:yi,toggleSavedForLaterCollapsed:Il,startSidebarResize:Kr,startDiffPanelResize:Wr,cloudProjectById:_o,localProjectById:wa,selectedApp:rr,selectedCloudProject:Gi,selectedProject:pa,selectedProjectLinkedApp:Cl,selectedProjectLinkedOpenPondApp:Rl,selectedSession:Mn,sidebarSessions:Oa,runtimeIndexes:Ro,chatMentionApps:Pl,connectedAppMentions:Jr,pendingApproval:lr,codexHistoryEvents:Ji,setCodexHistoryEvents:Po,account:Ao,accountPending:Zr,accountSignedOut:Yr,activeModel:$a,activeProvider:Na,activeWorkspaceAppId:Qr,activeWorkspaceId:cr,activeWorkspaceKind:Si,activeWorkspaceLocation:dr,appDefaults:Zi,selectedSessionProjectId:ts,startMessage:Al,workspaceName:ns,accountScopeKey:as,organizations:To,teamChatOrganization:is,teamChatTeamId:ur,teamChat:xi,publishTeamProfileAgent:El,communities:Ml,communitySidebar:jl,communityView:Ol,teamAiThreadId:ki,toggleTeamAiSidebar:$l,selectedProjectConfirmedCloudProject:Nl,activeOpenPondCommandAccessMode:Dl,viewWorkspaceAppId:Ia,viewWorkspaceId:rs,viewWorkspaceKind:Hl,viewWorkspaceName:gt,openPondActionCatalog:cn,selectedActionCatalog:fa,expandedProjectIds:vn,expandProject:zn,toggleProjectExpanded:_a,setExpandedProjectIds:wp,changeCodexPermissionMode:Ip,changeCodexReasoningEffort:_p,changeOpenPondCommandAccessMode:_d,resolveApproval:Cp,beginNewChat:Cd,advanceTrainingModelChatAfterTurn:Rp,beginNewChatWithTrainingModel:Pp,bindTrainingModelChatSession:Ap,dismissTrainingChatHandoff:Tp,trainingChatHandoff:Ep,prepareTrainingModelChatTurn:Mp,selectTrainingChatTaskForComposer:jp,chatHistoryLoadStates:Op,loadMoreSelectedChatHistory:$p,selectedPagedSessionEvents:Np,activeSessions:Dp,archivedSessions:Hp,pinnedSessions:Ll,savedForLaterSessions:Pd,pinnedFiles:qp,savedForLaterFiles:Up,sidebarFileBookmarks:x,setSidebarFileStatus:wo,projectRows:Td,localProjectRows:zp,visibleProjectRows:ls,cloudProjectRows:Bp,projectSessionRowsByProjectId:Ed,childSessionRowsByParentId:Fp,sidebarProjectIdBySessionId:ql,chatRows:Md,visibleChatRows:jd,chatRowsVisibleCount:be,sessionEvents:Vp,chatMessages:Od,goalRuntime:Xp,subagentRuntime:$d,pendingChatUserMessages:Jp,recordPendingChatUserMessage:Zp,visibleChatMessages:Yp,activeTerminalScope:Eo,terminalSummaries:Qp,runningSessionIds:Ul,selectedSessionRunning:ef,sidebarGoalRuntimeBySessionId:tf,sidebarSubagentRuntimeBySessionId:nf,taskDragSessionId:pf,taskPreviewSessionIds:ff,startTaskDrag:cs,clearTaskDrag:uf,previewTaskDrop:ni,commitTaskDrop:Hd,commitTaskPreviewDrop:mf,dragItem:af,startPinnedDrag:rf,clearSidebarDrag:sf,previewPinnedDrop:lf,commitPinnedDrop:cf,commitPinnedPreviewDrop:df,commandProjectRows:hf,contextWindowStatus:zl,pinnedRows:gf,workspaceStates:ds,workspaceBusy:us,diffBusy:bf,visibleWorkspaceState:pr,visibleWorkspaceDiff:Bl,rememberWorkspaceState:ms,refreshWorkspace:Fl,refreshWorkspaceDiff:wi,setWorkspaceBusy:qd,refreshWorkspaceDiffWhenNeeded:yf,refreshVisibleWorkspaceDiff:Sf,managedWorkspace:xf,canSyncActiveWorkspace:wf,canPublishOpenPondProject:If,pendingWorkspaceTarget:Ud,setPendingWorkspaceTarget:zd,pendingSidebarWorkspaceTarget:_f,setPendingSidebarWorkspaceTarget:Bd,projectTarget:Cf,workspaceTarget:Rf}}const Qte=/^(localhost|\[::1\]|127(?:\.\d{1,3}){3})(?::\d+)?(?:[/?#].*)?$/i,Xte=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+(?:[:/?#].*)?$/i;function ene(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)?yu(n,new Set(["http:","https:"])):/^file:\/\//i.test(n)?t.explicitFile?yu(n,new Set(["file:"])):null:Qte.test(n)?yu(`http://${n}`,new Set(["http:"])):Xte.test(n)?yu(`https://${n}`,new Set(["https:"])):null}function yu(e,t){try{const n=new URL(e);return t.has(n.protocol)?n.toString():null}catch{return null}}async function tne(e){const t=ene(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 nne="openpond-coding-core-v1",ane="feature";function cv(e){const t=new URL("/sandboxes",Ky(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",ane),t.searchParams.set("runtimeProfileId",nne),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 pre(e){const t=e.organizationSlug?.trim(),n=t?`/sandboxes/${encodeURIComponent(t)}/billing`:"/sandboxes/billing",a=new URL(n,Ky(e.accountBaseUrl));return!t&&e.teamId?.trim()&&a.searchParams.set("teamId",e.teamId.trim()),a.toString()}function Zk(e){const t=e.organizationSlug?.trim(),n=e.projectSlug?.trim();return!t||!n?null:new URL(`/${encodeURIComponent(t)}/${encodeURIComponent(n)}`,Ky(e.accountBaseUrl)).toString()}function Ky(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 ine({account:e,browserConversationId:t,cloudProjectById:n,cloudProjects:a,diffPanelOpen:o,rightPanelMode:r,selectedProjectId:s,setDiffPanelOpen:l,setNewProjectDialogOpen:m,setNewProjectMode:d,setNewProjectName:f,setRightPanelMode:g}){const x=y.useCallback(()=>{g("changes"),l(!0)},[l,g]),k=y.useCallback(()=>{if(o&&r==="changes"){l(!1);return}x()},[o,r,l,x]),C=y.useCallback(()=>{g("browser"),l(!0)},[l,g]),R=y.useCallback(()=>{g("goal"),l(!0)},[l,g]),E=y.useCallback((M,w)=>{tne({conversationId:t,href:M,explicitFile:w?.explicitFile,newTab:w?.newTab}).then(P=>{P&&C()})},[t,C]),A=y.useCallback(()=>{d("cloud"),f(""),m(!0)},[m,d,f]),O=y.useCallback(M=>{const w=n.get(M);w&&E(cv({accountBaseUrl:e?.baseUrl??e?.activeProfile?.baseUrl??null,teamId:w.teamId,projectId:w.id,projectName:w.name,baseBranch:w.defaultBranch,source:"openpond-app"}),{newTab:!0})},[e,n,E]);return{createCloudEnvironmentFromSidebar:y.useCallback(()=>{const M=s?.startsWith("cloud:")?s.slice(6):a[0]?.id??null;if(M){O(M);return}A()},[a,A,s,O]),openCloudProjectDialog:A,openUrlInBrowserPanel:E,showBrowserPanel:C,showChangesPanel:x,showGoalSidebarTab:R,toggleChangesPanel:k}}function one(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 rne({browserConversationId:e,sessionIds:t,onOpenSession:n,onShowBrowserPanel:a}){y.useEffect(()=>window.openpond?.browser?.onRevealRequest?.(r=>{const s=one({currentConversationId:e,requestConversationId:r.conversationId,sessionIds:t});s.reveal&&(s.sessionIdToOpen&&n(s.sessionIdToOpen),a())}),[e,n,a,t])}const sne="chat",lne=["help me","please","can you","could you","make","create","build"],cne=new Set(["a","an","and","for","from","i","me","my","of","our","please","produce","summary","the","to","with"]);function Yk(e){const t=eg(e.label);if(t&&!dv(t))return Qk(t);const n=eg(e.name);if(n&&!dv(n))return Qk(n);const a=eg(e.actionId)?.replace(/\.chat$/i,"")??"";return dne(a||t||"Profile Agent")}function dv(e){return e.trim().toLowerCase()===sne}function dne(e){const t=une(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&&!cne.has(o)).slice(0,3);return IT(a.length?a.join(" "):t||e)}function Qk(e){return IT(e).split(/\s+/).slice(0,4).join(" ")}function une(e){let t=e.trim();for(const n of lne)if(t.toLowerCase().startsWith(`${n} `)){t=t.slice(n.length).trim();break}return t}function eg(e){return typeof e=="string"&&e.trim()?e.trim():null}function IT(e){return e.replace(/[._-]+/g," ").replace(/\s+/g," ").trim().replace(/\b[a-z0-9]/gi,t=>t.toUpperCase())}const mne="openpond-profile-action";function pne(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Su(e){return typeof e=="string"&&e.trim()?e.trim():null}function fne(e){const t=pne(e.implementation);if(t?.type!==mne)return null;const n=Su(t.actionId)??e.id;if(e.sourceActionId!=="chat"&&n!=="chat"&&!n.endsWith(".chat"))return null;const a=Su(e.label);if(a&&!dv(a))return Yk({label:a,description:e.description});const o=Su(t.agentName)??Su(e.name);return Yk({actionId:n,description:e.description,name:o})}function hne(e){const t=fne(e);return t||e.label?.trim()||e.name?.trim()||e.id}function _T(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 gne=new Set(["action","agent","chat","customer","default","filter","items","open","openpond","profile","run","summarize","track","workflow"]);function CT(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function sl(e){return typeof e=="string"&&e.trim()?e.trim():null}function Ds(e,t,n={}){const a=sl(t)?Qn(String(t)):"";a&&(!n.generic&&gne.has(a)||e.add(a))}function xu(e,t){const n=sl(t);if(n)for(const a of n.split(/[.:/\\\s]+/g))Ds(e,a)}function vne(e,t){const n=sl(t);if(n)for(const a of n.split(/[^A-Za-z0-9_-]+/g))a.length<4||Ds(e,a)}function RT(e){const t=new Set,n=CT(e.implementation),a=sl(n?.actionId);return Ds(t,e.id,{generic:!0}),xu(t,e.id),Ds(t,a,{generic:!0}),xu(t,a),Ds(t,e.name,{generic:!0}),xu(t,e.name),Ds(t,e.label,{generic:!0}),xu(t,e.label),vne(t,e.description),t}function bne(e){const t=CT(e.implementation);return[e.id,e.name??"",e.label??"",e.description??"",sl(t?.actionId)??"",sl(t?.agentName)??"",_T(e),...Array.from(RT(e))].join(" ").toLowerCase()}function fre(e,t,n=8){const a=Qn(t);return e.length===0?[]:e.filter(o=>a?bne(o).includes(a):!0).slice(0,n)}function yne(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>Qn(t[1]??"")).filter(Boolean)}function Sne(e,t){const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return e.replace(new RegExp(`(^|\\s)@${n}(?=\\s|$)`,"g"),"$1").replace(/\s+/g," ").trim()}function xne(e,t){const n=yne(e);if(n.length===0||t.length===0)return null;const a=new Map;for(const r of n)for(const s of t)RT(s).has(r)&&a.set(s.id,{action:s,mention:r});if(a.size!==1)return null;const o=Array.from(a.values())[0];return{action:o.action,mention:o.mention,prompt:Sne(e,o.mention)}}function hre(e){return hne(e)}function gre(e){return e.description||_T(e)}const Wy=[{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 kne(e){return Wy.filter(t=>t.id!=="goal"||e==="codex")}function PT(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 vre(e,t){return kne(e).filter(n=>PT(n,t))}const wne=new Set(Wy.map(e=>e.id));function bre(e){return e.subcommands?.length?e.subcommands.join(", "):e.description}function Ine(e){return[e.id,e.command,e.label,e.description].join(" ")}function _ne(e){return(e.subcommands??[]).flatMap(t=>[t,`${e.id} ${t}`,`${e.command} ${t}`]).join(" ")}function Cne(e){const t=/^\/([a-z][a-z0-9_-]*)(?:\s+([\s\S]*))?$/.exec(e.trim());if(!t)return null;const n=t[1];return wne.has(n)?{command:n,args:t[2]?.trim()??""}:null}function Rne(e){const t=e.trim();if(!t.startsWith("!"))return null;const n=t.slice(1).trim();return n?{command:n}:null}function yre({commands:e=Wy,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 r=e.filter(l=>Ine(l).toLowerCase().includes(a));return(r.length>0?r:e.filter(l=>_ne(l).toLowerCase().includes(a))).slice(0,n)}function Sre(e){return e==="owner"?"Owner":e==="admin"?"Admin":"Member"}function xp(e){return e?.role==="owner"||e?.role==="admin"}function xre(e){const t=kp(e.organizations,e.defaultTeamId),n=xp(t),a=e.localProject??null;if(!a)return Pne("Open a local project to set up an Agent.");const o=Ane(a,e.projects),r=Tne(a,o,e.agents),s=!!a.sandboxTemplate?.detected,l=t&&!n?"Ask an owner or admin to connect this project.":null;return s?o?Ene(a,o)?ku({state:"needs_sync",actionLabel:"Sync Project",project:o,agent:r,canManage:n,actionBlockedReason:l}):r?{state:"ready",actionLabel:"Run Agent",canAct:!0,reason:null,project:o,agent:r}:ku({state:"needs_agent",actionLabel:"Create Agent",project:o,agent:null,canManage:n,actionBlockedReason:l}):ku({state:"needs_project",actionLabel:"Connect Project",project:null,agent:null,canManage:n,actionBlockedReason:l}):ku({state:"missing_config",actionLabel:"Add Agent config",project:o,agent:r,canManage:n,actionBlockedReason:l})}function ku(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 Pne(e){return{state:"blocked",actionLabel:"Ask admin",canAct:!1,reason:e,project:null,agent:null}}function kp(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 Ane(e,t){const n=e.linkedSandboxProject;return n?.projectId?t.find(a=>a.id===n.projectId)??null:null}function Tne(e,t,n){if(!t)return null;const a=e.preferredSandboxAgentId;if(a){const o=n.find(r=>r.id===a&&r.projectId===t.id);if(o)return o}return n.find(o=>o.projectId===t.id)??null}function Ene(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 fr=e=>e.slice(0,2e4);function Mne({model:e,provider:t,providerSettings:n}){return{model:Cy(t,e,n),modelRef:ii(t,e,n)}}function jne(e,t){return e.some(n=>n.id===t.id)?e:[...e,t]}function One(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 $ne(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 Xk({action:e,prompt:t,runPayload:n,sessionId:a}){const o=new Date().toISOString(),r=`openpond_action_${n.run.id}`,s=n.run.status==="failed"?"failed":n.run.status==="succeeded"?"completed":"started";return[{id:`${r}_user`,sessionId:a,turnId:r,name:"turn.started",timestamp:o,source:"chat_action",args:{prompt:t}},{id:`${r}_result`,sessionId:a,turnId:r,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 Nne({applyBootstrapPayload:e,connection:t,codexPermissionMode:n,codexReasoningEffort:a,openPondCommandAccessMode:o,draftModel:r,draftProvider:s,experience:l,expandProject:m,ensureCloudSessionReady:d,getPrompt:f,bootstrap:g,chatMessages:x,apps:k,connectedAppMentions:C,mentionedAppId:R,refreshWorkspace:E,refreshWorkspaceDiff:A,selectedApp:O,selectedActionCatalog:$,openPondActionCatalog:M,cloudProjects:w,accountScopeKey:P,selectedCloudProject:j,selectedProject:N,selectedProjectLinkedOpenPondApp:z,selectedSession:D,workspaceTarget:F,subagentDelegationMode:te,setDraftModel:ve,setDraftProvider:re,setError:K,setPrompt:L,setMentionedAppId:de,setCodexHistoryEvents:X,setCodexHistorySessions:Z,onCodexHistoryTurnActivityChange:pe,onCodexHistoryTurnPayload:ee,onPendingUserMessage:me,setEvents:be,setSelectedAppId:je,setSelectedProjectId:ke,setSelectedSessionId:ue,setSessions:Ie,setView:Le,setWorkspaceBusy:Fe}){function Xe(Y){ie.bootstrap(Y).then(e).catch(_=>{console.warn("[chat] Message was accepted, but the post-send bootstrap refresh failed.",_);const G=_ instanceof Error?_.message:String(_);K(`Message sent, but the chat list could not refresh: ${G}`)})}const Ze=y.useRef(new Set),Be=g?.providers??null;function Ge(Y,_){return Y==="codex"?void 0:_}function Ve(Y){return!!(Y&&Y.provider!=="codex"&&(Y.workspaceKind==="local_project"&&Y.cwd?.trim()||(Y.workspaceKind==="sandbox"||Y.workspaceKind==="sandbox_template"||Y.workspaceKind==="sandbox_app")&&Y.workspaceId))}function U(Y){re(Y),ve(_=>nr(Y,_,Be)),Le("chat")}async function J(Y,_){return(lT(_,P)??await qy({teamId:_,accountKey:P,fetchAgents:async ne=>(await ie.listSandboxAgents(t,{teamId:ne})).agents})).find(ne=>ne.projectId===Y)??null}async function q(){if(!t)throw new Error("OpenPond App server is not connected.");if(g?.account.state!=="signed_in")throw new Error("Add an OpenPond account before syncing a Project to Cloud.");const Y=await ie.organizations(t),_=kp(Y.organizations.map(gp).filter(G=>!!G).filter(G=>G.status==="active"),g?.preferences.defaultTeamId??null);if(!_)throw new Error("Add an OpenPond account before syncing a Project to Cloud.");if(!xp(_))throw new Error(`You need owner or admin access to create projects in ${_.displayName}.`);return _}async function oe(Y){if(!t)return!1;const _=N;if(!_)throw new Error("Select a local Project before using /sync-cloud.");const G=await q(),se=_.linkedSandboxProject?.defaultBranch?.trim()||"main",ne=kt("local",_.id),ge=Ga(_,w),Se=await ie.createSession(t,{provider:"openpond",modelRef:ii("openpond",Ws,Be),openPondCommandAccessMode:Ge("openpond",o),appId:null,appName:null,workspaceKind:"local_project",workspaceId:_.id,workspaceName:_.name,localProjectId:_.id,cloudProjectId:ge?.id??null,cloudTeamId:ge?.teamId??null,cwd:_.workspacePath,title:`Sync ${_.name} to Cloud`});Ie(xe=>[Se,...xe]),Y.onSessionCreated?.(Se),Y.selectSession&&(ue(Se.id),ke(ne),je(null),Le("chat"),m(ne)),Y.clearPromptForTurn(),Fe(!0);try{const xe=await ie.uploadLocalProjectCloudSource(t,_.id,{teamId:G.teamId,projectName:_.name,branch:se,chatSessionId:Se.id,displayPrompt:Y.displayPrompt});return e(xe.bootstrap),m(ne),m(kt("cloud",xe.project.id)),!0}catch(xe){const Oe=await ie.bootstrap(t).catch(()=>null);throw Oe&&e(Oe),xe}finally{Fe(!1)}}async function he(Y){if(!t||Y.providerForTurn==="codex"||Y.selectedSessionForTurn?.provider==="codex")return!1;let _=Ve(Y.selectedSessionForTurn)?Y.selectedSessionForTurn:null;if(!_&&Y.selectedSessionForTurn)throw new Error("Select a project to use this.");if(!_)if(j){const se=kt("cloud",j.id),ne=Y.providerForTurn;_=await ie.createSession(t,{provider:ne,modelRef:ii(ne,Y.modelForTurnValue,Be),openPondCommandAccessMode:Ge(ne,Y.openPondCommandAccessModeForTurn),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:j.id,workspaceName:j.name,localProjectId:null,cloudProjectId:j.id,cloudTeamId:j.teamId,cwd:null,autoTitlePrompt:fr(Y.command)}),Ie(ge=>[_,...ge]),Y.onSessionCreated?.(_),Y.selectSession&&(ue(_.id),ke(se),je(null),Le("chat"),m(se))}else{const se=N;if(!se)throw new Error("Select a project to use this.");const ne=Ga(se,w),ge=kt("local",se.id),Se=Y.providerForTurn;_=await ie.createSession(t,{provider:Se,modelRef:ii(Se,Y.modelForTurnValue,Be),openPondCommandAccessMode:Ge(Se,Y.openPondCommandAccessModeForTurn),appId:null,appName:null,workspaceKind:"local_project",workspaceId:se.id,workspaceName:se.name,localProjectId:se.id,cloudProjectId:ne?.id??null,cloudTeamId:ne?.teamId??null,cwd:se.workspacePath,autoTitlePrompt:fr(Y.command)}),Ie(xe=>[_,...xe]),Y.onSessionCreated?.(_),Y.selectSession&&(ue(_.id),ke(ge),je(null),Le("chat"),m(ge))}if(!_)throw new Error("Select a project to use this.");Y.clearPromptForTurn();const G=await ie.runSessionCommand(t,_.id,{command:Y.command,cwd:_.cwd});return Ie(se=>rc(se,G.session)),be(se=>ao(se,G.events)),!0}async function Re(Y=[],_=null,G,se={}){const ne=G??f();let ge=ne.trim()||(Y.length>0?"Please review the attached files.":"");if(!t||!ge)return!1;const Se=se.displayPrompt?.trim()||ge,xe=se.provider??s,Oe=se.model??r,Te=se.openPondCommandAccessMode??o,Ue=se.session!==void 0,Ee=Ue?se.session??null:D,tt=se.experience??Ee?.experience??l,ht=tt==="development"||tt==="work"&&(Ee?.workspaceKind==="local_project"||!!Ee?.localProjectId||!!Ee?.cloudProjectId||!Ue&&!!(N||j||O||F==="hybrid"||F==="local")),xn=Ue||!ht?null:O,xt=Ue||!ht?null:N,Xn=Ue||!ht?null:j,kn=Ue||!ht?null:z,Pn=!Ue&&ht&&F==="hybrid",Zt=se.selectSession??!0,Dn=se.chatMessages??x,An=se.session!==void 0?null:R,Hn=se.clearPrompt===void 0?()=>{L(""),de(null)}:se.clearPrompt,Un=_?null:xne(ge,$),Wt=_??Un?.action??null,Ct=Un?.prompt||ge,Ln=ht&&!Wt?Rne(ge):null,mt=Wt||Ln?null:Cne(ge),Nt=mt&&!PT({id:mt.command},tt)?mt:null,ea=se.usageAttribution??(mt?{surface:"chat",workflowKind:"slash_command",commandName:`/${mt.command}`,commandSource:"prompt_parse"}:void 0);K(null);let $t=null,Tn=null;try{if(!ht&&xe==="codex")throw new Error("The Codex provider requires repository-aware Work.");if(Nt)throw new Error(`/${Nt.command} isn't available in ${tt}.`);if(Ln&&xe!=="codex"&&Ee?.provider!=="codex"){if(Y.length>0)throw new Error("Direct commands do not accept attachments.");return await he({command:Ln.command,clearPromptForTurn:Hn,modelForTurnValue:Oe,onSessionCreated:se.onSessionCreated,openPondCommandAccessModeForTurn:Te,providerForTurn:xe,selectedSessionForTurn:Ee,selectSession:Zt})}if(!Ue&&mt?.command==="sync-cloud")return await oe({clearPromptForTurn:Hn,displayPrompt:Se,onSessionCreated:se.onSessionCreated,selectSession:Zt});if(Wt){const wt=Uee(Wt);if(wt){let nt=Ee;if(!nt||nt.cloudProjectId!==wt.projectId){nt=await ie.createSession(t,{provider:"openpond",modelRef:ii("openpond",Oe,Be),openPondCommandAccessMode:Ge("openpond",Te),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:wt.projectId,workspaceName:wt.projectName??wt.agentName,localProjectId:null,cloudProjectId:wt.projectId,cloudTeamId:wt.teamId,cwd:null,autoTitlePrompt:fr(Se)}),Ie(pt=>[nt,...pt]),se.onSessionCreated?.(nt),Zt&&ue(nt.id);const De=kt("cloud",wt.projectId);Zt&&ke(De),Zt&&m(De)}const Q=await ie.runSandboxAgent(t,wt.agentId,Kee({agent:wt,attachments:Y,displayPrompt:Se,prompt:Ct})),Ae=await ie.bootstrap(t);return e(Ae),Hn(),be(De=>ao(De,Xk({action:Wt,prompt:Se,runPayload:Q,sessionId:nt.id}))),!0}const pn=Fy(Wt);if(pn){let nt=Ee;(!nt||nt.provider!=="openpond")&&(nt=await ie.createSession(t,{provider:"openpond",modelRef:ii("openpond",Oe,Be),openPondCommandAccessMode:Ge("openpond",Te),appId:null,appName:null,workspaceId:null,workspaceName:"OpenPond profile",localProjectId:null,cloudProjectId:null,cloudTeamId:null,cwd:null,autoTitlePrompt:fr(Se)}),Ie(Ae=>[nt,...Ae]),se.onSessionCreated?.(nt),Zt&&ue(nt.id)),await ie.runProfileAction(t,Fee({action:pn,attachments:Y,displayPrompt:Se,prompt:Ct,sessionId:nt.id}));const Q=await ie.bootstrap(t);return e(Q),Hn(),!0}const Rt=fT({cloudProjects:w,selectedCloudProject:j,selectedProject:N});if(!Rt)throw new Error("Select a Project linked to an OpenPond Cloud Project before running an action.");let ut=Ee;(!ut||ut.cloudProjectId!==Rt.id)&&(ut=await ie.createSession(t,{provider:"openpond",modelRef:ii("openpond",Oe,Be),openPondCommandAccessMode:Ge("openpond",Te),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:Rt.id,workspaceName:Rt.name,localProjectId:Rt.localProjectId,cloudProjectId:Rt.id,cloudTeamId:Rt.teamId,cwd:null,autoTitlePrompt:fr(Se)}),Ie(nt=>[ut,...nt]),se.onSessionCreated?.(ut),Zt&&(ue(ut.id),ke(Rt.selectionKey),m(Rt.selectionKey)));const ln=await J(Rt.id,Rt.teamId);if(!ln)throw new Error("No OpenPond Agent is available for this Project.");Hn();const ta=await ie.runSandboxAgent(t,ln.id,Vee({action:Wt,attachments:Y,displayPrompt:Se,prompt:Ct,teamId:Rt.teamId})),wn=await ie.bootstrap(t);return e(wn),be(nt=>ao(nt,Xk({action:Wt,prompt:Se,runPayload:ta,sessionId:ut.id}))),!0}let st=Ee;if(st&&Jt(st.id)){Tn=ck({afterMessageId:Dn.at(-1)?.id??null,attachments:Y,content:ge,sessionId:st.id}),Hn(),$t=st.id,Ze.current.add($t),me?.(Tn),pe?.($t,!0);const wt=One(st.id,ge),pn=ut=>{(!Ue||D?.id===st.id)&&X(ln=>jne(ln,ut)),se.onCodexHistoryOptimisticEvent?.(ut)};pn(wt),Z(ut=>ut.map(ln=>ln.id===st.id?{...ln,status:"active"}:ln));const Rt=await ie.sendCodexHistoryTurn(t,st.id,{prompt:ge,attachments:Y.length>0?Y:void 0,model:Cy("codex",Oe,Be),modelRef:ii("codex",Oe,Be),...wx(n),codexPermissionMode:n,codexReasoningEffort:a}).catch(ut=>{throw pn($ne(wt,ut)),ut});return(!Ue||D?.id===st.id)&&X(ut=>ao(ut,Rt.events)),Z(ut=>rc(ut,Rt.session)),ee?.(Rt),Xe(t),!0}const gi=(An?k.find(wt=>wt.id===An&&DZ(ne,wt)&&wt.sandbox)??null:null)??HZ(ne,MA(k)),vi=tt==="chat"?[]:XZ(ne,C).map(wt=>wt.ref);if(!st){const wt=kn?.appId??xn?.id??null,pn=kn?.appName??xn?.name??null,Rt=Xn,ut=Ue?null:Ga(xt,w),ln=Pn?CA({cloudProjects:w,selectedCloudProject:Rt,selectedProject:xt}):null;if(ln?.kind==="missing_cloud_project")throw new Error(ln.message);const ta=ln?.kind==="ready",wn=ta?xe:Rt?"openpond":xe,nt=ii(wn,Oe,Be),Q=Ge(wn,Te),Ae=ta?RA({modelRef:nt,provider:wn,target:ln,title:ge.slice(0,64)}):null;st=await ie.createSession(t,Ae?{...Ae,subagentDelegationMode:te,metadata:{...Ae.metadata,...se.sessionMetadata??{}},...Q?{openPondCommandAccessMode:Q}:{},autoTitlePrompt:fr(ge)}:{experience:tt,provider:wn,modelRef:nt,subagentDelegationMode:te,...Q?{openPondCommandAccessMode:Q}:{},appId:wt,appName:pn,workspaceKind:Rt?"sandbox":xt?"local_project":xn?"sandbox_app":void 0,workspaceId:xt?.id??(xn?wt:void 0),workspaceName:Rt?.name??xt?.name??pn,localProjectId:xt?.id??null,cloudProjectId:Rt?.id??ut?.id??null,cloudTeamId:Rt?.teamId??ut?.teamId??null,...!Rt&&!xt&&!xn&&F==="local"?{metadata:{...gZ(),...se.sessionMetadata??{}}}:{cwd:xt?xt.workspacePath:null,...se.sessionMetadata?{metadata:se.sessionMetadata}:{}},autoTitlePrompt:fr(ge)}),Ie(De=>[st,...De]),se.onSessionCreated?.(st),Zt&&(ue(st.id),Rt&&ke(kt("cloud",Rt.id)),st.workspaceKind==="local_project"&&st.workspaceId&&m(kt("local",st.workspaceId)),Rt&&m(kt("cloud",Rt.id)))}if(e1(st)&&Ui(st.workspaceKind)&&st.provider!=="openpond"&&!zi(st))throw new Error("Cloud workspaces use OpenPond Chat. Switch to Local to use local providers.");if(e1(st)&&Ui(st.workspaceKind)&&d)try{st=await d(st)}catch(wt){const pn=wt instanceof Error?wt.message:String(wt);throw await ie.recordPreflightTurnFailure(t,st.id,{prompt:ge,error:pn,target:zi(st)?"hybrid_sandbox":"cloud_workspace"}).then(e).catch(()=>{}),wt}Tn=ck({afterMessageId:Dn.at(-1)?.id??null,attachments:Y,content:ge,sessionId:st.id}),Hn(),$t=st.id,Ze.current.add($t),me?.(Tn),Ie(wt=>wt.map(pn=>pn.id===$t?{...pn,status:"active"}:pn));const Wn=xe,da=Mne({provider:Wn,model:Oe,providerSettings:Be}),Gn=J8(Wn,da.model??Oe,Be),Vi=Wn==="codex"?wx(n):{approvalPolicy:"on-request",sandbox:"workspace-write"};await ie.sendTurn(t,st.id,{prompt:ge,metadata:se.turnMetadata,attachments:Y.length>0?Y:void 0,mentionedAppIds:gi?[gi.id]:void 0,mentionedConnectedApps:vi.length>0?vi:void 0,openPondActionCatalog:M.length>0?M:void 0,usageAttribution:ea,...da,...Vi,codexPermissionMode:Wn==="codex"?n:"default",codexReasoningEffort:Gn?G8(Wn,da.model??Oe,a,Be):void 0}),Xe(t);const ei=st.workspaceId??st.appId;return ei&&st.workspaceKind!=="sandbox"&&st.workspaceKind!=="sandbox_template"&&E(ei,!1).then(wt=>{wt?.initialized&&A(ei)}),!0}catch(st){return K(st instanceof Error?st.message:String(st)),!1}finally{$t&&Ze.current.delete($t),$t&&Jt($t)&&pe?.($t,!1),$t&&(Jt($t)?Z(st=>st.map(En=>En.id===$t&&En.status==="active"?{...En,status:"idle"}:En)):Ie(st=>st.map(En=>En.id===$t&&En.status==="active"?{...En,status:"idle"}:En)))}}async function qe(Y,_){const G=Ze.current.values().next().value??null,se=Y??D?.id??G;if(!t||!se)return!1;if(K(null),Jt(se))try{const ne=await ie.interruptCodexHistoryTurn(t,se);if(!ne.interrupted){if(ne.reason==="no_active_openpond_turn"){const Se=await ie.codexHistoryThread(t,se,{tail:!0}),xe={...Se.session,status:"idle"};return D?.id===se&&X(Oe=>ao(Oe,Se.events)),Z(Oe=>rc(Oe,xe)),K("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 K("This Codex history turn is still starting. Try stopping it again in a moment."),!1}const ge=await ie.codexHistoryThread(t,se,{tail:!0});return D?.id===se&&X(Se=>ao(Se,ge.events)),Z(Se=>rc(Se,ge.session)),!0}catch(ne){const ge=ne instanceof Error?ne.message:String(ne);return K(ge==="Not found"?"OpenPond could not find this Codex history session, so it cannot interrupt it here.":ge),!1}try{await ie.interruptTurn(t,se,_);const ne=await ie.bootstrap(t);return e(ne),!0}catch(ne){return K(ne instanceof Error?ne.message:String(ne)),!1}}async function Je(Y,_){if(!t){K("OpenPond App server is not connected.");return}K(null),await ie.applyCreateImproveAction(t,Y.id,{..._,runId:Y.id,expectedRevision:Y.revision,actionId:`web:${_.type}:${crypto.randomUUID()}`});const G=await ie.bootstrap(t);e(G)}async function et(Y){await Je(Y.run,{type:"approve_plan"})}async function dt(Y){await Je(Y.run,{type:"cancel",reason:null})}async function _t(Y,_){await Je(Y.run,{type:"revise_plan",revision:_})}async function Ne(Y,_,G){await Je(Y.run,{type:"answer_question",questionId:_,value:G})}async function Ye(Y){await Je(Y.run,{type:"pause"})}async function h(Y){await Je(Y.run,{type:"resume"})}async function V(Y,_){await Je(Y.run,{type:"open_pull_request",candidateId:_})}async function ae(Y,_){await Je(Y.run,{type:"apply_candidate",candidateId:_})}async function we(Y,_){await Je(Y.run,{type:"reject_candidate",candidateId:_,reason:null})}async function fe(Y,_){await Je(Y.run,{type:"reconcile_pull_request",candidateId:_})}return{answerCreateImproveQuestion:Ne,approveCreateImproveRun:et,applyCreateImproveCandidate:ae,cancelCreateImproveRun:dt,changeDraftProvider:U,openCreateImprovePullRequest:V,pauseCreateImproveRun:Ye,reconcileCreateImprovePullRequest:fe,rejectCreateImproveCandidate:we,resumeCreateImproveRun:h,reviseCreateImproveRun:_t,sendPrompt:Re,stopTurn:qe}}function e1(e){return e.experience==="development"||e.experience==="work"&&(e.workspaceKind==="local_project"||!!e.localProjectId||!!e.cloudProjectId||e.metadata?.workspaceTarget==="local")}async function Dne({branch:e,connection:t,session:n}){if(!Ui(n.workspaceKind))return{sandbox:null,session:n,status:"already_running"};const a=await ie.ensureCloudWorkspaceReady(t,n.id,{branch:e,surface:"desktop"});return{bootstrap:await ie.bootstrap(t),output:a.output,sandbox:null,session:a.session,status:a.status}}function Hne(e){return zi(e)?"Preparing Hybrid sandbox...":"Starting Cloud workspace..."}function Lne(e,t){if(e==="already_running")return null;const n=zi(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 qne(e,t){return!e.cloudProjectId||!e.cloudTeamId?!0:t.some(n=>n.id===e.cloudProjectId&&n.teamId===e.cloudTeamId)}function Une({applyBootstrapPayload:e,cloudProjects:t,connection:n,localProjectById:a,selectedCloudProject:o,selectedProject:r,setWorkspaceBusy:s,showToast:l,visibleWorkspaceState:m}){return y.useCallback(async d=>{if(!n)throw new Error("OpenPond App server is not connected.");const f=r??(d.localProjectId?a.get(d.localProjectId)??null:null);if(d.cloudProjectId&&d.cloudTeamId&&!qne(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(Hne(d),"info"),s(!0);try{const g=await Dne({branch:r?.linkedSandboxProject?.defaultBranch??o?.defaultBranch??m?.currentBranch??null,connection:n,localProject:f,session:d,source:zi(d)?"openpond-app-hybrid-chat-preflight":"openpond-app-cloud-chat-preflight"});g.bootstrap&&e(g.bootstrap);const x=Lne(g.status,d);return x&&l(x,"success"),g.session}finally{s(!1)}},[e,t,n,a,o,r,s,l,m?.currentBranch])}function zne(){return{diffPanelOpen:!1,diffPanelExpanded:!1,rightPanelMode:"changes",rightChatPanels:[]}}function Bne(e){return{diffPanelOpen:e.diffPanelOpen,diffPanelExpanded:e.diffPanelExpanded,rightPanelMode:e.rightPanelMode,rightChatPanels:e.rightChatPanels}}function t1(e){return{...e,rightChatPanels:e.rightChatPanels.map(t=>({...t}))}}function Fne(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 Vne(e){return`${e.conversationId}\0${e.workspaceSourceKey||"none"}`}function Kne(e){const{appDispatch:t,diffPanelExpanded:n,diffPanelOpen:a,rightChatPanels:o,rightPanelMode:r,selectedAppId:s,selectedCloudProject:l,selectedProjectId:m,selectedSession:d,selectedSessionId:f,setWorkspaceDiffPanelViewState:g,view:x,viewWorkspaceAppId:k,viewWorkspaceId:C,viewWorkspaceKind:R,workspaceDiffPanelViewState:E}=e,A=y.useRef(new Map),O=y.useRef(new Map),$=y.useRef(null),M=y.useRef(null),w=f??`draft:${m??s??l?.id??"general"}`,P=y.useMemo(()=>C?`${R??"workspace"}:${C}`:k?`app:${k}`:d?.cwd&&!Ui(d.workspaceKind)?`cwd:${d.cwd}`:"none",[d?.cwd,d?.workspaceKind,x,k,C,R]),j=Vne({conversationId:w,workspaceSourceKey:P}),N=y.useMemo(()=>Bne({diffPanelExpanded:n,diffPanelOpen:a,rightChatPanels:o,rightPanelMode:r}),[n,a,o,r]);y.useEffect(()=>{const D=$.current;D&&A.current.set(D,t1(N))},[w,N]),y.useEffect(()=>{if($.current===w)return;$.current=w;const F=A.current.get(w)??zne();Fne(N,F)||t({type:"patch",patch:t1(F)})},[w,N]),y.useEffect(()=>{const D=M.current;D&&O.current.set(D,Dh(E))},[j,E]),y.useEffect(()=>{if(M.current===j)return;M.current=j;const F=O.current.get(j)??PA();g(te=>Yx(te,F)?te:Dh(F))},[j]);const z=y.useCallback(D=>{g(F=>Yx(F,D)?F:Dh(D))},[]);return{browserConversationId:w,handleWorkspaceDiffPanelViewStateChange:z}}function Wne({account:e,accountPending:t,accountSignedOut:n,activeWorkspaceKind:a,activeWorkspaceLocation:o,appDispatch:r,applyBootstrapPayload:s,busy:l,cloudSetupDialog:m,cloudProjects:d,connection:f,defaultTeamId:g,expandProject:x,localProjectById:k,selectedCloudProject:C,selectedProject:R,selectedSession:E,selectedSessionProjectId:A,setCloudSetupDialog:O,setDiffPanelOpen:$,setError:M,setSessions:w,setWorkspaceBusy:P,showToast:j,visibleWorkspaceState:N,workspaceBusy:z}){const D=e?.baseUrl??e?.activeProfile?.baseUrl??null,F=y.useCallback(async(L,de)=>{if(f)try{const X=await ie.previewLocalProjectCloudSource(f,L.id,{branch:de});O(Z=>!Z||Z.status!=="confirm"||Z.localProjectId!==L.id||Z.branch!==de?Z:{...Z,branch:X.preview.branch,cloudProjectId:X.preview.targetProjectId,preview:X.preview,previewLoading:!1,previewError:null})}catch(X){const Z=X instanceof Error?X.message:String(X);O(pe=>!pe||pe.status!=="confirm"||pe.localProjectId!==L.id||pe.branch!==de?pe:{...pe,preview:null,previewLoading:!1,previewError:Z})}},[f,O]),te=y.useCallback(async()=>{const L=m;if(!L||L.status==="uploading")return;if(L.projectKind==="cloud"){O(pe=>pe&&{...pe,status:"ready",error:null});return}if(!f){O(pe=>pe&&{...pe,status:"error",error:"OpenPond App server is not connected."});return}const de=L.localProjectId??"",X=k.get(de);if(!X){O(pe=>pe&&{...pe,status:"error",error:"Project is no longer available."});return}P(!0);const Z=Ga(X,d);O(pe=>pe&&{...pe,status:"uploading",error:null,previewLoading:!1});try{const pe=await ie.organizations(f),ee=kp(pe.organizations.map(gp).filter(Le=>!!Le).filter(Le=>Le.status==="active"),g);if(!ee)throw new Error("Add an OpenPond account before creating a Cloud environment.");if(!xp(ee))throw new Error(`You need owner or admin access to create projects in ${ee.displayName}.`);const me=L.branch||X.linkedSandboxProject?.defaultBranch||"main",be=kt("local",X.id),je=await ie.createSession(f,{provider:"openpond",appId:null,appName:null,workspaceKind:"local_project",workspaceId:X.id,workspaceName:X.name,localProjectId:X.id,cloudProjectId:Z?.id??null,cloudTeamId:Z?.teamId??null,cwd:X.workspacePath,title:`Sync ${X.name} to Cloud`});w(Le=>[je,...Le]),r({type:"selectSession",sessionId:je.id,projectId:be}),x(be);const ke=await ie.uploadLocalProjectCloudSource(f,X.id,{teamId:ee.teamId,projectName:X.name,branch:me,chatSessionId:je.id,displayPrompt:`/sync-cloud ${X.name}`});s(ke.bootstrap),x(be),x(kt("cloud",ke.project.id));const ue=cv({accountBaseUrl:D,teamId:ke.project.teamId,projectId:ke.project.id,projectName:ke.project.name,baseBranch:ke.upload.branch,localProjectId:X.id,source:"openpond-app"}),Ie=Zk({accountBaseUrl:D,organizationSlug:ke.project.organizationSlug,projectSlug:ke.project.slug});O({status:"ready",localProjectId:X.id,cloudProjectId:ke.project.id,teamId:ke.project.teamId,projectName:ke.project.name,projectKind:"local",projectUrl:Ie,setupUrl:ue,branch:ke.upload.branch,preview:L.preview??null,previewLoading:!1,previewError:null,upload:{branch:ke.upload.branch,headCommit:ke.upload.headCommit,fileCount:ke.upload.fileCount,byteCount:ke.upload.byteCount,skippedCount:ke.upload.skippedCount,initializedEmptyProject:ke.upload.initializedEmptyProject},error:null}),j("Source uploaded to OpenPond Git. Cloud setup link is ready.","success")}catch(pe){const ee=pe instanceof Error?pe.message:String(pe),me=f?await ie.bootstrap(f).catch(()=>null):null;me&&s(me),M(ee),O(be=>be&&{...be,status:"error",error:ee})}finally{P(!1)}},[D,r,s,m,d,f,g,x,k,O,M,w,P,j]),ve=y.useCallback((L,de)=>{if(!f){j("OpenPond App server is not connected.","error");return}if(t){j("Checking OpenPond account. Try again in a moment.","info");return}if(n){j("Add an OpenPond account before using Cloud.","error");return}const X=de||L.linkedSandboxProject?.defaultBranch||"main";O({status:"confirm",localProjectId:L.id,projectName:L.name,projectKind:"local",projectUrl:null,setupUrl:null,branch:X,preview:null,previewLoading:!0,previewError:null,upload:null,error:null}),F(L,X)},[t,n,f,F,O,j]),re=y.useCallback(async L=>{if(L===o||z||l)return;if(M(null),L==="upload_cloud"){if(!R){j("Select a local Project before uploading source.","error");return}ve(R,N?.currentBranch??null);return}if(L==="local"){const Z=E?.localProjectId??R?.id??A??null,pe=Z?k.get(Z)??null:null;if(!pe){j("No linked local workspace for this Cloud chat.","error");return}if(Ui(a)&&!window.confirm("Switch to Local? Cloud changes will stay in the hosted workspace until you preserve or export them."))return;const ee=kt("local",pe.id);r({type:"selectProject",projectId:ee}),x(ee),$(!1),j(`Switched to Local: ${pe.name}`,"info");return}if(!f){j("OpenPond App server is not connected.","error");return}if(t){j("Checking OpenPond account. Try again in a moment.","info");return}if(n){j("Add an OpenPond account before using Cloud.","error");return}if(C){O({status:"ready",cloudProjectId:C.id,teamId:C.teamId,projectName:C.name,projectKind:"cloud",projectUrl:Zk({accountBaseUrl:D,organizationSlug:C.organizationSlug,projectSlug:C.slug}),setupUrl:cv({accountBaseUrl:D,teamId:C.teamId,projectId:C.id,projectName:C.name,baseBranch:C.defaultBranch,source:"openpond-app"}),branch:C.defaultBranch??"main",preview:null,previewLoading:!1,previewError:null,upload:null,error:null});return}const de=R;if(!de){j("Select a Project before Cloud coding.","error");return}const X=N?.currentBranch||de.linkedSandboxProject?.defaultBranch||"main";ve(de,X)},[D,t,n,a,o,r,l,f,d,x,k,ve,C,R,E,A,O,$,M,j,N?.currentBranch,z]),K=y.useCallback(L=>{wy(L)&&ve(L.project)},[ve]);return{changeWorkspaceTarget:re,moveProjectToCloud:K,openCloudSetupForLocalProject:ve,startCloudSetupUpload:te}}function Gne({advanceTrainingTurn:e,bindTrainingSession:t,composerDraftStore:n,onSessionCreated:a,onSubmitted:o,prepareTrainingTurn:r,sendPrompt:s,setMentionedAppId:l,showToast:m}){return y.useCallback(async(d=[],f=null,g,x={})=>{const k=g??n.getSnapshot(),C=r(k);if(C.active&&k.trim()&&!C.metadata)return m(C.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,f,g,{clearPrompt:x.preservePrompt?()=>{}:void 0,displayPrompt:x.displayPrompt,onSessionCreated:E=>{a(E),C.metadata&&t(E.id)},turnMetadata:C.metadata||x.turnMetadata?{...C.metadata??{},...x.turnMetadata??{}}:void 0,sessionMetadata:C.metadata?{trainingTasksetId:C.metadata.trainingTasksetId,trainingTasksetName:C.metadata.trainingTasksetName}:void 0});return R&&await o?.(),R&&C.metadata&&e(),R},[e,t,n,a,o,r,s,l,m])}function Jne({appDispatch:e,connection:t,sessions:n,setDiffPanelOpen:a,setRightPanelMode:o,setSessions:r,setView:s}){return y.useCallback(async l=>{if(!t)return;const m=n.find(g=>!g.archived&&g.workspaceKind==="sandbox"&&g.workspaceId===l.sandboxId);if(m){e({type:"selectSession",sessionId:m.id,appId:null,projectId:null}),o("changes"),a(!0),s("chat");return}const d=l.name??`Sandbox ${l.sandboxId.slice(0,8)}`,f=await ie.createSession(t,{provider:"openpond",appId:null,appName:null,workspaceKind:"sandbox",workspaceId:l.sandboxId,workspaceName:d,cwd:null,title:d});r(g=>[f,...g]),e({type:"selectSession",sessionId:f.id,appId:null,projectId:null}),o("changes"),a(!0),s("chat")},[e,t,n,a,o,r,s])}function Zne({connection:e,defaultTeamId:t,sessions:n,selectedProjectId:a,confirmProjectAction:o,applyBootstrapPayload:r,expandProject:s,setExpandedProjectIds:l,setSelectedAppId:m,setSelectedProjectId:d,setSelectedSessionId:f,setError:g,setView:x,showToast:k}){function C($){const M=kt("local",$.id);m(null),d(M),f(null),x("chat"),s(M)}async function R($){if(!e)return!1;g(null);try{const M=await ie.createLocalProject(e,$);return r(M.bootstrap),C(M.project),k(M.created===!1?`Opened ${M.project.name}`:`Created ${M.project.name}`,"success"),!0}catch(M){const w=M instanceof Error?M.message:String(M);return g(w),k(w,"error"),!1}}async function E($){if(!e)return!1;const M=$.trim();if(!M)return!1;g(null);try{const w=await ie.createLocalProject(e,{createNew:!0,name:M});return r(w.bootstrap),C(w.project),k(`Created ${w.project.name}`,"success"),!0}catch(w){return g(w instanceof Error?w.message:String(w)),k("Project could not be created","error"),!1}}async function A($){if(!e)return!1;const M=$.trim();if(!M)return!1;g(null);try{const w=await ie.organizations(e),P=kp(w.organizations.map(gp).filter(F=>!!F).filter(F=>F.status==="active"),t);if(!P)throw new Error("Add an OpenPond account before creating a Cloud Project.");if(!xp(P))throw new Error(`You need owner or admin access to create projects in ${P.displayName}.`);const j=`${AA(M)}-${Date.now().toString(36)}`;let N=(await ie.upsertSandboxProject(e,{teamId:P.teamId,name:M,sourceType:"internal_repo",normalizedSourceIdentity:j,internalRepoPath:j,defaultBranch:"main",sourceConfig:{sourceType:"internal_repo",sourceValue:j},metadata:{source:"openpond-app-new-cloud-project"}})).project;N=(await ie.uploadSandboxProjectSource(e,N.id,{teamId:P.teamId,branch:"main",commitMessage:"Initialize cloud project",entries:[{path:"README.md",type:"file",contentsBase64:RZ(`# ${M}
|
|
219
|
-
|
|
220
|
-
Created in OpenPond Cloud.
|
|
221
|
-
`)}]})).project;const z=await ie.bootstrap(e);r(z);const D=kt("cloud",N.id);return m(null),d(D),f(null),x("chat"),s(D),k(`Created Cloud Project: ${N.name}`,"success"),!0}catch(w){const P=w instanceof Error?w.message:String(w);return g(P),k(P,"error"),!1}}async function O($){if(!e)return;if(z8($)){const j=`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(j)))return;g(null);try{await ie.archiveSandboxProject(e,$.project.id,{teamId:$.project.teamId}),r(await ie.bootstrap(e)),l(z=>{const D=new Set(z);return D.delete($.id),D}),a===$.id&&(d(null),f(null)),k(`Archived ${$.project.name}`,"success")}catch(z){g(z instanceof Error?z.message:String(z)),k("Cloud Project could not be archived","error")}return}if(!wy($))return;const M=$.project,w=`Remove ${M.name} from Projects? The folder will not be deleted.`;if(o?await o({title:"Remove Project",body:`${M.name} will be removed from the sidebar. The folder and files on disk will not be deleted.`,confirmLabel:"Remove project"}):window.confirm(w)){g(null);try{const j=await ie.deleteLocalProject(e,M.id);r(j),l(N=>{const z=new Set(N);return z.delete($.id),z}),a===$.id&&(d(null),f(N=>{const z=n.find(D=>D.id===N);return z?.workspaceKind==="local_project"&&z.workspaceId===M.id?null:N})),k(`Removed ${M.name}`,"success")}catch(j){g(j instanceof Error?j.message:String(j)),k("Project could not be removed","error")}}}return{createCloudProjectFromScratch:A,createProjectFromScratch:E,createProjectCollection:R,removeProject:O}}function Yne({appDispatch:e,busy:t,cloudProjectById:n,createCloudProjectFromScratch:a,createProjectFromScratch:o,createProjectCollection:r,expandProject:s,localProjectById:l,onCreateCloudEnvironment:m,onNewCloudProject:d,onNewLocalProject:f,onUseExistingFolderPath:g,newProjectBusy:x,newProjectMode:k,newProjectName:C,projectTargetValue:R,setDiffPanelOpen:E,setDraftModel:A,setDraftProvider:O,setError:$,setNewProjectBusy:M,setNewProjectDialogOpen:w,setNewProjectName:P,setNewProjectPath:j,showToast:N,workspaceBusy:z}){const D=y.useCallback(te=>{if(te===R||t||z)return;if($(null),te==="action:new-local-project"){f();return}if(te==="action:add-local-project"){g();return}if(te==="action:add-local-project-path"){g();return}if(te==="action:new-cloud-project"){d();return}if(te==="action:create-cloud-environment"){m();return}if(te==="none"){e({type:"selectProject",projectId:null}),E(!1),N("Started a chat without project files.","info");return}const ve=te.indexOf(":"),re=ve>=0?te.slice(0,ve):"",K=ve>=0?te.slice(ve+1):"";if(re==="local"){const L=l.get(K);if(!L){N("Project is no longer available.","error");return}const de=kt("local",L.id);e({type:"selectProject",projectId:de}),s(de),E(!1);return}if(re==="cloud"){const L=n.get(K);if(!L){N("Cloud Project is no longer available.","error");return}const de=kt("cloud",L.id);e({type:"selectProject",projectId:de}),s(de),O("openpond"),A(X=>nr("openpond",X)),E(!1)}},[e,t,n,s,l,m,d,f,g,R,E,A,O,$,N,z]),F=y.useCallback(async te=>{const ve=C.trim();if(!x){if(k==="existing-local"?!te?.name.trim()||!te.sourceFolders.length:!ve)return!1;M(!0);try{const re=k==="cloud"?await a(ve):k==="existing-local"?await r(te):await o(ve);return re&&(w(!1),P(""),j("")),!!re}finally{M(!1)}}},[a,o,r,x,k,C,M,w,P,j]);return{changeProjectTarget:D,submitNewProjectDialog:F}}function Qne(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 kre(e){return e.reduce((t,n)=>!t||n.activationVersion>=t.activationVersion?n:t,null)}function Xne(e,t){const n=Math.max(0,...e.map(r=>r.activationVersion))+1;let a=!1;const o=e.map(r=>r.id!==t?r:(a=!0,{...r,activationVersion:n}));return a?o:[...e]}function eae(e,t){const n=Math.max(0,...e.map(r=>r.activationVersion))+1;let a=!1;const o=e.map(r=>r.sessionId!==t.sessionId?r:(a=!0,{...r,activationVersion:n,prompt:t.prompt??r.prompt}));return a?o:[...e]}function AT(e){return!!(e.parentSessionId&&e.subagentRunId)}function tae(e){const t=e.sessions.filter(AT);return{knownSessionIds:new Set(t.map(n=>n.id)),newSessions:t.filter(n=>!e.knownSessionIds.has(n.id))}}function nae(e,t){const n=new Set(e.map(o=>o.sessionId).filter(Boolean)),a=t.filter(AT).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 n1="openpond/openpond",aae="github.issue.write";function iae(e){return e.some(t=>t.provider==="github"&&(t.ref.capabilities??[]).includes(aae))}function wre(e){return[`Title: ${e.title.trim()}`,"","Description:",e.description.trim()].join(`
|
|
222
|
-
`)}function oae(e){const t=e.trim();return[`@github Submit this request as a new GitHub issue in ${n1}.`,`Use the GitHub connected app write operation github.issue.create with input.repo set to ${n1}, 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:
|
|
223
|
-
${t}`].join(`
|
|
224
|
-
`)}function rae(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(`
|
|
225
|
-
|
|
226
|
-
`),requiresInstructions:!0};case"train":return{kind:"open_training",objective:n||null};case"submit-issue":return{kind:"send_prompt",prompt:oae(n),requiresInstructions:!0};case"sync-cloud":return{kind:"send_prompt",prompt:`/sync-cloud ${n}`,requiresInstructions:!1}}}const a1=[];function sae(e){const{approvals:t,codexHistoryEvents:n,contextCompaction:a,pendingChatUserMessages:o,rightChatHistoryEvents:r,rightChatPanels:s,runningSessionIds:l,selectedSessionId:m,sidebarSessions:d}=e;return y.useMemo(()=>{const f=new Map(d.map(x=>[x.id,x])),g=lae(t);return s.map(x=>{const k=x.sessionId?f.get(x.sessionId)??null:null,C=Jt(x.sessionId),R=C?(x.sessionId?r[x.sessionId]:void 0)??(x.sessionId===m?n:a1):a1,E=Zg(R,[]),A=x.sessionId?g.get(x.sessionId)??null:null,O=!!(k&&l.has(k.id)),$=C?$J({events:R}):null,M=k?.cwd??null,w=k?.appId??k?.localProjectId??(k?.workspaceKind==="local_project"?k.workspaceId??null:null)??(k?.cwd&&!Ui(k.workspaceKind)?qw(k.cwd):null),P=x.sessionId?o[x.sessionId]??null:null;return{...x,session:k,title:NJ($,k?.title??"New task"),messages:C?UA(yp(R),P):[],createImproveRun:$,contextWindowStatus:oA({provider:x.provider,snapshot:xA(E,x.sessionId),preferences:a}),goalRuntime:kA(E,x.sessionId),pendingApproval:A,running:O,workspaceRootPath:M,activeWorkspaceAppId:w,pendingUserMessage:P,runtimeSource:C?"history":"live"}})},[t,n,a,o,r,s,l,m,d])}function lae(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 cae(e){const{applyPayload:t,connection:n,locallyActiveSessionIds:a,panels:o,sessions:r,setError:s}=e,l=y.useMemo(()=>{const f=new Set,g=[];for(const x of o)!Jt(x.sessionId)||!x.sessionId||f.has(x.sessionId)||(f.add(x.sessionId),g.push(x.sessionId));return g.join(`
|
|
227
|
-
`)},[o]),m=y.useMemo(()=>{if(!l)return"";const f=new Set(l.split(`
|
|
228
|
-
`).filter(Boolean));return r.filter(g=>f.has(g.id)&&g.status==="active").map(g=>g.id).join(`
|
|
229
|
-
`)},[l,r]),d=y.useMemo(()=>l?l.split(`
|
|
230
|
-
`).filter(f=>a.has(f)).join(`
|
|
231
|
-
`):"",[a,l]);y.useEffect(()=>{if(!n||!l)return;const f=l.split(`
|
|
232
|
-
`).filter(Boolean),g=new Set(m.split(`
|
|
233
|
-
`).filter(Boolean)),x=new Set(d.split(`
|
|
234
|
-
`).filter(Boolean)),k=f.map(C=>Dy({connection:n,locallyActive:x.has(C),onError:R=>s(R instanceof Error?R.message:String(R)),onPayload:R=>t(Ny(R,x.has(C))),reportedActive:g.has(C),sessionId:C,surface:"thread"}));return()=>k.forEach(C=>C())},[m,t,n,d,l,s])}const i1=[];function dae(e){const{activeModel:t,activeProvider:n,approvals:a,applyRightCodexHistoryPayload:o,codexHistoryEvents:r,connectedAppMentions:s,connection:l,contextCompaction:m,openLabTraining:d,locallyActiveCodexHistorySessionIds:f,openPondCommandAccessMode:g,pendingChatUserMessages:x,providerSettings:k,rightChatHistoryEvents:C,rightChatPanels:R,rightPanelMode:E,runtimeIndexes:A,runtimeEventStore:O,runningSessionIds:$,selectedSession:M,selectedSessionId:w,sendPrompt:P,setDiffPanelOpen:j,setError:N,setRightChatHistoryEvents:z,setRightChatPanels:D,setRightPanelMode:F,setRightPanelTabRequest:te,setView:ve,showChangesPanel:re,showToast:K,sidebarSessions:L,startupReady:de}=e,X=y.useRef(null),Z=y.useRef(new Map),pe=y.useRef(new Set);y.useEffect(()=>{if(!l)return;const Be=R.flatMap(Ge=>Ge.sessionId&&!Jt(Ge.sessionId)?[Ge.sessionId]:[]);for(const Ge of Be)Object.hasOwn(C,Ge)||pe.current.has(Ge)||(pe.current.add(Ge),ie.runtimeEventsPage(l,{sessionId:Ge,beforeSequence:Number.MAX_SAFE_INTEGER,limit:500}).then(Ve=>{const U=Ve.events.map(J=>J.event);z(J=>({...J,[Ge]:io(J[Ge]??i1,U)}))}).catch(Ve=>{N(Ve instanceof Error?Ve.message:String(Ve))}).finally(()=>{pe.current.delete(Ge)}))},[l,C,R,N,z]);const ee=y.useCallback(Be=>{te(Ge=>({id:(Ge?.id??0)+1,tab:Be})),re()},[re]),me=y.useCallback((Be=null,Ge={})=>{const Ve=Be?.id?R.find(J=>J.sessionId===Be.id)??null:null;if(Ve)return D(J=>eae(J,{sessionId:Be.id,prompt:Ge.prompt})),j(!0),F("chat"),Ge.preserveView||ve("chat"),Ve.id;const U=Qne({sessionId:Be?.id??null,provider:Be?.provider??n,model:Be?.modelRef?.modelId??t,prompt:Ge.prompt});return D(J=>[...J,U]),j(!0),F("chat"),Ge.preserveView||ve("chat"),U.id},[t,n,R,j,D,F,ve]);y.useEffect(()=>{if(!de)return;const Be=X.current;if(!Be){X.current=new Set(L.filter(J=>!!(J.parentSessionId&&J.subagentRunId)).map(J=>J.id));return}const Ge=tae({sessions:L,knownSessionIds:Be});X.current=Ge.knownSessionIds;for(const J of Ge.newSessions)Z.current.set(J.id,J);const Ve=M?.parentSessionId??M?.id??null;if(!Ve)return;const U=[...Z.current.values()].filter(J=>J.parentSessionId===Ve);if(U.length!==0){for(const J of U)Z.current.delete(J.id);D(J=>nae(J,U)),j(!0),F("chat")}},[M?.id,M?.parentSessionId,j,D,F,L,de]);const be=y.useCallback(()=>{if(R.length===0){me(null);return}j(!0),F("chat"),ve("chat")},[me,R.length,j,F,ve]),je=y.useCallback(Be=>{const Ge=R.length<=1&&R.some(U=>U.id===Be),Ve=()=>{D(U=>U.filter(J=>J.id!==Be))};if(Ge&&E==="chat"){if(ee("files"),typeof window>"u"){Ve();return}window.requestAnimationFrame(Ve);return}Ve()},[R,E,D,ee]),ke=y.useCallback((Be,Ge)=>{D(Ve=>Ve.map(U=>U.id===Be?{...U,prompt:Ge}:U))},[D]),ue=y.useCallback(Be=>{D(Ge=>Xne(Ge,Be))},[D]),Ie=y.useCallback((Be,Ge)=>{D(Ve=>Ve.map(U=>U.id===Be?{...U,...Ge}:U))},[D]),Le=y.useCallback((Be,Ge)=>{D(Ve=>Ve.map(U=>U.id===Be?{...U,model:Ge}:U))},[D]),Fe=y.useCallback((Be,Ge)=>{D(Ve=>Ve.map(U=>U.id===Be?{...U,provider:Ge,model:nr(Ge,U.model,k)}:U))},[k,D]);cae({applyPayload:o,connection:l,locallyActiveSessionIds:f,panels:R,sessions:L,setError:N});const Xe=sae({approvals:a,codexHistoryEvents:r,contextCompaction:m,pendingChatUserMessages:x,rightChatHistoryEvents:C,rightChatPanels:R,runningSessionIds:$,selectedSessionId:w,sidebarSessions:L}),Ze=y.useCallback(async(Be,Ge=[],Ve=null,U=null,J={})=>{const q=R.find(_t=>_t.id===Be);if(!q)return!1;const oe=J.promptOverride??q.prompt,he=U?rae(U,oe):null;if(he?.kind==="open_training")return Ge.length>0?(K("/train uses this chat; add other chats from Models.","error"),!1):(d({objective:he.objective,sessionId:q.sessionId}),J.preservePrompt||ke(Be,""),!0);if(U&&he?.kind==="send_prompt"&&he.requiresInstructions&&!oe.trim())return K(`Add instructions after ${U.command}.`,"info"),!1;if(U&&Ge.length>0)return K(`${U.command} tasks do not accept attachments yet. Add file context in the task thread.`,"error"),!1;if(U?.id==="submit-issue"&&!iae(s))return K("Connect the GitHub app before using /submit-issue.","error"),!1;const Re=q.sessionId?L.find(_t=>_t.id===q.sessionId)??null:null,qe=q.provider==="codex"?g:Re?.openPondCommandAccessMode??g,Je=he?.kind==="send_prompt"?he.prompt:oe,et=Jt(q.sessionId)?(q.sessionId?C[q.sessionId]:void 0)??(q.sessionId===w?r:i1):O.getSessionEvents(q.sessionId),dt=Jt(q.sessionId)&&q.sessionId?_t=>{const Ne=q.sessionId;z(Ye=>({...Ye,[Ne]:io(Ye[Ne]??et,[_t])}))}:void 0;return P(Ge,Ve,Je,{session:Re,selectSession:!1,provider:q.provider,model:q.model,openPondCommandAccessMode:qe,chatMessages:yp(et),displayPrompt:J.displayPrompt,turnMetadata:J.turnMetadata,usageAttribution:U?.id==="submit-issue"?{surface:"chat",workflowKind:"slash_command",commandName:U.command,commandSource:"composer_selection"}:void 0,onCodexHistoryOptimisticEvent:dt,clearPrompt:J.preservePrompt?()=>{}:()=>ke(Be,""),onSessionCreated:_t=>{D(Ne=>Ne.map(Ye=>Ye.id===Be?{...Ye,sessionId:_t.id,provider:_t.provider,model:_t.modelRef?.modelId??Ye.model}:Ye))}})},[r,s,C,R,A,O,w,d,g,P,D,ve,L,K,ke]);return{activateRightChatPanel:ue,closeRightChatPanel:je,openRightChatPanel:me,rightChatPanelViews:Xe,showRightChatPanel:be,showRightPanelDiffTab:ee,submitRightChatPrompt:Ze,updateRightChatModel:Le,updateRightChatPrompt:ke,updateRightChatProvider:Fe,updateRightChatScrollState:Ie}}function uae(e){const{appPreferences:t,connection:n,selectedSessionId:a,setAppPreferences:o,setCodexHistorySessions:r,setError:s,setSelectedSessionId:l,setSessions:m}=e;async function d(A,O){if(!n)return;const $=t[A]??{},M={...$,...O,archived:O.pinned?!1:O.archived??$.archived};o(w=>({...w,[A]:M}));try{const w=await ie.patchSidebarAppPreference(n,A,O);o(P=>({...P,[A]:w}))}catch(w){s(w instanceof Error?w.message:String(w)),o(P=>({...P,[A]:$}))}}function f(A){d(A.id,{pinned:!A.pinned,archived:!1})}async function g(A,O){if(!n)return;const $=Jt(A.id)?r:m,M={...A,...O};$(w=>w.some(P=>P.id===A.id)?w.map(P=>P.id===A.id?M:P):[M,...w]);try{const w=await ie.patchSession(n,A.id,O);$(P=>P.some(j=>j.id===w.id)?P.map(j=>j.id===w.id?w:j):[w,...P])}catch(w){s(w instanceof Error?w.message:String(w)),$(P=>P.map(j=>j.id===A.id?A:j))}}function x(A){g(A,{pinned:!1,savedForLater:!A.savedForLater,archived:!1})}function k(A){g(A,{pinned:!A.pinned,savedForLater:!1,archived:!1})}function C(A){g(A,{pinned:!1,savedForLater:!1,archived:!0}),a===A.id&&l(null)}function R(A){g(A,{archived:!1})}function E(A,O){const $=O.trim();!$||$===A.title||g(A,{title:$})}return{archiveSession:C,renameSession:E,restoreSession:R,toggleProjectPinned:f,toggleSessionPinned:k,toggleSessionSavedForLater:x}}function mae(e){return e.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,72)||"new-branch"}function pae({connection:e,activeWorkspaceAppId:t,appDefaults:n,bootstrap:a,branchDialogName:o,commitIncludeUnstaged:r,commitMessage:s,commitNextStep:l,draftModel:m,draftProvider:d,cloudProjects:f,selectedApp:g,selectedProject:x,selectedProjectLinkedOpenPondApp:k,selectedSession:C,sessions:R,title:E,visibleWorkspaceDiff:A,visibleWorkspaceState:O,workspaceBusy:$,workspaceName:M,appDispatch:w,applyBootstrapPayload:P,expandProject:j,refreshWorkspace:N,refreshWorkspaceDiff:z,rememberWorkspaceState:D,setBranchDialogOpen:F,setCommitDialogOpen:te,setError:ve,setSessions:re,setSettingsSection:K,setSyncingWorkspaceAppId:L,setView:de,setWorkspaceBusy:X,showToast:Z}){function pe(){return`${NP(n.defaultBranchPrefix)}${mae(M??E??"new-branch")}`}function ee(){return M?`Update ${M}`:(A?.filesChanged??O?.changedFilesCount??0)===1?"Update workspace file":"Update workspace files"}function me(Ve="commit"){w({type:"openCommitDialog",nextStep:Ve})}function be(){w({type:"openBranchDialog",branchName:pe()})}function je(){$||F(!1),K("configuration"),de("settings"),Vt({kind:"settings",section:"configuration"})}async function ke(Ve){if(!(!e||!t)){X(!0),ve(null);try{const U=await ie.checkoutWorkspaceBranch(e,t,{branch:Ve});D(U),U.initialized&&z(t)}catch(U){ve(U instanceof Error?U.message:String(U))}finally{X(!1)}}}async function ue(){if(!e||!t)return;const Ve=o.trim();if(Ve){X(!0),ve(null);try{const U=await ie.createWorkspaceBranch(e,t,{branch:Ve});D(U),U.initialized&&z(t),F(!1),Z(`Checked out ${Ve}`,"success")}catch(U){ve(U instanceof Error?U.message:String(U))}finally{X(!1)}}}async function Ie(Ve){L(Ve);const U=a?.apps.find(J=>J.id===Ve)?.name??a?.localProjects.find(J=>J.id===Ve)?.name??"Workspace";try{const J=await N(Ve,!0);J?.initialized&&Ve===t&&z(Ve),J?.initialized&&!J.error?Z(`${U} synced locally`,"success"):J?.error&&Z("Workspace sync failed","error")}finally{L(J=>J===Ve?null:J)}}async function Le(){t&&await Ie(t)}async function Fe(Ve,U,J={}){if(!e)return null;const q=C&&!Jt(C.id)?C:null;if(vae(U,q,J)||q&&fae(q,x,g))return q;const oe=q?await Xe(q):null;if(oe)return oe;const he=hae(R,x,g);if(he){const et=he.workspaceKind==="local_project"&&he.workspaceId?kt("local",he.workspaceId):null;return w({type:"selectSession",sessionId:he.id,appId:he.appId,projectId:et}),he.workspaceKind==="local_project"&&he.workspaceId&&j(kt("local",he.workspaceId)),he}const Re=Ga(x,f),qe=await ie.createSession(e,{provider:d,modelRef:ii(d,m,a?.providers??null),appId:k?.appId??g?.id??null,appName:k?.appName??g?.name??null,workspaceKind:x?"local_project":g?"sandbox_app":void 0,workspaceId:x?.id??g?.id??null,workspaceName:x?.name??g?.name??null,localProjectId:x?.id??null,cloudProjectId:Re?.id??null,cloudTeamId:Re?.teamId??null,cwd:x?x.workspacePath:null,title:Ve});re(et=>[qe,...et]);const Je=qe.workspaceKind==="local_project"&&qe.workspaceId?kt("local",qe.workspaceId):null;return w({type:"selectSession",sessionId:qe.id,appId:qe.appId,projectId:Je}),qe.workspaceKind==="local_project"&&qe.workspaceId&&j(kt("local",qe.workspaceId)),qe}async function Xe(Ve){if(!e||!x||!k?.appId||Jt(Ve.id)||Ve.workspaceKind==="local_project"||Ve.appId!==k.appId)return null;const U=Ga(x,f),J=await ie.patchSession(e,Ve.id,{appId:k.appId,appName:k.appName,workspaceKind:"local_project",workspaceId:x.id,workspaceName:x.name,localProjectId:x.id,cloudProjectId:U?.id??null,cloudTeamId:U?.teamId??null,cwd:x.workspacePath});return re(q=>q.map(oe=>oe.id===J.id?J:oe)),w({type:"selectSession",sessionId:J.id,appId:J.appId,projectId:kt("local",x.id)}),j(kt("local",x.id)),J}async function Ze(Ve,U={}){if(!e)return null;const J=await Fe(M?`${M} workspace`:"Workspace action",Ve,U);if(!J)return null;const q=await ie.workspaceTool(e,J.id,{action:Ve,args:U,source:"ui_button"});Z(q.output,q.ok?"success":"error"),P(await ie.bootstrap(e));const oe=q.appId??gae(J);return oe&&(await N(oe,!1))?.initialized&&await z(oe),q}async function Be(Ve,U={}){if(Ve==="git_commit"&&typeof U.message!="string")return me("commit"),null;X(!0),ve(null);try{return await Ze(Ve,U)}catch(J){return ve(J instanceof Error?J.message:String(J)),null}finally{X(!1)}}async function Ge(){const Ve=s.trim()||ee(),U=l==="commit_publish",J=U&&!!O?.remoteUrl;if(!(J&&!window.confirm("Replace the current origin remote with the new OpenPond repo after committing?"))){X(!0),ve(null);try{if(!(await Ze("git_commit",{message:Ve,includeUnstaged:r}))?.ok||l==="commit_push"&&!(await Ze("git_push",{runChecks:!1}))?.ok||U&&!(await Ze("publish_openpond_repo",{replaceOrigin:J}))?.ok)return;te(!1)}catch(q){ve(q instanceof Error?q.message:String(q))}finally{X(!1)}}}return{changeWorkspaceBranch:ke,openCommitDialog:me,openCreateWorkspaceBranchDialog:be,openDefaultsSettingsFromBranchDialog:je,runWorkspaceTool:Be,submitCommitDialog:Ge,submitCreateWorkspaceBranch:ue,syncWorkspaceLocally:Le,syncWorkspaceLocallyForApp:Ie}}function fae(e,t,n){return!t&&!n?!0:TT(e,t,n)}function hae(e,t,n){if(!t&&!n)return null;let a=null,o=Number.NEGATIVE_INFINITY;for(const r of e){if(r.archived||!TT(r,t,n))continue;const s=Date.parse(r.updatedAt),l=Number.isFinite(s)?s:0;(!a||l>o)&&(a=r,o=l)}return a}function TT(e,t,n){return t?e.workspaceKind==="local_project"&&e.workspaceId===t.id:n?e.appId===n.id||e.workspaceId===n.id:!1}function gae(e){return e.workspaceKind==="sandbox"?e.localProjectId??null:e.workspaceId??e.appId??null}function vae(e,t,n={}){return(bae(e)||Sae(e,n))&&yae(t)}function bae(e){return e.startsWith("sandbox_")?e!=="sandbox_create"&&e!=="sandbox_templates"&&e!=="sandbox_template_launch":!1}function yae(e){return e?.workspaceKind==="sandbox"||e?.workspaceKind==="sandbox_template"}function Sae(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 xae(e,t){return e.kind==="general"?"# general":e.title?e.title:e.participants.find(a=>a.userId!==t)?.name??"Direct message"}const kae=[];function wae(e){const{composerDraftStore:t,appDispatch:n,mentionedAppId:a,setMentionedAppId:o,cloudSetupDialog:r,setCloudSetupDialog:s,setRightPanelTabRequest:l,workspaceDiffPanelViewState:m,setWorkspaceDiffPanelViewState:d,rightChatHistoryEvents:f,setRightChatHistoryEvents:g,locallyActiveCodexHistorySessionIds:x,setCodexHistoryTurnLocallyActive:k,draftSubagentDelegationMode:C,setDraftSubagentDelegationMode:R,confirmProjectAction:E,view:A,selectedAppId:O,selectedProjectId:$,selectedSessionId:M,draftProvider:w,draftModel:P,activeExperience:j,codexPermissionMode:N,codexReasoningEffort:z,openPondCommandAccessMode:D,busy:F,diffPanelOpen:te,diffPanelExpanded:ve,rightPanelMode:re,rightChatPanels:K,newProjectMode:L,newProjectName:de,newProjectBusy:X,commitMessage:Z,commitIncludeUnstaged:pe,commitNextStep:ee,branchDialogName:me,setSectionMenuOpen:be,setView:je,setSelectedAppId:ke,setSelectedProjectId:ue,setSelectedSessionId:Ie,setPrompt:Le,setDraftProvider:Fe,setDraftModel:Xe,setDiffPanelOpen:Ze,setRightPanelMode:Be,setRightChatPanels:Ge,setSyncingWorkspaceAppId:Ve,setSettingsSection:U,setNewProjectDialogOpen:J,setNewProjectMode:q,setNewProjectName:oe,setNewProjectPath:he,setNewProjectBusy:Re,setCommitDialogOpen:qe,setBranchDialogOpen:Je,setError:et,showToast:dt,appPreferences:_t,applyBootstrapPayload:Ne,approvals:Ye,bootstrap:h,connection:V,events:ae,runtimeEventStore:we,sessions:fe,startup:Y,setAppPreferences:_,setCodexHistorySessions:G,setEvents:se,setSessions:ne,cloudProjectById:ge,localProjectById:Se,selectedApp:xe,selectedCloudProject:Oe,selectedProject:Te,selectedProjectLinkedOpenPondApp:Ue,selectedSession:Ee,sidebarSessions:tt,runtimeIndexes:ht,connectedAppMentions:xn,codexHistoryEvents:xt,setCodexHistoryEvents:Xn,account:kn,accountPending:Pn,accountSignedOut:Zt,activeModel:Dn,activeProvider:An,activeWorkspaceAppId:Hn,activeWorkspaceKind:Un,activeWorkspaceLocation:Wt,appDefaults:Ct,selectedSessionProjectId:Ln,workspaceName:mt,accountScopeKey:Nt,teamChat:ea,communities:$t,selectedProjectConfirmedCloudProject:Tn,activeOpenPondCommandAccessMode:st,viewWorkspaceAppId:En,viewWorkspaceId:gi,viewWorkspaceKind:vi,openPondActionCatalog:Wn,selectedActionCatalog:da,expandProject:Gn,setExpandedProjectIds:Vi,advanceTrainingModelChatAfterTurn:ei,bindTrainingModelChatSession:wt,prepareTrainingModelChatTurn:pn,chatMessages:Rt,pendingChatUserMessages:ut,recordPendingChatUserMessage:ln,runningSessionIds:ta,workspaceBusy:wn,visibleWorkspaceState:nt,visibleWorkspaceDiff:Q,rememberWorkspaceState:Ae,refreshWorkspace:De,setWorkspaceBusy:pt,refreshWorkspaceDiffWhenNeeded:Yt,setPendingWorkspaceTarget:ua,pendingSidebarWorkspaceTarget:bi,setPendingSidebarWorkspaceTarget:In,projectTarget:Ki,workspaceTarget:Jn}=e,ja=A==="apps"?"Apps":A==="get-started"?"Walkthroughs":A==="labs"?"Models":A==="scheduled"?"Workflows":A==="outputs"?"Outputs":A==="projects"?"Projects":A==="team"?ea.detail?xae(ea.detail.thread,ea.currentUserId):"Team Chat":A==="community"?$t.preview?.displayName??"Communities":Ee?.title??kP(j),{browserConversationId:ma,handleWorkspaceDiffPanelViewStateChange:ko}=Kne({appDispatch:n,diffPanelExpanded:ve,diffPanelOpen:te,rightChatPanels:K,rightPanelMode:re,selectedAppId:O,selectedCloudProject:Oe,selectedProjectId:$,selectedSession:Ee,selectedSessionId:M,setWorkspaceDiffPanelViewState:d,view:A,viewWorkspaceAppId:En,viewWorkspaceId:gi,viewWorkspaceKind:vi,workspaceDiffPanelViewState:m}),ir=y.useCallback(gt=>{Vt({kind:"chat",sessionId:gt}),Ie(gt),ke(null),ue(null),je("chat")},[ke,ue,Ie,je]),wo=y.useCallback(()=>{q("existing-local"),oe(""),he(""),J(!0)},[J,q,oe,he]),Io=y.useCallback(()=>{q("local"),oe(""),he(""),J(!0)},[J,q,oe,he]),{createCloudProjectFromScratch:It,createProjectFromScratch:bl,createProjectCollection:or,removeProject:yl}=Zne({connection:V,defaultTeamId:Ct.defaultTeamId,sessions:fe,selectedProjectId:$,confirmProjectAction:E,applyBootstrapPayload:Ne,expandProject:Gn,setExpandedProjectIds:Vi,setSelectedAppId:ke,setSelectedProjectId:ue,setSelectedSessionId:Ie,setError:et,setView:je,showToast:dt}),{changeWorkspaceBranch:zr,openCommitDialog:Sl,openCreateWorkspaceBranchDialog:Wi,openDefaultsSettingsFromBranchDialog:xl,runWorkspaceTool:Br,submitCommitDialog:Fr,submitCreateWorkspaceBranch:Vr,syncWorkspaceLocally:kl}=pae({connection:V,activeWorkspaceAppId:Hn,appDefaults:Ct,bootstrap:h,branchDialogName:me,commitIncludeUnstaged:pe,commitMessage:Z,commitNextStep:ee,draftModel:P,draftProvider:w,cloudProjects:h?.cloudProjects??[],selectedApp:xe,selectedProject:Te,selectedProjectLinkedOpenPondApp:Ue,selectedSession:Ee,sessions:fe,title:ja,visibleWorkspaceDiff:Q,visibleWorkspaceState:nt,workspaceBusy:wn,workspaceName:mt,appDispatch:n,applyBootstrapPayload:Ne,expandProject:Gn,refreshWorkspace:De,refreshWorkspaceDiff:Yt,rememberWorkspaceState:Ae,setBranchDialogOpen:Je,setCommitDialogOpen:qe,setError:et,setSessions:ne,setSettingsSection:U,setSyncingWorkspaceAppId:Ve,setView:je,setWorkspaceBusy:pt,showToast:dt}),wl=Une({applyBootstrapPayload:Ne,cloudProjects:h?.cloudProjects??[],connection:V,localProjectById:Se,selectedCloudProject:Oe,selectedProject:Te,setWorkspaceBusy:pt,showToast:dt,visibleWorkspaceState:nt}),yi=h?.preferences.subagents.delegationMode??"manual",Il=Ee?.subagentDelegationMode??C,Kr=!!(j==="development"&&h?.preferences.subagents.enabled&&An!=="codex"&&!Jt(M)&&!Ee?.subagentRunId),Wr=y.useCallback(gt=>{if(!Ee){R(gt);return}if(!V||Jt(Ee.id)||Ee.subagentRunId)return;const cn=Ee.id,fa=Ee.subagentDelegationMode??null;ne(vn=>vn.map(zn=>zn.id===cn?{...zn,subagentDelegationMode:gt}:zn)),ie.patchSession(V,cn,{subagentDelegationMode:gt}).then(vn=>{ne(zn=>zn.map(_a=>_a.id===vn.id?vn:_a))}).catch(vn=>{ne(zn=>zn.map(_a=>_a.id===cn?{..._a,subagentDelegationMode:fa}:_a)),et(vn instanceof Error?vn.message:String(vn))})},[V,Ee,et,ne]),_o=y.useCallback(gt=>{g(cn=>cn[gt.session.id]===gt.events?cn:{...cn,[gt.session.id]:gt.events}),G(cn=>vp(cn,gt.session))},[G]),{answerCreateImproveQuestion:Gr,applyCreateImproveCandidate:wa,approveCreateImproveRun:_l,cancelCreateImproveRun:rr,changeDraftProvider:Gi,openCreateImprovePullRequest:pa,reconcileCreateImprovePullRequest:Cl,rejectCreateImproveCandidate:Rl,pauseCreateImproveRun:Mn,resumeCreateImproveRun:Co,reviseCreateImproveRun:Oa,sendPrompt:ti,stopTurn:sr}=Nne({applyBootstrapPayload:Ne,bootstrap:h,chatMessages:Rt,connection:V,codexPermissionMode:N,codexReasoningEffort:z,openPondCommandAccessMode:st,draftModel:P,draftProvider:w,experience:j,expandProject:Gn,getPrompt:t.getSnapshot,apps:h?.apps??[],connectedAppMentions:xn,mentionedAppId:a,ensureCloudSessionReady:wl,refreshWorkspace:De,refreshWorkspaceDiff:Yt,selectedApp:xe,selectedActionCatalog:da,openPondActionCatalog:Wn,cloudProjects:h?.cloudProjects??[],accountScopeKey:Nt,selectedCloudProject:Oe,selectedProject:Te,selectedProjectLinkedOpenPondApp:Ue,selectedSession:Ee,sessions:fe,workspaceTarget:Jn.value,subagentDelegationMode:Ee?.subagentDelegationMode??C,setDraftModel:Xe,setDraftProvider:Fe,setError:et,setPrompt:Le,setMentionedAppId:o,setCodexHistoryEvents:Xn,setCodexHistorySessions:G,onCodexHistoryTurnActivityChange:k,onCodexHistoryTurnPayload:_o,onPendingUserMessage:ln,setEvents:se,setSelectedAppId:ke,setSelectedProjectId:ue,setSelectedSessionId:Ie,setSessions:ne,setView:je,setWorkspaceBusy:pt}),{archiveSession:Ro,restoreSession:Pl,renameSession:Jr,toggleProjectPinned:lr,toggleSessionPinned:Ji,toggleSessionSavedForLater:Po}=uae({appPreferences:_t,connection:V,selectedSessionId:M,setAppPreferences:_,setCodexHistorySessions:G,setError:et,setSelectedSessionId:Ie,setSessions:ne}),{changeWorkspaceTarget:Ao,moveProjectToCloud:Zr,startCloudSetupUpload:Yr}=Wne({account:kn,accountPending:Pn,accountSignedOut:Zt,activeWorkspaceKind:Un,activeWorkspaceLocation:Wt,appDispatch:n,applyBootstrapPayload:Ne,busy:F,cloudSetupDialog:r,cloudProjects:h?.cloudProjects??[],connection:V,defaultTeamId:Ct.defaultTeamId,expandProject:Gn,localProjectById:Se,selectedCloudProject:Oe,selectedProject:Te,selectedSession:Ee,selectedSessionProjectId:Ln,setCloudSetupDialog:s,setDiffPanelOpen:Ze,setError:et,setSessions:ne,setWorkspaceBusy:pt,showToast:dt,visibleWorkspaceState:nt,workspaceBusy:wn}),$a=y.useCallback(async gt=>{if(j==="work"&&!Ee){if(gt==="local"){ua("local"),dt(Te?`Next task will use the local ${Te.name} checkout.`:"Next task will use an app-managed local workspace.","info");return}if(gt==="cloud"&&!Te&&!Oe){if(Pn){dt("Checking OpenPond account. Try again in a moment.","info");return}if(Zt){dt("Add an OpenPond account before using Hosted.","error");return}ua("cloud"),dt("Next task will use Hosted without a Project.","info");return}}if(gt==="hybrid"){const cn=Oe?.id??Tn?.id??Ee?.cloudProjectId??null,fa=Oe?.teamId??Tn?.teamId??Ee?.cloudTeamId??null;if(Pn){dt("Checking OpenPond account. Try again in a moment.","info");return}if(Zt){dt("Add an OpenPond account before using Hybrid.","error");return}if(!cn||!fa){ua(null),dt("Upload/sync this Project to Cloud before using Hybrid.","error");return}if(Ee&&!Jt(Ee.id)){if(zi(Ee))return;if(!V){dt("OpenPond App server is not connected.","error");return}const vn=await ie.patchSession(V,Ee.id,{provider:w,modelRef:ii(w,P,h?.providers??null),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:null,workspaceName:Oe?.name??Tn?.name??Te?.name??Ee.workspaceName??"Hybrid workspace",localProjectId:Te?.id??Ee.localProjectId??null,cloudProjectId:cn,cloudTeamId:fa,metadata:_A(Ee.metadata),cwd:Te?.workspacePath??Ee.cwd??null});ne(zn=>zn.map(_a=>_a.id===vn.id?vn:_a)),ua(null),dt("Hybrid will use your selected model with hosted sandbox edits.","info");return}ua("hybrid"),dt("Next message will use Hybrid with a hosted sandbox.","info");return}ua(null),await Ao(gt)},[Pn,Zt,j,h?.providers,Ao,V,P,w,Oe?.id,Oe?.name,Oe?.teamId,Te?.id,Tn?.id,Tn?.name,Tn?.teamId,Te?.name,Te?.workspacePath,Ee,ua,ne,dt]),Na=y.useCallback((gt,cn)=>{ke(null),ue(gt),Ie(null),je("chat"),Gn(gt),In({projectId:gt,target:cn})},[Gn,ke,ue,Ie,je]);y.useEffect(()=>{if(!bi||A!=="chat"||$!==bi.projectId||M!==null)return;const gt=bi.target;In(null),$a(gt)},[$a,bi,$,M,A]);const Qr=Gne({advanceTrainingTurn:ei,bindTrainingSession:wt,composerDraftStore:t,onSessionCreated:gt=>{Ie(gt.id),je("chat"),Vt({kind:"chat",sessionId:gt.id}),R(null)},onSubmitted:async()=>{const gt=Ee;if(!(!V||!gt||!zc(gt)))try{const cn=await ie.patchSession(V,gt.id,{metadata:X8(gt.metadata)});ne(fa=>fa.map(vn=>vn.id===cn.id?cn:vn))}catch(cn){dt(cn instanceof Error?`Task started, but its Draft label could not be cleared: ${cn.message}`:"Task started, but its Draft label could not be cleared.","error")}},prepareTrainingTurn:pn,sendPrompt:ti,setMentionedAppId:o,showToast:dt}),cr=Jne({appDispatch:n,connection:V,sessions:fe,setDiffPanelOpen:Ze,setRightPanelMode:Be,setSessions:ne,setView:je}),{createCloudEnvironmentFromSidebar:Si,openCloudProjectDialog:dr,openUrlInBrowserPanel:Zi,showBrowserPanel:Xr,showChangesPanel:es,showGoalSidebarTab:ts}=ine({account:kn,browserConversationId:ma,cloudProjectById:ge,cloudProjects:h?.cloudProjects??[],diffPanelOpen:te,rightPanelMode:re,selectedProjectId:$,setDiffPanelOpen:Ze,setNewProjectDialogOpen:J,setNewProjectMode:q,setNewProjectName:oe,setRightPanelMode:Be}),{changeProjectTarget:Al,submitNewProjectDialog:ns}=Yne({appDispatch:n,busy:F,cloudProjectById:ge,createCloudProjectFromScratch:It,createProjectFromScratch:bl,createProjectCollection:or,expandProject:Gn,localProjectById:Se,newProjectBusy:X,newProjectMode:L,newProjectName:de,onCreateCloudEnvironment:Si,onNewCloudProject:dr,onNewLocalProject:Io,onUseExistingFolderPath:wo,projectTargetValue:Ki.value,setDiffPanelOpen:Ze,setDraftModel:Xe,setDraftProvider:Fe,setError:et,setNewProjectBusy:Re,setNewProjectDialogOpen:J,setNewProjectName:oe,setNewProjectPath:he,showToast:dt,workspaceBusy:wn}),as=y.useMemo(()=>fe.map(gt=>gt.id),[fe]);rne({browserConversationId:ma,sessionIds:as,onOpenSession:ir,onShowBrowserPanel:Xr});const[Tl,To]=y.useState(null),is=y.useCallback(gt=>{To({id:Date.now(),objective:gt.objective,initialSessionIds:gt.sessionId?[gt.sessionId]:[]}),Ar(Fa()),je("labs")},[je]),{activateRightChatPanel:ur,closeRightChatPanel:xi,openRightChatPanel:El,rightChatPanelViews:Ml,showRightChatPanel:jl,showRightPanelDiffTab:Ol,submitRightChatPrompt:ki,updateRightChatModel:os,updateRightChatPrompt:$l,updateRightChatProvider:Nl,updateRightChatScrollState:Dl}=dae({activeModel:Dn,activeProvider:An,approvals:Ye,applyRightCodexHistoryPayload:_o,codexHistoryEvents:xt,connectedAppMentions:xn,connection:V,contextCompaction:Ct.contextCompaction,openLabTraining:is,locallyActiveCodexHistorySessionIds:x,openPondCommandAccessMode:D,pendingChatUserMessages:ut,providerSettings:h?.providers??null,rightChatHistoryEvents:f,rightChatPanels:K,rightPanelMode:re,runtimeIndexes:ht,runtimeEventStore:we,runningSessionIds:ta,selectedSession:Ee,selectedSessionId:M,sendPrompt:ti,setDiffPanelOpen:Ze,setError:et,setRightChatHistoryEvents:g,setRightChatPanels:Ge,setRightPanelMode:Be,setRightPanelTabRequest:l,setView:je,showChangesPanel:es,showToast:dt,sidebarSessions:tt,startupReady:Y.ready}),Ia=y.useCallback(()=>{be(null),U("profile"),je("settings"),Vt({kind:"settings",section:"profile"})},[be,U,je]),rs=y.useMemo(()=>ao(h?.diagnostics??kae,ae.filter(gt=>gt.name==="diagnostic")),[h?.diagnostics,ae]),Hl=y.useCallback(()=>{if(te){Ze(!1);return}if(A==="labs"){Be("changes"),l({id:Date.now(),tab:"summary"}),Ze(!0);return}Be("home"),Ze(!0)},[te,Ze,Be,l,A]);return{title:ja,browserConversationId:ma,handleWorkspaceDiffPanelViewStateChange:ko,openSessionInChat:ir,openExistingProjectPathDialog:wo,removeProject:yl,changeProjectTarget:Al,submitNewProjectDialog:ns,changeWorkspaceBranch:zr,openCommitDialog:Sl,openCreateWorkspaceBranchDialog:Wi,openDefaultsSettingsFromBranchDialog:xl,runWorkspaceTool:Br,submitCommitDialog:Fr,submitCreateWorkspaceBranch:Vr,syncWorkspaceLocally:kl,subagentDelegationDefaultMode:yi,subagentDelegationMode:Il,subagentDelegationAvailable:Kr,changeSubagentDelegationMode:Wr,answerCreateImproveQuestion:Gr,applyCreateImproveCandidate:wa,approveCreateImproveRun:_l,cancelCreateImproveRun:rr,changeDraftProvider:Gi,openCreateImprovePullRequest:pa,reconcileCreateImprovePullRequest:Cl,rejectCreateImproveCandidate:Rl,pauseCreateImproveRun:Mn,resumeCreateImproveRun:Co,reviseCreateImproveRun:Oa,sendPrompt:ti,stopTurn:sr,archiveSession:Ro,restoreSession:Pl,renameSession:Jr,toggleProjectPinned:lr,toggleSessionPinned:Ji,toggleSessionSavedForLater:Po,moveProjectToCloud:Zr,startCloudSetupUpload:Yr,changeWorkspaceTarget:$a,switchProjectWorkspaceTarget:Na,sendPromptFromMainComposer:Qr,openSandboxWorkspace:cr,createCloudEnvironmentFromSidebar:Si,openCloudProjectDialog:dr,openUrlInBrowserPanel:Zi,showBrowserPanel:Xr,showChangesPanel:es,showGoalSidebarTab:ts,rightChatTrainingLaunchRequest:Tl,setRightChatTrainingLaunchRequest:To,closeRightChatPanel:xi,openRightChatPanel:El,rightChatPanelViews:Ml,showRightChatPanel:jl,showRightPanelDiffTab:Ol,submitRightChatPrompt:ki,activateRightChatPanel:ur,updateRightChatModel:os,updateRightChatPrompt:$l,updateRightChatProvider:Nl,updateRightChatScrollState:Dl,openProfileSettings:Ia,diagnosticEvents:rs,toggleRightSidebar:Hl}}const Iae=_E();function _ae(){return S.jsx(UT,{client:Iae,children:S.jsx(Cae,{})})}function Cae(){const e=Yte(),t=wae(e);return S.jsx(SZ,{primary:e,secondary:t})}const Ire=Object.freeze(Object.defineProperty({__proto__:null,App:_ae},Symbol.toStringTag,{value:"Module"}));export{nr as $,$E as A,gW as B,Go as C,w8 as D,al as E,hP as F,ie as G,Vo as H,J8 as I,hoe as J,goe as K,yP as L,W8 as M,HW as N,Ay as O,e8 as P,n1 as Q,xr as R,$g as S,Wy as T,Qn as U,fre as V,TA as W,Sd as X,Woe as Y,yre as Z,Cc as _,wx as a,Ux as a$,vre as a0,Vg as a1,Soe as a2,Voe as a3,DZ as a4,wre as a5,Cne as a6,Foe as a7,Koe as a8,rre as a9,UW as aA,Ih as aB,Jt as aC,io as aD,UA as aE,Ooe as aF,lZ as aG,Bee as aH,joe as aI,aZ as aJ,ore as aK,zee as aL,La as aM,Ui as aN,PT as aO,iae as aP,oae as aQ,tne as aR,$oe as aS,z8 as aT,cy as aU,dP as aV,mp as aW,Zoe as aX,wy as aY,N8 as aZ,poe as a_,ere as aa,hJ as ab,ii as ac,$J as ad,ks as ae,Ok as af,Xoe as ag,Yoe as ah,Qoe as ai,Yk as aj,dv as ak,Tu as al,NW as am,i8 as an,Joe as ao,Og as ap,vm as aq,FA as ar,mm as as,pp as at,BW as au,l8 as av,gP as aw,eie as ax,pre as ay,RW as az,aX as b,Uoe as b$,bP as b0,dJ as b1,Yg as b2,PZ as b3,Sre as b4,xZ as b5,Zx as b6,gp as b7,uJ as b8,qy as b9,Jae as bA,sW as bB,xre as bC,kp as bD,BP as bE,koe as bF,Bc as bG,Mae as bH,jae as bI,woe as bJ,KW as bK,Fa as bL,Ar as bM,c as bN,i as bO,p as bP,ct as bQ,jm as bR,dy as bS,uP as bT,yd as bU,Doe as bV,zoe as bW,Boe as bX,Qx as bY,Loe as bZ,Dh as b_,NP as ba,AW as bb,voe as bc,boe as bd,W$ as be,r8 as bf,sZ as bg,rZ as bh,sy as bi,n8 as bj,pP as bk,ly as bl,Yae as bm,Ov as bn,xoe as bo,foe as bp,py as bq,SP as br,Vt as bs,x8 as bt,BA as bu,ya as bv,Zae as bw,Rv as bx,Pv as by,ru as bz,rt as c,P_ as c$,qoe as c0,Hoe as c1,Yx as c2,Noe as c3,Dt as c4,PD as c5,Xae as c6,PA as c7,tie as c8,coe as c9,Ef as cA,bc as cB,cE as cC,Fn as cD,va as cE,m1 as cF,wE as cG,Oae as cH,Z1 as cI,Km as cJ,rie as cK,Qa as cL,s4 as cM,pi as cN,iie as cO,Fm as cP,cd as cQ,lt as cR,Lt as cS,sd as cT,vt as cU,T as cV,B_ as cW,v4 as cX,fh as cY,L_ as cZ,a4 as c_,u as ca,v as cb,He as cc,ot as cd,b as ce,Ys as cf,ld as cg,Tt as ch,I as ci,GP as cj,y7 as ck,OG as cl,ch as cm,Qae as cn,yoe as co,Coe as cp,Roe as cq,Poe as cr,Aoe as cs,D8 as ct,Ioe as cu,_oe as cv,rE as cw,Tae as cx,Aae as cy,Vc as cz,xee as d,qS as d$,Fz as d0,r4 as d1,p4 as d2,die as d3,d4,k4 as d5,ye as d6,W as d7,H as d8,$_ as d9,moe as dA,JV as dB,rV as dC,Hie as dD,Lie as dE,uoe as dF,bie as dG,fd as dH,Y1 as dI,on as dJ,Gie as dK,soe as dL,Ub as dM,AK as dN,Jie as dO,fy as dP,iy as dQ,Qie as dR,p_ as dS,mu as dT,nie as dU,Cn as dV,d_ as dW,ce as dX,eJ as dY,od as dZ,pb as d_,w_ as da,h4 as db,H_ as dc,lie as dd,sie as de,b4 as df,D_ as dg,Sb as dh,yb as di,N_ as dj,Wm as dk,Gm as dl,pie as dm,cie as dn,g4 as dp,c4 as dq,HK as dr,loe as ds,Moe as dt,Iie as du,_ie as dv,Q3 as dw,Tie as dx,f6 as dy,Aie as dz,IE as e,la as e$,aie as e0,Ac as e1,C4 as e2,Ke as e3,Xa as e4,Uz as e5,kie as e6,wie as e7,gie as e8,SR as e9,Bi as eA,qU as eB,tu as eC,id as eD,xie as eE,q3 as eF,tre as eG,nre as eH,oie as eI,mie as eJ,fie as eK,uie as eL,Pie as eM,Rie as eN,si as eO,hie as eP,N4 as eQ,ap as eR,sR as eS,jie as eT,Bie as eU,zie as eV,Uie as eW,Yie as eX,vie as eY,eC as eZ,Lr as e_,Cie as ea,i6 as eb,Nie as ec,$R as ed,Die as ee,cC as ef,$ie as eg,Oie as eh,yie as ei,pc as ej,OR as ek,e4 as el,ioe as em,noe as en,ooe as eo,roe as ep,eoe as eq,Pm as er,aoe as es,toe as et,bd as eu,em as ev,fb as ew,le as ex,Li as ey,Zie as ez,gm as f,a3 as f0,J4 as f1,qie as f2,V9 as f3,vd as f4,Fie as f5,Wie as f6,Kie as f7,Vie as f8,A9 as f9,cre as fA,sre as fB,lre as fC,fte as fD,xae as fE,dre as fF,ure as fG,mre as fH,yx as fI,Ire as fJ,Y9 as fa,Jm as fb,I8 as fc,E8 as fd,doe as fe,Eie as ff,Mie as fg,fp as fh,are as fi,ire as fj,Sie as fk,uo as fl,RC as fm,WF as fn,Xo as fo,Ko as fp,LS as fq,Eoe as fr,mP as fs,Zk as ft,ene as fu,Zg as fv,kA as fw,oA as fx,xA as fy,kre as fz,Jo as g,uW as h,Ai as i,up as j,G8 as k,PP as l,Uc as m,Goe as n,Toe as o,bx as p,ry as q,OP as r,qK as s,hne as t,s1 as u,hre as v,bre as w,_T as x,gre as y,B as z};
|