openpond 0.2.24 → 0.2.26
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/{actions-command-S27YU6NW.js → actions-command-NOCBOF5S.js} +1 -1
- package/dist/chunks/{app-layer-57323XKJ.js → app-layer-GLXYIT4B.js} +1 -1
- package/dist/chunks/app-server-runtime-AN4K6VLN.js +2 -0
- package/dist/chunks/{apps-U3TXSPU6.js → apps-YSWZT656.js} +1 -1
- package/dist/chunks/chunk-2LSP2AAN.js +166 -0
- package/dist/chunks/{chunk-K5IJNSHP.js → chunk-3YSCXFE6.js} +3 -3
- package/dist/chunks/{chunk-NVVETL4F.js → chunk-44ZSILEZ.js} +1 -1
- package/dist/chunks/{chunk-B3LJ777T.js → chunk-4G5UTX4U.js} +1 -1
- package/dist/chunks/{chunk-YNH6AUGE.js → chunk-6ZK5EZGN.js} +2 -2
- package/dist/chunks/{chunk-WTZYPCLS.js → chunk-B2WPTD3H.js} +1 -1
- package/dist/chunks/{chunk-TR37PJIQ.js → chunk-ETH4SZO6.js} +11 -28
- package/dist/chunks/{chunk-KLSLHUTO.js → chunk-I7XD5OBR.js} +1 -1
- package/dist/chunks/{chunk-F3VURV3Q.js → chunk-JKMPJFMN.js} +2 -2
- package/dist/chunks/{chunk-4KDHMGKI.js → chunk-JPCPNW6T.js} +1 -1
- package/dist/chunks/chunk-L3KS6MOV.js +2 -0
- package/dist/chunks/chunk-MAMUNDBZ.js +26 -0
- package/dist/chunks/{chunk-WK5HTGXV.js → chunk-P57W2CB2.js} +1 -1
- package/dist/chunks/{chunk-4D3JNBSP.js → chunk-PNULH6UG.js} +333 -333
- package/dist/chunks/chunk-TOIG2PMH.js +19 -0
- package/dist/chunks/{chunk-AC2M2HO3.js → chunk-WVUPFGU7.js} +1 -1
- package/dist/chunks/chunk-XLF7VRKY.js +2 -0
- package/dist/chunks/{chunk-M4VGRNP6.js → chunk-Y2KDWP74.js} +1 -1
- package/dist/chunks/cli-H3KOANKJ.js +2 -0
- package/dist/chunks/{configuration-command-BASDSNVK.js → configuration-command-VGYAJAKN.js} +1 -1
- package/dist/chunks/{core-commands-YQTVPPLJ.js → core-commands-QQNCA4WQ.js} +1 -1
- package/dist/chunks/{desktop-test-JITAYXCK.js → desktop-test-BMDAEN6Z.js} +1 -1
- package/dist/chunks/{extension-ZKWQ3ZPJ.js → extension-IQW2KDT6.js} +5 -5
- package/dist/chunks/{help-SDEZHWZL.js → help-DZBHIKVE.js} +1 -1
- package/dist/chunks/{opchat-IOP37GN3.js → opchat-BSTDLB7O.js} +1 -1
- package/dist/chunks/organizations-LAUKUPDF.js +2 -0
- package/dist/chunks/profile-ESJFHPYC.js +3 -0
- package/dist/chunks/{project-agent-DALYNEZ4.js → project-agent-CPQP4ZY6.js} +1 -1
- package/dist/chunks/{sandbox-command-VHCKLKN5.js → sandbox-command-W6NWHFAR.js} +1 -1
- package/dist/chunks/{sandbox-template-WY7XIMDK.js → sandbox-template-SM62NUMJ.js} +1 -1
- package/dist/chunks/{src-22KEI2VU.js → src-4L62URN6.js} +1 -1
- package/dist/chunks/{src-DT7YDHH6.js → src-K3J2DSVY.js} +113 -109
- package/dist/chunks/{teams-bot-47H7LRFD.js → teams-bot-6LEMA4OH.js} +1 -1
- package/dist/chunks/{workspaces-QCCYGHZG.js → workspaces-BXILKKGY.js} +1 -1
- package/dist/cli.js +1 -1
- package/dist/index.js +1 -1
- package/dist/web/assets/App-eRfSvxdE.js +226 -0
- package/dist/web/assets/{AppDialog-C3H3HARP.js → AppDialog-FvWvdWfk.js} +1 -1
- package/dist/web/assets/{AppTerminalPanel-DIXARKfe.js → AppTerminalPanel-Dfo_tXAE.js} +2 -2
- package/dist/web/assets/{AppsView-D0xPDTPJ.js → AppsView-CKg2_SXF.js} +1 -1
- package/dist/web/assets/{BrowserSidebar-D5eE9O30.js → BrowserSidebar-CBRz9dVj.js} +1 -1
- package/dist/web/assets/{CartesianChart-KMVbiMJX.js → CartesianChart-iXtVfIXm.js} +1 -1
- package/dist/web/assets/{CollaborationTabs-C1LTvUbK.js → CollaborationTabs-BFuRwsEy.js} +1 -1
- package/dist/web/assets/{CommandMenu-C9elnZaI.js → CommandMenu-Coahy7-K.js} +1 -1
- package/dist/web/assets/{CommunityView-BvXxVHmL.js → CommunityView-C0B6EVIp.js} +1 -1
- package/dist/web/assets/{ComposerCreateImproveStrip-Cwu8EaCb.js → ComposerCreateImproveStrip-C0MkRhov.js} +1 -1
- package/dist/web/assets/{GetStartedView-BI1j30-I.js → GetStartedView-f90pfPRp.js} +1 -1
- package/dist/web/assets/HostedModelLearningReview-DdZnSPKb.js +1 -0
- package/dist/web/assets/{HostedModelLearningSettings-DhaT1bxX.js → HostedModelLearningSettings-p9RdBxGd.js} +1 -1
- package/dist/web/assets/{LabModelVersionDetailPage-CeSm-sAq.js → LabModelVersionDetailPage-DLqT1fMT.js} +1 -1
- package/dist/web/assets/{LabSkillSidebar-BzGs7EC8.js → LabSkillSidebar-C7BuAuNK.js} +1 -1
- package/dist/web/assets/{LabsRoute-BQi8W0-2.js → LabsRoute-CUVbklNy.js} +4 -4
- package/dist/web/assets/{MainChatThread-D3KXQ4Te.js → MainChatThread-Crjs_iFv.js} +2 -2
- package/dist/web/assets/{MainPane-J15DRf-n.js → MainPane-Bl91XbhC.js} +7 -7
- package/dist/web/assets/{MarkdownText-BWIVACAt.js → MarkdownText-DV3sDJG3.js} +1 -1
- package/dist/web/assets/{Messages-BPbo8ih9.js → Messages-Bxo_ATcK.js} +1 -1
- package/dist/web/assets/{NativeSkillSidebar-BeqI4dXF.js → NativeSkillSidebar-B3wc0iGh.js} +1 -1
- package/dist/web/assets/{NewExperienceSwitcher-BggrQVIi.js → NewExperienceSwitcher-DBdsaysM.js} +1 -1
- package/dist/web/assets/{NewProjectDialog-B4PTFf78.js → NewProjectDialog-CtJJ6u5l.js} +1 -1
- package/dist/web/assets/{OutputsPage-DChjcyaP.js → OutputsPage-CV9rYjbQ.js} +1 -1
- package/dist/web/assets/{ProjectsPage-BdUkyg6I.js → ProjectsPage-O162K_Yb.js} +1 -1
- package/dist/web/assets/{RightChatPanelStack-CLCOzLVJ.js → RightChatPanelStack-CXzHpD5V.js} +1 -1
- package/dist/web/assets/{RightSidebarHomePanel-qs2Fa4JQ.js → RightSidebarHomePanel-DweT04nf.js} +1 -1
- package/dist/web/assets/ScheduledWorkPage-DFvjzhvz.js +1 -0
- package/dist/web/assets/SettingsView-B-O30p4h.js +9 -0
- package/dist/web/assets/{TeamChatView-uGwanVsA.js → TeamChatView-BoQYnywK.js} +1 -1
- package/dist/web/assets/{TerminalOverlay-DJNdErEp.js → TerminalOverlay-oLOOTbdP.js} +1 -1
- package/dist/web/assets/{TrainingCreationPanel-CwyKMNwt.js → TrainingCreationPanel-aCFYDuYZ.js} +1 -1
- package/dist/web/assets/{TrainingDraftPanel-Rdusv4s_.js → TrainingDraftPanel-CFa1YRTU.js} +1 -1
- package/dist/web/assets/{UsageSettingsSection-BkRalGcP.js → UsageSettingsSection-CakaMl6_.js} +1 -1
- package/dist/web/assets/{WorkSidebarPanel-d8PB-XNy.js → WorkSidebarPanel-XFwuIBFa.js} +1 -1
- package/dist/web/assets/{WorkspaceDiffPanel-DfpyLroX.js → WorkspaceDiffPanel-CL-lAcvW.js} +3 -3
- package/dist/web/assets/{WorkspaceEnvironmentMenu-DhUUB-lq.js → WorkspaceEnvironmentMenu-DcFKeae1.js} +1 -1
- package/dist/web/assets/{WorkspaceGitDialogs-0juVLtVy.js → WorkspaceGitDialogs-CE6uwWBo.js} +1 -1
- package/dist/web/assets/{WorkspaceMonacoEditor-Blo5esSN.js → WorkspaceMonacoEditor-Dd1yWxIF.js} +3 -3
- package/dist/web/assets/{arrow-up-right-BXeo-8KJ.js → arrow-up-right-DrBHDOjJ.js} +1 -1
- package/dist/web/assets/{chat-file-links-BEbA_E33.js → chat-file-links-DKYaOINv.js} +1 -1
- package/dist/web/assets/chevron-up-CT-jxFh0.js +1 -0
- package/dist/web/assets/{clipboard-17OIp5F-.js → clipboard-BwxTBPCP.js} +1 -1
- package/dist/web/assets/{cloud-upload-D28o8URw.js → cloud-upload-Ce9uYXcQ.js} +1 -1
- package/dist/web/assets/{cssMode-DDPYV_bh.js → cssMode-DDD1HmKz.js} +1 -1
- package/dist/web/assets/{folder-open-CqBlANkk.js → folder-open-BmWqQp0P.js} +1 -1
- package/dist/web/assets/{folder-plus-DkUnvZhx.js → folder-plus-B402AJf4.js} +1 -1
- package/dist/web/assets/{git-commit-horizontal-BEIomQj0.js → git-commit-horizontal-C1uAivqm.js} +1 -1
- package/dist/web/assets/{htmlMode-gF-t3JxJ.js → htmlMode-1MNILRvh.js} +1 -1
- package/dist/web/assets/{index-C5EoPZr0.css → index-BZ4iTv8E.css} +1 -1
- package/dist/web/assets/{index-Dg_FWrRZ.js → index-CPTsOhRN.js} +2 -2
- package/dist/web/assets/{info-n9PKmODI.js → info-BNROwjpD.js} +1 -1
- package/dist/web/assets/{jsonMode-B5DVQ7wE.js → jsonMode-mGxJ8u70.js} +1 -1
- package/dist/web/assets/{lspLanguageFeatures-FK4QlUnB.js → lspLanguageFeatures-DnwAgCyz.js} +1 -1
- package/dist/web/assets/{minimize-2--J7-Zqg1.js → minimize-2-DFgldo5D.js} +1 -1
- package/dist/web/assets/{monaco.contribution-DCmsluF_.js → monaco.contribution-BlgPPKyd.js} +2 -2
- package/dist/web/assets/{monaco.contribution-DEkLSjvo.js → monaco.contribution-CBuz55_x.js} +2 -2
- package/dist/web/assets/{monaco.contribution-CV2W_Ydj.js → monaco.contribution-CGYtN1vj.js} +2 -2
- package/dist/web/assets/{monaco.contribution-CM_Srh4F.js → monaco.contribution-qZ9QzQ68.js} +2 -2
- package/dist/web/assets/{play-CT6lFZDI.js → play-BQFyTfNz.js} +1 -1
- package/dist/web/assets/{python-DQHHAEpa.js → python-CpsWHcA8.js} +1 -1
- package/dist/web/assets/{refresh-cw-Cm-4hHSn.js → refresh-cw-DfFBmfXv.js} +1 -1
- package/dist/web/assets/{save-CwgR_oyc.js → save-8XYI0E0Y.js} +1 -1
- package/dist/web/assets/{square-DPrPBeHW.js → square-FQ0GLxuE.js} +1 -1
- package/dist/web/assets/{toggleHighContrast-C1QZjrPj.js → toggleHighContrast-CX2hgvvU.js} +1 -1
- package/dist/web/assets/{tsMode-DY4Ji1ac.js → tsMode-D9XBNmxG.js} +1 -1
- package/dist/web/assets/{upload-DABGNAIq.js → upload-BNXILcvp.js} +1 -1
- package/dist/web/assets/{useLocalAgentSchedules-D5P28Jej.js → useLocalAgentSchedules-Ccst1Wnz.js} +1 -1
- package/dist/web/assets/{wifi-off-CJOdJJRb.js → wifi-off-BoQdtnnN.js} +1 -1
- package/dist/web/assets/{workers-BLjr7D_D.js → workers-DpMJzLwE.js} +1 -1
- package/dist/web/assets/{yaml-eXk00scV.js → yaml-BqS3gPsN.js} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/chunks/app-server-runtime-AOSX4AH5.js +0 -2
- package/dist/chunks/chunk-D6BBQHZM.js +0 -28
- package/dist/chunks/chunk-M4CJXPMH.js +0 -26
- package/dist/chunks/cli-WZ5H6EPA.js +0 -2
- package/dist/chunks/organizations-4LQEILYG.js +0 -2
- package/dist/chunks/profile-MVLYUDLU.js +0 -3
- package/dist/web/assets/App-BzNZ7ycx.js +0 -176
- package/dist/web/assets/HostedModelLearningReview-Bwkg3lyV.js +0 -1
- package/dist/web/assets/ScheduledWorkPage-DzehKDhk.js +0 -1
- package/dist/web/assets/SettingsView-DJiJKYWW.js +0 -9
- package/dist/web/assets/chevron-up-Dx5rir4H.js +0 -1
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CommandMenu-Coahy7-K.js","./index-CPTsOhRN.js","./index-BZ4iTv8E.css","./CommandMenu-Cb3vNGJr.css","./SettingsView-B-O30p4h.js","./refresh-cw-DfFBmfXv.js","./chat-file-links-DKYaOINv.js","./save-8XYI0E0Y.js","./folder-open-BmWqQp0P.js","./chevron-up-CT-jxFh0.js","./play-BQFyTfNz.js","./wifi-off-BoQdtnnN.js","./useLocalAgentSchedules-Ccst1Wnz.js","./cloud-upload-Ce9uYXcQ.js","./git-commit-horizontal-C1uAivqm.js","./folder-plus-B402AJf4.js","./AppDialog-FvWvdWfk.js","./WorkspaceDiffPanel-CL-lAcvW.js","./MarkdownText-DV3sDJG3.js","./desktop-files-BQj1J-ob.js","./training-model-data-CKOkpBBL.js","./info-BNROwjpD.js","./minimize-2-DFgldo5D.js","./clipboard-BwxTBPCP.js","./SettingsView-BaWWvIJW.css","./git-dialogs-BZDqS1eT.css","./NewProjectDialog-CtJJ6u5l.js","./WorkspaceGitDialogs-CE6uwWBo.js","./upload-BNXILcvp.js","./WorkspaceEnvironmentMenu-DcFKeae1.js","./square-FQ0GLxuE.js","./WorkspaceEnvironmentMenu-DGIFdG3o.css","./MainPane-Bl91XbhC.js","./arrow-up-right-DrBHDOjJ.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as g,j as x,a as GC,_ as Gr}from"./index-CPTsOhRN.js";const wS=g.createContext(void 0),IS=e=>{const t=g.useContext(wS);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},ZC=({client:e,children:t})=>(g.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),x.jsx(wS.Provider,{value:e,children:t})),JC={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)};var YC=class{#e=JC;#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 Or=new YC;function QC(e){setTimeout(e,0)}const XC=typeof window>"u"||"Deno"in globalThis;function Qn(){}function eR(e,t){return typeof e=="function"?e(t):e}function _S(e){return typeof e=="number"&&e>=0&&e!==1/0}function CS(e,t){return Math.max(e+(t||0)-Date.now(),0)}function an(e,t){return typeof e=="function"?e(t):e}function jv(e,t){const{type:n="all",exact:a,fetchStatus:o,predicate:i,queryKey:s,stale:l}=e;if(s){if(a){if(t.queryHash!==yh(s,t.options))return!1}else if(!Yi(t.queryKey,s))return!1}if(n!=="all"){const m=t.isActive();if(n==="active"&&!m||n==="inactive"&&m)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||o&&o!==t.state.fetchStatus||i&&!i(t))}function Ov(e,t){const{exact:n,status:a,predicate:o,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Rl(t.options.mutationKey)!==Rl(i))return!1}else if(!Yi(t.options.mutationKey,i))return!1}return!(a&&t.state.status!==a||o&&!o(t))}function yh(e,t){return(t?.queryKeyHashFn||Rl)(e)}function Rl(e){return JSON.stringify(e,(t,n)=>mf(n)?Object.keys(n).sort().reduce((a,o)=>(a[o]=n[o],a),{}):n)}function Yi(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(!Yi(e[a],t[a]))return!1;return!0}const n=Object.keys(t);for(const a of n)if(!Yi(e[a],t[a]))return!1;return!0}return!1}const tR=Object.prototype.hasOwnProperty;function RS(e,t,n=0){if(e===t)return e;if(n>500)return t;const a=$v(e)&&$v(t);if(!a&&!(mf(e)&&mf(t)))return t;const o=(a?e:Object.keys(e)).length,i=a?t:Object.keys(t),s=i.length,l=a?new Array(s):{};let m=0;for(let d=0;d<s;d++){const h=a?d:i[d],v=e[h],y=t[h];if(v===y){l[h]=v,(a?d<o:tR.call(e,h))&&m++;continue}if(v===null||y===null||typeof v!="object"||typeof y!="object"){l[h]=y;continue}const w=RS(v,y,n+1);l[h]=w,w===v&&m++}return o===s&&m===o?e:l}function Zm(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 $v(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function mf(e){if(!Nv(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!Nv(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Nv(e){return Object.prototype.toString.call(e)==="[object Object]"}function nR(e){return new Promise(t=>{Or.setTimeout(t,e)})}function pf(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?RS(e,t):t}function aR(e,t,n=0){const a=[...e,t];return n&&a.length>n?a.slice(1):a}function oR(e,t,n=0){const a=[t,...e];return n&&a.length>n?a.slice(0,-1):a}const Sh=Symbol();function PS(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Sh?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function AS(e,t){return typeof e=="function"?e(...t):!!e}function rR(e,t,n){let a=!1,o;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(o??=t(),a||(a=!0,o.aborted?n():o.addEventListener("abort",n,{once:!0})),o)}),e}let iR=()=>XC;const kh=()=>iR();var Wl=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(){}},sR=class extends Wl{#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 xh=new sR,lR=QC;function cR(){let e=[],t=0,n=l=>{l()},a=l=>{l()},o=lR;const i=l=>{t?e.push(l):o(()=>{n(l)})},s=()=>{const l=e;e=[],l.length&&o(()=>{a(()=>{l.forEach(m=>{n(m)})})})};return{batch:l=>{let m;t++;try{m=l()}finally{t--,t||s()}return m},batchCalls:l=>(...m)=>{i(()=>{l(...m)})},schedule:i,setNotifyFunction:l=>{n=l},setBatchNotifyFunction:l=>{a=l},setScheduler:l=>{o=l}}}const An=cR();var dR=class extends Wl{#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 kd=new dR;function uR(e){return Math.min(1e3*2**e,3e4)}function TS(e){return(e??"online")==="online"?kd.isOnline():!0}var ff=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function ES(e){let t=!1,n=0,a,o="pending",i,s;const l=new Promise((N,O)=>{i=N,s=O});l.catch(Qn);const m=()=>o!=="pending",d=N=>{if(!m()){const O=new ff(N);R(O),e.onCancel?.(O)}},h=()=>{t=!0},v=()=>{t=!1},y=()=>xh.isFocused()&&(e.networkMode==="always"||kd.isOnline())&&e.canRun(),w=()=>TS(e.networkMode)&&e.canRun(),I=N=>{m()||(a?.(),o="resolved",i(N))},R=N=>{m()||(a?.(),o="rejected",s(N))},M=()=>new Promise(N=>{a=O=>{(m()||y())&&N(O)},e.onPause?.()}).then(()=>{a=void 0,m()||e.onContinue?.()}),P=()=>{if(m())return;let N;const O=n===0?e.initialPromise:void 0;try{N=O??e.fn()}catch(j){N=Promise.reject(j)}Promise.resolve(N).then(I).catch(j=>{if(m())return;const k=e.retry??(kh()?0:3),C=e.retryDelay??uR,T=typeof C=="function"?C(n,j):C,z=k===!0||typeof k=="number"&&n<k||typeof k=="function"&&k(n,j);if(t||!z){R(j);return}n++,e.onFail?.(n,j),nR(T).then(()=>y()?void 0:M()).then(()=>{t?R(j):P()})})};return{promise:l,status:()=>o,cancel:d,continue:()=>(a?.(),l),cancelRetry:h,continueRetry:v,canStart:w,start:()=>(w()?P():M().then(P),l)}}var MS=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),_S(this.gcTime)&&(this.#e=Or.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(kh()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(Or.clearTimeout(this.#e),this.#e=void 0)}};function mR(e){return{onFetch:(t,n)=>{const a=t.options,o=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],s=t.state.data?.pageParams||[];let l={pages:[],pageParams:[]},m=0;const d=async()=>{let h=!1;const v=I=>{rR(I,()=>t.signal,()=>h=!0)},y=PS(t.options,t.fetchOptions),w=async(I,R,M)=>{if(h)return Promise.reject(t.signal.reason);if(R==null&&I.pages.length)return Promise.resolve(I);const N=(()=>{const C={client:t.client,queryKey:t.queryKey,pageParam:R,direction:M?"backward":"forward",meta:t.options.meta};return v(C),C})(),O=await y(N),{maxPages:j}=t.options,k=M?oR:aR;return{pages:k(I.pages,O,j),pageParams:k(I.pageParams,R,j)}};if(o&&i.length){const I=o==="backward",R=I?pR:Dv,M={pages:i,pageParams:s};l=await w(M,R(a,M),I)}else{const I=e??i.length;do{const R=m===0?s[0]??a.initialPageParam:Dv(a,l);if(m>0&&R==null)break;l=await w(l,R),m++}while(m<I)}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 Dv(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 pR(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var fR=class extends MS{#e;#t;#n;#a;#r;#o;#i;#l;constructor(e){super(),this.#l=!1,this.#i=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#r=e.client,this.#a=this.#r.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=Uv(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#o?.promise}setOptions(e){if(this.options={...this.#i,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=Uv(this.options);t.data!==void 0&&(this.setState(Lv(t.data,t.dataUpdatedAt)),this.#t=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#a.remove(this)}setData(e,t){const n=pf(this.state.data,e,this.options);return this.#s({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#s({type:"setState",state:e})}cancel(e){const t=this.#o?.promise;return this.#o?.cancel(e),t?t.then(Qn).catch(Qn):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>an(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Sh||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>an(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!CS(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#o?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#o?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#a.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){const t=this.observers.indexOf(e);t!==-1&&(this.observers.splice(t,1),this.observers.length||(this.#o&&(this.#l||this.state.fetchStatus==="paused"&&this.state.status==="pending"?this.#o.cancel({revert:!0}):this.#o.cancelRetry()),this.scheduleGc()),this.#a.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#s({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#o?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#o)return this.#o.continueRetry(),this.#o.promise}if(e&&this.setOptions(e),!this.options.queryFn){const m=this.observers.find(d=>d.options.queryFn);m&&this.setOptions(m.options)}const n=new AbortController,a=m=>{Object.defineProperty(m,"signal",{enumerable:!0,get:()=>(this.#l=!0,n.signal)})},o=()=>{const m=PS(this.options,t),h=(()=>{const v={client:this.#r,queryKey:this.queryKey,meta:this.meta};return a(v),v})();return this.#l=!1,this.options.persister?this.options.persister(m,h,this):m(h)},s=(()=>{const m={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#r,state:this.state,fetchFn:o};return a(m),m})();(this.#e==="infinite"?mR(this.options.pages):this.options.behavior)?.onFetch(s,this),this.#n=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==s.fetchOptions?.meta)&&this.#s({type:"fetch",meta:s.fetchOptions?.meta});const l=this.#o=ES({initialPromise:t?.initialPromise,fn:s.fetchFn,onCancel:m=>{m instanceof ff&&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 ff){if(m.silent)return this.#o.promise;if(m.revert){if(this.state.data===void 0)throw m;return this.state.data}}throw this.#s({type:"error",error:m}),this.#a.config.onError?.(m,this),this.#a.config.onSettled?.(this.state.data,m,this),m}finally{this.#o===l&&(this.#o=void 0),this.scheduleGc()}}#s(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...jS(n.data,this.options),fetchMeta:e.meta??null};case"success":const a={...n,...Lv(e.data,e.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?a:void 0,a;case"error":const o=e.error;return{...n,error:o,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:o,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),An.batch(()=>{this.observers.slice().forEach(n=>{n.onQueryUpdate()}),this.#a.notify({query:this,type:"updated",action:e})})}};function jS(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:TS(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Lv(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Uv(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 hR=class extends Wl{#e;#t=void 0;#n=void 0;#a=void 0;#r;#o;#i;#l;#s;#p;#d;#u;#c;#f=new Set;constructor(e,t){super(),this.options=t,this.#e=e,this.#i=null,this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),zv(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return hf(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return hf(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#S(),this.#k(),this.#t.removeObserver(this)}setOptions(e){const t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof an(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#x(),this.#t.setOptions(this.options),t._defaulted&&!Zm(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const a=this.hasListeners();a&&Hv(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),a&&(this.#t!==n||an(this.options.enabled,this.#t)!==an(t.enabled,this.#t)||an(this.options.staleTime,this.#t)!==an(t.staleTime,this.#t))&&this.#g();const o=this.#v();a&&(this.#t!==n||an(this.options.enabled,this.#t)!==an(t.enabled,this.#t)||o!==this.#c)&&this.#b(o)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return Zm(this.getCurrentResult(),n)||(this.#a=n,this.#o=this.options,this.#r=this.#t.state),n}getCurrentResult(){return this.#a}trackResult(e,t){return new Proxy(e,{get:(n,a)=>(this.trackProp(a),t?.(a),Reflect.get(n,a))})}trackProp(e){this.#f.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);let a=()=>{},o;const i=new Promise(s=>{o=s,a=this.#e.getQueryCache().subscribe(l=>{l.type==="updated"&&l.query.queryHash===n.queryHash&&n.state.data!==void 0&&(a(),s(this.createResult(n,t)))})});return Promise.race([n.fetch().then(()=>{const s=this.createResult(n,t);return o?.(s),s}).finally(()=>{a()}),i])}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#a))}#m(e){this.#x();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Qn)),t}#h(e){return!kh()&&an(this.options.enabled,this.#t)!==!1&&_S(e)}#g(){this.#S();const e=an(this.options.staleTime,this.#t);if(this.#a.isStale||!this.#h(e))return;const t=CS(this.#a.dataUpdatedAt,e)+1;this.#d=Or.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.#k(),this.#c=e,!(this.#c===0||!this.#h(this.#c))&&(this.#u=Or.setInterval(()=>{(this.options.refetchIntervalInBackground||xh.isFocused())&&this.#m()},this.#c))}#y(){this.#g(),this.#b(this.#v())}#S(){this.#d!==void 0&&(Or.clearTimeout(this.#d),this.#d=void 0)}#k(){this.#u!==void 0&&(Or.clearInterval(this.#u),this.#u=void 0)}createResult(e,t){const n=this.#t,a=this.options,o=this.#a,i=this.#r,s=this.#o,l=e!==n?e.state:this.#n,{state:m}=e;let d={...m},h=!1,v;if(t._optimisticResults){const k=this.hasListeners(),C=!k&&zv(e,t),T=k&&Hv(e,n,t,a);(C||T)&&(d={...d,...jS(m.data,e.options)}),t._optimisticResults==="isRestoring"&&(d.fetchStatus="idle")}let{error:y,errorUpdatedAt:w,status:I}=d;v=d.data;let R=!1;if(t.placeholderData!==void 0&&v===void 0&&I==="pending"){let k;o?.isPlaceholderData&&t.placeholderData===s?.placeholderData?(k=o.data,R=!0):k=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,k!==void 0&&(I="success",v=pf(o?.data,k,t),h=!0)}if(t.select&&v!==void 0&&!R)if(o&&v===i?.data&&t.select===this.#l)v=this.#s;else try{this.#l=t.select,v=t.select(v),v=pf(o?.data,v,t),this.#s=v,this.#i=null}catch(k){this.#i=k}else v===void 0&&(this.#i=null);this.#i&&(y=this.#i,v=this.#s,w=Date.now(),I="error",h=!1);const M=d.fetchStatus==="fetching",P=I==="pending",N=I==="error",O=P&&M,j=v!==void 0;return{status:I,fetchStatus:d.fetchStatus,isPending:P,isSuccess:I==="success",isError:N,isInitialLoading:O,isLoading:O,data:v,dataUpdatedAt:d.dataUpdatedAt,error:y,errorUpdatedAt:w,failureCount:d.fetchFailureCount,failureReason:d.fetchFailureReason,errorUpdateCount:d.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:d.dataUpdateCount>l.dataUpdateCount||d.errorUpdateCount>l.errorUpdateCount,isFetching:M,isRefetching:M&&!P,isLoadingError:N&&!j,isPaused:d.fetchStatus==="paused",isPlaceholderData:h,isRefetchError:N&&j,isStale:wh(e,t),refetch:this.refetch,isEnabled:an(t.enabled,e)!==!1}}updateResult(){const e=this.#a,t=this.createResult(this.#t,this.options);if(this.#r=this.#t.state,this.#o=this.options,this.#r.data!==void 0&&(this.#p=this.#t),Zm(t,e))return;this.#a=t;const a=(()=>{if(!e)return!0;const{notifyOnChangeProps:o}=this.options,i=typeof o=="function"?o():o;if(i==="all"||!i&&!this.#f.size)return!0;const s=new Set(i??this.#f);return this.options.throwOnError&&s.add("error"),Object.keys(this.#a).some(l=>{const m=l;return this.#a[m]!==e[m]&&s.has(m)})})();An.batch(()=>{a&&this.listeners.forEach(o=>{o(this.#a)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}#x(){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 gR(e,t){return an(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&an(t.retryOnMount,e)===!1)}function zv(e,t){return gR(e,t)||e.state.data!==void 0&&hf(e,t,t.refetchOnMount)}function hf(e,t,n){if(an(t.enabled,e)!==!1&&an(t.staleTime,e)!=="static"){const a=typeof n=="function"?n(e):n;return a==="always"||a!==!1&&wh(e,t)}return!1}function Hv(e,t,n,a){return(e!==t||an(a.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&wh(e,n)}function wh(e,t){return an(t.enabled,e)!==!1&&e.isStaleByTime(an(t.staleTime,e))}var vR=class extends MS{#e;#t;#n;#a;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||bR(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#n.remove(this))}continue(){return this.#a?.continue()??(this.state.status==="pending"?this.execute(this.state.variables):Promise.resolve())}async execute(e){const t=()=>{this.#r({type:"continue"})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey},a=this.#a=ES({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(new Error("No mutationFn found")),onFail:(s,l)=>{this.#r({type:"failed",failureCount:s,error:l})},onPause:()=>{this.#r({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)}),o=this.state.status==="pending",i=!a.canStart();try{if(o)t();else{this.#r({type:"pending",variables:e,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);const l=await this.options.onMutate?.(e,n);l!==this.state.context&&this.#r({type:"pending",context:l,variables:e,isPaused:i})}const s=await a.start();return await this.#n.config.onSuccess?.(s,e,this.state.context,this,n),await this.options.onSuccess?.(s,e,this.state.context,n),await this.#n.config.onSettled?.(s,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(s,null,e,this.state.context,n),this.#r({type:"success",data:s}),s}catch(s){try{await this.#n.config.onError?.(s,e,this.state.context,this,n)}catch(l){Promise.reject(l)}try{await this.options.onError?.(s,e,this.state.context,n)}catch(l){Promise.reject(l)}try{await this.#n.config.onSettled?.(void 0,s,this.state.variables,this.state.context,this,n)}catch(l){Promise.reject(l)}try{await this.options.onSettled?.(void 0,s,e,this.state.context,n)}catch(l){Promise.reject(l)}throw this.#r({type:"error",error:s}),s}finally{this.#a===a&&(this.#a=void 0),this.#n.runNext(this)}}#r(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),An.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:"updated",action:e})})}};function bR(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var yR=class extends Wl{#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 vR({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=$c(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=$c(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=$c(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=$c(e);return typeof t=="string"?this.#t.get(t)?.find(n=>n!==e&&n.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){An.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>Ov(t,n))}findAll(e={}){return this.getAll().filter(t=>Ov(e,t))}notify(e){An.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return An.batch(()=>Promise.all(e.map(t=>t.continue().catch(Qn))))}};function $c(e){return e.options.scope?.id}var SR=class extends Wl{#e;constructor(e={}){super(),this.config=e,this.#e=new Map}build(e,t,n){const a=t.queryKey,o=t.queryHash??yh(a,t);let i=this.get(o);return i||(i=new fR({client:e,queryKey:a,queryHash:o,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(a)}),this.add(i)),i}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){An.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>jv(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>jv(e,n)):t}notify(e){An.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){An.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){An.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},kR=class{#e;#t;#n;#a;#r;#o;#i;#l;constructor(e={}){this.#e=e.queryCache||new SR,this.#t=e.mutationCache||new yR,this.#n=e.defaultOptions||{},this.#a=new Map,this.#r=new Map,this.#o=0}mount(){this.#o++,this.#o===1&&(this.#i=xh.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#l=kd.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#o--,this.#o===0&&(this.#i?.(),this.#i=void 0,this.#l?.(),this.#l=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#e.build(this,t),a=n.state.data;return a===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(an(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(a))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:n})=>[t,n.data])}setQueryData(e,t,n){const a=this.defaultQueryOptions({queryKey:e}),o=this.#e.get(a.queryHash)?.state.data,i=eR(t,o);if(i!==void 0)return this.#e.build(this,a).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return An.batch(()=>this.#e.findAll(e).map(({queryKey:a})=>[a,this.setQueryData(a,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;An.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return An.batch(()=>{const a=n.findAll(e),o=new Set(a);return a.forEach(i=>{i.reset()}),this.refetchQueries({type:"active",predicate:i=>o.has(i)},t)})}cancelQueries(e,t={}){const n={revert:!0,...t},a=An.batch(()=>this.#e.findAll(e).map(o=>o.cancel(n)));return Promise.all(a).then(Qn).catch(Qn)}invalidateQueries(e,t={}){return An.batch(()=>(this.#e.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},a=An.batch(()=>this.#e.findAll(e).filter(o=>!o.isDisabled()&&!o.isStatic()).map(o=>{let i=o.fetch(void 0,n);return n.throwOnError||(i=i.catch(Qn)),o.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(a).then(Qn)}async query(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t),a=n.isStaleByTime(an(t.staleTime,n))?await n.fetch(t):n.state.data,o=t.select;return o?o(a):a}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t);return n.isStaleByTime(an(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Qn).catch(Qn)}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(Qn).catch(Qn)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return kd.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(Rl(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#a.values()],n={};return t.forEach(a=>{Yi(e,a.queryKey)&&Object.assign(n,a.defaultOptions)}),n}setMutationDefaults(e,t){this.#r.set(Rl(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#r.values()],n={};return t.forEach(a=>{Yi(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=yh(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===Sh&&(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 OS=g.createContext(!1),xR=()=>g.useContext(OS);OS.Provider;function wR(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}const IR=g.createContext(wR()),_R=()=>g.useContext(IR),CR=(e,t,n)=>{const a=n?.state.error&&typeof e.throwOnError=="function"?AS(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||a)&&(t.isReset()||(e.retryOnMount=!1))},RR=e=>{g.useEffect(()=>{e.clearReset()},[e])},PR=({result:e,errorResetBoundary:t,throwOnError:n,query:a,suspense:o})=>e.isError&&!t.isReset()&&!e.isFetching&&a&&(o&&e.data===void 0||AS(n,[e.error,a])),AR=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))}},TR=(e,t)=>e?.suspense&&t.isPending,ER=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function MR(e,t,n){const a=xR(),o=_R(),i=IS(),s=i.defaultQueryOptions(e),l=i.getQueryCache().get(s.queryHash),m=e.subscribed!==!1;s._optimisticResults=a?"isRestoring":m?"optimistic":void 0,AR(s),CR(s,o,l),RR(o);const[d]=g.useState(()=>new t(i,s)),h=d.getOptimisticResult(s),v=!a&&m;if(g.useSyncExternalStore(g.useCallback(y=>{const w=v?d.subscribe(An.batchCalls(y)):Qn;return d.updateResult(),w},[d,v]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),g.useEffect(()=>{d.setOptions(s)},[s,d]),TR(s,h))throw ER(s,d,o);if(PR({result:h,errorResetBoundary:o,throwOnError:s.throwOnError,query:l,suspense:s.suspense}))throw h.error;return s.notifyOnChangeProps?h:d.trackResult(h)}function jR(e,t){return MR(e,hR)}function OR(){return new kR({defaultOptions:{queries:{staleTime:6e4,gcTime:15*6e4,retry:1,refetchOnWindowFocus:!1}}})}var qv;function ve(e,t,n){function a(l,m){if(l._zod||Object.defineProperty(l,"_zod",{value:{def:m,constr:s,traits:new Set},enumerable:!1}),l._zod.traits.has(e))return;l._zod.traits.add(e),t(l,m);const d=s.prototype,h=Object.keys(d);for(let v=0;v<h.length;v++){const y=h[v];y in l||(l[y]=d[y].bind(l))}}const o=n?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function s(l){var m;const d=n?.Parent?new i:this;a(d,l),(m=d._zod).deferred??(m.deferred=[]);for(const h of d._zod.deferred)h();return d}return Object.defineProperty(s,"init",{value:a}),Object.defineProperty(s,Symbol.hasInstance,{value:l=>n?.Parent&&l instanceof n.Parent?!0:l?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}class Ki extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class $S extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(qv=globalThis).__zod_globalConfig??(qv.__zod_globalConfig={});const Ih=globalThis.__zod_globalConfig;function Ko(e){return Ih}function NS(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 gf(e,t){return typeof t=="bigint"?t.toString():t}function Zd(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function _h(e){return e==null}function Ch(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function $R(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 Bv=Symbol("evaluating");function Pt(e,t,n){let a;Object.defineProperty(e,t,{get(){if(a!==Bv)return a===void 0&&(a=Bv,a=n()),a},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function Zr(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function pr(...e){const t={};for(const n of e){const a=Object.getOwnPropertyDescriptors(n);Object.assign(t,a)}return Object.defineProperties({},t)}function Fv(e){return JSON.stringify(e)}function NR(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const DS="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Pl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const DR=Zd(()=>{if(Ih.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Qi(e){if(Pl(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Pl(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function LS(e){return Qi(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const LR=new Set(["string","number","symbol"]);function Xi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function fr(e,t,n){const a=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(a._zod.parent=e),a}function nt(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 UR(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const zR={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 HR(e,t){const n=e._zod.def,a=n.checks;if(a&&a.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const i=pr(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 Zr(this,"shape",s),s},checks:[]});return fr(e,i)}function qR(e,t){const n=e._zod.def,a=n.checks;if(a&&a.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const i=pr(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 Zr(this,"shape",s),s},checks:[]});return fr(e,i)}function BR(e,t){if(!Qi(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const i=e._zod.def.shape;for(const s in t)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const o=pr(e._zod.def,{get shape(){const i={...e._zod.def.shape,...t};return Zr(this,"shape",i),i}});return fr(e,o)}function FR(e,t){if(!Qi(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=pr(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t};return Zr(this,"shape",a),a}});return fr(e,n)}function VR(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=pr(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t._zod.def.shape};return Zr(this,"shape",a),a},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return fr(e,n)}function KR(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=pr(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 Zr(this,"shape",m),m},checks:[]});return fr(t,s)}function WR(e,t,n){const a=pr(t._zod.def,{get shape(){const o=t._zod.def.shape,i={...o};if(n)for(const s in n){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(i[s]=new e({type:"nonoptional",innerType:o[s]}))}else for(const s in o)i[s]=new e({type:"nonoptional",innerType:o[s]});return Zr(this,"shape",i),i}});return fr(t,a)}function Oi(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 GR(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 $i(e,t){return t.map(n=>{var a;return(a=n).path??(a.path=[]),n.path.unshift(e),n})}function Nc(e){return typeof e=="string"?e:e?.message}function Wo(e,t,n){const a=e.message?e.message:Nc(e.inst?._zod.def?.error?.(e))??Nc(t?.error?.(e))??Nc(n.customError?.(e))??Nc(n.localeError?.(e))??"Invalid input",{inst:o,continue:i,input:s,...l}=e;return l.path??(l.path=[]),l.message=a,t?.reportInput&&(l.input=s),l}function Rh(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Al(...e){const[t,n,a]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:a}:{...t}}const US=(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,gf,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},zS=ve("$ZodError",US),HS=ve("$ZodError",US,{Parent:Error});function ZR(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 JR(e,t=n=>n.message){const n={_errors:[]},a=(o,i=[])=>{for(const s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(l=>a({issues:l},[...i,...s.path]));else if(s.code==="invalid_key")a({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")a({issues:s.issues},[...i,...s.path]);else{const l=[...i,...s.path];if(l.length===0)n._errors.push(t(s));else{let m=n,d=0;for(;d<l.length;){const h=l[d];d===l.length-1?(m[h]=m[h]||{_errors:[]},m[h]._errors.push(t(s))):m[h]=m[h]||{_errors:[]},m=m[h],d++}}}};return a(e),n}const Ph=e=>(t,n,a,o)=>{const i=a?{...a,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw new Ki;if(s.issues.length){const l=new(o?.Err??e)(s.issues.map(m=>Wo(m,i,Ko())));throw DS(l,o?.callee),l}return s.value},Ah=e=>async(t,n,a,o)=>{const i=a?{...a,async:!0}:{async:!0};let s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){const l=new(o?.Err??e)(s.issues.map(m=>Wo(m,i,Ko())));throw DS(l,o?.callee),l}return s.value},Jd=e=>(t,n,a)=>{const o=a?{...a,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise)throw new Ki;return i.issues.length?{success:!1,error:new(e??zS)(i.issues.map(s=>Wo(s,o,Ko())))}:{success:!0,data:i.value}},YR=Jd(HS),Yd=e=>async(t,n,a)=>{const o=a?{...a,async:!0}:{async:!0};let i=t._zod.run({value:n,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(s=>Wo(s,o,Ko())))}:{success:!0,data:i.value}},QR=Yd(HS),XR=e=>(t,n,a)=>{const o=a?{...a,direction:"backward"}:{direction:"backward"};return Ph(e)(t,n,o)},eP=e=>(t,n,a)=>Ph(e)(t,n,a),tP=e=>async(t,n,a)=>{const o=a?{...a,direction:"backward"}:{direction:"backward"};return Ah(e)(t,n,o)},nP=e=>async(t,n,a)=>Ah(e)(t,n,a),aP=e=>(t,n,a)=>{const o=a?{...a,direction:"backward"}:{direction:"backward"};return Jd(e)(t,n,o)},oP=e=>(t,n,a)=>Jd(e)(t,n,a),rP=e=>async(t,n,a)=>{const o=a?{...a,direction:"backward"}:{direction:"backward"};return Yd(e)(t,n,o)},iP=e=>async(t,n,a)=>Yd(e)(t,n,a),sP=/^[cC][0-9a-z]{6,}$/,lP=/^[0-9a-z]+$/,cP=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,dP=/^[0-9a-vA-V]{20}$/,uP=/^[A-Za-z0-9]{27}$/,mP=/^[a-zA-Z0-9_-]{21}$/,pP=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,fP=/^([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})$/,Vv=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)$/,hP=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,gP="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function vP(){return new RegExp(gP,"u")}const bP=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,yP=/^(([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}|:))$/,SP=/^((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])$/,kP=/^(([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])$/,xP=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,qS=/^[A-Za-z0-9_-]*$/,wP=/^https?$/,IP=/^\+[1-9]\d{6,14}$/,BS="(?:(?:\\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])))",_P=new RegExp(`^${BS}$`);function FS(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 CP(e){return new RegExp(`^${FS(e)}$`)}function RP(e){const t=FS({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(`^${BS}T(?:${a})$`)}const PP=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},AP=/^-?\d+$/,VS=/^-?\d+(?:\.\d+)?$/,TP=/^(?:true|false)$/i,EP=/^null$/i,MP=/^[^A-Z]*$/,jP=/^[^a-z]*$/,aa=ve("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),KS={number:"number",bigint:"bigint",object:"date"},WS=ve("$ZodCheckLessThan",(e,t)=>{aa.init(e,t);const n=KS[typeof t.value];e._zod.onattach.push(a=>{const o=a._zod.bag,i=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=a=>{(t.inclusive?a.value<=t.value:a.value<t.value)||a.issues.push({origin:n,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:a.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),GS=ve("$ZodCheckGreaterThan",(e,t)=>{aa.init(e,t);const n=KS[typeof t.value];e._zod.onattach.push(a=>{const o=a._zod.bag,i=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=a=>{(t.inclusive?a.value>=t.value:a.value>t.value)||a.issues.push({origin:n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:a.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),OP=ve("$ZodCheckMultipleOf",(e,t)=>{aa.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):$R(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})}}),$P=ve("$ZodCheckNumberFormat",(e,t)=>{aa.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),a=n?"int":"number",[o,i]=zR[t.format];e._zod.onattach.push(s=>{const l=s._zod.bag;l.format=t.format,l.minimum=o,l.maximum=i,n&&(l.pattern=AP)}),e._zod.check=s=>{const l=s.value;if(n){if(!Number.isInteger(l)){s.issues.push({expected:a,format:t.format,code:"invalid_type",continue:!1,input:l,inst:e});return}if(!Number.isSafeInteger(l)){l>0?s.issues.push({input:l,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:a,inclusive:!0,continue:!t.abort}):s.issues.push({input:l,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:a,inclusive:!0,continue:!t.abort});return}}l<o&&s.issues.push({origin:"number",input:l,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),l>i&&s.issues.push({origin:"number",input:l,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),NP=ve("$ZodCheckMaxLength",(e,t)=>{var n;aa.init(e,t),(n=e._zod.def).when??(n.when=a=>{const o=a.value;return!_h(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=Rh(o);a.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),DP=ve("$ZodCheckMinLength",(e,t)=>{var n;aa.init(e,t),(n=e._zod.def).when??(n.when=a=>{const o=a.value;return!_h(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=Rh(o);a.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),LP=ve("$ZodCheckLengthEquals",(e,t)=>{var n;aa.init(e,t),(n=e._zod.def).when??(n.when=a=>{const o=a.value;return!_h(o)&&o.length!==void 0}),e._zod.onattach.push(a=>{const o=a._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=a=>{const o=a.value,i=o.length;if(i===t.length)return;const s=Rh(o),l=i>t.length;a.issues.push({origin:s,...l?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:a.value,inst:e,continue:!t.abort})}}),Qd=ve("$ZodCheckStringFormat",(e,t)=>{var n,a;aa.init(e,t),e._zod.onattach.push(o=>{const i=o._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(a=e._zod).check??(a.check=()=>{})}),UP=ve("$ZodCheckRegex",(e,t)=>{Qd.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})}}),zP=ve("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=MP),Qd.init(e,t)}),HP=ve("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=jP),Qd.init(e,t)}),qP=ve("$ZodCheckIncludes",(e,t)=>{aa.init(e,t);const n=Xi(t.includes),a=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=a,e._zod.onattach.push(o=>{const i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(a)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),BP=ve("$ZodCheckStartsWith",(e,t)=>{aa.init(e,t);const n=new RegExp(`^${Xi(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})}}),FP=ve("$ZodCheckEndsWith",(e,t)=>{aa.init(e,t);const n=new RegExp(`.*${Xi(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})}}),VP=ve("$ZodCheckOverwrite",(e,t)=>{aa.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class KP{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const a=t.split(`
|
|
3
|
+
`).filter(s=>s),o=Math.min(...a.map(s=>s.length-s.trimStart().length)),i=a.map(s=>s.slice(o)).map(s=>" ".repeat(this.indent*2)+s);for(const s of i)this.content.push(s)}compile(){const t=Function,n=this?.args,o=[...(this?.content??[""]).map(i=>` ${i}`)];return new t(...n,o.join(`
|
|
4
|
+
`))}}const WP={major:4,minor:4,patch:3},Jt=ve("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=WP;const a=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&a.unshift(e);for(const o of a)for(const i of o._zod.onattach)i(e);if(a.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=(s,l,m)=>{let d=Oi(s),h;for(const v of l){if(v._zod.def.when){if(GR(s)||!v._zod.def.when(s))continue}else if(d)continue;const y=s.issues.length,w=v._zod.check(s);if(w instanceof Promise&&m?.async===!1)throw new Ki;if(h||w instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await w,s.issues.length!==y&&(d||(d=Oi(s,y)))});else{if(s.issues.length===y)continue;d||(d=Oi(s,y))}}return h?h.then(()=>s):s},i=(s,l,m)=>{if(Oi(s))return s.aborted=!0,s;const d=o(l,a,m);if(d instanceof Promise){if(m.async===!1)throw new Ki;return d.then(h=>e._zod.parse(h,m))}return e._zod.parse(d,m)};e._zod.run=(s,l)=>{if(l.skipChecks)return e._zod.parse(s,l);if(l.direction==="backward"){const d=e._zod.parse({value:s.value,issues:[]},{...l,skipChecks:!0});return d instanceof Promise?d.then(h=>i(h,s,l)):i(d,s,l)}const m=e._zod.parse(s,l);if(m instanceof Promise){if(l.async===!1)throw new Ki;return m.then(d=>o(d,a,l))}return o(m,a,l)}}Pt(e,"~standard",()=>({validate:o=>{try{const i=YR(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return QR(e,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),Th=ve("$ZodString",(e,t)=>{Jt.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??PP(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}}),en=ve("$ZodStringFormat",(e,t)=>{Qd.init(e,t),Th.init(e,t)}),GP=ve("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=fP),en.init(e,t)}),ZP=ve("$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=Vv(a))}else t.pattern??(t.pattern=Vv());en.init(e,t)}),JP=ve("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=hP),en.init(e,t)}),YP=ve("$ZodURL",(e,t)=>{en.init(e,t),e._zod.check=n=>{try{const a=n.value.trim();if(!t.normalize&&t.protocol?.source===wP.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})}}}),QP=ve("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=vP()),en.init(e,t)}),XP=ve("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=mP),en.init(e,t)}),eA=ve("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=sP),en.init(e,t)}),tA=ve("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=lP),en.init(e,t)}),nA=ve("$ZodULID",(e,t)=>{t.pattern??(t.pattern=cP),en.init(e,t)}),aA=ve("$ZodXID",(e,t)=>{t.pattern??(t.pattern=dP),en.init(e,t)}),oA=ve("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=uP),en.init(e,t)}),rA=ve("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=RP(t)),en.init(e,t)}),iA=ve("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=_P),en.init(e,t)}),sA=ve("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=CP(t)),en.init(e,t)}),lA=ve("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=pP),en.init(e,t)}),cA=ve("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=bP),en.init(e,t),e._zod.bag.format="ipv4"}),dA=ve("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=yP),en.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})}}}),uA=ve("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=SP),en.init(e,t)}),mA=ve("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=kP),en.init(e,t),e._zod.check=n=>{const a=n.value.split("/");try{if(a.length!==2)throw new Error;const[o,i]=a;if(!i)throw new Error;const s=Number(i);if(`${s}`!==i)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${o}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function ZS(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const pA=ve("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=xP),en.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{ZS(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function fA(e){if(!qS.test(e))return!1;const t=e.replace(/[-_]/g,a=>a==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return ZS(n)}const hA=ve("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=qS),en.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{fA(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),gA=ve("$ZodE164",(e,t)=>{t.pattern??(t.pattern=IP),en.init(e,t)});function vA(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 bA=ve("$ZodJWT",(e,t)=>{en.init(e,t),e._zod.check=n=>{vA(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),JS=ve("$ZodNumber",(e,t)=>{Jt.init(e,t),e._zod.pattern=e._zod.bag.pattern??VS,e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;const i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),n}}),yA=ve("$ZodNumberFormat",(e,t)=>{$P.init(e,t),JS.init(e,t)}),SA=ve("$ZodBoolean",(e,t)=>{Jt.init(e,t),e._zod.pattern=TP,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}}),kA=ve("$ZodNull",(e,t)=>{Jt.init(e,t),e._zod.pattern=EP,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}}),xA=ve("$ZodUnknown",(e,t)=>{Jt.init(e,t),e._zod.parse=n=>n}),wA=ve("$ZodNever",(e,t)=>{Jt.init(e,t),e._zod.parse=(n,a)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Kv(e,t,n){e.issues.length&&t.issues.push(...$i(n,e.issues)),t.value[n]=e.value}const IA=ve("$ZodArray",(e,t)=>{Jt.init(e,t),e._zod.parse=(n,a)=>{const o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);const i=[];for(let s=0;s<o.length;s++){const l=o[s],m=t.element._zod.run({value:l,issues:[]},a);m instanceof Promise?i.push(m.then(d=>Kv(d,n,s))):Kv(m,n,s)}return i.length?Promise.all(i).then(()=>n):n}});function xd(e,t,n,a,o,i){const s=n in a;if(e.issues.length){if(o&&i&&!s)return;t.issues.push(...$i(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 YS(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=UR(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function QS(e,t,n,a,o,i){const s=[],l=o.keySet,m=o.catchall._zod,d=m.def.type,h=m.optin==="optional",v=m.optout==="optional";for(const y in t){if(y==="__proto__"||l.has(y))continue;if(d==="never"){s.push(y);continue}const w=m.run({value:t[y],issues:[]},a);w instanceof Promise?e.push(w.then(I=>xd(I,n,y,t,h,v))):xd(w,n,y,t,h,v)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i}),e.length?Promise.all(e).then(()=>n):n}const _A=ve("$ZodObject",(e,t)=>{if(Jt.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=Zd(()=>YS(t));Pt(e._zod,"propValues",()=>{const l=t.shape,m={};for(const d in l){const h=l[d]._zod;if(h.values){m[d]??(m[d]=new Set);for(const v of h.values)m[d].add(v)}}return m});const o=Pl,i=t.catchall;let s;e._zod.parse=(l,m)=>{s??(s=a.value);const d=l.value;if(!o(d))return l.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),l;l.value={};const h=[],v=s.shape;for(const y of s.keys){const w=v[y],I=w._zod.optin==="optional",R=w._zod.optout==="optional",M=w._zod.run({value:d[y],issues:[]},m);M instanceof Promise?h.push(M.then(P=>xd(P,l,y,d,I,R))):xd(M,l,y,d,I,R)}return i?QS(h,d,l,m,a.value,e):h.length?Promise.all(h).then(()=>l):l}}),CA=ve("$ZodObjectJIT",(e,t)=>{_A.init(e,t);const n=e._zod.parse,a=Zd(()=>YS(t)),o=y=>{const w=new KP(["shape","payload","ctx"]),I=a.value,R=O=>{const j=Fv(O);return`shape[${j}]._zod.run({ value: input[${j}], issues: [] }, ctx)`};w.write("const input = payload.value;");const M=Object.create(null);let P=0;for(const O of I.keys)M[O]=`key_${P++}`;w.write("const newResult = {};");for(const O of I.keys){const j=M[O],k=Fv(O),C=y[O],T=C?._zod?.optin==="optional",z=C?._zod?.optout==="optional";w.write(`const ${j} = ${R(O)};`),T&&z?w.write(`
|
|
5
|
+
if (${j}.issues.length) {
|
|
6
|
+
if (${k} in input) {
|
|
7
|
+
payload.issues = payload.issues.concat(${j}.issues.map(iss => ({
|
|
8
|
+
...iss,
|
|
9
|
+
path: iss.path ? [${k}, ...iss.path] : [${k}]
|
|
10
|
+
})));
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
if (${j}.value === undefined) {
|
|
15
|
+
if (${k} in input) {
|
|
16
|
+
newResult[${k}] = undefined;
|
|
17
|
+
}
|
|
18
|
+
} else {
|
|
19
|
+
newResult[${k}] = ${j}.value;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
`):T?w.write(`
|
|
23
|
+
if (${j}.issues.length) {
|
|
24
|
+
payload.issues = payload.issues.concat(${j}.issues.map(iss => ({
|
|
25
|
+
...iss,
|
|
26
|
+
path: iss.path ? [${k}, ...iss.path] : [${k}]
|
|
27
|
+
})));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
if (${j}.value === undefined) {
|
|
31
|
+
if (${k} in input) {
|
|
32
|
+
newResult[${k}] = undefined;
|
|
33
|
+
}
|
|
34
|
+
} else {
|
|
35
|
+
newResult[${k}] = ${j}.value;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
`):w.write(`
|
|
39
|
+
const ${j}_present = ${k} in input;
|
|
40
|
+
if (${j}.issues.length) {
|
|
41
|
+
payload.issues = payload.issues.concat(${j}.issues.map(iss => ({
|
|
42
|
+
...iss,
|
|
43
|
+
path: iss.path ? [${k}, ...iss.path] : [${k}]
|
|
44
|
+
})));
|
|
45
|
+
}
|
|
46
|
+
if (!${j}_present && !${j}.issues.length) {
|
|
47
|
+
payload.issues.push({
|
|
48
|
+
code: "invalid_type",
|
|
49
|
+
expected: "nonoptional",
|
|
50
|
+
input: undefined,
|
|
51
|
+
path: [${k}]
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (${j}_present) {
|
|
56
|
+
if (${j}.value === undefined) {
|
|
57
|
+
newResult[${k}] = undefined;
|
|
58
|
+
} else {
|
|
59
|
+
newResult[${k}] = ${j}.value;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
`)}w.write("payload.value = newResult;"),w.write("return payload;");const N=w.compile();return(O,j)=>N(y,O,j)};let i;const s=Pl,l=!Ih.jitless,d=l&&DR.value,h=t.catchall;let v;e._zod.parse=(y,w)=>{v??(v=a.value);const I=y.value;return s(I)?l&&d&&w?.async===!1&&w.jitless!==!0?(i||(i=o(t.shape)),y=i(y,w),h?QS([],I,y,w,v,e):y):n(y,w):(y.issues.push({expected:"object",code:"invalid_type",input:I,inst:e}),y)}});function Wv(e,t,n,a){for(const i of e)if(i.issues.length===0)return t.value=i.value,t;const o=e.filter(i=>!Oi(i));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(i=>i.issues.map(s=>Wo(s,a,Ko())))}),t)}const XS=ve("$ZodUnion",(e,t)=>{Jt.init(e,t),Pt(e._zod,"optin",()=>t.options.some(a=>a._zod.optin==="optional")?"optional":void 0),Pt(e._zod,"optout",()=>t.options.some(a=>a._zod.optout==="optional")?"optional":void 0),Pt(e._zod,"values",()=>{if(t.options.every(a=>a._zod.values))return new Set(t.options.flatMap(a=>Array.from(a._zod.values)))}),Pt(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=>Ch(o.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(a,o)=>{if(n)return n(a,o);let i=!1;const s=[];for(const l of t.options){const m=l._zod.run({value:a.value,issues:[]},o);if(m instanceof Promise)s.push(m),i=!0;else{if(m.issues.length===0)return m;s.push(m)}}return i?Promise.all(s).then(l=>Wv(l,a,e,o)):Wv(s,a,e,o)}}),RA=ve("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,XS.init(e,t);const n=e._zod.parse;Pt(e._zod,"propValues",()=>{const o={};for(const i of t.options){const s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(const[l,m]of Object.entries(s)){o[l]||(o[l]=new Set);for(const d of m)o[l].add(d)}}return o});const a=Zd(()=>{const o=t.options,i=new Map;for(const s of o){const l=s._zod.propValues?.[t.discriminator];if(!l||l.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const m of l){if(i.has(m))throw new Error(`Duplicate discriminator value "${String(m)}"`);i.set(m,s)}}return i});e._zod.parse=(o,i)=>{const s=o.value;if(!Pl(s))return o.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),o;const l=a.value.get(s?.[t.discriminator]);return l?l._zod.run(o,i):t.unionFallback||i.direction==="backward"?n(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(a.value.keys()),input:s,path:[t.discriminator],inst:e}),o)}}),PA=ve("$ZodIntersection",(e,t)=>{Jt.init(e,t),e._zod.parse=(n,a)=>{const o=n.value,i=t.left._zod.run({value:o,issues:[]},a),s=t.right._zod.run({value:o,issues:[]},a);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([m,d])=>Gv(n,m,d)):Gv(n,i,s)}});function vf(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(Qi(e)&&Qi(t)){const n=Object.keys(t),a=Object.keys(e).filter(i=>n.indexOf(i)!==-1),o={...e,...t};for(const i of a){const s=vf(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};o[i]=s.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let a=0;a<e.length;a++){const o=e[a],i=t[a],s=vf(o,i);if(!s.valid)return{valid:!1,mergeErrorPath:[a,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Gv(e,t,n){const a=new Map;let o;for(const l of t.issues)if(l.code==="unrecognized_keys"){o??(o=l);for(const m of l.keys)a.has(m)||a.set(m,{}),a.get(m).l=!0}else e.issues.push(l);for(const l of n.issues)if(l.code==="unrecognized_keys")for(const m of l.keys)a.has(m)||a.set(m,{}),a.get(m).r=!0;else e.issues.push(l);const i=[...a].filter(([,l])=>l.l&&l.r).map(([l])=>l);if(i.length&&o&&e.issues.push({...o,keys:i}),Oi(e))return e;const s=vf(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 AA=ve("$ZodRecord",(e,t)=>{Jt.init(e,t),e._zod.parse=(n,a)=>{const o=n.value;if(!Qi(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;const i=[],s=t.keyType._zod.values;if(s){n.value={};const l=new Set;for(const d of s)if(typeof d=="string"||typeof d=="number"||typeof d=="symbol"){l.add(typeof d=="number"?d.toString():d);const h=t.keyType._zod.run({value:d,issues:[]},a);if(h instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(h.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:h.issues.map(w=>Wo(w,a,Ko())),input:d,path:[d],inst:e});continue}const v=h.value,y=t.valueType._zod.run({value:o[d],issues:[]},a);y instanceof Promise?i.push(y.then(w=>{w.issues.length&&n.issues.push(...$i(d,w.issues)),n.value[v]=w.value})):(y.issues.length&&n.issues.push(...$i(d,y.issues)),n.value[v]=y.value)}let m;for(const d in o)l.has(d)||(m=m??[],m.push(d));m&&m.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:m})}else{n.value={};for(const l of Reflect.ownKeys(o)){if(l==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,l))continue;let m=t.keyType._zod.run({value:l,issues:[]},a);if(m instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof l=="string"&&VS.test(l)&&m.issues.length){const v=t.keyType._zod.run({value:Number(l),issues:[]},a);if(v instanceof Promise)throw new Error("Async schemas not supported in object keys currently");v.issues.length===0&&(m=v)}if(m.issues.length){t.mode==="loose"?n.value[l]=o[l]:n.issues.push({code:"invalid_key",origin:"record",issues:m.issues.map(v=>Wo(v,a,Ko())),input:l,path:[l],inst:e});continue}const h=t.valueType._zod.run({value:o[l],issues:[]},a);h instanceof Promise?i.push(h.then(v=>{v.issues.length&&n.issues.push(...$i(l,v.issues)),n.value[m.value]=v.value})):(h.issues.length&&n.issues.push(...$i(l,h.issues)),n.value[m.value]=h.value)}}return i.length?Promise.all(i).then(()=>n):n}}),TA=ve("$ZodEnum",(e,t)=>{Jt.init(e,t);const n=NS(t.entries),a=new Set(n);e._zod.values=a,e._zod.pattern=new RegExp(`^(${n.filter(o=>LR.has(typeof o)).map(o=>typeof o=="string"?Xi(o):o.toString()).join("|")})$`),e._zod.parse=(o,i)=>{const s=o.value;return a.has(s)||o.issues.push({code:"invalid_value",values:n,input:s,inst:e}),o}}),EA=ve("$ZodLiteral",(e,t)=>{if(Jt.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"?Xi(a):a?Xi(a.toString()):String(a)).join("|")})$`),e._zod.parse=(a,o)=>{const i=a.value;return n.has(i)||a.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),a}}),MA=ve("$ZodTransform",(e,t)=>{Jt.init(e,t),e._zod.optin="optional",e._zod.parse=(n,a)=>{if(a.direction==="backward")throw new $S(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 Ki;return n.value=o,n.fallback=!0,n}});function Zv(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const ek=ve("$ZodOptional",(e,t)=>{Jt.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Pt(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Pt(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Ch(n.source)})?$`):void 0}),e._zod.parse=(n,a)=>{if(t.innerType._zod.optin==="optional"){const o=n.value,i=t.innerType._zod.run(n,a);return i instanceof Promise?i.then(s=>Zv(s,o)):Zv(i,o)}return n.value===void 0?n:t.innerType._zod.run(n,a)}}),jA=ve("$ZodExactOptional",(e,t)=>{ek.init(e,t),Pt(e._zod,"values",()=>t.innerType._zod.values),Pt(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,a)=>t.innerType._zod.run(n,a)}),OA=ve("$ZodNullable",(e,t)=>{Jt.init(e,t),Pt(e._zod,"optin",()=>t.innerType._zod.optin),Pt(e._zod,"optout",()=>t.innerType._zod.optout),Pt(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Ch(n.source)}|null)$`):void 0}),Pt(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)}),$A=ve("$ZodDefault",(e,t)=>{Jt.init(e,t),e._zod.optin="optional",Pt(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,a)=>{if(a.direction==="backward")return t.innerType._zod.run(n,a);if(n.value===void 0)return n.value=t.defaultValue,n;const o=t.innerType._zod.run(n,a);return o instanceof Promise?o.then(i=>Jv(i,t)):Jv(o,t)}});function Jv(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const NA=ve("$ZodPrefault",(e,t)=>{Jt.init(e,t),e._zod.optin="optional",Pt(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))}),DA=ve("$ZodNonOptional",(e,t)=>{Jt.init(e,t),Pt(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(a=>a!==void 0)):void 0}),e._zod.parse=(n,a)=>{const o=t.innerType._zod.run(n,a);return o instanceof Promise?o.then(i=>Yv(i,e)):Yv(o,e)}});function Yv(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 LA=ve("$ZodCatch",(e,t)=>{Jt.init(e,t),e._zod.optin="optional",Pt(e._zod,"optout",()=>t.innerType._zod.optout),Pt(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,a)=>{if(a.direction==="backward")return t.innerType._zod.run(n,a);const o=t.innerType._zod.run(n,a);return o instanceof Promise?o.then(i=>(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(s=>Wo(s,a,Ko()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=o.value,o.issues.length&&(n.value=t.catchValue({...n,error:{issues:o.issues.map(i=>Wo(i,a,Ko()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),tk=ve("$ZodPipe",(e,t)=>{Jt.init(e,t),Pt(e._zod,"values",()=>t.in._zod.values),Pt(e._zod,"optin",()=>t.in._zod.optin),Pt(e._zod,"optout",()=>t.out._zod.optout),Pt(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,a)=>{if(a.direction==="backward"){const i=t.out._zod.run(n,a);return i instanceof Promise?i.then(s=>Dc(s,t.in,a)):Dc(i,t.in,a)}const o=t.in._zod.run(n,a);return o instanceof Promise?o.then(i=>Dc(i,t.out,a)):Dc(o,t.out,a)}});function Dc(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 UA=ve("$ZodPreprocess",(e,t)=>{tk.init(e,t)}),zA=ve("$ZodReadonly",(e,t)=>{Jt.init(e,t),Pt(e._zod,"propValues",()=>t.innerType._zod.propValues),Pt(e._zod,"values",()=>t.innerType._zod.values),Pt(e._zod,"optin",()=>t.innerType?._zod?.optin),Pt(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(Qv):Qv(o)}});function Qv(e){return e.value=Object.freeze(e.value),e}const HA=ve("$ZodLazy",(e,t)=>{Jt.init(e,t),Pt(e._zod,"innerType",()=>{const n=t;return n._cachedInner||(n._cachedInner=t.getter()),n._cachedInner}),Pt(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),Pt(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),Pt(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),Pt(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(n,a)=>e._zod.innerType._zod.run(n,a)}),qA=ve("$ZodCustom",(e,t)=>{aa.init(e,t),Jt.init(e,t),e._zod.parse=(n,a)=>n,e._zod.check=n=>{const a=n.value,o=t.fn(a);if(o instanceof Promise)return o.then(i=>Xv(i,n,a,e));Xv(o,n,a,e)}});function Xv(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(Al(o))}}var eb;class BA{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 FA(){return new BA}(eb=globalThis).__zod_globalRegistry??(eb.__zod_globalRegistry=FA());const pl=globalThis.__zod_globalRegistry;function VA(e,t){return new e({type:"string",...nt(t)})}function KA(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...nt(t)})}function tb(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...nt(t)})}function WA(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...nt(t)})}function GA(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...nt(t)})}function ZA(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...nt(t)})}function JA(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...nt(t)})}function YA(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...nt(t)})}function QA(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...nt(t)})}function XA(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...nt(t)})}function eT(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...nt(t)})}function tT(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...nt(t)})}function nT(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...nt(t)})}function aT(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...nt(t)})}function oT(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...nt(t)})}function rT(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...nt(t)})}function iT(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...nt(t)})}function sT(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...nt(t)})}function lT(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...nt(t)})}function cT(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...nt(t)})}function dT(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...nt(t)})}function uT(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...nt(t)})}function mT(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...nt(t)})}function pT(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...nt(t)})}function fT(e,t){return new e({type:"string",format:"date",check:"string_format",...nt(t)})}function hT(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...nt(t)})}function gT(e,t){return new e({type:"string",format:"duration",check:"string_format",...nt(t)})}function vT(e,t){return new e({type:"number",checks:[],...nt(t)})}function bT(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...nt(t)})}function yT(e,t){return new e({type:"boolean",...nt(t)})}function ST(e,t){return new e({type:"null",...nt(t)})}function kT(e){return new e({type:"unknown"})}function xT(e,t){return new e({type:"never",...nt(t)})}function nb(e,t){return new WS({check:"less_than",...nt(t),value:e,inclusive:!1})}function Jm(e,t){return new WS({check:"less_than",...nt(t),value:e,inclusive:!0})}function ab(e,t){return new GS({check:"greater_than",...nt(t),value:e,inclusive:!1})}function Ym(e,t){return new GS({check:"greater_than",...nt(t),value:e,inclusive:!0})}function ob(e,t){return new OP({check:"multiple_of",...nt(t),value:e})}function nk(e,t){return new NP({check:"max_length",...nt(t),maximum:e})}function wd(e,t){return new DP({check:"min_length",...nt(t),minimum:e})}function ak(e,t){return new LP({check:"length_equals",...nt(t),length:e})}function wT(e,t){return new UP({check:"string_format",format:"regex",...nt(t),pattern:e})}function IT(e){return new zP({check:"string_format",format:"lowercase",...nt(e)})}function _T(e){return new HP({check:"string_format",format:"uppercase",...nt(e)})}function CT(e,t){return new qP({check:"string_format",format:"includes",...nt(t),includes:e})}function RT(e,t){return new BP({check:"string_format",format:"starts_with",...nt(t),prefix:e})}function PT(e,t){return new FP({check:"string_format",format:"ends_with",...nt(t),suffix:e})}function ms(e){return new VP({check:"overwrite",tx:e})}function AT(e){return ms(t=>t.normalize(e))}function TT(){return ms(e=>e.trim())}function ET(){return ms(e=>e.toLowerCase())}function MT(){return ms(e=>e.toUpperCase())}function jT(){return ms(e=>NR(e))}function OT(e,t,n){return new e({type:"array",element:t,...nt(n)})}function $T(e,t,n){const a=nt(n);return a.abort??(a.abort=!0),new e({type:"custom",check:"custom",fn:t,...a})}function NT(e,t,n){return new e({type:"custom",check:"custom",fn:t,...nt(n)})}function DT(e,t){const n=LT(a=>(a.addIssue=o=>{if(typeof o=="string")a.issues.push(Al(o,a.value,n._zod.def));else{const i=o;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=a.value),i.inst??(i.inst=n),i.continue??(i.continue=!n._zod.def.abort),a.issues.push(Al(i))}},e(a.value,a)),t);return n}function LT(e,t){const n=new aa({check:"custom",...nt(t)});return n._zod.check=e,n}function ok(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??pl,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 un(e,t,n={path:[],schemaPath:[]}){var a;const o=e._zod.def,i=t.seen.get(e);if(i)return i.count++,n.schemaPath.includes(e)&&(i.cycle=n.path),i.schema;const s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s);const l=e._zod.toJSONSchema?.();if(l)s.schema=l;else{const h={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,h);else{const y=s.schema,w=t.processors[o.type];if(!w)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);w(e,t,y,h)}const v=e._zod.parent;v&&(s.ref||(s.ref=v),un(v,t,h),t.seen.get(v).isParent=!0)}const m=t.metadataRegistry.get(e);return m&&Object.assign(s.schema,m),t.io==="input"&&qn(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 rk(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const a=new Map;for(const s of e.seen.entries()){const l=e.metadataRegistry.get(s[0])?.id;if(l){const m=a.get(l);if(m&&m!==s[0])throw new Error(`Duplicate schema id "${l}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);a.set(l,s[0])}}const o=s=>{const l=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const v=e.external.registry.get(s[0])?.id,y=e.external.uri??(I=>I);if(v)return{ref:y(v)};const w=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=w,{defId:w,ref:`${y("__shared")}#/${l}/${w}`}}if(s[1]===n)return{ref:"#"};const d=`#/${l}/`,h=s[1].schema.id??`__schema${e.counter++}`;return{defId:h,ref:d+h}},i=s=>{if(s[1].schema.$ref)return;const l=s[1],{ref:m,defId:d}=o(s);l.def={...l.schema},d&&(l.defId=d);const h=l.schema;for(const v in h)delete h[v];h.$ref=m};if(e.cycles==="throw")for(const s of e.seen.entries()){const l=s[1];if(l.cycle)throw new Error(`Cycle detected: #/${l.cycle?.join("/")}/<root>
|
|
64
|
+
|
|
65
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const s of e.seen.entries()){const l=s[1];if(t===s[0]){i(s);continue}if(e.external){const d=e.external.registry.get(s[0])?.id;if(t!==s[0]&&d){i(s);continue}}if(e.metadataRegistry.get(s[0])?.id){i(s);continue}if(l.cycle){i(s);continue}if(l.count>1&&e.reused==="ref"){i(s);continue}}}function ik(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const a=l=>{const m=e.seen.get(l);if(m.ref===null)return;const d=m.def??m.schema,h={...d},v=m.ref;if(m.ref=null,v){a(v);const w=e.seen.get(v),I=w.schema;if(I.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(d.allOf=d.allOf??[],d.allOf.push(I)):Object.assign(d,I),Object.assign(d,h),l._zod.parent===v)for(const M in d)M==="$ref"||M==="allOf"||M in h||delete d[M];if(I.$ref&&w.def)for(const M in d)M==="$ref"||M==="allOf"||M in w.def&&JSON.stringify(d[M])===JSON.stringify(w.def[M])&&delete d[M]}const y=l._zod.parent;if(y&&y!==v){a(y);const w=e.seen.get(y);if(w?.schema.$ref&&(d.$ref=w.schema.$ref,w.def))for(const I in d)I==="$ref"||I==="allOf"||I in w.def&&JSON.stringify(d[I])===JSON.stringify(w.def[I])&&delete d[I]}e.override({zodSchema:l,jsonSchema:d,path:m.path??[]})};for(const l of[...e.seen.entries()].reverse())a(l[0]);const o={};if(e.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const l=e.external.registry.get(t)?.id;if(!l)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(l)}Object.assign(o,n.def??n.schema);const i=e.metadataRegistry.get(t)?.id;i!==void 0&&o.id===i&&delete o.id;const s=e.external?.defs??{};for(const l of e.seen.entries()){const m=l[1];m.def&&m.defId&&(m.def.id===m.defId&&delete m.def.id,s[m.defId]=m.def)}e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?o.$defs=s:o.definitions=s);try{const l=JSON.parse(JSON.stringify(o));return Object.defineProperty(l,"~standard",{value:{...t["~standard"],jsonSchema:{input:Id(t,"input",e.processors),output:Id(t,"output",e.processors)}},enumerable:!1,writable:!1}),l}catch{throw new Error("Error converting schema to JSON.")}}function qn(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 qn(a.element,n);if(a.type==="set")return qn(a.valueType,n);if(a.type==="lazy")return qn(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 qn(a.innerType,n);if(a.type==="intersection")return qn(a.left,n)||qn(a.right,n);if(a.type==="record"||a.type==="map")return qn(a.keyType,n)||qn(a.valueType,n);if(a.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:qn(a.in,n)||qn(a.out,n);if(a.type==="object"){for(const o in a.shape)if(qn(a.shape[o],n))return!0;return!1}if(a.type==="union"){for(const o of a.options)if(qn(o,n))return!0;return!1}if(a.type==="tuple"){for(const o of a.items)if(qn(o,n))return!0;return!!(a.rest&&qn(a.rest,n))}return!1}const UT=(e,t={})=>n=>{const a=ok({...n,processors:t});return un(e,a),rk(a,e),ik(a,e)},Id=(e,t,n={})=>a=>{const{libraryOptions:o,target:i}=a??{},s=ok({...o??{},target:i,io:t,processors:n});return un(e,s),rk(s,e),ik(s,e)},zT={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},HT=(e,t,n,a)=>{const o=n;o.type="string";const{minimum:i,maximum:s,format:l,patterns:m,contentEncoding:d}=e._zod.bag;if(typeof i=="number"&&(o.minLength=i),typeof s=="number"&&(o.maxLength=s),l&&(o.format=zT[l]??l,o.format===""&&delete o.format,l==="time"&&delete o.format),d&&(o.contentEncoding=d),m&&m.size>0){const h=[...m];h.length===1?o.pattern=h[0].source:h.length>1&&(o.allOf=[...h.map(v=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:v.source}))])}},qT=(e,t,n,a)=>{const o=n,{minimum:i,maximum:s,format:l,multipleOf:m,exclusiveMaximum:d,exclusiveMinimum:h}=e._zod.bag;typeof l=="string"&&l.includes("int")?o.type="integer":o.type="number";const v=typeof h=="number"&&h>=(i??Number.NEGATIVE_INFINITY),y=typeof d=="number"&&d<=(s??Number.POSITIVE_INFINITY),w=t.target==="draft-04"||t.target==="openapi-3.0";v?w?(o.minimum=h,o.exclusiveMinimum=!0):o.exclusiveMinimum=h:typeof i=="number"&&(o.minimum=i),y?w?(o.maximum=d,o.exclusiveMaximum=!0):o.exclusiveMaximum=d:typeof s=="number"&&(o.maximum=s),typeof m=="number"&&(o.multipleOf=m)},BT=(e,t,n,a)=>{n.type="boolean"},FT=(e,t,n,a)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},VT=(e,t,n,a)=>{n.not={}},KT=(e,t,n,a)=>{},WT=(e,t,n,a)=>{const o=e._zod.def,i=NS(o.entries);i.every(s=>typeof s=="number")&&(n.type="number"),i.every(s=>typeof s=="string")&&(n.type="string"),n.enum=i},GT=(e,t,n,a)=>{const o=e._zod.def,i=[];for(const s of o.values)if(s===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(s))}else i.push(s);if(i.length!==0)if(i.length===1){const s=i[0];n.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[s]:n.const=s}else i.every(s=>typeof s=="number")&&(n.type="number"),i.every(s=>typeof s=="string")&&(n.type="string"),i.every(s=>typeof s=="boolean")&&(n.type="boolean"),i.every(s=>s===null)&&(n.type="null"),n.enum=i},ZT=(e,t,n,a)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},JT=(e,t,n,a)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},YT=(e,t,n,a)=>{const o=n,i=e._zod.def,{minimum:s,maximum:l}=e._zod.bag;typeof s=="number"&&(o.minItems=s),typeof l=="number"&&(o.maxItems=l),o.type="array",o.items=un(i.element,t,{...a,path:[...a.path,"items"]})},QT=(e,t,n,a)=>{const o=n,i=e._zod.def;o.type="object",o.properties={};const s=i.shape;for(const d in s)o.properties[d]=un(s[d],t,{...a,path:[...a.path,"properties",d]});const l=new Set(Object.keys(s)),m=new Set([...l].filter(d=>{const h=i.shape[d]._zod;return t.io==="input"?h.optin===void 0:h.optout===void 0}));m.size>0&&(o.required=Array.from(m)),i.catchall?._zod.def.type==="never"?o.additionalProperties=!1:i.catchall?i.catchall&&(o.additionalProperties=un(i.catchall,t,{...a,path:[...a.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},XT=(e,t,n,a)=>{const o=e._zod.def,i=o.inclusive===!1,s=o.options.map((l,m)=>un(l,t,{...a,path:[...a.path,i?"oneOf":"anyOf",m]}));i?n.oneOf=s:n.anyOf=s},eE=(e,t,n,a)=>{const o=e._zod.def,i=un(o.left,t,{...a,path:[...a.path,"allOf",0]}),s=un(o.right,t,{...a,path:[...a.path,"allOf",1]}),l=d=>"allOf"in d&&Object.keys(d).length===1,m=[...l(i)?i.allOf:[i],...l(s)?s.allOf:[s]];n.allOf=m},tE=(e,t,n,a)=>{const o=n,i=e._zod.def;o.type="object";const s=i.keyType,m=s._zod.bag?.patterns;if(i.mode==="loose"&&m&&m.size>0){const h=un(i.valueType,t,{...a,path:[...a.path,"patternProperties","*"]});o.patternProperties={};for(const v of m)o.patternProperties[v.source]=h}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(o.propertyNames=un(i.keyType,t,{...a,path:[...a.path,"propertyNames"]})),o.additionalProperties=un(i.valueType,t,{...a,path:[...a.path,"additionalProperties"]});const d=s._zod.values;if(d){const h=[...d].filter(v=>typeof v=="string"||typeof v=="number");h.length>0&&(o.required=h)}},nE=(e,t,n,a)=>{const o=e._zod.def,i=un(o.innerType,t,a),s=t.seen.get(e);t.target==="openapi-3.0"?(s.ref=o.innerType,n.nullable=!0):n.anyOf=[i,{type:"null"}]},aE=(e,t,n,a)=>{const o=e._zod.def;un(o.innerType,t,a);const i=t.seen.get(e);i.ref=o.innerType},oE=(e,t,n,a)=>{const o=e._zod.def;un(o.innerType,t,a);const i=t.seen.get(e);i.ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))},rE=(e,t,n,a)=>{const o=e._zod.def;un(o.innerType,t,a);const i=t.seen.get(e);i.ref=o.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},iE=(e,t,n,a)=>{const o=e._zod.def;un(o.innerType,t,a);const i=t.seen.get(e);i.ref=o.innerType;let s;try{s=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=s},sE=(e,t,n,a)=>{const o=e._zod.def,i=o.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?i?o.out:o.in:o.out;un(s,t,a);const l=t.seen.get(e);l.ref=s},lE=(e,t,n,a)=>{const o=e._zod.def;un(o.innerType,t,a);const i=t.seen.get(e);i.ref=o.innerType,n.readOnly=!0},sk=(e,t,n,a)=>{const o=e._zod.def;un(o.innerType,t,a);const i=t.seen.get(e);i.ref=o.innerType},cE=(e,t,n,a)=>{const o=e._zod.innerType;un(o,t,a);const i=t.seen.get(e);i.ref=o},dE=ve("ZodISODateTime",(e,t)=>{rA.init(e,t),tn.init(e,t)});function uE(e){return pT(dE,e)}const mE=ve("ZodISODate",(e,t)=>{iA.init(e,t),tn.init(e,t)});function pE(e){return fT(mE,e)}const fE=ve("ZodISOTime",(e,t)=>{sA.init(e,t),tn.init(e,t)});function hE(e){return hT(fE,e)}const gE=ve("ZodISODuration",(e,t)=>{lA.init(e,t),tn.init(e,t)});function vE(e){return gT(gE,e)}const lk=(e,t)=>{zS.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>JR(e,n)},flatten:{value:n=>ZR(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,gf,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,gf,2)}},isEmpty:{get(){return e.issues.length===0}}})},bE=ve("ZodError",lk),Ca=ve("ZodError",lk,{Parent:Error}),yE=Ph(Ca),SE=Ah(Ca),kE=Jd(Ca),xE=Yd(Ca),wE=XR(Ca),IE=eP(Ca),_E=tP(Ca),CE=nP(Ca),RE=aP(Ca),PE=oP(Ca),AE=rP(Ca),TE=iP(Ca),rb=new WeakMap;function Gl(e,t,n){const a=Object.getPrototypeOf(e);let o=rb.get(a);if(o||(o=new Set,rb.set(a,o)),!o.has(t)){o.add(t);for(const i in n){const s=n[i];Object.defineProperty(a,i,{configurable:!0,enumerable:!1,get(){const l=s.bind(this);return Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:l}),l},set(l){Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:l})}})}}}const Yt=ve("ZodType",(e,t)=>(Jt.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Id(e,"input"),output:Id(e,"output")}}),e.toJSONSchema=UT(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,a)=>yE(e,n,a,{callee:e.parse}),e.safeParse=(n,a)=>kE(e,n,a),e.parseAsync=async(n,a)=>SE(e,n,a,{callee:e.parseAsync}),e.safeParseAsync=async(n,a)=>xE(e,n,a),e.spa=e.safeParseAsync,e.encode=(n,a)=>wE(e,n,a),e.decode=(n,a)=>IE(e,n,a),e.encodeAsync=async(n,a)=>_E(e,n,a),e.decodeAsync=async(n,a)=>CE(e,n,a),e.safeEncode=(n,a)=>RE(e,n,a),e.safeDecode=(n,a)=>PE(e,n,a),e.safeEncodeAsync=async(n,a)=>AE(e,n,a),e.safeDecodeAsync=async(n,a)=>TE(e,n,a),Gl(e,"ZodType",{check(...n){const a=this.def;return this.clone(pr(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 fr(this,n,a)},brand(){return this},register(n,a){return n.add(this,a),this},refine(n,a){return this.check(kM(n,a))},superRefine(n,a){return this.check(xM(n,a))},overwrite(n){return this.check(ms(n))},optional(){return cb(this)},exactOptional(){return sM(this)},nullable(){return db(this)},nullish(){return cb(db(this))},nonoptional(n){return pM(this,n)},array(){return f(this)},or(n){return Dt([this,n])},and(n){return aM(this,n)},transform(n){return ub(this,fk(n))},default(n){return dM(this,n)},prefault(n){return mM(this,n)},catch(n){return hM(this,n)},pipe(n){return ub(this,n)},readonly(){return bM(this)},describe(n){const a=this.clone();return pl.add(a,{description:n}),a},meta(...n){if(n.length===0)return pl.get(this);const a=this.clone();return pl.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 pl.get(e)?.description},configurable:!0}),e)),ck=ve("_ZodString",(e,t)=>{Th.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(a,o,i)=>HT(e,a,o);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Gl(e,"_ZodString",{regex(...a){return this.check(wT(...a))},includes(...a){return this.check(CT(...a))},startsWith(...a){return this.check(RT(...a))},endsWith(...a){return this.check(PT(...a))},min(...a){return this.check(wd(...a))},max(...a){return this.check(nk(...a))},length(...a){return this.check(ak(...a))},nonempty(...a){return this.check(wd(1,...a))},lowercase(a){return this.check(IT(a))},uppercase(a){return this.check(_T(a))},trim(){return this.check(TT())},normalize(...a){return this.check(AT(...a))},toLowerCase(){return this.check(ET())},toUpperCase(){return this.check(MT())},slugify(){return this.check(jT())}})}),EE=ve("ZodString",(e,t)=>{Th.init(e,t),ck.init(e,t),e.email=n=>e.check(KA(ME,n)),e.url=n=>e.check(YA(jE,n)),e.jwt=n=>e.check(mT(GE,n)),e.emoji=n=>e.check(QA(OE,n)),e.guid=n=>e.check(tb(ib,n)),e.uuid=n=>e.check(WA(Lc,n)),e.uuidv4=n=>e.check(GA(Lc,n)),e.uuidv6=n=>e.check(ZA(Lc,n)),e.uuidv7=n=>e.check(JA(Lc,n)),e.nanoid=n=>e.check(XA($E,n)),e.guid=n=>e.check(tb(ib,n)),e.cuid=n=>e.check(eT(NE,n)),e.cuid2=n=>e.check(tT(DE,n)),e.ulid=n=>e.check(nT(LE,n)),e.base64=n=>e.check(cT(VE,n)),e.base64url=n=>e.check(dT(KE,n)),e.xid=n=>e.check(aT(UE,n)),e.ksuid=n=>e.check(oT(zE,n)),e.ipv4=n=>e.check(rT(HE,n)),e.ipv6=n=>e.check(iT(qE,n)),e.cidrv4=n=>e.check(sT(BE,n)),e.cidrv6=n=>e.check(lT(FE,n)),e.e164=n=>e.check(uT(WE,n)),e.datetime=n=>e.check(uE(n)),e.date=n=>e.check(pE(n)),e.time=n=>e.check(hE(n)),e.duration=n=>e.check(vE(n))});function r(e){return VA(EE,e)}const tn=ve("ZodStringFormat",(e,t)=>{en.init(e,t),ck.init(e,t)}),ME=ve("ZodEmail",(e,t)=>{JP.init(e,t),tn.init(e,t)}),ib=ve("ZodGUID",(e,t)=>{GP.init(e,t),tn.init(e,t)}),Lc=ve("ZodUUID",(e,t)=>{ZP.init(e,t),tn.init(e,t)}),jE=ve("ZodURL",(e,t)=>{YP.init(e,t),tn.init(e,t)}),OE=ve("ZodEmoji",(e,t)=>{QP.init(e,t),tn.init(e,t)}),$E=ve("ZodNanoID",(e,t)=>{XP.init(e,t),tn.init(e,t)}),NE=ve("ZodCUID",(e,t)=>{eA.init(e,t),tn.init(e,t)}),DE=ve("ZodCUID2",(e,t)=>{tA.init(e,t),tn.init(e,t)}),LE=ve("ZodULID",(e,t)=>{nA.init(e,t),tn.init(e,t)}),UE=ve("ZodXID",(e,t)=>{aA.init(e,t),tn.init(e,t)}),zE=ve("ZodKSUID",(e,t)=>{oA.init(e,t),tn.init(e,t)}),HE=ve("ZodIPv4",(e,t)=>{cA.init(e,t),tn.init(e,t)}),qE=ve("ZodIPv6",(e,t)=>{dA.init(e,t),tn.init(e,t)}),BE=ve("ZodCIDRv4",(e,t)=>{uA.init(e,t),tn.init(e,t)}),FE=ve("ZodCIDRv6",(e,t)=>{mA.init(e,t),tn.init(e,t)}),VE=ve("ZodBase64",(e,t)=>{pA.init(e,t),tn.init(e,t)}),KE=ve("ZodBase64URL",(e,t)=>{hA.init(e,t),tn.init(e,t)}),WE=ve("ZodE164",(e,t)=>{gA.init(e,t),tn.init(e,t)}),GE=ve("ZodJWT",(e,t)=>{bA.init(e,t),tn.init(e,t)}),dk=ve("ZodNumber",(e,t)=>{JS.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(a,o,i)=>qT(e,a,o),Gl(e,"ZodNumber",{gt(a,o){return this.check(ab(a,o))},gte(a,o){return this.check(Ym(a,o))},min(a,o){return this.check(Ym(a,o))},lt(a,o){return this.check(nb(a,o))},lte(a,o){return this.check(Jm(a,o))},max(a,o){return this.check(Jm(a,o))},int(a){return this.check(sb(a))},safe(a){return this.check(sb(a))},positive(a){return this.check(ab(0,a))},nonnegative(a){return this.check(Ym(0,a))},negative(a){return this.check(nb(0,a))},nonpositive(a){return this.check(Jm(0,a))},multipleOf(a,o){return this.check(ob(a,o))},step(a,o){return this.check(ob(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 vT(dk,e)}const ZE=ve("ZodNumberFormat",(e,t)=>{yA.init(e,t),dk.init(e,t)});function sb(e){return bT(ZE,e)}const JE=ve("ZodBoolean",(e,t)=>{SA.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>BT(e,n,a)});function A(e){return yT(JE,e)}const YE=ve("ZodNull",(e,t)=>{kA.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>FT(e,n,a)});function Xd(e){return ST(YE,e)}const QE=ve("ZodUnknown",(e,t)=>{xA.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>KT()});function ce(){return kT(QE)}const XE=ve("ZodNever",(e,t)=>{wA.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>VT(e,n,a)});function uk(e){return xT(XE,e)}const eM=ve("ZodArray",(e,t)=>{IA.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>YT(e,n,a,o),e.element=t.element,Gl(e,"ZodArray",{min(n,a){return this.check(wd(n,a))},nonempty(n){return this.check(wd(1,n))},max(n,a){return this.check(nk(n,a))},length(n,a){return this.check(ak(n,a))},unwrap(){return this.element}})});function f(e,t){return OT(eM,e,t)}const mk=ve("ZodObject",(e,t)=>{CA.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>QT(e,n,a,o),Pt(e,"shape",()=>t.shape),Gl(e,"ZodObject",{keyof(){return b(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:ce()})},loose(){return this.clone({...this._zod.def,catchall:ce()})},strict(){return this.clone({...this._zod.def,catchall:uk()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return BR(this,n)},safeExtend(n){return FR(this,n)},merge(n){return VR(this,n)},pick(n){return HR(this,n)},omit(n){return qR(this,n)},partial(...n){return KR(hk,this,n[0])},required(...n){return WR(gk,this,n[0])}})});function c(e,t){const n={type:"object",shape:e??{},...nt(t)};return new mk(n)}function Qm(e,t){return new mk({type:"object",shape:e,catchall:uk(),...nt(t)})}const pk=ve("ZodUnion",(e,t)=>{XS.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>XT(e,n,a,o),e.options=t.options});function Dt(e,t){return new pk({type:"union",options:e,...nt(t)})}const tM=ve("ZodDiscriminatedUnion",(e,t)=>{pk.init(e,t),RA.init(e,t)});function Rt(e,t,n){return new tM({type:"union",options:t,discriminator:e,...nt(n)})}const nM=ve("ZodIntersection",(e,t)=>{PA.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>eE(e,n,a,o)});function aM(e,t){return new nM({type:"intersection",left:e,right:t})}const lb=ve("ZodRecord",(e,t)=>{AA.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>tE(e,n,a,o),e.keyType=t.keyType,e.valueType=t.valueType});function ie(e,t,n){return!t||!t._zod?new lb({type:"record",keyType:r(),valueType:e,...nt(t)}):new lb({type:"record",keyType:e,valueType:t,...nt(n)})}const bf=ve("ZodEnum",(e,t)=>{TA.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(a,o,i)=>WT(e,a,o),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(a,o)=>{const i={};for(const s of a)if(n.has(s))i[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new bf({...t,checks:[],...nt(o),entries:i})},e.exclude=(a,o)=>{const i={...t.entries};for(const s of a)if(n.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new bf({...t,checks:[],...nt(o),entries:i})}});function b(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(a=>[a,a])):e;return new bf({type:"enum",entries:n,...nt(t)})}const oM=ve("ZodLiteral",(e,t)=>{EA.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>GT(e,n,a),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function S(e,t){return new oM({type:"literal",values:Array.isArray(e)?e:[e],...nt(t)})}const rM=ve("ZodTransform",(e,t)=>{MA.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>JT(e,n),e._zod.parse=(n,a)=>{if(a.direction==="backward")throw new $S(e.constructor.name);n.addIssue=i=>{if(typeof i=="string")n.issues.push(Al(i,n.value,t));else{const s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=e),n.issues.push(Al(s))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(i=>(n.value=i,n.fallback=!0,n)):(n.value=o,n.fallback=!0,n)}});function fk(e){return new rM({type:"transform",transform:e})}const hk=ve("ZodOptional",(e,t)=>{ek.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>sk(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function cb(e){return new hk({type:"optional",innerType:e})}const iM=ve("ZodExactOptional",(e,t)=>{jA.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>sk(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function sM(e){return new iM({type:"optional",innerType:e})}const lM=ve("ZodNullable",(e,t)=>{OA.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>nE(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function db(e){return new lM({type:"nullable",innerType:e})}const cM=ve("ZodDefault",(e,t)=>{$A.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>oE(e,n,a,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function dM(e,t){return new cM({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():LS(t)}})}const uM=ve("ZodPrefault",(e,t)=>{NA.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>rE(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function mM(e,t){return new uM({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():LS(t)}})}const gk=ve("ZodNonOptional",(e,t)=>{DA.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>aE(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function pM(e,t){return new gk({type:"nonoptional",innerType:e,...nt(t)})}const fM=ve("ZodCatch",(e,t)=>{LA.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>iE(e,n,a,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function hM(e,t){return new fM({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const vk=ve("ZodPipe",(e,t)=>{tk.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>sE(e,n,a,o),e.in=t.in,e.out=t.out});function ub(e,t){return new vk({type:"pipe",in:e,out:t})}const gM=ve("ZodPreprocess",(e,t)=>{vk.init(e,t),UA.init(e,t)}),vM=ve("ZodReadonly",(e,t)=>{zA.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>lE(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function bM(e){return new vM({type:"readonly",innerType:e})}const yM=ve("ZodLazy",(e,t)=>{HA.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>cE(e,n,a,o),e.unwrap=()=>e._zod.def.getter()});function SM(e){return new yM({type:"lazy",getter:e})}const bk=ve("ZodCustom",(e,t)=>{qA.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>ZT(e,n)});function Xm(e,t){return $T(bk,(()=>!0),t)}function kM(e,t={}){return NT(bk,e,t)}function xM(e,t){return DT(e,t)}function Br(e){const t=SM(()=>Dt([r(e),u(),A(),Xd(),f(t),ie(r(),t)]));return t}function wM(e,t){return new gM({type:"pipe",in:fk(e),out:t})}const Fn={custom:"custom"},IM=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),_M=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function CM(e){const t=typeof e=="string"?new TextEncoder().encode(e):e,n=Math.ceil((t.byteLength+9)/64)*64,a=new Uint8Array(n);a.set(t),a[t.byteLength]=128;const o=t.byteLength*8,i=new DataView(a.buffer);i.setUint32(n-8,Math.floor(o/4294967296),!1),i.setUint32(n-4,o>>>0,!1);const s=new Uint32Array(IM),l=new Uint32Array(64);for(let m=0;m<n;m+=64){for(let P=0;P<16;P+=1)l[P]=i.getUint32(m+P*4,!1);for(let P=16;P<64;P+=1){const N=l[P-15],O=l[P-2],j=no(N,7)^no(N,18)^N>>>3,k=no(O,17)^no(O,19)^O>>>10;l[P]=l[P-16]+j+l[P-7]+k>>>0}let d=s[0],h=s[1],v=s[2],y=s[3],w=s[4],I=s[5],R=s[6],M=s[7];for(let P=0;P<64;P+=1){const N=w&I^~w&R,O=d&h^d&v^h&v,j=no(d,2)^no(d,13)^no(d,22),k=no(w,6)^no(w,11)^no(w,25),C=M+k+N+_M[P]+l[P]>>>0,T=j+O>>>0;M=R,R=I,I=w,w=y+C>>>0,y=v,v=h,h=d,d=C+T>>>0}s[0]=s[0]+d>>>0,s[1]=s[1]+h>>>0,s[2]=s[2]+v>>>0,s[3]=s[3]+y>>>0,s[4]=s[4]+w>>>0,s[5]=s[5]+I>>>0,s[6]=s[6]+R>>>0,s[7]=s[7]+M>>>0}return Array.from(s,m=>m.toString(16).padStart(8,"0")).join("")}function no(e,t){return e>>>t|e<<32-t}const RM=2e3,yk=25e7,E=r().trim().min(1).max(240),Y=r().regex(/^[a-f0-9]{64}$/),Pe=r().datetime({offset:!0}),Cn=ie(r(),ce()).default({}),ee=c({id:E,contentHash:Y}).strict(),Kt=ee.extend({revision:u().int().positive()}).strict(),dn=c({id:E,path:r().trim().min(1).max(RM).refine(AM),contentHash:Y,sizeBytes:u().int().nonnegative().max(yk),mediaType:r().trim().min(1).max(200),visibility:b(["policy","verifier","host_private"])}).strict(),za=c({id:E,contentHash:Y,mediaType:r().trim().min(1).max(200).nullable().default(null),sizeBytes:u().int().nonnegative().max(yk).nullable().default(null)}).strict(),Zl=b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]);function PM(e){return`${JSON.stringify(yf(e),null,2)}
|
|
66
|
+
`}function Eh(e){return CM(e)}function rn(e){return Eh(PM(e))}function AM(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function yf(e){return Array.isArray(e)?e.map(yf):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,yf(n)]))}const Mh=c({provider:E,model:E,revision:r().trim().min(1).max(500).nullable().default(null),artifactHash:Y.nullable().default(null),tokenizerRevision:r().trim().min(1).max(500).nullable().default(null),chatTemplateHash:Y.nullable().default(null)}).strict(),jh=["openpond","codex","anthropic","openai","xai","google","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],Jr=b(jh),mn=c({providerId:Jr,modelId:r().trim().min(1).max(300)}),eu=b(["active","preview","planned","deprecated"]),Sk=b(["openpond-account","openpond-managed","codex-login","chatgpt-subscription","local-byok","hosted-byok","custom"]),TM=b(["none","local_secret","env","openpond_account","codex_login","chatgpt_subscription","hosted"]),mb=c({connected:A().default(!1),source:TM.default("none"),redacted:r().nullable().default(null),lastValidatedAt:r().nullable().default(null),lastError:r().nullable().default(null)}),Sf=c({hostedOpChat:A().default(!1),localRuntime:A().default(!0),localByok:A().default(!1),hostedByok:A().default(!1)}),EM=b(["hosted","provider","manual","none"]),kf=c({chatCompletions:A().default(!0),streaming:A().default(!0),modelDiscovery:EM.default("none"),toolCalling:A().default(!1),reasoning:A().default(!1),imageInput:A().default(!1),structuredOutput:A().default(!1)}),MM=b(["hosted","provider","curated","manual","cache"]),xf=c({streaming:A().default(!0),toolCalling:A().default(!1),reasoning:A().default(!1),vision:A().default(!1),structuredOutput:A().default(!1)}),jM=c({id:r().trim().min(1).max(300),providerId:Jr,displayName:r().trim().min(1).max(300),contextWindow:u().int().positive().nullable().default(null),outputLimit:u().int().positive().nullable().default(null),lifecycleStatus:eu.default("active"),source:MM,capabilities:xf.default(()=>xf.parse({})),raw:ie(r(),ce()).optional()}),OM=c({providerId:Jr,models:f(jM).default([]),fetchedAt:r().nullable().default(null),lastError:r().nullable().default(null),source:b(["none","hosted","provider","curated","manual"]).default("none")}),$M=c({enabled:A().default(!1),baseUrl:r().trim().min(1).max(2048).nullable().default(null),defaultModel:r().trim().min(1).max(300).nullable().default(null),modelOverrides:f(r().trim().min(1).max(300)).max(500).default([]),updatedAt:r().nullable().default(null)}),NM=c({enabled:A().optional(),baseUrl:r().trim().min(1).max(2048).nullable().optional(),defaultModel:r().trim().min(1).max(300).nullable().optional(),modelOverrides:f(r().trim().min(1).max(300)).max(500).optional()}),DM=c({id:r().trim().min(1).max(300),displayName:r().trim().min(1).max(300),contextWindow:u().int().positive().nullable().optional(),outputLimit:u().int().positive().nullable().optional(),lifecycleStatus:eu.optional(),capabilities:xf.partial().optional()}),LM=c({id:Jr,displayName:r().trim().min(1).max(160),lifecycleStatus:eu.default("active"),credentialModes:f(Sk).default([]),routing:Sf,capabilities:kf,defaultEnabled:A().optional(),defaultBaseUrl:r().trim().min(1).max(2048).nullable().optional(),defaultModel:r().trim().min(1).max(300).nullable().optional(),modelCacheSource:b(["none","hosted","provider","curated","manual"]),models:f(DM).default([])});c({version:S(1).default(1),generatedAt:r().datetime(),providers:f(LM)});const UM=c({id:Jr,displayName:r().trim().min(1).max(160),lifecycleStatus:eu.default("active"),credentialModes:f(Sk).default([]),routing:Sf.default(()=>Sf.parse({})),capabilities:kf.default(()=>kf.parse({})),credential:mb.default(()=>mb.parse({})),enabled:A().default(!1),available:A().default(!1),defaultModel:r().trim().min(1).max(300).nullable().default(null),modelIds:f(r().trim().min(1).max(300)).max(1e3).default([]),lastError:r().nullable().default(null)}),pb=c({version:S(1).default(1),providers:ie(r(),$M).default({}),statuses:ie(r(),UM).default({}),modelCaches:ie(r(),OM).default({}),updatedAt:r().nullable().default(null)});c({providers:ie(r(),NM).optional()});c({source:b(["local_secret","env"]).default("local_secret"),value:r().min(1).max(2e4).optional(),envVar:r().trim().min(1).max(160).optional()}).superRefine((e,t)=>{e.source==="env"&&!e.envVar&&t.addIssue({code:"custom",path:["envVar"],message:"envVar is required when provider credential source is env."}),e.source==="local_secret"&&!e.value&&t.addIssue({code:"custom",path:["value"],message:"value is required when provider credential source is local_secret."})});c({source:b(["local_secret","env","chatgpt_subscription"]).optional()});c({modelId:r().trim().min(1).max(300).optional(),baseUrl:r().trim().min(1).max(2048).optional()});c({query:r().trim().max(200).optional(),refresh:A().default(!1),limit:u().int().positive().max(500).default(100)});c({query:r().trim().max(200).optional(),force:A().default(!1)});const zM=["coding","research","review","test","docs","planner","summarizer"];b(zM);const ps=r().trim().min(1).max(80).regex(/^[a-z][a-z0-9_-]*$/),kk=b(["none","worktree","copy_on_write"]),xk=b(["read_only","workspace_write","full_tools"]),wk=b(["disabled","parent_scoped"]),tu=b(["manual","balanced","proactive"]),HM=b(["queued","running","completed","failed","cancelled","needs_resume"]),Ik=["subagent.started","subagent.reported","subagent.completed","subagent.progress","subagent.failed","subagent.cancelled","subagent.cleanup","subagent.workspace_retained","subagent.workspace_retention_expiring","subagent.archived","subagent.message"];b(Ik);const qM=[{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"}],Oh=c({id:ps,enabled:A().default(!0),modelRef:mn.nullable().default(null),isolationMode:kk.default("none"),maxConcurrentRuns:u().int().min(1).max(16).default(1),toolPolicy:xk.default("read_only"),background:A().default(!0),peerMessages:wk.default("parent_scoped")}),Tl=c({enabled:A().default(!0),workspaceDefaultsVersion:S(1).default(1),toolDefaultsVersion:S(1).default(1),delegationMode:tu.default("manual"),defaultModelRef:mn.nullable().default(null),roles:f(Oh).max(64).default(()=>Rk()),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:XM(e.roles)})),yl=c({kind:b(["session","turn","file","diff","artifact"]),id:r().trim().min(1).max(500),label:r().trim().min(1).max(500)}),BM=c({kind:b(["retain_with_parent"]).default("retain_with_parent"),messageRetentionDays:u().int().min(1).max(3650).nullable().default(null),artifactRetentionDays:u().int().min(1).max(3650).nullable().default(null),cleanupAfterExpiry:A().default(!1)}).default(()=>({kind:"retain_with_parent",messageRetentionDays:null,artifactRetentionDays:null,cleanupAfterExpiry:!1})),FM=b(["orient","edit","validate","report"]),VM=c({command:r().trim().min(1).max(2e3),status:b(["passed","failed","unknown"]).default("unknown"),exitCode:u().int().nullable().default(null),outputSummary:r().trim().max(5e3).nullable().default(null),startedAt:r().nullable().default(null),completedAt:r().nullable().default(null)}),KM=c({phase:FM.default("orient"),inspectedFiles:f(r().trim().min(1).max(1e3)).max(500).default([]),inspectedResources:f(r().trim().min(1).max(1e3)).max(500).default([]),repeatedSearches:f(r().trim().min(1).max(1e3)).max(200).default([]),repeatedReads:f(r().trim().min(1).max(1e3)).max(200).default([]),repeatedCommands:f(r().trim().min(1).max(1e3)).max(200).default([]),changedFiles:f(r().trim().min(1).max(1e3)).max(500).default([]),patchRefs:f(yl).max(100).default([]),validationAttempts:f(VM).max(100).default([]),latestMeaningfulActivity:r().trim().max(5e3).nullable().default(null),currentBlocker:r().trim().max(5e3).nullable().default(null),updatedAt:r().nullable().default(null)}).default(()=>({phase:"orient",inspectedFiles:[],inspectedResources:[],repeatedSearches:[],repeatedReads:[],repeatedCommands:[],changedFiles:[],patchRefs:[],validationAttempts:[],latestMeaningfulActivity:null,currentBlocker:null,updatedAt:null})),WM=c({summary:r().trim().max(2e4).default(""),findings:f(r().trim().min(1).max(5e3)).max(200).default([]),artifacts:f(yl).max(200).default([]),patchRef:yl.nullable().default(null),diffRef:yl.nullable().default(null),testsRun:f(r().trim().min(1).max(2e3)).max(100).default([]),blockers:f(r().trim().min(1).max(5e3)).max(100).default([]),confidence:b(["low","medium","high"]).nullable().default(null),followUpNeeded:A().default(!1)}),_k=c({id:r().trim().min(1).max(200),parentSessionId:r().trim().min(1).max(200),parentTurnId:r().trim().min(1).max(200).nullable().default(null),childSessionId:r().trim().min(1).max(200).nullable().default(null),roleId:ps,objective:r().trim().min(1).max(5e4),modelRef:mn.nullable().default(null),isolationMode:kk.default("none"),toolPolicy:xk.default("read_only"),background:A().default(!0),peerMessages:wk.default("parent_scoped"),status:HM.default("queued"),progress:KM,evidenceRetention:BM,createdAt:r(),startedAt:r().nullable().default(null),completedAt:r().nullable().default(null),updatedAt:r().nullable().default(null),error:r().nullable().default(null),report:WM.nullable().default(null),metadata:ie(r(),ce()).optional().default({})}),Ck=b(["cleanup","archive","cleanup_and_archive"]);c({action:Ck,reason:r().trim().min(1).max(2e3).nullable().default(null)});c({action:Ck,run:_k,workspaceCleanup:ie(r(),ce()).nullable().default(null),sessionArchive:ie(r(),ce()).nullable().default(null),nextStep:r()});const GM=b(["question","answer","handoff","artifact","status","blocker"]),ZM=b(["normal","interrupt"]),JM=c({inputIds:f(r()).default([]),status:b(["pending","delivered","undelivered"]).default("pending"),deliveredRunIds:f(r().trim().min(1).max(200)).max(200).default([]),acknowledgedRunIds:f(r().trim().min(1).max(200)).max(200).default([]),deliveredParentSessionId:r().trim().min(1).max(200).nullable().default(null),acknowledgedParentSessionId:r().trim().min(1).max(200).nullable().default(null),wakeRequestedParentSessionId:r().trim().min(1).max(200).nullable().default(null),wakeQueuedParentSessionId:r().trim().min(1).max(200).nullable().default(null),wakeDeferredParentSessionId:r().trim().min(1).max(200).nullable().default(null),wakeParentReason:r().trim().min(1).max(1e3).nullable().default(null),wakeRequestedRunIds:f(r().trim().min(1).max(200)).max(200).default([]),wakeInterruptedRunIds:f(r().trim().min(1).max(200)).max(200).default([]),wakeDeferredRunIds:f(r().trim().min(1).max(200)).max(200).default([]),reason:r().trim().min(1).max(1e3).nullable().default(null)}),YM=c({id:r().trim().min(1).max(200),fromRunId:r().trim().min(1).max(200),toRunId:r().trim().min(1).max(200).nullable().default(null),toRole:ps.nullable().default(null),kind:GM,priority:ZM.optional(),body:r().trim().min(1).max(5e4),refs:f(yl).max(100).default([]),delivery:JM.optional(),createdAt:r()});function Rk(){return qM.map(e=>Oh.parse({id:e.id,toolPolicy:e.defaultToolPolicy}))}function QM(){return Tl.parse({})}function XM(e){const t=Rk(),n=new Map(t.map(o=>[o.id,o])),a=[];for(const o of e??[]){const i=Oh.parse(o);n.has(i.id)?n.set(i.id,i):a.push(i)}return[...t.map(o=>n.get(o.id)??o),...a]}const ej=b(["task.inbox","task.input","task.wait","session.started","session.title.updated","turn.started","assistant.delta","assistant.reasoning.delta","tool.started","tool.completed","skill.selected","skill.loaded","skill.load_failed","user_question.asked","user_question.answered","user_question.dismissed","approval.requested","approval.resolved","command.output","workspace_action","workspace_action_result","workspace.diff","create_improve.updated","session.context.updated","session.compaction.started","session.compaction.completed","session.compaction.failed","goal.continuation.started","goal.continuation.skipped","goal.continuation.failed","harness.refiner.queued","harness.refiner.started","harness.refiner.completed","harness.refiner.failed","turn.completed","turn.failed","turn.interrupted","session.closed",...Ik,"diagnostic"]),fb=c({id:r(),sequence:u().int().positive().optional(),sessionId:r().optional(),turnId:r().optional(),name:ej,timestamp:r(),source:b(["ui_button","chat_action","terminal_command","hook","provider","server"]).optional(),action:r().optional(),appId:r().nullable().optional(),args:ie(r(),ce()).optional(),status:b(["started","completed","failed","pending"]).optional(),output:r().optional(),error:r().optional(),relatedDeploymentId:r().optional(),data:ce().optional()}),tj=c({id:r().trim().min(1).max(80),label:r().trim().min(1).max(160),description:r().trim().max(500).nullable().optional().default(null)}),nj=c({id:r().trim().min(1),sessionId:r().trim().min(1),turnId:r().trim().min(1),toolCallId:r().trim().min(1),question:r().trim().min(1).max(2e3),reason:r().trim().max(1e3).nullable().optional().default(null),options:f(tj).max(5).default([]),allowFreeform:A().default(!0),status:b(["pending","answered","dismissed"]),answer:c({optionId:r().trim().min(1).nullable(),text:r().max(4e3)}).nullable(),createdAt:r(),answeredAt:r().nullable()}),aj=c({questionId:r().trim().min(1),action:b(["answer","dismiss"]),optionId:r().trim().min(1).nullable().optional().default(null),text:r().trim().max(4e3).optional().default("")});c({kind:b(["session","project","draft"]),id:r().trim().min(1).max(300)});b(["unknown","idle","running","success","failed"]);b(["none","idle","running","success","failed","unknown"]);function oj(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var $n={},Uc={},tr={},hb;function Jl(){if(hb)return tr;hb=1;function e(s){return typeof s>"u"||s===null}function t(s){return typeof s=="object"&&s!==null}function n(s){return Array.isArray(s)?s:e(s)?[]:[s]}function a(s,l){if(l){const m=Object.keys(l);for(let d=0,h=m.length;d<h;d+=1){const v=m[d];s[v]=l[v]}}return s}function o(s,l){let m="";for(let d=0;d<l;d+=1)m+=s;return m}function i(s){return s===0&&Number.NEGATIVE_INFINITY===1/s}return tr.isNothing=e,tr.isObject=t,tr.toArray=n,tr.repeat=o,tr.isNegativeZero=i,tr.extend=a,tr}var ep,gb;function Yl(){if(gb)return ep;gb=1;function e(n,a){let o="";const i=n.reason||"(unknown reason)";return n.mark?(n.mark.name&&(o+='in "'+n.mark.name+'" '),o+="("+(n.mark.line+1)+":"+(n.mark.column+1)+")",!a&&n.mark.snippet&&(o+=`
|
|
67
|
+
|
|
68
|
+
`+n.mark.snippet),i+" "+o):i}function t(n,a){Error.call(this),this.name="YAMLException",this.reason=n,this.mark=a,this.message=e(this,!1),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||""}return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t.prototype.toString=function(a){return this.name+": "+e(this,a)},ep=t,ep}var tp,vb;function rj(){if(vb)return tp;vb=1;const e=Jl();function t(o,i,s,l,m){let d="",h="";const v=Math.floor(m/2)-1;return l-i>v&&(d=" ... ",i=l-v+d.length),s-l>v&&(h=" ...",s=l+v-h.length),{str:d+o.slice(i,s).replace(/\t/g,"→")+h,pos:l-i+d.length}}function n(o,i){return e.repeat(" ",i-o.length)+o}function a(o,i){if(i=Object.create(i||null),!o.buffer)return null;i.maxLength||(i.maxLength=79),typeof i.indent!="number"&&(i.indent=1),typeof i.linesBefore!="number"&&(i.linesBefore=3),typeof i.linesAfter!="number"&&(i.linesAfter=2);const s=/\r?\n|\r|\0/g,l=[0],m=[];let d,h=-1;for(;d=s.exec(o.buffer);)m.push(d.index),l.push(d.index+d[0].length),o.position<=d.index&&h<0&&(h=l.length-2);h<0&&(h=l.length-1);let v="";const y=Math.min(o.line+i.linesAfter,m.length).toString().length,w=i.maxLength-(i.indent+y+3);for(let R=1;R<=i.linesBefore&&!(h-R<0);R++){const M=t(o.buffer,l[h-R],m[h-R],o.position-(l[h]-l[h-R]),w);v=e.repeat(" ",i.indent)+n((o.line-R+1).toString(),y)+" | "+M.str+`
|
|
69
|
+
`+v}const I=t(o.buffer,l[h],m[h],o.position,w);v+=e.repeat(" ",i.indent)+n((o.line+1).toString(),y)+" | "+I.str+`
|
|
70
|
+
`,v+=e.repeat("-",i.indent+y+3+I.pos)+`^
|
|
71
|
+
`;for(let R=1;R<=i.linesAfter&&!(h+R>=m.length);R++){const M=t(o.buffer,l[h+R],m[h+R],o.position-(l[h]-l[h+R]),w);v+=e.repeat(" ",i.indent)+n((o.line+R+1).toString(),y)+" | "+M.str+`
|
|
72
|
+
`}return v.replace(/\n$/,"")}return tp=a,tp}var np,bb;function Vn(){if(bb)return np;bb=1;const e=Yl(),t=["kind","multi","resolve","construct","instanceOf","predicate","represent","representName","defaultStyle","styleAliases"],n=["scalar","sequence","mapping"];function a(i){const s={};return i!==null&&Object.keys(i).forEach(function(l){i[l].forEach(function(m){s[String(m)]=l})}),s}function o(i,s){if(s=s||{},Object.keys(s).forEach(function(l){if(t.indexOf(l)===-1)throw new e('Unknown option "'+l+'" is met in definition of "'+i+'" YAML type.')}),this.options=s,this.tag=i,this.kind=s.kind||null,this.resolve=s.resolve||function(){return!0},this.construct=s.construct||function(l){return l},this.instanceOf=s.instanceOf||null,this.predicate=s.predicate||null,this.represent=s.represent||null,this.representName=s.representName||null,this.defaultStyle=s.defaultStyle||null,this.multi=s.multi||!1,this.styleAliases=a(s.styleAliases||null),n.indexOf(this.kind)===-1)throw new e('Unknown kind "'+this.kind+'" is specified for "'+i+'" YAML type.')}return np=o,np}var ap,yb;function Pk(){if(yb)return ap;yb=1;const e=Yl(),t=Vn();function n(i,s){const l=[];return i[s].forEach(function(m){let d=l.length;l.forEach(function(h,v){h.tag===m.tag&&h.kind===m.kind&&h.multi===m.multi&&(d=v)}),l[d]=m}),l}function a(){const i={scalar:{},sequence:{},mapping:{},fallback:{},multi:{scalar:[],sequence:[],mapping:[],fallback:[]}};function s(l){l.multi?(i.multi[l.kind].push(l),i.multi.fallback.push(l)):i[l.kind][l.tag]=i.fallback[l.tag]=l}for(let l=0,m=arguments.length;l<m;l+=1)arguments[l].forEach(s);return i}function o(i){return this.extend(i)}return o.prototype.extend=function(s){let l=[],m=[];if(s instanceof t)m.push(s);else if(Array.isArray(s))m=m.concat(s);else if(s&&(Array.isArray(s.implicit)||Array.isArray(s.explicit)))s.implicit&&(l=l.concat(s.implicit)),s.explicit&&(m=m.concat(s.explicit));else throw new e("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");l.forEach(function(h){if(!(h instanceof t))throw new e("Specified list of YAML types (or a single Type object) contains a non-Type object.");if(h.loadKind&&h.loadKind!=="scalar")throw new e("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");if(h.multi)throw new e("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.")}),m.forEach(function(h){if(!(h instanceof t))throw new e("Specified list of YAML types (or a single Type object) contains a non-Type object.")});const d=Object.create(o.prototype);return d.implicit=(this.implicit||[]).concat(l),d.explicit=(this.explicit||[]).concat(m),d.compiledImplicit=n(d,"implicit"),d.compiledExplicit=n(d,"explicit"),d.compiledTypeMap=a(d.compiledImplicit,d.compiledExplicit),d},ap=o,ap}var op,Sb;function Ak(){if(Sb)return op;Sb=1;const e=Vn();return op=new e("tag:yaml.org,2002:str",{kind:"scalar",construct:function(t){return t!==null?t:""}}),op}var rp,kb;function Tk(){if(kb)return rp;kb=1;const e=Vn();return rp=new e("tag:yaml.org,2002:seq",{kind:"sequence",construct:function(t){return t!==null?t:[]}}),rp}var ip,xb;function Ek(){if(xb)return ip;xb=1;const e=Vn();return ip=new e("tag:yaml.org,2002:map",{kind:"mapping",construct:function(t){return t!==null?t:{}}}),ip}var sp,wb;function Mk(){if(wb)return sp;wb=1;const e=Pk();return sp=new e({explicit:[Ak(),Tk(),Ek()]}),sp}var lp,Ib;function jk(){if(Ib)return lp;Ib=1;const e=Vn();function t(o){if(o===null)return!0;const i=o.length;return i===1&&o==="~"||i===4&&(o==="null"||o==="Null"||o==="NULL")}function n(){return null}function a(o){return o===null}return lp=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"}),lp}var cp,_b;function Ok(){if(_b)return cp;_b=1;const e=Vn();function t(o){if(o===null)return!1;const i=o.length;return i===4&&(o==="true"||o==="True"||o==="TRUE")||i===5&&(o==="false"||o==="False"||o==="FALSE")}function n(o){return o==="true"||o==="True"||o==="TRUE"}function a(o){return Object.prototype.toString.call(o)==="[object Boolean]"}return cp=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"}),cp}var dp,Cb;function $k(){if(Cb)return dp;Cb=1;const e=Jl(),t=Vn();function n(d){return d>=48&&d<=57||d>=65&&d<=70||d>=97&&d<=102}function a(d){return d>=48&&d<=55}function o(d){return d>=48&&d<=57}function i(d){if(d===null)return!1;const h=d.length;let v=0,y=!1;if(!h)return!1;let w=d[v];if((w==="-"||w==="+")&&(w=d[++v]),w==="0"){if(v+1===h)return!0;if(w=d[++v],w==="b"){for(v++;v<h;v++){if(w=d[v],w!=="0"&&w!=="1")return!1;y=!0}return y&&isFinite(s(d))}if(w==="x"){for(v++;v<h;v++){if(!n(d.charCodeAt(v)))return!1;y=!0}return y&&isFinite(s(d))}if(w==="o"){for(v++;v<h;v++){if(!a(d.charCodeAt(v)))return!1;y=!0}return y&&isFinite(s(d))}}for(;v<h;v++){if(!o(d.charCodeAt(v)))return!1;y=!0}return y?isFinite(s(d)):!1}function s(d){let h=d,v=1,y=h[0];if((y==="-"||y==="+")&&(y==="-"&&(v=-1),h=h.slice(1),y=h[0]),h==="0")return 0;if(y==="0"){if(h[1]==="b")return v*parseInt(h.slice(2),2);if(h[1]==="x")return v*parseInt(h.slice(2),16);if(h[1]==="o")return v*parseInt(h.slice(2),8)}return v*parseInt(h,10)}function l(d){return s(d)}function m(d){return Object.prototype.toString.call(d)==="[object Number]"&&d%1===0&&!e.isNegativeZero(d)}return dp=new t("tag:yaml.org,2002:int",{kind:"scalar",resolve:i,construct:l,predicate:m,represent:{binary:function(d){return d>=0?"0b"+d.toString(2):"-0b"+d.toString(2).slice(1)},octal:function(d){return d>=0?"0o"+d.toString(8):"-0o"+d.toString(8).slice(1)},decimal:function(d){return d.toString(10)},hexadecimal:function(d){return d>=0?"0x"+d.toString(16).toUpperCase():"-0x"+d.toString(16).toUpperCase().slice(1)}},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}}),dp}var up,Rb;function Nk(){if(Rb)return up;Rb=1;const e=Jl(),t=Vn(),n=new RegExp("^(?:[-+]?(?:[0-9]+)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"),a=new RegExp("^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function o(d){return d===null||!n.test(d)?!1:isFinite(parseFloat(d,10))?!0:a.test(d)}function i(d){let h=d.toLowerCase();const v=h[0]==="-"?-1:1;return"+-".indexOf(h[0])>=0&&(h=h.slice(1)),h===".inf"?v===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:h===".nan"?NaN:v*parseFloat(h,10)}const s=/^[-+]?[0-9]+e/;function l(d,h){if(isNaN(d))switch(h){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===d)switch(h){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===d)switch(h){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(e.isNegativeZero(d))return"-0.0";const v=d.toString(10);return s.test(v)?v.replace("e",".e"):v}function m(d){return Object.prototype.toString.call(d)==="[object Number]"&&(d%1!==0||e.isNegativeZero(d))}return up=new t("tag:yaml.org,2002:float",{kind:"scalar",resolve:o,construct:i,predicate:m,represent:l,defaultStyle:"lowercase"}),up}var mp,Pb;function Dk(){return Pb||(Pb=1,mp=Mk().extend({implicit:[jk(),Ok(),$k(),Nk()]})),mp}var pp,Ab;function Lk(){return Ab||(Ab=1,pp=Dk()),pp}var fp,Tb;function Uk(){if(Tb)return fp;Tb=1;const e=Vn(),t=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),n=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");function a(s){return s===null?!1:t.exec(s)!==null||n.exec(s)!==null}function o(s){let l=0,m=null,d=t.exec(s);if(d===null&&(d=n.exec(s)),d===null)throw new Error("Date resolve error");const h=+d[1],v=+d[2]-1,y=+d[3];if(!d[4])return new Date(Date.UTC(h,v,y));const w=+d[4],I=+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 P=+d[10],N=+(d[11]||0);m=(P*60+N)*6e4,d[9]==="-"&&(m=-m)}const M=new Date(Date.UTC(h,v,y,w,I,R,l));return m&&M.setTime(M.getTime()-m),M}function i(s){return s.toISOString()}return fp=new e("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:a,construct:o,instanceOf:Date,represent:i}),fp}var hp,Eb;function zk(){if(Eb)return hp;Eb=1;const e=Vn();function t(n){return n==="<<"||n===null}return hp=new e("tag:yaml.org,2002:merge",{kind:"scalar",resolve:t}),hp}var gp,Mb;function Hk(){if(Mb)return gp;Mb=1;const e=Vn(),t=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
|
|
73
|
+
\r`;function n(s){if(s===null)return!1;let l=0;const m=s.length,d=t;for(let h=0;h<m;h++){const v=d.indexOf(s.charAt(h));if(!(v>64)){if(v<0)return!1;l+=6}}return l%8===0}function a(s){const l=s.replace(/[\r\n=]/g,""),m=l.length,d=t;let h=0;const v=[];for(let w=0;w<m;w++)w%4===0&&w&&(v.push(h>>16&255),v.push(h>>8&255),v.push(h&255)),h=h<<6|d.indexOf(l.charAt(w));const y=m%4*6;return y===0?(v.push(h>>16&255),v.push(h>>8&255),v.push(h&255)):y===18?(v.push(h>>10&255),v.push(h>>2&255)):y===12&&v.push(h>>4&255),new Uint8Array(v)}function o(s){let l="",m=0;const d=s.length,h=t;for(let y=0;y<d;y++)y%3===0&&y&&(l+=h[m>>18&63],l+=h[m>>12&63],l+=h[m>>6&63],l+=h[m&63]),m=(m<<8)+s[y];const v=d%3;return v===0?(l+=h[m>>18&63],l+=h[m>>12&63],l+=h[m>>6&63],l+=h[m&63]):v===2?(l+=h[m>>10&63],l+=h[m>>4&63],l+=h[m<<2&63],l+=h[64]):v===1&&(l+=h[m>>2&63],l+=h[m<<4&63],l+=h[64],l+=h[64]),l}function i(s){return Object.prototype.toString.call(s)==="[object Uint8Array]"}return gp=new e("tag:yaml.org,2002:binary",{kind:"scalar",resolve:n,construct:a,predicate:i,represent:o}),gp}var vp,jb;function qk(){if(jb)return vp;jb=1;const e=Vn(),t=Object.prototype.hasOwnProperty,n=Object.prototype.toString;function a(i){if(i===null)return!0;const s=[],l=i;for(let m=0,d=l.length;m<d;m+=1){const h=l[m];let v=!1;if(n.call(h)!=="[object Object]")return!1;let y;for(y in h)if(t.call(h,y))if(!v)v=!0;else return!1;if(!v)return!1;if(s.indexOf(y)===-1)s.push(y);else return!1}return!0}function o(i){return i!==null?i:[]}return vp=new e("tag:yaml.org,2002:omap",{kind:"sequence",resolve:a,construct:o}),vp}var bp,Ob;function Bk(){if(Ob)return bp;Ob=1;const e=Vn(),t=Object.prototype.toString;function n(o){if(o===null)return!0;const i=o,s=new Array(i.length);for(let l=0,m=i.length;l<m;l+=1){const d=i[l];if(t.call(d)!=="[object Object]")return!1;const h=Object.keys(d);if(h.length!==1)return!1;s[l]=[h[0],d[h[0]]]}return!0}function a(o){if(o===null)return[];const i=o,s=new Array(i.length);for(let l=0,m=i.length;l<m;l+=1){const d=i[l],h=Object.keys(d);s[l]=[h[0],d[h[0]]]}return s}return bp=new e("tag:yaml.org,2002:pairs",{kind:"sequence",resolve:n,construct:a}),bp}var yp,$b;function Fk(){if($b)return yp;$b=1;const e=Vn(),t=Object.prototype.hasOwnProperty;function n(o){if(o===null)return!0;const i=o;for(const s in i)if(t.call(i,s)&&i[s]!==null)return!1;return!0}function a(o){return o!==null?o:{}}return yp=new e("tag:yaml.org,2002:set",{kind:"mapping",resolve:n,construct:a}),yp}var Sp,Nb;function $h(){return Nb||(Nb=1,Sp=Lk().extend({implicit:[Uk(),zk()],explicit:[Hk(),qk(),Bk(),Fk()]})),Sp}var Db;function ij(){if(Db)return Uc;Db=1;const e=Jl(),t=Yl(),n=rj(),a=$h(),o=Object.prototype.hasOwnProperty,i=1,s=2,l=3,m=4,d=1,h=2,v=3,y=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,w=/[\x85\u2028\u2029]/,I=/[,\[\]{}]/,R=/^(?:!|!!|![0-9A-Za-z-]+!)$/,M=/^(?:!|[^,\[\]{}])(?:%[0-9a-f]{2}|[0-9a-z\-#;/?:@&=+$,_.!~*'()\[\]])*$/i;function P(p){return Object.prototype.toString.call(p)}function N(p){return p===10||p===13}function O(p){return p===9||p===32}function j(p){return p===9||p===32||p===10||p===13}function k(p){return p===44||p===91||p===93||p===123||p===125}function C(p){if(p>=48&&p<=57)return p-48;const U=p|32;return U>=97&&U<=102?U-97+10:-1}function T(p){return p===120?2:p===117?4:p===85?8:0}function z(p){return p>=48&&p<=57?p-48:-1}function B(p){switch(p){case 48:return"\0";case 97:return"\x07";case 98:return"\b";case 116:return" ";case 9:return" ";case 110:return`
|
|
74
|
+
`;case 118:return"\v";case 102:return"\f";case 114:return"\r";case 101:return"\x1B";case 32:return" ";case 34:return'"';case 47:return"/";case 92:return"\\";case 78:return"
";case 95:return" ";case 76:return"\u2028";case 80:return"\u2029";default:return""}}function D(p){return p<=65535?String.fromCharCode(p):String.fromCharCode((p-65536>>10)+55296,(p-65536&1023)+56320)}function V(p,U,K){U==="__proto__"?Object.defineProperty(p,U,{configurable:!0,enumerable:!0,writable:!0,value:K}):p[U]=K}const le=new Array(256),te=new Array(256);for(let p=0;p<256;p++)le[p]=B(p)?1:0,te[p]=B(p);function Ie(p,U){this.input=p,this.filename=U.filename||null,this.schema=U.schema||a,this.onWarning=U.onWarning||null,this.legacy=U.legacy||!1,this.json=U.json||!1,this.listener=U.listener||null,this.maxDepth=typeof U.maxDepth=="number"?U.maxDepth:100,this.maxTotalMergeKeys=typeof U.maxTotalMergeKeys=="number"?U.maxTotalMergeKeys:1e4,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=p.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.depth=0,this.totalMergeKeys=0,this.firstTabInLine=-1,this.documents=[],this.anchorMapTransactions=[]}function ke(p,U){const K={name:p.filename,buffer:p.input.slice(0,-1),position:p.position,line:p.line,column:p.position-p.lineStart};return K.snippet=n(K),new t(U,K)}function Z(p,U){throw ke(p,U)}function Ae(p,U){p.onWarning&&p.onWarning.call(null,ke(p,U))}function he(p,U,K){const de=p.anchorMapTransactions;if(de.length!==0){const re=de[de.length-1];o.call(re,U)||(re[U]={existed:o.call(p.anchorMap,U),value:p.anchorMap[U]})}p.anchorMap[U]=K}function ue(p){p.anchorMapTransactions.push(Object.create(null))}function be(p){const U=p.anchorMapTransactions.pop(),K=p.anchorMapTransactions;if(K.length===0)return;const de=K[K.length-1],re=Object.keys(U);for(let F=0,_=re.length;F<_;F+=1){const W=re[F];o.call(de,W)||(de[W]=U[W])}}function ne(p){const U=p.anchorMapTransactions.pop(),K=Object.keys(U);for(let de=K.length-1;de>=0;de-=1){const re=U[K[de]];re.existed?p.anchorMap[K[de]]=re.value:delete p.anchorMap[K[de]]}}function ge(p){return{position:p.position,line:p.line,lineStart:p.lineStart,lineIndent:p.lineIndent,firstTabInLine:p.firstTabInLine,tag:p.tag,anchor:p.anchor,kind:p.kind,result:p.result}}function xe(p,U){p.position=U.position,p.line=U.line,p.lineStart=U.lineStart,p.lineIndent=U.lineIndent,p.firstTabInLine=U.firstTabInLine,p.tag=U.tag,p.anchor=U.anchor,p.kind=U.kind,p.result=U.result}const qe={YAML:function(U,K,de){U.version!==null&&Z(U,"duplication of %YAML directive"),de.length!==1&&Z(U,"YAML directive accepts exactly one argument");const re=/^([0-9]+)\.([0-9]+)$/.exec(de[0]);re===null&&Z(U,"ill-formed argument of the YAML directive");const F=parseInt(re[1],10),_=parseInt(re[2],10);F!==1&&Z(U,"unacceptable YAML version of the document"),U.version=de[0],U.checkLineBreaks=_<2,_!==1&&_!==2&&Ae(U,"unsupported YAML version of the document")},TAG:function(U,K,de){let re;de.length!==2&&Z(U,"TAG directive accepts exactly two arguments");const F=de[0];re=de[1],R.test(F)||Z(U,"ill-formed tag handle (first argument) of the TAG directive"),o.call(U.tagMap,F)&&Z(U,'there is a previously declared suffix for "'+F+'" tag handle'),M.test(re)||Z(U,"ill-formed tag prefix (second argument) of the TAG directive");try{re=decodeURIComponent(re)}catch{Z(U,"tag prefix is malformed: "+re)}U.tagMap[F]=re}};function Se(p,U,K,de){if(U<K){const re=p.input.slice(U,K);if(de)for(let F=0,_=re.length;F<_;F+=1){const W=re.charCodeAt(F);W===9||W>=32&&W<=1114111||Z(p,"expected valid JSON character")}else y.test(re)&&Z(p,"the stream contains non-printable characters");p.result+=re}}function se(p,U,K,de){e.isObject(K)||Z(p,"cannot merge mappings; the provided source object is unacceptable");const re=Object.keys(K);for(let F=0,_=re.length;F<_;F+=1){const W=re[F];p.maxTotalMergeKeys!==-1&&++p.totalMergeKeys>p.maxTotalMergeKeys&&Z(p,"merge keys exceeded maxTotalMergeKeys ("+p.maxTotalMergeKeys+")"),o.call(U,W)||(V(U,W,K[W]),de[W]=!0)}}function we(p,U,K,de,re,F,_,W,X){if(Array.isArray(re)){re=Array.prototype.slice.call(re);for(let oe=0,G=re.length;oe<G;oe+=1)Array.isArray(re[oe])&&Z(p,"nested arrays are not supported inside keys"),typeof re=="object"&&P(re[oe])==="[object Object]"&&(re[oe]="[object Object]")}if(typeof re=="object"&&P(re)==="[object Object]"&&(re="[object Object]"),re=String(re),U===null&&(U={}),de==="tag:yaml.org,2002:merge")if(Array.isArray(F))for(let oe=0,G=F.length;oe<G;oe+=1)se(p,U,F[oe],K);else se(p,U,F,K);else!p.json&&!o.call(K,re)&&o.call(U,re)&&(p.line=_||p.line,p.lineStart=W||p.lineStart,p.position=X||p.position,Z(p,"duplicated mapping key")),V(U,re,F),delete K[re];return U}function Oe(p){const U=p.input.charCodeAt(p.position);U===10?p.position++:U===13?(p.position++,p.input.charCodeAt(p.position)===10&&p.position++):Z(p,"a line break is expected"),p.line+=1,p.lineStart=p.position,p.firstTabInLine=-1}function Qe(p,U,K){let de=0,re=p.input.charCodeAt(p.position);for(;re!==0;){for(;O(re);)re===9&&p.firstTabInLine===-1&&(p.firstTabInLine=p.position),re=p.input.charCodeAt(++p.position);if(U&&re===35)do re=p.input.charCodeAt(++p.position);while(re!==10&&re!==13&&re!==0);if(N(re))for(Oe(p),re=p.input.charCodeAt(p.position),de++,p.lineIndent=0;re===32;)p.lineIndent++,re=p.input.charCodeAt(++p.position);else break}return K!==-1&&de!==0&&p.lineIndent<K&&Ae(p,"deficient indentation"),de}function Ge(p){let U=p.position,K=p.input.charCodeAt(U);return!!((K===45||K===46)&&K===p.input.charCodeAt(U+1)&&K===p.input.charCodeAt(U+2)&&(U+=3,K=p.input.charCodeAt(U),K===0||j(K)))}function st(p,U){U===1?p.result+=" ":U>1&&(p.result+=e.repeat(`
|
|
75
|
+
`,U-1))}function Le(p,U,K){let de,re,F,_,W,X;const oe=p.kind,G=p.result;let pe=p.input.charCodeAt(p.position);if(j(pe)||k(pe)||pe===35||pe===38||pe===42||pe===33||pe===124||pe===62||pe===39||pe===34||pe===37||pe===64||pe===96)return!1;if(pe===63||pe===45){const fe=p.input.charCodeAt(p.position+1);if(j(fe)||K&&k(fe))return!1}for(p.kind="scalar",p.result="",de=re=p.position,F=!1;pe!==0;){if(pe===58){const fe=p.input.charCodeAt(p.position+1);if(j(fe)||K&&k(fe))break}else if(pe===35){const fe=p.input.charCodeAt(p.position-1);if(j(fe))break}else{if(p.position===p.lineStart&&Ge(p)||K&&k(pe))break;if(N(pe))if(_=p.line,W=p.lineStart,X=p.lineIndent,Qe(p,!1,-1),p.lineIndent>=U){F=!0,pe=p.input.charCodeAt(p.position);continue}else{p.position=re,p.line=_,p.lineStart=W,p.lineIndent=X;break}}F&&(Se(p,de,re,!1),st(p,p.line-_),de=re=p.position,F=!1),O(pe)||(re=p.position+1),pe=p.input.charCodeAt(++p.position)}return Se(p,de,re,!1),p.result?!0:(p.kind=oe,p.result=G,!1)}function Fe(p,U){let K,de,re=p.input.charCodeAt(p.position);if(re!==39)return!1;for(p.kind="scalar",p.result="",p.position++,K=de=p.position;(re=p.input.charCodeAt(p.position))!==0;)if(re===39)if(Se(p,K,p.position,!0),re=p.input.charCodeAt(++p.position),re===39)K=p.position,p.position++,de=p.position;else return!0;else N(re)?(Se(p,K,de,!0),st(p,Qe(p,!1,U)),K=de=p.position):p.position===p.lineStart&&Ge(p)?Z(p,"unexpected end of the document within a single quoted scalar"):(p.position++,O(re)||(de=p.position));Z(p,"unexpected end of the stream within a single quoted scalar")}function De(p,U){let K,de,re,F=p.input.charCodeAt(p.position);if(F!==34)return!1;for(p.kind="scalar",p.result="",p.position++,K=de=p.position;(F=p.input.charCodeAt(p.position))!==0;){if(F===34)return Se(p,K,p.position,!0),p.position++,!0;if(F===92){if(Se(p,K,p.position,!0),F=p.input.charCodeAt(++p.position),N(F))Qe(p,!1,U);else if(F<256&&le[F])p.result+=te[F],p.position++;else if((re=T(F))>0){let _=re,W=0;for(;_>0;_--)F=p.input.charCodeAt(++p.position),(re=C(F))>=0?W=(W<<4)+re:Z(p,"expected hexadecimal character");p.result+=D(W),p.position++}else Z(p,"unknown escape sequence");K=de=p.position}else N(F)?(Se(p,K,de,!0),st(p,Qe(p,!1,U)),K=de=p.position):p.position===p.lineStart&&Ge(p)?Z(p,"unexpected end of the document within a double quoted scalar"):(p.position++,O(F)||(de=p.position))}Z(p,"unexpected end of the stream within a double quoted scalar")}function L(p,U){let K=!0,de,re,F;const _=p.tag;let W;const X=p.anchor;let oe,G,pe,fe;const je=Object.create(null);let Ee,Ne,Ve,Ue=p.input.charCodeAt(p.position);if(Ue===91)oe=93,fe=!1,W=[];else if(Ue===123)oe=125,fe=!0,W={};else return!1;for(p.anchor!==null&&he(p,p.anchor,W),Ue=p.input.charCodeAt(++p.position);Ue!==0;){if(Qe(p,!0,U),Ue=p.input.charCodeAt(p.position),Ue===oe)return p.position++,p.tag=_,p.anchor=X,p.kind=fe?"mapping":"sequence",p.result=W,!0;if(K?Ue===44&&Z(p,"expected the node content, but found ','"):Z(p,"missed comma between flow collection entries"),Ne=Ee=Ve=null,G=pe=!1,Ue===63){const ut=p.input.charCodeAt(p.position+1);j(ut)&&(G=pe=!0,p.position++,Qe(p,!0,U))}de=p.line,re=p.lineStart,F=p.position,et(p,U,i,!1,!0),Ne=p.tag,Ee=p.result,Qe(p,!0,U),Ue=p.input.charCodeAt(p.position),(pe||p.line===de)&&Ue===58&&(G=!0,Ue=p.input.charCodeAt(++p.position),Qe(p,!0,U),et(p,U,i,!1,!0),Ve=p.result),fe?we(p,W,je,Ne,Ee,Ve,de,re,F):G?W.push(we(p,null,je,Ne,Ee,Ve,de,re,F)):W.push(Ee),Qe(p,!0,U),Ue=p.input.charCodeAt(p.position),Ue===44?(K=!0,Ue=p.input.charCodeAt(++p.position)):K=!1}Z(p,"unexpected end of the stream within a flow collection")}function $(p,U){let K,de=d,re=!1,F=!1,_=U,W=0,X=!1,oe,G=p.input.charCodeAt(p.position);if(G===124)K=!1;else if(G===62)K=!0;else return!1;for(p.kind="scalar",p.result="";G!==0;)if(G=p.input.charCodeAt(++p.position),G===43||G===45)d===de?de=G===43?v:h:Z(p,"repeat of a chomping mode identifier");else if((oe=z(G))>=0)oe===0?Z(p,"bad explicit indentation width of a block scalar; it cannot be less than one"):F?Z(p,"repeat of an indentation width identifier"):(_=U+oe-1,F=!0);else break;if(O(G)){do G=p.input.charCodeAt(++p.position);while(O(G));if(G===35)do G=p.input.charCodeAt(++p.position);while(!N(G)&&G!==0)}for(;G!==0;){for(Oe(p),p.lineIndent=0,G=p.input.charCodeAt(p.position);(!F||p.lineIndent<_)&&G===32;)p.lineIndent++,G=p.input.charCodeAt(++p.position);if(!F&&p.lineIndent>_&&(_=p.lineIndent),N(G)){W++;continue}if(!F&&_===0&&Z(p,"missing indentation for block scalar"),p.lineIndent<_){de===v?p.result+=e.repeat(`
|
|
76
|
+
`,re?1+W:W):de===d&&re&&(p.result+=`
|
|
77
|
+
`);break}K?O(G)?(X=!0,p.result+=e.repeat(`
|
|
78
|
+
`,re?1+W:W)):X?(X=!1,p.result+=e.repeat(`
|
|
79
|
+
`,W+1)):W===0?re&&(p.result+=" "):p.result+=e.repeat(`
|
|
80
|
+
`,W):p.result+=e.repeat(`
|
|
81
|
+
`,re?1+W:W),re=!0,F=!0,W=0;const pe=p.position;for(;!N(G)&&G!==0;)G=p.input.charCodeAt(++p.position);Se(p,pe,p.position,!1)}return!0}function H(p,U){const K=p.tag,de=p.anchor,re=[];let F=!1;if(p.firstTabInLine!==-1)return!1;p.anchor!==null&&he(p,p.anchor,re);let _=p.input.charCodeAt(p.position);for(;_!==0&&(p.firstTabInLine!==-1&&(p.position=p.firstTabInLine,Z(p,"tab characters must not be used in indentation")),_===45);){const W=p.input.charCodeAt(p.position+1);if(!j(W))break;if(F=!0,p.position++,Qe(p,!0,-1)&&p.lineIndent<=U){re.push(null),_=p.input.charCodeAt(p.position);continue}const X=p.line;if(et(p,U,l,!1,!0),re.push(p.result),Qe(p,!0,-1),_=p.input.charCodeAt(p.position),(p.line===X||p.lineIndent>U)&&_!==0)Z(p,"bad indentation of a sequence entry");else if(p.lineIndent<U)break}return F?(p.tag=K,p.anchor=de,p.kind="sequence",p.result=re,!0):!1}function Q(p,U,K){let de,re,F,_;const W=p.tag,X=p.anchor,oe={},G=Object.create(null);let pe=null,fe=null,je=null,Ee=!1,Ne=!1;if(p.firstTabInLine!==-1)return!1;p.anchor!==null&&he(p,p.anchor,oe);let Ve=p.input.charCodeAt(p.position);for(;Ve!==0;){!Ee&&p.firstTabInLine!==-1&&(p.position=p.firstTabInLine,Z(p,"tab characters must not be used in indentation"));const Ue=p.input.charCodeAt(p.position+1),ut=p.line;if((Ve===63||Ve===58)&&j(Ue))Ve===63?(Ee&&(we(p,oe,G,pe,fe,null,re,F,_),pe=fe=je=null),Ne=!0,Ee=!0,de=!0):Ee?(Ee=!1,de=!0):Z(p,"incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line"),p.position+=1,Ve=Ue;else{if(re=p.line,F=p.lineStart,_=p.position,!et(p,K,s,!1,!0))break;if(p.line===ut){for(Ve=p.input.charCodeAt(p.position);O(Ve);)Ve=p.input.charCodeAt(++p.position);if(Ve===58)Ve=p.input.charCodeAt(++p.position),j(Ve)||Z(p,"a whitespace character is expected after the key-value separator within a block mapping"),Ee&&(we(p,oe,G,pe,fe,null,re,F,_),pe=fe=je=null),Ne=!0,Ee=!1,de=!1,pe=p.tag,fe=p.result;else if(Ne)Z(p,"can not read an implicit mapping pair; a colon is missed");else return p.tag=W,p.anchor=X,!0}else if(Ne)Z(p,"can not read a block mapping entry; a multiline key may not be an implicit key");else return p.tag=W,p.anchor=X,!0}if((p.line===ut||p.lineIndent>U)&&(Ee&&(re=p.line,F=p.lineStart,_=p.position),et(p,U,m,!0,de)&&(Ee?fe=p.result:je=p.result),Ee||(we(p,oe,G,pe,fe,je,re,F,_),pe=fe=je=null),Qe(p,!0,-1),Ve=p.input.charCodeAt(p.position)),(p.line===ut||p.lineIndent>U)&&Ve!==0)Z(p,"bad indentation of a mapping entry");else if(p.lineIndent<U)break}return Ee&&we(p,oe,G,pe,fe,null,re,F,_),Ne&&(p.tag=W,p.anchor=X,p.kind="mapping",p.result=oe),Ne}function me(p){let U=!1,K=!1,de,re,F=p.input.charCodeAt(p.position);if(F!==33)return!1;p.tag!==null&&Z(p,"duplication of a tag property"),F=p.input.charCodeAt(++p.position),F===60?(U=!0,F=p.input.charCodeAt(++p.position)):F===33?(K=!0,de="!!",F=p.input.charCodeAt(++p.position)):de="!";let _=p.position;if(U){do F=p.input.charCodeAt(++p.position);while(F!==0&&F!==62);p.position<p.length?(re=p.input.slice(_,p.position),F=p.input.charCodeAt(++p.position)):Z(p,"unexpected end of the stream within a verbatim tag")}else{for(;F!==0&&!j(F);)F===33&&(K?Z(p,"tag suffix cannot contain exclamation marks"):(de=p.input.slice(_-1,p.position+1),R.test(de)||Z(p,"named tag handle cannot contain such characters"),K=!0,_=p.position+1)),F=p.input.charCodeAt(++p.position);re=p.input.slice(_,p.position),I.test(re)&&Z(p,"tag suffix cannot contain flow indicator characters")}re&&!M.test(re)&&Z(p,"tag name cannot contain such characters: "+re);try{re=decodeURIComponent(re)}catch{Z(p,"tag name is malformed: "+re)}return U?p.tag=re:o.call(p.tagMap,de)?p.tag=p.tagMap[de]+re:de==="!"?p.tag="!"+re:de==="!!"?p.tag="tag:yaml.org,2002:"+re:Z(p,'undeclared tag handle "'+de+'"'),!0}function _e(p){let U=p.input.charCodeAt(p.position);if(U!==38)return!1;p.anchor!==null&&Z(p,"duplication of an anchor property"),U=p.input.charCodeAt(++p.position);const K=p.position;for(;U!==0&&!j(U)&&!k(U);)U=p.input.charCodeAt(++p.position);return p.position===K&&Z(p,"name of an anchor node must contain at least one character"),p.anchor=p.input.slice(K,p.position),!0}function $e(p){let U=p.input.charCodeAt(p.position);if(U!==42)return!1;U=p.input.charCodeAt(++p.position);const K=p.position;for(;U!==0&&!j(U)&&!k(U);)U=p.input.charCodeAt(++p.position);p.position===K&&Z(p,"name of an alias node must contain at least one character");const de=p.input.slice(K,p.position);return o.call(p.anchorMap,de)||Z(p,'unidentified alias "'+de+'"'),p.result=p.anchorMap[de],Qe(p,!0,-1),!0}function Xe(p,U,K,de){const re=ge(p);return ue(p),xe(p,U),p.tag=null,p.anchor=null,p.kind=null,p.result=null,Q(p,K,de)&&p.kind==="mapping"?(be(p),!0):(ne(p),xe(p,re),!1)}function et(p,U,K,de,re){let F,_,W=1,X=!1,oe=!1,G=null,pe,fe,je;p.depth>=p.maxDepth&&Z(p,"nesting exceeded maxDepth ("+p.maxDepth+")"),p.depth+=1,p.listener!==null&&p.listener("open",p),p.tag=null,p.anchor=null,p.kind=null,p.result=null;const Ee=F=_=m===K||l===K;if(de&&Qe(p,!0,-1)&&(X=!0,p.lineIndent>U?W=1:p.lineIndent===U?W=0:p.lineIndent<U&&(W=-1)),W===1)for(;;){const Ne=p.input.charCodeAt(p.position),Ve=ge(p);if(X&&(Ne===33&&p.tag!==null||Ne===38&&p.anchor!==null)||!me(p)&&!_e(p))break;G===null&&(G=Ve),Qe(p,!0,-1)?(X=!0,_=Ee,p.lineIndent>U?W=1:p.lineIndent===U?W=0:p.lineIndent<U&&(W=-1)):_=!1}if(_&&(_=X||re),W===1||m===K)if(i===K||s===K?fe=U:fe=U+1,je=p.position-p.lineStart,W===1)if(_&&(H(p,je)||Q(p,je,fe))||L(p,fe))oe=!0;else{const Ne=p.input.charCodeAt(p.position);G!==null&&Ee&&!_&&Ne!==124&&Ne!==62&&Xe(p,G,G.position-G.lineStart,fe)||F&&$(p,fe)||Fe(p,fe)||De(p,fe)?oe=!0:$e(p)?(oe=!0,(p.tag!==null||p.anchor!==null)&&Z(p,"alias node should not have any properties")):Le(p,fe,i===K)&&(oe=!0,p.tag===null&&(p.tag="?")),p.anchor!==null&&he(p,p.anchor,p.result)}else W===0&&(oe=_&&H(p,je));if(p.tag===null)p.anchor!==null&&he(p,p.anchor,p.result);else if(p.tag==="?"){p.result!==null&&p.kind!=="scalar"&&Z(p,'unacceptable node kind for !<?> tag; it should be "scalar", not "'+p.kind+'"');for(let Ne=0,Ve=p.implicitTypes.length;Ne<Ve;Ne+=1)if(pe=p.implicitTypes[Ne],pe.resolve(p.result)){p.result=pe.construct(p.result),p.tag=pe.tag,p.anchor!==null&&he(p,p.anchor,p.result);break}}else if(p.tag!=="!"){if(o.call(p.typeMap[p.kind||"fallback"],p.tag))pe=p.typeMap[p.kind||"fallback"][p.tag];else{pe=null;const Ne=p.typeMap.multi[p.kind||"fallback"];for(let Ve=0,Ue=Ne.length;Ve<Ue;Ve+=1)if(p.tag.slice(0,Ne[Ve].tag.length)===Ne[Ve].tag){pe=Ne[Ve];break}}pe||Z(p,"unknown tag !<"+p.tag+">"),p.result!==null&&pe.kind!==p.kind&&Z(p,"unacceptable node kind for !<"+p.tag+'> tag; it should be "'+pe.kind+'", not "'+p.kind+'"'),pe.resolve(p.result,p.tag)?(p.result=pe.construct(p.result,p.tag),p.anchor!==null&&he(p,p.anchor,p.result)):Z(p,"cannot resolve a node with !<"+p.tag+"> explicit tag")}return p.listener!==null&&p.listener("close",p),p.depth-=1,p.tag!==null||p.anchor!==null||oe}function rt(p){const U=p.position;let K=!1,de;for(p.version=null,p.checkLineBreaks=p.legacy,p.tagMap=Object.create(null),p.anchorMap=Object.create(null);(de=p.input.charCodeAt(p.position))!==0&&(Qe(p,!0,-1),de=p.input.charCodeAt(p.position),!(p.lineIndent>0||de!==37));){K=!0,de=p.input.charCodeAt(++p.position);let re=p.position;for(;de!==0&&!j(de);)de=p.input.charCodeAt(++p.position);const F=p.input.slice(re,p.position),_=[];for(F.length<1&&Z(p,"directive name must not be less than one character in length");de!==0;){for(;O(de);)de=p.input.charCodeAt(++p.position);if(de===35){do de=p.input.charCodeAt(++p.position);while(de!==0&&!N(de));break}if(N(de))break;for(re=p.position;de!==0&&!j(de);)de=p.input.charCodeAt(++p.position);_.push(p.input.slice(re,p.position))}de!==0&&Oe(p),o.call(qe,F)?qe[F](p,F,_):Ae(p,'unknown document directive "'+F+'"')}if(Qe(p,!0,-1),p.lineIndent===0&&p.input.charCodeAt(p.position)===45&&p.input.charCodeAt(p.position+1)===45&&p.input.charCodeAt(p.position+2)===45?(p.position+=3,Qe(p,!0,-1)):K&&Z(p,"directives end mark is expected"),et(p,p.lineIndent-1,m,!1,!0),Qe(p,!0,-1),p.checkLineBreaks&&w.test(p.input.slice(U,p.position))&&Ae(p,"non-ASCII line breaks are interpreted as content"),p.documents.push(p.result),p.position===p.lineStart&&Ge(p)){p.input.charCodeAt(p.position)===46&&(p.position+=3,Qe(p,!0,-1));return}p.position<p.length-1&&Z(p,"end of the stream or a document separator is expected")}function it(p,U){p=String(p),U=U||{},p.length!==0&&(p.charCodeAt(p.length-1)!==10&&p.charCodeAt(p.length-1)!==13&&(p+=`
|
|
82
|
+
`),p.charCodeAt(0)===65279&&(p=p.slice(1)));const K=new Ie(p,U),de=p.indexOf("\0");for(de!==-1&&(K.position=de,Z(K,"null byte is not allowed in input")),K.input+="\0";K.input.charCodeAt(K.position)===32;)K.lineIndent+=1,K.position+=1;for(;K.position<K.length-1;)rt(K);return K.documents}function Me(p,U,K){U!==null&&typeof U=="object"&&typeof K>"u"&&(K=U,U=null);const de=it(p,K);if(typeof U!="function")return de;for(let re=0,F=de.length;re<F;re+=1)U(de[re])}function Be(p,U){const K=it(p,U);if(K.length!==0){if(K.length===1)return K[0];throw new t("expected a single document in the stream, but found more")}}return Uc.loadAll=Me,Uc.load=Be,Uc}var kp={},Lb;function sj(){if(Lb)return kp;Lb=1;const e=Jl(),t=Yl(),n=$h(),a=Object.prototype.toString,o=Object.prototype.hasOwnProperty,i=65279,s=9,l=10,m=13,d=32,h=33,v=34,y=35,w=37,I=38,R=39,M=42,P=44,N=45,O=58,j=61,k=62,C=63,T=64,z=91,B=93,D=96,V=123,le=124,te=125,Ie={};Ie[0]="\\0",Ie[7]="\\a",Ie[8]="\\b",Ie[9]="\\t",Ie[10]="\\n",Ie[11]="\\v",Ie[12]="\\f",Ie[13]="\\r",Ie[27]="\\e",Ie[34]='\\"',Ie[92]="\\\\",Ie[133]="\\N",Ie[160]="\\_",Ie[8232]="\\L",Ie[8233]="\\P";const ke=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"],Z=/^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;function Ae(_,W){if(W===null)return{};const X={},oe=Object.keys(W);for(let G=0,pe=oe.length;G<pe;G+=1){let fe=oe[G],je=String(W[fe]);fe.slice(0,2)==="!!"&&(fe="tag:yaml.org,2002:"+fe.slice(2));const Ee=_.compiledTypeMap.fallback[fe];Ee&&o.call(Ee.styleAliases,je)&&(je=Ee.styleAliases[je]),X[fe]=je}return X}function he(_){let W,X;const oe=_.toString(16).toUpperCase();if(_<=255)W="x",X=2;else if(_<=65535)W="u",X=4;else if(_<=4294967295)W="U",X=8;else throw new t("code point within a string may not be greater than 0xFFFFFFFF");return"\\"+W+e.repeat("0",X-oe.length)+oe}const ue=1,be=2;function ne(_){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=Ae(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==='"'?be:ue,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 ge(_,W){const X=e.repeat(" ",W);let oe=0,G="";const pe=_.length;for(;oe<pe;){let fe;const je=_.indexOf(`
|
|
83
|
+
`,oe);je===-1?(fe=_.slice(oe),oe=pe):(fe=_.slice(oe,je+1),oe=je+1),fe.length&&fe!==`
|
|
84
|
+
`&&(G+=X),G+=fe}return G}function xe(_,W){return`
|
|
85
|
+
`+e.repeat(" ",_.indent*W)}function qe(_,W){for(let X=0,oe=_.implicitTypes.length;X<oe;X+=1)if(_.implicitTypes[X].resolve(W))return!0;return!1}function Se(_){return _===d||_===s}function se(_){return _>=32&&_<=126||_>=161&&_<=55295&&_!==8232&&_!==8233||_>=57344&&_<=65533&&_!==i||_>=65536&&_<=1114111}function we(_){return se(_)&&_!==i&&_!==m&&_!==l}function Oe(_,W,X){const oe=we(_),G=oe&&!Se(_);return(X?oe:oe&&_!==P&&_!==z&&_!==B&&_!==V&&_!==te)&&_!==y&&!(W===O&&!G)||we(W)&&!Se(W)&&_===y||W===O&&G}function Qe(_){return se(_)&&_!==i&&!Se(_)&&_!==N&&_!==C&&_!==O&&_!==P&&_!==z&&_!==B&&_!==V&&_!==te&&_!==y&&_!==I&&_!==M&&_!==h&&_!==le&&_!==j&&_!==k&&_!==R&&_!==v&&_!==w&&_!==T&&_!==D}function Ge(_){return!Se(_)&&_!==O}function st(_,W){const X=_.charCodeAt(W);let oe;return X>=55296&&X<=56319&&W+1<_.length&&(oe=_.charCodeAt(W+1),oe>=56320&&oe<=57343)?(X-55296)*1024+oe-56320+65536:X}function Le(_){return/^\n* /.test(_)}const Fe=1,De=2,L=3,$=4,H=5;function Q(_,W,X,oe,G,pe,fe,je){let Ee,Ne=0,Ve=null,Ue=!1,ut=!1;const Qt=oe!==-1;let zt=-1,Mn=Qe(st(_,0))&&Ge(st(_,_.length-1));if(W||fe)for(Ee=0;Ee<_.length;Ne>=65536?Ee+=2:Ee++){if(Ne=st(_,Ee),!se(Ne))return H;Mn=Mn&&Oe(Ne,Ve,je),Ve=Ne}else{for(Ee=0;Ee<_.length;Ne>=65536?Ee+=2:Ee++){if(Ne=st(_,Ee),Ne===l)Ue=!0,Qt&&(ut=ut||Ee-zt-1>oe&&_[zt+1]!==" ",zt=Ee);else if(!se(Ne))return H;Mn=Mn&&Oe(Ne,Ve,je),Ve=Ne}ut=ut||Qt&&Ee-zt-1>oe&&_[zt+1]!==" "}return!Ue&&!ut?Mn&&!fe&&!G(_)?Fe:pe===be?H:De:X>9&&Le(_)?H:fe?pe===be?H:De:ut?$:L}function me(_,W,X,oe,G){_.dump=(function(){if(W.length===0)return _.quotingType===be?'""':"''";if(!_.noCompatMode&&(ke.indexOf(W)!==-1||Z.test(W)))return _.quotingType===be?'"'+W+'"':"'"+W+"'";const pe=_.indent*Math.max(1,X),fe=_.lineWidth===-1?-1:Math.max(Math.min(_.lineWidth,40),_.lineWidth-pe),je=oe||_.flowLevel>-1&&X>=_.flowLevel;function Ee(Ne){return qe(_,Ne)}switch(Q(W,je,_.indent,fe,Ee,_.quotingType,_.forceQuotes&&!oe,G)){case Fe:return W;case De:return"'"+W.replace(/'/g,"''")+"'";case L:return"|"+_e(W,_.indent)+$e(ge(W,pe));case $:return">"+_e(W,_.indent)+$e(ge(Xe(W,fe),pe));case H:return'"'+rt(W)+'"';default:throw new t("impossible error: invalid scalar style")}})()}function _e(_,W){const X=Le(_)?String(W):"",oe=_[_.length-1]===`
|
|
86
|
+
`,pe=oe&&(_[_.length-2]===`
|
|
87
|
+
`||_===`
|
|
88
|
+
`)?"+":oe?"":"-";return X+pe+`
|
|
89
|
+
`}function $e(_){return _[_.length-1]===`
|
|
90
|
+
`?_.slice(0,-1):_}function Xe(_,W){const X=/(\n+)([^\n]*)/g;let oe=(function(){let je=_.indexOf(`
|
|
91
|
+
`);return je=je!==-1?je:_.length,X.lastIndex=je,et(_.slice(0,je),W)})(),G=_[0]===`
|
|
92
|
+
`||_[0]===" ",pe,fe;for(;fe=X.exec(_);){const je=fe[1],Ee=fe[2];pe=Ee[0]===" ",oe+=je+(!G&&!pe&&Ee!==""?`
|
|
93
|
+
`:"")+et(Ee,W),G=pe}return oe}function et(_,W){if(_===""||_[0]===" ")return _;const X=/ [^ ]/g;let oe,G=0,pe,fe=0,je=0,Ee="";for(;oe=X.exec(_);)je=oe.index,je-G>W&&(pe=fe>G?fe:je,Ee+=`
|
|
94
|
+
`+_.slice(G,pe),G=pe+1),fe=je;return Ee+=`
|
|
95
|
+
`,_.length-G>W&&fe>G?Ee+=_.slice(G,fe)+`
|
|
96
|
+
`+_.slice(fe+1):Ee+=_.slice(G),Ee.slice(1)}function rt(_){let W="",X=0;for(let oe=0;oe<_.length;X>=65536?oe+=2:oe++){X=st(_,oe);const G=Ie[X];!G&&se(X)?(W+=_[oe],X>=65536&&(W+=_[oe+1])):W+=G||he(X)}return W}function it(_,W,X){let oe="";const G=_.tag;for(let pe=0,fe=X.length;pe<fe;pe+=1){let je=X[pe];_.replacer&&(je=_.replacer.call(X,String(pe),je)),(K(_,W,je,!1,!1)||typeof je>"u"&&K(_,W,null,!1,!1))&&(oe!==""&&(oe+=","+(_.condenseFlow?"":" ")),oe+=_.dump)}_.tag=G,_.dump="["+oe+"]"}function Me(_,W,X,oe){let G="";const pe=_.tag;for(let fe=0,je=X.length;fe<je;fe+=1){let Ee=X[fe];_.replacer&&(Ee=_.replacer.call(X,String(fe),Ee)),(K(_,W+1,Ee,!0,!0,!1,!0)||typeof Ee>"u"&&K(_,W+1,null,!0,!0,!1,!0))&&((!oe||G!=="")&&(G+=xe(_,W)),_.dump&&l===_.dump.charCodeAt(0)?G+="-":G+="- ",G+=_.dump)}_.tag=pe,_.dump=G||"[]"}function Be(_,W,X){let oe="";const G=_.tag,pe=Object.keys(X);for(let fe=0,je=pe.length;fe<je;fe+=1){let Ee="";oe!==""&&(Ee+=", "),_.condenseFlow&&(Ee+='"');const Ne=pe[fe];let Ve=X[Ne];_.replacer&&(Ve=_.replacer.call(X,Ne,Ve)),K(_,W,Ne,!1,!1)&&(_.dump.length>1024&&(Ee+="? "),Ee+=_.dump+(_.condenseFlow?'"':"")+":"+(_.condenseFlow?"":" "),K(_,W,Ve,!1,!1)&&(Ee+=_.dump,oe+=Ee))}_.tag=G,_.dump="{"+oe+"}"}function p(_,W,X,oe){let G="";const pe=_.tag,fe=Object.keys(X);if(_.sortKeys===!0)fe.sort();else if(typeof _.sortKeys=="function")fe.sort(_.sortKeys);else if(_.sortKeys)throw new t("sortKeys must be a boolean or a function");for(let je=0,Ee=fe.length;je<Ee;je+=1){let Ne="";(!oe||G!=="")&&(Ne+=xe(_,W));const Ve=fe[je];let Ue=X[Ve];if(_.replacer&&(Ue=_.replacer.call(X,Ve,Ue)),!K(_,W+1,Ve,!0,!0,!0))continue;const ut=_.tag!==null&&_.tag!=="?"||_.dump&&_.dump.length>1024;ut&&(_.dump&&l===_.dump.charCodeAt(0)?Ne+="?":Ne+="? "),Ne+=_.dump,ut&&(Ne+=xe(_,W)),K(_,W+1,Ue,!0,ut)&&(_.dump&&l===_.dump.charCodeAt(0)?Ne+=":":Ne+=": ",Ne+=_.dump,G+=Ne)}_.tag=pe,_.dump=G||"{}"}function U(_,W,X){const oe=X?_.explicitTypes:_.implicitTypes;for(let G=0,pe=oe.length;G<pe;G+=1){const fe=oe[G];if((fe.instanceOf||fe.predicate)&&(!fe.instanceOf||typeof W=="object"&&W instanceof fe.instanceOf)&&(!fe.predicate||fe.predicate(W))){if(X?fe.multi&&fe.representName?_.tag=fe.representName(W):_.tag=fe.tag:_.tag="?",fe.represent){const je=_.styleMap[fe.tag]||fe.defaultStyle;let Ee;if(a.call(fe.represent)==="[object Function]")Ee=fe.represent(W,je);else if(o.call(fe.represent,je))Ee=fe.represent[je](W,je);else throw new t("!<"+fe.tag+'> tag resolver accepts not "'+je+'" style');_.dump=Ee}return!0}}return!1}function K(_,W,X,oe,G,pe,fe){_.tag=null,_.dump=X,U(_,X,!1)||U(_,X,!0);const je=a.call(_.dump),Ee=oe;oe&&(oe=_.flowLevel<0||_.flowLevel>W);const Ne=je==="[object Object]"||je==="[object Array]";let Ve,Ue;if(Ne&&(Ve=_.duplicates.indexOf(X),Ue=Ve!==-1),(_.tag!==null&&_.tag!=="?"||Ue||_.indent!==2&&W>0)&&(G=!1),Ue&&_.usedDuplicates[Ve])_.dump="*ref_"+Ve;else{if(Ne&&Ue&&!_.usedDuplicates[Ve]&&(_.usedDuplicates[Ve]=!0),je==="[object Object]")oe&&Object.keys(_.dump).length!==0?(p(_,W,_.dump,G),Ue&&(_.dump="&ref_"+Ve+_.dump)):(Be(_,W,_.dump),Ue&&(_.dump="&ref_"+Ve+" "+_.dump));else if(je==="[object Array]")oe&&_.dump.length!==0?(_.noArrayIndent&&!fe&&W>0?Me(_,W-1,_.dump,G):Me(_,W,_.dump,G),Ue&&(_.dump="&ref_"+Ve+_.dump)):(it(_,W,_.dump),Ue&&(_.dump="&ref_"+Ve+" "+_.dump));else if(je==="[object String]")_.tag!=="?"&&me(_,_.dump,W,pe,Ee);else{if(je==="[object Undefined]")return!1;if(_.skipInvalid)return!1;throw new t("unacceptable kind of an object to dump "+je)}if(_.tag!==null&&_.tag!=="?"){let ut=encodeURI(_.tag[0]==="!"?_.tag.slice(1):_.tag).replace(/!/g,"%21");_.tag[0]==="!"?ut="!"+ut:ut.slice(0,18)==="tag:yaml.org,2002:"?ut="!!"+ut.slice(18):ut="!<"+ut+">",_.dump=ut+" "+_.dump}}return!0}function de(_,W){const X=[],oe=[];re(_,X,oe);const G=oe.length;for(let pe=0;pe<G;pe+=1)W.duplicates.push(X[oe[pe]]);W.usedDuplicates=new Array(G)}function re(_,W,X){if(_!==null&&typeof _=="object"){const oe=W.indexOf(_);if(oe!==-1)X.indexOf(oe)===-1&&X.push(oe);else if(W.push(_),Array.isArray(_))for(let G=0,pe=_.length;G<pe;G+=1)re(_[G],W,X);else{const G=Object.keys(_);for(let pe=0,fe=G.length;pe<fe;pe+=1)re(_[G[pe]],W,X)}}}function F(_,W){W=W||{};const X=new ne(W);X.noRefs||de(_,X);let oe=_;return X.replacer&&(oe=X.replacer.call({"":oe},"",oe)),K(X,0,oe,!0,!0)?X.dump+`
|
|
97
|
+
`:""}return kp.dump=F,kp}var Ub;function lj(){if(Ub)return $n;Ub=1;const e=ij(),t=sj();function n(a,o){return function(){throw new Error("Function yaml."+a+" is removed in js-yaml 4. Use yaml."+o+" instead, which is now safe by default.")}}return $n.Type=Vn(),$n.Schema=Pk(),$n.FAILSAFE_SCHEMA=Mk(),$n.JSON_SCHEMA=Dk(),$n.CORE_SCHEMA=Lk(),$n.DEFAULT_SCHEMA=$h(),$n.load=e.load,$n.loadAll=e.loadAll,$n.dump=t.dump,$n.YAMLException=Yl(),$n.types={binary:Hk(),float:Nk(),map:Ek(),null:jk(),pairs:Bk(),set:Fk(),timestamp:Uk(),bool:Ok(),int:$k(),merge:zk(),omap:qk(),seq:Tk(),str:Ak()},$n.safeLoad=n("safeLoad","load"),$n.safeLoadAll=n("safeLoadAll","loadAll"),$n.safeDump=n("safeDump","dump"),$n}var cj=lj();const dj=oj(cj),{Type:FJ,Schema:VJ,FAILSAFE_SCHEMA:KJ,JSON_SCHEMA:WJ,CORE_SCHEMA:GJ,DEFAULT_SCHEMA:ZJ,load:JJ,loadAll:YJ,dump:QJ,YAMLException:XJ,types:eY,safeLoad:tY,safeLoadAll:nY,safeDump:aY}=dj,Nh=3e3,Dh=9999,oY="openpond.yaml",uj=["google","github","x"],Lh=new Set([22,2222,2375,2376,3108,5900,5901,6080,7818]),zb=f(r().trim().min(1).max(1e3)).max(50),El=r().trim().min(1).max(4096).refine(Gk,{message:"path must be a relative workspace path"}),mj=r().trim().min(1).max(500).refine(e=>!e.includes("\0")&&!/\s/.test(e),"image ref must be a single OCI reference"),pj=r().trim().regex(/^sha256:[0-9a-f]{64}$/i),Vk=r().trim().min(1).max(500).refine(e=>e.startsWith("/")&&!e.includes("\0"),"workspaceRoot must be an absolute guest path"),fj=c({ref:mj,digest:pj.optional(),registrySecretRef:r().trim().min(1).max(500).optional(),platform:S("linux/amd64").optional(),workspaceRoot:Vk.optional()}).strict(),hj=c({context:El.default("."),path:El.default("Dockerfile"),target:r().trim().min(1).max(191).optional(),buildArgs:ie(r().max(191),r().max(500)).optional(),registrySecretRefs:f(r().trim().min(1).max(500)).max(10).optional(),platform:S("linux/amd64").optional(),workspaceRoot:Vk.optional()}).strict(),gj=c({base:r().trim().min(1).max(120).optional(),snapshot:r().trim().min(1).max(191).optional(),image:fj.optional(),dockerfile:hj.optional()}).strict().superRefine((e,t)=>{[e.base,e.snapshot,e.image,e.dockerfile].filter(Boolean).length!==1&&t.addIssue({code:Fn.custom,message:"runtime must declare exactly one of base, snapshot, image, or dockerfile"})}),Kk=c({cpu:u().positive().max(8).optional(),memoryGb:u().positive().max(32).optional(),diskGb:u().positive().max(100).optional()}).strict(),vj=c({provider:b(uj),scopes:f(r().trim().min(1).max(200)).max(100).default([]),capabilities:f(r().trim().min(1).max(200)).max(100).default([])}).strict(),bj=c({models:f(r().trim().min(1).max(200)).max(100).default([]),scopes:f(r().trim().min(1).max(200)).max(100).default([])}).strict(),yj=c({opchat:bj.optional()}).catchall(ie(r(),ce())).default({}),Sj=c({name:r().trim().regex(/^[A-Za-z_][A-Za-z0-9_-]*$/).max(63).optional(),mountPath:r().trim().min(1).max(256).optional(),storageGb:u().int().positive().max(100).optional(),deleteOnSandboxDelete:A().optional()}).strict(),kj=c({port:u().int().min(Nh).max(Dh).refine(e=>!Lh.has(e),{message:"preview port is reserved"}),protocol:S("http").default("http"),label:r().trim().min(1).max(80).optional(),access:b(["private","public"]).default("private"),path:r().trim().min(1).max(512).refine(e=>e.startsWith("/"),{message:"preview path must start with /"}).default("/")}).strict(),Wk=c({command:r().trim().min(1).max(1e3),cwd:El.optional(),timeoutSeconds:u().int().positive().max(86400).optional(),requiresStart:A().default(!1),ports:f(kj).max(20).default([]),artifactPaths:f(El).max(100).default([])}).strict(),Hb=Wk.extend({name:r().trim().min(1).max(80)}).strict(),xj=c({name:r().trim().min(1).max(80).optional(),service:r().trim().min(1).max(80).optional(),port:u().int().min(Nh).max(Dh).refine(e=>!Lh.has(e),{message:"app MCP port is reserved"}),path:r().trim().min(1).max(512).refine(e=>e.startsWith("/"),{message:"app MCP path must start with /"}).default("/mcp")}).strict(),wj=c({name:r().trim().min(1).max(80).optional(),port:u().int().min(Nh).max(Dh).refine(e=>!Lh.has(e),{message:"validation probe port is reserved"}),path:r().trim().min(1).max(512).refine(e=>e.startsWith("/"),{message:"validation probe path must start with /"}).default("/"),expectedStatus:u().int().min(100).max(599).default(200)}).strict(),Ij=ie(r(),ce()).refine(e=>e.type==="object","input schema must be a JSON schema object"),_j=c({name:r().trim().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).max(191),required:A().default(!1),secret:A().default(!0),description:r().trim().max(500).optional()}).strict(),xp=r().trim().min(1).max(120),Cj=c({name:r().trim().min(1).max(120),description:r().trim().max(500).optional(),cron:r().trim().min(1).max(500).optional(),rate:r().trim().min(1).max(500).optional(),once:xp.optional(),scheduleType:b(["rate","cron","once"]).optional(),scheduleExpression:r().trim().min(1).max(500).optional(),timezone:r().trim().min(1).max(100).optional(),enabled:A().default(!0),startAt:xp.optional(),endAt:xp.optional(),maxRuns:u().int().positive().nullable().optional(),runtimePolicy:b(["run_and_stop","run_and_archive","run_and_delete","use_existing_running"]).default("run_and_stop"),action:r().trim().min(1).max(120).optional(),actionName:r().trim().min(1).max(120).optional(),command:r().trim().min(1).max(2e3).optional(),target:c({kind:b(["start","action","service","command"]).optional(),name:r().trim().min(1).max(120).optional(),actionName:r().trim().min(1).max(120).optional(),command:r().trim().min(1).max(2e3).optional(),requiresStart:A().optional()}).strict().optional(),requiresStart:A().optional(),budget:c({maxUsd:r().trim().min(1).max(40).optional()}).strict().optional(),resources:Kk.optional(),quotas:ie(r(),ce()).optional(),lifecycle:ie(r(),ce()).optional(),retentionPolicy:ie(r(),ce()).optional(),env:f(c({name:r().trim().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).max(191),value:r().optional(),secretRef:r().optional()}).strict()).max(100).optional(),integrationLeases:f(ie(r(),ce())).max(20).optional(),metadata:ie(r(),ce()).optional()}).strict().superRefine((e,t)=>{[e.cron,e.rate,e.once,e.scheduleExpression].filter(l=>typeof l=="string"&&l.trim()).length!==1&&t.addIssue({code:Fn.custom,path:["scheduleExpression"],message:"schedule must declare exactly one of cron, rate, once, or scheduleExpression"}),e.scheduleExpression&&!e.scheduleType&&t.addIssue({code:Fn.custom,path:["scheduleType"],message:"scheduleType is required with scheduleExpression"});const a=e.command??e.target?.command??null,o=e.target?.name??null,i=e.actionName??e.action??e.target?.actionName??(e.target?.kind==="action"?o:null),s=e.target?.kind??(a?"command":"action");s==="action"&&!i&&t.addIssue({code:Fn.custom,path:["action"],message:"schedule action target is required"}),s==="service"&&!o&&t.addIssue({code:Fn.custom,path:["target","name"],message:"schedule service target name is required"}),s==="command"&&!a&&t.addIssue({code:Fn.custom,path:["command"],message:"schedule command target is required"})}),Rj=c({schemaVersion:S(1),name:r().trim().min(1).max(80).regex(/^[a-z0-9][a-z0-9-]*[a-z0-9]$/),version:r().trim().min(1).max(40),useCase:r().trim().min(1).max(80),description:r().trim().min(1).max(500),runtime:gj,resources:Kk.optional(),setup:c({commands:zb.default([])}).strict().default({commands:[]}),validation:c({commands:zb.min(1),probes:f(wj).max(20).default([])}).strict(),start:Wk,actions:f(Hb).max(20).default([]),services:f(Hb).max(20).default([]),schedules:f(Cj).max(20).default([]),mcp:c({endpoints:f(xj).max(10).default([])}).strict().default({endpoints:[]}),volumes:f(Sj).max(5).default([]),integrations:c({requiredLeases:f(vj).max(20).default([])}).strict().default({requiredLeases:[]}),permissions:yj,inputs:c({schema:Ij.default({type:"object"}),env:f(_j).max(100).default([])}).strict().default({schema:{type:"object"},env:[]}),artifacts:c({paths:f(El).max(100).default([])}).strict().default({paths:[]}),network:c({egress:b(["restricted","allow","block"]).default("restricted")}).strict().default({egress:"restricted"})}).strict().superRefine((e,t)=>{Aj(e,t),Uh(t,e.volumes.flatMap(n=>n.name?[n.name]:[]),"volume names must be unique","volumes"),Tj(e,t),Ej(e,t),Mj(e,t),jj(e,t)}),Pj=c({path:r(),message:r(),code:r()});function rY(e){return[{kind:"start",name:"start",...e.start,artifactPaths:Ip(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:Ip(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:Ip(t,e)}))]}function Gk(e){return!e.includes("\0")&&!e.startsWith("/")&&!e.split(/[\\/]+/).some(t=>t===".."||t==="")}function Uh(e,t,n,a){const o=new Set;for(const i of t){if(o.has(i)){e.addIssue({code:Fn.custom,path:[a],message:n});return}o.add(i)}}function Aj(e,t){const n=["start",...e.actions.map(a=>a.name),...e.services.map(a=>a.name)];Uh(t,n,"start, action, and service names must be unique","actions")}function Tj(e,t){const n=wp(e.inputs.schema.properties),a=new Set(e.volumes.map(o=>o.name).filter(o=>!!o));for(const[o,i]of Object.entries(n)){const s=wp(i),l=wp(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(!Gk(d)){t.addIssue({code:Fn.custom,path:["inputs","schema","properties",o,"x-openpond-upload","targetPath"],message:"upload target must be a relative workspace path"});continue}const h=d.split("/");h[0]==="volumes"&&(!h[1]||!a.has(h[1]))&&t.addIssue({code:Fn.custom,path:["inputs","schema","properties",o,"x-openpond-upload","targetPath"],message:"upload target references an undeclared volume"})}}function Ej(e,t){Uh(t,e.inputs.env.map(n=>n.name),"env input names must be unique","inputs")}function Mj(e,t){const n=new Map(e.services.map(o=>[o.name,new Set(o.ports.map(i=>i.port))])),a=new Set([...e.start.ports.map(o=>o.port),...e.services.flatMap(o=>o.ports.map(i=>i.port))]);for(const[o,i]of e.mcp.endpoints.entries()){if(i.service){const s=n.get(i.service);if(!s){t.addIssue({code:Fn.custom,path:["mcp","endpoints",o,"service"],message:`app MCP service does not exist: ${i.service}`});continue}s.has(i.port)||t.addIssue({code:Fn.custom,path:["mcp","endpoints",o,"port"],message:`app MCP port ${i.port} is not declared on service ${i.service}`});continue}a.has(i.port)||t.addIssue({code:Fn.custom,path:["mcp","endpoints",o,"port"],message:`app MCP port ${i.port} is not declared on start or services`})}}function jj(e,t){const n=new Set(e.actions.map(o=>o.name)),a=new Set(e.services.map(o=>o.name));for(const[o,i]of e.schedules.entries()){const s=i.command??i.target?.command??null;if(i.target?.kind==="command"||s)continue;const l=i.actionName??i.action??i.target?.actionName??(i.target?.kind==="action"?i.target?.name:null);if(l&&!n.has(l)&&t.addIssue({code:Fn.custom,path:["schedules",o,"action"],message:`schedule action target does not exist: ${l}`}),i.target?.kind==="service"){const m=i.target.name??"";m&&!a.has(m)&&t.addIssue({code:Fn.custom,path:["schedules",o,"target","name"],message:`schedule service target does not exist: ${m}`})}}}function wp(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Ip(e,t){return e.artifactPaths.length>0?e.artifactPaths:t.artifacts.paths}const Oj=c({id:r(),name:r(),description:r().nullable(),scheduleType:r(),scheduleExpression:r(),enabled:A(),rawEnabled:A().optional(),syncStatus:r().nullable(),syncError:r().nullable().optional(),startAt:r().nullable(),endAt:r().nullable(),maxRuns:u().nullable(),executionCount:u().nullable(),lifecycleStatus:r().nullable(),lifecycleReason:r().nullable(),lastExecutionAt:r().nullable().optional(),lastExecutionStatus:r().nullable().optional(),lastRunNowAt:r().nullable().optional(),lastRunNowStatus:r().nullable().optional(),updatedAt:r(),deploymentId:r(),isProduction:A().optional(),payload:ce().optional()}).passthrough(),$j=c({total:u().int().nonnegative(),active:u().int().nonnegative(),paused:u().int().nonnegative(),enabled:u().int().nonnegative().optional(),disabled:u().int().nonnegative().optional(),nextRunAt:r().nullable().optional(),lastRunAt:r().nullable().optional(),schedules:f(Oj).optional().default([]),truncated:A().optional()}).passthrough(),_p=c({name:r(),kind:b(["start","action","service"]),command:r(),cwd:r().nullable(),timeoutSeconds:u().nullable(),requiresStart:A(),ports:f(c({port:u(),protocol:r(),label:r().nullable(),access:r(),path:r()}).passthrough()).default([]),artifactPaths:f(r()).default([])}).passthrough(),Nj=c({schemaVersion:S(1),source:S("openpond.yaml"),manifestName:r(),manifestVersion:r(),manifestUseCase:r(),manifestDescription:r(),manifestPath:r(),manifestHash:r(),inputSchema:ie(r(),ce()).default({}),env:f(c({name:r(),required:A(),secret:A(),description:r().nullable()}).passthrough()).default([]),start:_p,actions:f(_p).default([]),services:f(_p).default([]),defaultActionName:r().nullable(),updatedAt:r()}).passthrough(),Dj=c({id:r(),name:r(),description:r().nullable(),visibility:r().nullable().optional(),gitOwner:r().nullable().optional(),gitRepo:r().nullable().optional(),gitHost:r().nullable().optional(),defaultBranch:r().nullable().optional(),sandbox:A().optional().default(!1),sandboxActionRegistry:Nj.nullable().optional(),sandboxManifestHash:r().nullable().optional(),sandboxManifestPath:r().nullable().optional(),sandboxManifestSyncedAt:r().nullable().optional(),sandboxManifestError:r().nullable().optional(),updatedAt:r().nullable().optional(),latestDeployment:c({id:r().optional(),status:r().optional(),deploymentDomain:r().nullable().optional(),createdAt:r().optional(),isProduction:A().nullable().optional(),gitBranch:r().nullable().optional()}).nullable().optional(),scheduleSummary:$j.nullable().optional()}),Lj=c({detected:A(),rootPath:r(),manifestPath:r(),manifestHash:r().nullable().optional().default(null),manifest:ie(r(),ce()).nullable().optional().default(null),normalizedManifest:Rj.nullable().optional().default(null),valid:A().optional().default(!1),diagnostics:f(Pj).optional().default([])}),Uj=c({appId:r(),appName:r(),gitOwner:r().nullable(),gitRepo:r().nullable(),gitHost:r().nullable(),defaultBranch:r().nullable(),linkedAt:r()}),Zk=c({teamId:r(),projectId:r(),projectSlug:r().nullable().optional().default(null),projectName:r().nullable().optional().default(null),sourceRepoUrl:r().nullable().optional().default(null),defaultBranch:r().nullable().optional().default(null),lastUploadedCommit:r().nullable().optional().default(null),lastUploadTransport:b(["git_head","snapshot","api_source_upload"]).nullable().optional().default(null),manifestPath:r().nullable().optional().default(null),manifestHash:r().nullable().optional().default(null),syncedAt:r().nullable().optional().default(null),linkedAt:r()}),zj=b(["github_repo","internal_repo","template","manual"]),Hj=c({id:r(),teamId:r(),name:r(),slug:r().nullable().optional().default(null),sourceType:zj.optional().default("manual"),sourceLabel:r().nullable().optional().default(null),defaultBranch:r().nullable().optional().default(null),internalRepoPath:r().nullable().optional().default(null),manifestPath:r().nullable().optional().default(null),manifestHash:r().nullable().optional().default(null),syncedAt:r().nullable().optional().default(null),organizationName:r().nullable().optional().default(null),organizationSlug:r().nullable().optional().default(null),createdAt:r().nullable().optional().default(null),updatedAt:r().nullable().optional().default(null)}),qj=c({id:r(),name:r(),path:r(),workspacePath:r(),repoPath:r().nullable(),source:b(["folder","git"]),hiddenFromDefaultSidebar:A().optional(),sandboxTemplate:Lj.nullable().optional().default(null),linkedOpenPondApp:Uj.nullable().optional().default(null),linkedSandboxProject:Zk.nullable().optional().default(null),preferredSandboxAgentId:r().nullable().optional().default(null),createdAt:r(),updatedAt:r()});c({path:r().trim().min(1).optional(),name:r().trim().min(1).max(120).optional(),createNew:A().optional(),baseDirectory:r().trim().min(1).max(4096).optional()}).superRefine((e,t)=>{if(e.createNew){e.name?.trim()||t.addIssue({code:"custom",path:["name"],message:"Project name is required when creating a new project."});return}e.path?.trim()||t.addIssue({code:"custom",path:["path"],message:"Project path is required."})});c({linkedSandboxProject:Zk.nullable().optional(),preferredSandboxAgentId:r().nullable().optional(),hiddenFromDefaultSidebar:A().optional()});const Bj=["connected_app_search","connected_app_read","connected_app_write"],Cp="https://openpond.ai",zh=["slack","google","github","turnkey","x","microsoft_teams","mcp"],Hh={slack:[Zt("slack.channel.bind","Bind channels","Bind Slack channels or threads to OpenPond profiles.","setup",!1),Zt("slack.message.ingest","Ingest messages","Ingest Slack channel or thread activity into OpenPond context.","setup",!1)],microsoft_teams:[Zt("microsoft_teams.channel.bind","Bind channels","Bind Teams channels or chats to OpenPond profiles.","setup",!1),Zt("microsoft_teams.message.ingest","Ingest messages","Ingest Teams channel or chat activity into OpenPond context.","setup",!1)],google:[Zt("google.drive.file.read","Read Drive files","Find and read Google Drive files.","read",!0),Zt("google.drive.file.write","Write Drive files","Create or update approved Google Drive files.","write",!0),Zt("google.docs.read","Read Docs","Read Google Docs content and structure.","read",!0),Zt("google.docs.write","Edit Docs","Apply approved Google Docs edits.","write",!0),Zt("google.comments.read","Read comments","Read Google file comments.","read",!0),Zt("google.comments.write","Write comments","Create or resolve approved Google comments.","write",!0)],github:[Zt("github.repo.read","Read repositories","Read repository metadata and file context.","read",!0),Zt("github.issue.read","Read issues","Read GitHub issues and comments.","read",!0),Zt("github.issue.write","Update issues","Create or update approved GitHub issue content.","write",!0),Zt("github.pull_request.read","Read pull requests","Read pull request metadata, diffs, checks, and reviews.","read",!0),Zt("github.pull_request.write","Update pull requests","Create approved comments or pull request updates.","write",!0)],turnkey:[Zt("turnkey.wallets.read","Read Agent Wallet","Read the connected OpenPond Agent Wallet address and metadata.","read",!0),Zt("turnkey.balances.read","Read wallet balances","Read balances for the connected OpenPond Agent Wallet.","read",!0),Zt("turnkey.activities.read","Read wallet activity","Read recent Turnkey activity for the connected OpenPond Agent Wallet.","read",!0)],x:[Zt("x.profile.read","Read profile","Read the connected X profile.","read",!0),Zt("x.search.read","Search X","Search public X posts when granted.","read",!0),Zt("x.mentions.read","Read mentions","Read mentions for the connected X account.","read",!0),Zt("x.post.write","Post","Create approved X posts.","write",!0),Zt("x.reply.write","Reply","Create approved X replies.","write",!0)],mcp:[Zt("mcp.tool.discover","Discover tools","Discover team-scoped MCP tools.","tooling",!1),Zt("mcp.tool.call","Call tools","Call approved MCP tools through the team endpoint.","tooling",!1)]},qh={slack:[],microsoft_teams:[],google:[Ut("google.drive.search","search","Search Drive","Search Google Drive files by grounded query.",["google.drive.file.read"]),Ut("google.drive.read_file","read","Read Drive file","Read Drive file metadata or exported content by stable ref.",["google.drive.file.read"],{requiredKeys:["ref"]}),Ut("google.docs.read","read","Read Google Doc","Read Google Docs content and structure by stable ref.",["google.docs.read"],{requiredKeys:["ref"]}),Ut("google.comments.read","read","Read comments","Read comments for a grounded Google file ref.",["google.comments.read"],{requiredKeys:["ref"]}),Ut("google.docs.update","write","Update Google Doc","Apply an explicitly approved Google Docs edit and return readback verification.",["google.docs.write"],{requiredKeys:["ref","patch"]}),Ut("google.comments.create","write","Create comment","Create an explicitly approved Google file comment and return readback verification.",["google.comments.write"],{requiredKeys:["ref","body"]}),Ut("google.comments.resolve","write","Resolve comment","Resolve an explicitly approved Google comment and return readback verification.",["google.comments.write"],{requiredKeys:["ref","commentId"]})],github:[Ut("github.repo.search","search","Search repositories","Search accessible repositories by owner, name, or topic.",["github.repo.read"]),Ut("github.issue.search","search","Search issues","Search accessible GitHub issues.",["github.issue.read"]),Ut("github.pull_request.search","search","Search pull requests","Search accessible GitHub pull requests.",["github.pull_request.read"]),Ut("github.repo.read","read","Read repository","Read grounded repository metadata or file context.",["github.repo.read"],{requiredKeys:["ref"]}),Ut("github.issue.read","read","Read issue","Read a grounded GitHub issue and comments.",["github.issue.read"],{requiredKeys:["ref"]}),Ut("github.pull_request.read","read","Read pull request","Read a grounded pull request, checks, reviews, or diff summary.",["github.pull_request.read"],{requiredKeys:["ref"]}),Ut("github.issue.create","write","Create issue","Create an explicitly approved GitHub issue and return readback verification.",["github.issue.write"],{requiredKeys:["repo","title","body"]}),Ut("github.issue.comment","write","Comment on issue","Create an explicitly approved GitHub issue comment and return readback verification.",["github.issue.write"],{requiredKeys:["ref","body"]}),Ut("github.issue.update","write","Update issue","Apply an explicitly approved issue metadata/content update and return readback verification.",["github.issue.write"],{requiredKeys:["ref"]}),Ut("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"]}),Ut("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:[Ut("turnkey.wallets.read","read","Read Agent Wallet","Read the address and metadata for the connected OpenPond Agent Wallet.",["turnkey.wallets.read"]),Ut("turnkey.balances.read","read","Read wallet balances","Read supported-network balances for the connected OpenPond Agent Wallet.",["turnkey.balances.read"]),Ut("turnkey.activities.read","read","Read wallet activity","Read recent Turnkey activity for the connected OpenPond Agent Wallet.",["turnkey.activities.read"])],x:[Ut("x.profile.read","read","Read profile","Read the connected X account profile.",["x.profile.read"]),Ut("x.post.read","read","Read post","Read a public X post by stable ref, status URL, or post id.",["x.search.read"],{requiredKeys:["ref"]}),Ut("x.search.posts","search","Search recent posts","Search public X posts from the X recent-search window by grounded query.",["x.search.read"]),Ut("x.mentions.search","search","Search mentions","Search mentions for the connected X account.",["x.mentions.read"]),Ut("x.mention.read","read","Read mention","Read a grounded mention or post ref.",["x.mentions.read"],{requiredKeys:["ref"]}),Ut("x.post.create","write","Create post","Create an explicitly approved X post and return readback verification.",["x.post.write"],{requiredKeys:["text"]}),Ut("x.reply.create","write","Create reply","Create an explicitly approved X reply and return readback verification.",["x.reply.write"],{requiredKeys:["inReplyToRef","text"]})],mcp:[]},Fj={google:["# Google Connected App","","Use Google only through server-provided connected app tools. Never ask for or infer OAuth tokens.","Before reading or editing, identify the exact Drive file, Doc, Sheet, Slide, or comment thread. If the target is ambiguous, ask a short clarification or search first.","Use only declared Google operation ids: google.drive.search, google.drive.read_file, google.docs.read, google.comments.read, google.docs.update, google.comments.create, google.comments.resolve.","For writes, require explicit user intent, summarize the planned change, and verify the target identity before applying updates.","After a write, read back the changed object or relevant range and report the result with the provider file name or stable reference.","Prefer narrow reads over broad Drive scans. Do not expose private file ids unless the tool result already presents them as stable refs."].join(`
|
|
98
|
+
`),github:["# GitHub Connected App","","Use GitHub only through server-provided connected app tools. Repository, issue, and pull request identity must be grounded before action.","Use only declared GitHub operation ids: github.repo.search, github.issue.search, github.pull_request.search, github.repo.read, github.issue.read, github.pull_request.read, github.issue.create, github.issue.comment, github.issue.update, github.pull_request.comment, github.pull_request.update.","For reads, name the owner/repo and issue or pull request number when available. If several targets match, ask or inspect before proceeding.","For writes, require explicit user intent and avoid destructive repository changes. Create issues only when the user clearly asks to submit or file a new issue. Prefer comments, labels, or metadata updates unless a stronger operation is clearly requested.","Do not claim CI, review, branch, or PR state changed until a tool result confirms it.","Keep local workspace git operations separate from connected GitHub operations unless the user explicitly asks to bridge them."].join(`
|
|
99
|
+
`),turnkey:["# Turnkey Agent Wallet Connected App","","Use Turnkey only through server-provided connected app tools. Never ask for, expose, or infer API keys, P-256 credentials, wallet private keys, or lease material.","Use only declared Turnkey read operation ids: turnkey.wallets.read, turnkey.balances.read, and turnkey.activities.read.","Turnkey connected-app access is read-only. Do not claim that a transaction was created, signed, approved, rejected, or sent.","Use turnkey.wallets.read for the Agent Wallet address and metadata, turnkey.balances.read for supported-network balances, and turnkey.activities.read for recent Turnkey activity.","Report the wallet address and network with balance results, and distinguish an empty balance from a failed provider read."].join(`
|
|
100
|
+
`),x:["# X Connected App","","Use X only through server-provided connected app tools. Distinguish profile, recent search, mention, post, and reply operations.","Use only declared X operation ids: x.profile.read, x.post.read, x.search.posts, x.mentions.search, x.mention.read, x.post.create, x.reply.create.","For x.com, twitter.com, or stable status URLs, first parse the status/post id and read the post with connected_app_read using operation x.post.read and ref set to the original URL, stable ref, or id. Do not open a browser before trying the X connector.","Use x.search.posts for discovery, related public posts, replies, quote-post searches, and conversation scans. It uses X API recent search, so report zero-result searches as zero recent public posts returned by X.","For conversation or reply collection, dedupe by returned post id/ref. Do not repeat the same search call unless the result exposes a usable cursor or next token; if pagination is unavailable, state that coverage is limited to returned recent-search results.","Reads can summarize recent public posts, connected-account profile details, and mentions when the capability is available.","Writes require explicit user intent for the exact post or reply. Do not publish drafts, jokes, endorsements, or replies unless the user clearly approves the content.","Before posting or replying, preserve account identity, quote the proposed content in summary form, and respect provider limits and policy boundaries.","After a write, verify the returned post or reply ref before reporting success."].join(`
|
|
101
|
+
`),microsoft_teams:["# Microsoft Teams Connected App","","Microsoft Teams is currently an ingestion/native binding surface only. Do not expose Teams OAuth reads, replies, file operations, or sandbox leases.","Native Teams setup can bind chats or channels to OpenPond profiles and ingest activity into OpenPond context.","If the user asks for Teams actions beyond ingestion or binding status, explain that the connector is not available yet rather than inventing tool access."].join(`
|
|
102
|
+
`),slack:["# Slack Connected App","","Slack is currently an ingestion/native binding surface only. Do not expose Slack OAuth reads, replies, file operations, or sandbox leases.","Native Slack setup can bind channels or threads to OpenPond profiles and ingest activity into OpenPond context.","If the user asks for Slack actions beyond ingestion or binding status, explain that the connector is not available yet rather than inventing tool access."].join(`
|
|
103
|
+
`),mcp:["# OpenPond MCP Connected App","","Use OpenPond MCP only through server-provided tool discovery and call paths. Do not invent MCP tools or endpoints.","Treat MCP as team-scoped tooling, not an OAuth connector. Tool availability must come from server-confirmed discovery results.","Before calling an MCP tool, match the requested operation to the tool name, description, input schema, and allowed team context.","For writes or side effects, require explicit user intent and report only confirmed tool results."].join(`
|
|
104
|
+
`)},iY=zh.map(e=>{const t=Yk(e),n=Fj[e];return{...t,provider:e,body:n,sourceHash:`connected-app-skill:${e}:${dO(n)}`,charCount:n.length}});function Vj(e){const t=Bh(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=rO(e.operation);if(e.toolName!==n)return{ok:!1,error:`Connected app tool ${e.toolName} does not match ${e.operation} operation.`};const a=e.operation==="write"?"write":"read",o=new Set(t.capabilities.filter(l=>l.access===a&&l.leaseable).map(l=>l.id)),i=e.capabilityIds.filter(l=>!o.has(l));if(i.length>0)return{ok:!1,error:`Connected app capability ${i[0]} is not allowed for ${e.provider} ${e.operation}.`};const s=Wj(e);return s.ok?{ok:!0,request:e}:s}function Kj(e){const t=au(e);return t?qh[t]:[]}function Wj(e){const t=Yj(e.args),n=Kj(e.provider).filter(s=>s.operation===e.operation);if(n.length===0)return{ok:!1,error:`Connected app provider ${e.provider} does not declare ${e.operation} operations.`};if(!t)return e.operation==="write"?{ok:!1,error:`Connected app ${e.provider} write calls require a provider operation id.`}:{ok:!0,request:e};const a=n.find(s=>s.id===t);if(!a)return{ok:!1,error:`Connected app operation ${t} is not allowed for ${e.provider} ${e.operation}.`};const o=e.capabilityIds.filter(s=>!a.capabilityIds.includes(s));if(o.length>0)return{ok:!1,error:`Connected app operation ${a.id} does not allow capability ${o[0]}.`};const i=Xj(e.args,e.operation);for(const s of a.input?.requiredKeys??[]){const l=i[s];if(l==null||typeof l=="string"&&!l.trim())return{ok:!1,error:`Connected app operation ${a.id} requires input.${s}.`}}return{ok:!0,request:e}}const Gj=[{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"}],nu=Gj,Zj=zh.map(e=>{const t=nu.filter(a=>a.providerFamily===e),n=t[0];return{id:e,label:Sl(e),shortLabel:n.shortLabel,category:n.category,icon:n.icon,description:n.description,setupSurfaces:t,capabilities:Hh[e],skills:aO(e),tools:oO(e),operations:qh[e],leasePolicy:iO(e)}});function Jk(e){const t=Jj(e);return t?nu.find(n=>n.id===t)??null:null}function Bh(e){const t=au(e);return t?Zj.find(n=>n.id===t)??null:null}function sY(e){const t=Jk(e.appId),n=tO(e.baseUrl),a=t?.kind==="mcp"?"/sandboxes/mcp":"/sandboxes/apps",o=new URL(a,n);t?.kind!=="mcp"&&o.searchParams.set("app",t?.deepLinkAppId??e.appId);const i=e.teamId?.trim();return i&&o.searchParams.set("teamId",i),o.toString()}function Jj(e){const t=e?.trim().toLowerCase().replace(/[-\s]+/g,"_");return t?t==="teams"||t==="microsoft"?"microsoft_teams":nu.some(n=>n.id===t)?t:null:null}function au(e){const t=e?.trim().toLowerCase().replace(/[-\s]+/g,"_");return t?t==="teams"||t==="microsoft"?"microsoft_teams":zh.includes(t)?t:Jk(t)?.providerFamily??null:null}function Rp(e={}){const t=sO(e.connections??[]);return nu.map(n=>{const a=Bh(n.providerFamily),o=n.statusSource==="integration_connection"?t.filter(l=>l.provider===n.providerFamily):[],i=o.some(l=>l.status==="active"),s=lO(n,i);return{...n,providerLabel:a.label,setupSurfaceLabel:nO(n.setupSurface),status:s,statusLabel:cO(n,s,o),connections:o,connected:i,capabilities:qb(n,a.capabilities),capabilityLabels:qb(n,a.capabilities).map(l=>l.label),leasePolicy:a.leasePolicy}})}function Zt(e,t,n,a,o){return{id:e,label:t,description:n,access:a,leaseable:o}}function Ut(e,t,n,a,o,i){return{id:e,operation:t,label:n,description:a,capabilityIds:o,...i?{input:i}:{},requiresReadback:t==="write",requiresRuntimeLease:!1}}function Yj(e){return Qj(e.operation)}function Qj(e){return typeof e=="string"&&e.trim()?e.trim():null}function Xj(e,t){return t==="write"?eO(e.input)?e.input:{}:e}function eO(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function tO(e){const t=e?.trim();if(!t)return Cp;try{const n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?Cp:(n.pathname="/",n.search="",n.hash="",n.toString())}catch{return Cp}}function Sl(e){return e==="microsoft_teams"?"Microsoft Teams":e==="mcp"?"OpenPond MCP":e==="x"?"X":e[0].toUpperCase()+e.slice(1)}function nO(e){return e==="native_bot"?"Native app":e==="oauth_connector"?"OAuth connector":e==="wallet_connector"?"Wallet connector":"MCP endpoint"}function aO(e){return[Yk(e)]}function Yk(e){return{name:`${e}-connected-app`,description:`Use ${Sl(e)} safely through connected app tools.`,path:`integration_skills/${e}.md`}}function oO(e){if(e==="mcp")return[];const t=Hh[e],n=qh[e],a=t.filter(s=>s.access==="read").map(s=>s.id),o=t.filter(s=>s.access==="write").map(s=>s.id),i=[];return n.some(s=>s.operation==="search")&&i.push({name:"connected_app_search",description:`Search ${Sl(e)} through a server-owned connected app connector.`,capabilityIds:a,write:!1}),n.some(s=>s.operation==="read")&&i.push({name:"connected_app_read",description:`Read a grounded ${Sl(e)} object through a server-owned connected app connector.`,capabilityIds:a,write:!1}),o.length>0&&n.some(s=>s.operation==="write")&&i.push({name:"connected_app_write",description:`Perform an explicitly approved ${Sl(e)} write through a server-owned connected app connector.`,capabilityIds:o,write:!0}),i}function rO(e){return e==="search"?"connected_app_search":e==="read"?"connected_app_read":"connected_app_write"}function iO(e){const t=Hh[e].filter(a=>a.leaseable).map(a=>a.id),n=e!=="mcp"&&t.length>0;return{leaseable:n,defaultTtlSeconds:n?e==="turnkey"?300:3600:null,allowedCapabilityIds:t,requiresProxy:n}}function qb(e,t){return e.setupSurface==="native_bot"?t.filter(n=>n.access==="setup"):e.setupSurface==="mcp_endpoint"?t:t.filter(n=>n.access!=="setup")}function sO(e){return e.flatMap(t=>{const n=au(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 lO(e,t){return e.statusSource==="integration_connection"?t?"connected":"disconnected":"setup_available"}function cO(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 dO(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 uO=b(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),mO=b(["search","read","write"]),pO=b(Bj);c({provider:uO,operation:mO,toolName:pO,sessionId:r().trim().min(1).max(200),turnId:r().trim().min(1).max(200),toolCallId:r().trim().min(1).max(300),userPrompt:r().max(2e5),connectionIds:f(r().trim().min(1).max(300)).min(1).max(8),capabilityIds:f(r().trim().min(1).max(200)).min(1).max(64),args:ie(r(),ce()).default({})}).strict().superRefine((e,t)=>{const n=Vj(e);n.ok||t.addIssue({code:Fn.custom,message:n.error})});c({ok:A(),output:r().nullable().optional(),data:ce().optional()}).strict();const fO="local_path:";function Qk(e){return`${fO}${e.trim()}`}c({appId:r(),source:b(["openpond","github","local_git","local_folder","unknown"]),workspacePath:r(),repoPath:r(),initialized:A(),remoteUrl:r().nullable(),expectedRemoteUrl:r().nullable(),currentBranch:r().nullable(),headCommit:r().nullable().optional().default(null),upstreamBranch:r().nullable().optional().default(null),ahead:u().int().nonnegative().optional().default(0),behind:u().int().nonnegative().optional().default(0),diverged:A().optional().default(!1),linkedSourceHeadCommit:r().nullable().optional().default(null),aheadOfLinkedSource:u().int().nonnegative().optional().default(0),behindLinkedSource:u().int().nonnegative().optional().default(0),divergedFromLinkedSource:A().optional().default(!1),linkedSourceComparisonError:r().nullable().optional().default(null),lastFetchAt:r().nullable().optional().default(null),defaultBranch:r().nullable(),branches:f(r()),dirty:A(),changedFilesCount:u(),untrackedFilesCount:u(),error:r().nullable(),updatedAt:r()});const hO=c({path:r(),status:r(),additions:u(),deletions:u(),patch:r(),content:r().nullable().optional().default(null)}),gO=c({appId:r(),repoPath:r(),initialized:A(),dirty:A(),filesChanged:u(),additions:u(),deletions:u(),repoFiles:f(r()).optional().default([]),files:f(hO),error:r().nullable(),updatedAt:r()});c({branch:r().trim().min(1).max(160)});c({path:r().trim().min(1),content:r()});const Bb=c({line:u().int().nonnegative(),character:u().int().nonnegative()}),vO=c({start:Bb,end:Bb}),bO=c({path:r(),range:vO,severity:b(["error","warning","info","hint"]),message:r(),source:r().nullable().optional().default(null),code:r().nullable().optional().default(null)}),Xk=c({id:r(),root:r(),status:b(["connected","unavailable","error"]),message:r().nullable().optional().default(null)});c({path:r().trim().min(1),content:r().optional(),waitForDiagnostics:A().optional().default(!0)});c({appId:r(),path:r(),diagnostics:f(bO),servers:f(Xk),updatedAt:r()});const yO=c({operation:b(["hover","definition","references","documentSymbol"]),path:r().trim().min(1),content:r().optional(),line:u().int().nonnegative().optional(),character:u().int().nonnegative().optional()});c({appId:r(),operation:yO.shape.operation,path:r(),results:ce(),servers:f(Xk),updatedAt:r()});const SO=c({pinned:A().optional(),archived:A().optional(),order:u().optional()}),kO=ie(r(),SO),ex=b(["local","sandbox"]),xO=b(["pinned","saved_for_later"]),tx=c({id:r().min(1),workspaceKind:ex,workspaceId:r().min(1),workspaceName:r().min(1),path:r().min(1),status:xO,order:u().int().nonnegative().nullable().default(null),sourceSessionId:r().min(1).nullable().default(null),available:A().default(!0),createdAt:r().min(1),updatedAt:r().min(1)});c({items:f(tx)});c({workspaceKind:ex,workspaceId:r().trim().min(1),workspaceName:r().trim().min(1),path:r().trim().min(1),status:b(["pinned","saved_for_later","none"]),order:u().int().nonnegative().nullable().optional(),sourceSessionId:r().trim().min(1).nullable().optional()});b(["pin","save_for_later","remove","list"]);function wO(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 lY(e){return["sidebar-file",e.workspaceKind,encodeURIComponent(e.workspaceId),encodeURIComponent(wO(e.path))].join(":")}const IO=c({id:r(),name:r(),type:r(),status:r(),isActive:A().nullable(),price:r().nullable(),currency:r().nullable(),credits:r().nullable()}).passthrough(),_O=c({reachable:A(),authenticated:A().nullable(),apiBase:r(),latencyMs:u(),status:u().nullable(),service:r().nullable(),checkedAt:r(),error:r().nullable()}),CO=c({id:r().nullable(),email:r().nullable(),name:r().nullable(),handle:r().nullable(),image:r().nullable(),timezone:r().nullable(),isAdmin:A().nullable(),isVerified:A().nullable(),dailyAgentAppId:r().nullable(),dailyAgentDeploymentId:r().nullable(),credits:r().nullable()}),RO=c({handle:r(),baseUrl:r().nullable().optional()}),PO=c({state:b(["signed_out","signed_in","loading","switching","auth_error"]),activeProfile:RO.nullable(),label:r(),email:r().nullable(),avatarUrl:r().nullable(),environment:r().nullable(),baseUrl:r().nullable(),apiBaseUrl:r().nullable(),chatApiBaseUrl:r().nullable().optional().default(null),creditsLabel:r().nullable(),profile:CO.nullable(),products:f(IO),apiHealth:_O.nullable(),accounts:f(c({handle:r(),baseUrl:r().nullable(),apiBaseUrl:r().nullable().optional().default(null),chatApiBaseUrl:r().nullable().optional(),environment:r().nullable(),isActive:A(),authHealth:b(["signed_out","signed_in","auth_error","unknown"]),displayLabel:r().nullable(),email:r().nullable().optional().default(null),avatarUrl:r().nullable()})),error:r().nullable()}),Fb=c({asOf:r().nullable(),refreshing:A(),lastRefreshError:r().nullable(),source:b(["fresh","cache","empty"])}),AO=c({available:A(),binaryPath:r().nullable(),version:r().nullable(),authHealth:b(["unknown","signed_in","signed_out","auth_error"]),account:c({type:r(),email:r().nullable(),planType:r().nullable(),label:r().nullable()}).nullable().default(null),appServer:c({status:b(["idle","starting","ready","error"]),lastError:r().nullable()})}),Fh="gpt-5.6-sol",es="openpond-chat",Fr="openpond",Ml=es,Vh="default",Kh="high",ou="ask",fs=Jr,Wh=b(["default","auto-review","full-access"]),Ql=b(["ask","full-access","disabled"]),ru=b(["low","medium","high","xhigh"]),Xl=b(["sandbox_app","local_project","sandbox","sandbox_template"]);b(["openpond"]);const TO=b(["provider_usage","provider_tokenizer","model_family","heuristic"]),EO=c({provider:fs,model:r().min(1),usedTokens:u().int().nonnegative(),maxContextTokens:u().int().positive(),usableContextTokens:u().int().positive(),percentFull:u().min(0).max(100),source:TO,updatedAtEventId:r().nullable()}),wf=c({pinned:A().default(!1),projects:A().default(!1),cloudProjects:A().default(!1),chats:A().default(!1),savedForLater:A().default(!0)}),MO=b(["auto","off"]),jO=b(["typescript","python","rust"]),nx=b(["auto","disabled","custom"]),Ro=c({mode:nx.default("auto"),customCommand:r().trim().max(4096).default("")}),_d=c({languageServers:MO.default("auto"),diagnosticsWhileEditing:A().default(!0),checkOnSave:A().default(!0),languages:c({typescript:Ro.optional().default(()=>Ro.parse({})),python:Ro.optional().default(()=>Ro.parse({})),rust:Ro.optional().default(()=>Ro.parse({}))}).optional().default(()=>({typescript:Ro.parse({}),python:Ro.parse({}),rust:Ro.parse({})}))}),OO=c({language:jO,label:r(),mode:nx,status:b(["found","missing","disabled","error"]),command:r().nullable(),message:r().nullable()});c({settings:_d,languages:f(OO),updatedAt:r()});const $O=c({id:r(),root:r(),status:b(["starting","connected","unavailable","error"]),message:r().nullable().optional().default(null),openedDocuments:u().int().nonnegative(),pendingRequests:u().int().nonnegative(),lastUsedAt:r(),stderrTail:r()});c({clients:f($O),maxClients:u().int().positive(),idleTimeoutMs:u().int().positive(),updatedAt:r()});const If=c({autoEnabled:A().default(!0),triggerPercent:u().int().min(50).max(95).default(85),summaryModel:b(["same_model"]).default("same_model")}),_f=c({defaultModelRef:mn.nullable().default(null),creationMode:b(["defaults","customize"]).default("customize"),autoApproveEvidence:A().default(!1)}),Vb=c({defaultChatProvider:fs.default(Fr),defaultChatModel:r().min(1).default(Ml),defaultChatModelRef:mn.nullable().optional(),subagents:Tl.optional().default(()=>Tl.parse({})),codexPermissionMode:Wh.default(Vh),codexReasoningEffort:ru.default(Kh),openPondCommandAccessMode:Ql.default(ou),defaultBranchPrefix:r().trim().max(48).default("feat/"),defaultNewProjectDirectory:r().trim().max(4096).default(""),defaultTeamId:r().trim().max(191).nullable().default(null),advancedWorkspaceControls:A().default(!1),steerActiveResponses:A().default(!0),contextCompaction:If.optional().default(()=>If.parse({})),training:_f.optional().default(()=>_f.parse({})),sidebarWidth:u().int().min(244).max(560).default(332),diffPanelWidth:u().int().min(320).max(2400).default(560),sidebarSectionsCollapsed:wf.optional().default(()=>wf.parse({})),editor:_d.optional().default(()=>_d.parse({}))}),NO="default",ax=[{id:"default",name:"Balanced",source:"built_in",description:"Clear, useful, and concise.",content:`You are OpenPond Chat, a clear and useful AI assistant.
|
|
105
|
+
Be concise, accurate, and direct.
|
|
106
|
+
Do not use emojis.
|
|
107
|
+
Ask only when missing information would materially change the answer.
|
|
108
|
+
Prioritize practical next steps.`},{id:"pragmatic",name:"Pragmatic",source:"built_in",description:"Direct, practical, and engineering-minded.",content:`You are a pragmatic AI assistant with strong engineering judgment.
|
|
109
|
+
Be direct, concrete, and outcome-focused.
|
|
110
|
+
Do not use emojis.
|
|
111
|
+
Prefer simple working solutions over clever abstractions.
|
|
112
|
+
Call out weak assumptions plainly.`},{id:"friendly",name:"Friendly",source:"built_in",description:"Warm, conversational, and approachable.",content:`You are a friendly AI assistant.
|
|
113
|
+
Use a warm, conversational tone without filler.
|
|
114
|
+
Do not use emojis.
|
|
115
|
+
Explain decisions clearly and keep the user moving.
|
|
116
|
+
Be patient when clarifying tradeoffs.`},{id:"formal",name:"Formal",source:"built_in",description:"Polished, careful, and professional.",content:`You are a formal AI assistant.
|
|
117
|
+
Use precise, professional language.
|
|
118
|
+
Do not use emojis.
|
|
119
|
+
Structure answers clearly and avoid casual phrasing.
|
|
120
|
+
State uncertainty and assumptions explicitly.`},{id:"technical",name:"Technical",source:"built_in",description:"Precise, detailed, and implementation-focused.",content:`You are a technical AI assistant.
|
|
121
|
+
Prioritize correctness, implementation detail, and edge cases.
|
|
122
|
+
Do not use emojis.
|
|
123
|
+
Use concise explanations, but include necessary specifics.
|
|
124
|
+
Surface risks, constraints, and verification steps.`}],Gh=r().trim().min(1).max(120),DO=c({id:Gh,name:r(),source:b(["built_in","custom"]).default("custom"),description:r(),content:r()}),Kb=c({activeTemplateId:Gh.default(NO),customized:A().default(!1),soul:r(),soulPath:r().nullable(),updatedAt:r().nullable(),templates:f(DO).default(()=>[...ax])}),LO=c({id:r(),host:r(),port:u(),startedAt:r(),storePath:r(),version:r(),runtimeVersion:r()}),Zh=b(["chat","work","development"]);b(["chat","models","development"]);const UO="work",We=r().trim().min(1).nullable(),Ra=ie(r(),ce()).default({}),zO=b(["direct_prompt_create","context_backed_create","create_as_agent","workflow_suggestion","local_extend","hosted_create","local_import","direct_prompt_improve","context_backed_improve","hosted_improve","lab_create","lab_improve","training"]),ox=b(["/create","/edit","openpond extend","create_as_agent","suggest_workflow","local_import","lab_create","lab_improve","training"]),HO=b(["create","improve","import","promote"]),qO=b(["planning","awaiting_questions","awaiting_plan_approval","paused","applying_source","running_checks","evaluating","awaiting_promotion","opening_pull_request","pull_request_open","reconciling_release","released","rejected","ready","ready_local","pushing_hosted","running_hosted_checks","published_hosted","blocked","failed","cancelled"]),zc=b(["always_require_plan_approval","approval_already_granted"]);b(["local_profile","hosted_profile","promote_local_to_hosted","managed_artifact"]);const BO=Rt("kind",[c({kind:S("local"),sourceAuthority:S("local_profile"),activeProfile:r().trim().min(1).nullable(),repoPath:We,sourcePath:We,localHead:We,confirmationPolicy:zc.default("always_require_plan_approval")}),c({kind:S("hosted"),sourceAuthority:S("hosted_profile"),teamId:We,projectId:We,activeProfile:r().trim().min(1).nullable(),sourceRef:We,baseSha:We,confirmationPolicy:zc.default("always_require_plan_approval")}),c({kind:S("promote_local_to_hosted"),sourceAuthority:S("promote_local_to_hosted"),teamId:We,projectId:We,activeProfile:r().trim().min(1).nullable(),repoPath:We,sourcePath:We,localHead:We,hostedHead:We,sourceRef:We,confirmationPolicy:zc.default("always_require_plan_approval")}),c({kind:S("managed_artifact"),sourceAuthority:S("managed_artifact"),activeProfile:r().trim().min(1).nullable(),confirmationPolicy:zc.default("always_require_plan_approval")})]),FO=c({id:We,kind:b(["user","system","automation"]).default("user"),label:We}),VO=c({profileId:r().trim().min(1),conversationId:We,originTurnId:We,projectId:We,targetProject:c({id:We,name:We,workspacePath:We,sourceRef:We,baseSha:We}).nullable()}),fl=c({messageIds:f(r().trim().min(1)).default([]),conversationExcerpts:f(c({messageId:We,role:r().trim().min(1).nullable(),excerpt:r().trim().min(1),reason:r().trim().min(1).nullable()})).default([]),attachments:f(c({id:We,name:r().trim().min(1),mediaType:We,ref:We})).default([]),apps:f(c({id:r().trim().min(1),name:r().trim().min(1),connectionId:We,required:A().default(!1)})).default([]),tools:f(c({name:r().trim().min(1),inputSummary:We,outputSummary:We,artifactRefs:f(r().trim().min(1)).default([]),sideEffects:f(r().trim().min(1)).default([])})).default([]),signalRefs:f(r().trim().min(1)).default([]),evalRefs:f(r().trim().min(1)).default([]),targetRepoAssumptions:f(r().trim().min(1)).default([])}),Ci={id:We,displayName:We},Jh=Rt("kind",[c({kind:S("unselected"),...Ci}),c({kind:S("agent"),...Ci,defaultActionKey:We}),c({kind:S("skill"),...Ci,skillName:We}),c({kind:S("extension"),...Ci,slot:We}),c({kind:S("model"),...Ci,trainingPlanId:We,trainingJobId:We,artifactId:We}),c({kind:S("configuration"),...Ci,key:We})]),Cf=b(["agent","skill","extension","model","configuration"]),KO=c({schemaVersion:S("openpond.createImprove.evidenceSnapshot.v1"),id:r().trim().min(1),contentHash:r().trim().min(8),consent:c({status:b(["granted","denied","revoked"]),scope:b(["metadata_only","selected_turns","full_session","direct_intent"]),reviewedBy:We,reviewedAt:r().trim().min(1)}),sources:f(c({kind:b(["signal","conversation","direct_correction","manual_intent","artifact"]),id:r().trim().min(1),sourceHash:r().trim().min(8),excerptRef:We})).min(1),reviewerIntent:r().trim().min(1),createdAt:r().trim().min(1),metadata:Ra}),rx=c({schemaVersion:S("openpond.createImprove.tasksetRef.v1"),id:r().trim().min(1),revision:u().int().positive(),contentHash:r().trim().min(8),evidenceSnapshotIds:f(r().trim().min(1)).min(1),policyBoundary:c({policyVisibleFields:f(r().trim().min(1)).default([]),privilegedFields:f(r().trim().min(1)).default([]),hiddenGraderRefs:f(r().trim().min(1)).default([]),connectedAppScopes:f(r().trim().min(1)).default([])}),targetRecommendation:c({kind:Cf,rationale:f(r().trim().min(1)).min(1),confidence:u().min(0).max(1)}),authoringSplitRefs:f(r().trim().min(1)).default([]),privateSplitRefs:f(r().trim().min(1)).default([]),approvedBy:We,approvedAt:r().trim().min(1),metadata:Ra}),WO=c({kind:b(["npm_package","runtime_tool","setup_command","secret","integration","volume","target_project","external_service"]),name:r().trim().min(1),status:b(["declared","required","blocked","satisfied"]).default("declared"),detail:We,metadata:Ra}),GO=c({mode:b(["chat","direct_action","chat_and_direct_actions"]),label:r().trim().min(1),detail:r().trim().min(1),defaultActionKey:We,directActionHint:We,artifactPolicy:r().trim().min(1)}),ZO=c({schemaVersion:S("openpond.createImprove.plan.v1"),id:r().trim().min(1),runId:r().trim().min(1),status:b(["draft","pending_approval","approved","rejected","cancelled","superseded"]).default("pending_approval"),objective:r().trim().min(1),summary:r().trim().min(1),capturedContextSummary:r().trim().min(1),defaultChatAction:c({key:We,label:We,required:A().default(!0)}),sourcePlan:f(c({path:r().trim().min(1),operation:b(["create","update","delete","inspect"]),reason:r().trim().min(1)})).default([]),requirements:f(WO).default([]),checks:f(c({name:r().trim().min(1),command:r().trim().min(1),required:A().default(!0)})).default([]),approvalId:We,approvedAt:We,editedFromPlanId:We,metadata:Ra,createdAt:r().trim().min(1),updatedAt:r().trim().min(1)}),JO=c({id:r().trim().min(1),label:r().trim().min(1),value:r().trim().min(1),description:We,metadata:Ra}),YO=c({value:r().trim().min(1),label:We,detail:We,answeredAt:r().trim().min(1),metadata:Ra}),QO=c({id:r().trim().min(1),kind:b(["single_choice","free_text"]).default("single_choice"),title:r().trim().min(1),prompt:r().trim().min(1),required:A().default(!0),status:b(["pending","answered","skipped"]).default("pending"),options:f(JO).default([]),answer:YO.nullable().default(null),metadata:Ra}),XO=c({schemaVersion:S("openpond.createImprove.workflowCapture.v1"),id:r().trim().min(1),runId:r().trim().min(1),command:ox,objective:r().trim().min(1),conversationExcerpts:fl.shape.conversationExcerpts,attachments:fl.shape.attachments,apps:fl.shape.apps,tools:fl.shape.tools,sideEffects:f(r().trim().min(1)).default([]),profileActions:f(r().trim().min(1)).default([]),externalProviders:f(r().trim().min(1)).default([]),environmentVariables:f(r().trim().min(1)).default([]),files:f(r().trim().min(1)).default([]),schedules:f(r().trim().min(1)).default([]),webhooks:f(r().trim().min(1)).default([]),channelTargets:f(r().trim().min(1)).default([]),outputArtifacts:f(r().trim().min(1)).default([]),targetRepoAssumptions:f(r().trim().min(1)).default([]),traceRefs:f(r().trim().min(1)).default([]),metadata:Ra,createdAt:r().trim().min(1)}),ix=c({provider:S("github"),number:u().int().positive(),url:r().url(),state:b(["open","merged","closed"]),baseBranch:r().trim().min(1),headBranch:r().trim().min(1),mergeCommit:We,openedAt:r().trim().min(1),updatedAt:r().trim().min(1)}),e2=c({baseBranch:r().trim().min(1),baseCommit:r().trim().min(1),branch:r().trim().min(1),headCommit:We,remoteName:r().trim().min(1).default("origin"),remoteUrl:We,worktreePath:We,changedPaths:f(r().trim().min(1)).default([]),diffStat:We,pullRequest:ix.nullable().default(null)}),t2=c({id:r().trim().min(1),target:Jh,status:b(["draft","authored","checking","evaluated","accepted","rejected","failed"]),git:e2.nullable().default(null),parentCandidateId:We.default(null),tasksetRef:rx.nullable().default(null),authoringModelRef:We.default(null),allowedPaths:f(r().trim().min(1)).default([]),sourceRefs:f(r().trim().min(1)).default([]),artifactRefs:f(r().trim().min(1)).default([]),checkRefs:f(r().trim().min(1)).default([]),evaluationReceiptRefs:f(r().trim().min(1)).default([]),createdAt:r().trim().min(1),updatedAt:r().trim().min(1),metadata:Ra}),n2=c({id:r().trim().min(1),candidateId:We,target:Jh,evaluatorKind:b(["agent_sdk","taskset","extension","skill","configuration","checks"]).default("checks"),subject:b(["active","candidate","post_release","standalone"]).default("standalone"),sourceCommit:We.default(null),sourceBranch:We.default(null),tasksetId:We.default(null),tasksetHash:We.default(null),taskAttemptRefs:f(r().trim().min(1)).default([]),status:b(["pending","passed","failed","blocked"]),publishGate:b(["passed","failed","not_applicable"]).default("not_applicable"),summaryCounts:c({total:u().int().nonnegative(),passed:u().int().nonnegative(),failed:u().int().nonnegative()}).nullable().default(null),evalRefs:f(r().trim().min(1)).default([]),artifactRefs:f(r().trim().min(1)).default([]),summary:We,createdAt:r().trim().min(1),metadata:Ra}),a2=c({mode:b(["foreground","background"]).default("background"),pauseAllowed:A().default(!0),cancellationAllowed:A().default(!0)}),o2=c({mode:b(["single","bounded","until_evals_pass"]).default("single"),maximumAttempts:u().int().min(1).max(20).default(1),currentAttempt:u().int().min(0).max(20).default(0)}),r2=c({kind:b(["candidate_authoring","local_apply","hosted_turn","training_job","evaluation","pull_request","release"]),id:r().trim().min(1),status:We,metadata:Ra}),i2=c({status:b(["not_requested","pending","released","rejected","rolled_back"]),profileCommit:We,profileTag:We,releaseReceiptRef:We,pullRequest:ix.nullable().default(null),updatedAt:We}),ec=c({schemaVersion:S("openpond.createImprove.run.v1"),id:r().trim().min(1),revision:u().int().nonnegative(),operation:HO,surface:zO,command:ox,objective:r().trim().min(1),state:qO,adapter:BO,actor:FO,scope:VO,context:fl,target:Jh,evidenceSnapshots:f(KO).default([]),tasksetRef:rx.nullable().default(null),targetSelection:c({status:b(["open","recommended","confirmed"]),preselectedKind:Cf.nullable(),confirmedKind:Cf.nullable()}).nullable().default(null),plan:ZO.nullable(),workflowCapture:XO.nullable(),executionPolicy:a2.default({mode:"background",pauseAllowed:!0,cancellationAllowed:!0}),iterationPolicy:o2.default({mode:"single",maximumAttempts:1,currentAttempt:0}),approvalIds:f(r().trim().min(1)).default([]),questionIds:f(r().trim().min(1)).default([]),questions:f(QO).default([]),candidates:f(t2).default([]),evaluationReceipts:f(n2).default([]),checkRefs:f(r().trim().min(1)).default([]),sourceRefs:f(r().trim().min(1)).default([]),externalExecutionRefs:f(r2).default([]),localProfileCommit:We,hostedSourceCommit:We,hostedSourceRef:We,releaseOutcome:i2.default({status:"not_requested",profileCommit:null,profileTag:null,releaseReceiptRef:null,pullRequest:null,updatedAt:null}),blockedReason:We,appliedActionIds:f(r().trim().min(1)).max(200).default([]),metadata:Ra,createdAt:r().trim().min(1),updatedAt:r().trim().min(1)}),ao={runId:r().trim().min(1),expectedRevision:u().int().nonnegative(),actionId:r().trim().min(1)};Rt("type",[c({...ao,type:S("answer_question"),questionId:r().trim().min(1),value:r().trim().min(1)}),c({...ao,type:S("approve_plan")}),c({...ao,type:S("revise_plan"),revision:r().trim().min(1)}),c({...ao,type:S("cancel"),reason:We.optional().default(null)}),c({...ao,type:S("pause")}),c({...ao,type:S("resume")}),c({...ao,type:S("open_pull_request"),candidateId:r().trim().min(1)}),c({...ao,type:S("apply_candidate"),candidateId:r().trim().min(1)}),c({...ao,type:S("reject_candidate"),candidateId:r().trim().min(1),reason:We.optional().default(null)}),c({...ao,type:S("reconcile_pull_request"),candidateId:r().trim().min(1)})]);c({schemaVersion:S("openpond.createImprove.runList.v1"),runs:f(ec),generatedAt:r().trim().min(1)});function cY(e){const t=GO.safeParse(e?.actionShape);return t.success?t.data:null}const hr=c({source:b(["local","github","openpond_git"]),repositoryId:r().trim().min(1),profileId:r().trim().min(1)}),s2=c({ref:hr,revision:r().nullable(),sourceHash:r()}),hs=ie(r(),ce()).default({}),Sa=u().int().nonnegative(),iu=r().trim().min(1).max(1e5),sx=c({kind:b(["personal","team"]),id:E}).strict(),l2=c({name:E,release:ee.nullable(),revision:Sa}).strict();c({schemaVersion:S("openpond.harnessWorkspace.v1"),id:E,ownerScope:sx,name:r().trim().min(1).max(240),location:b(["local","hosted"]),sourceRevision:r().trim().min(1).max(500),revision:Sa,dirty:A(),currentChannel:l2,createdAt:Pe,updatedAt:Pe,metadata:hs}).strict();const ts=b(["runtime","memory","prompt","skill","agent","product","taskset","training"]),lx=b(["text_instruction","memory","dependency_selection","executable_code","business_logic","financial_logic","permission","connected_app","publication","deployment","training","model_binding","team_or_global"]),cx=c({id:E,route:ts,operation:b(["create","update","delete"]),target:r().trim().min(1).max(2e3),summary:r().trim().min(1).max(2e3),content:r().max(1e6).nullable(),contentHash:Y.nullable(),effects:f(lx).min(1).max(20)}).strict().superRefine((e,t)=>{if(e.operation==="delete"){(e.content!==null||e.contentHash!==null)&&t.addIssue({code:"custom",message:"delete edits cannot include replacement content",path:["content"]});return}if(e.content===null||e.contentHash===null){t.addIssue({code:"custom",message:"create and update edits require content and contentHash",path:["content"]});return}const n=rn(e.content);e.contentHash!==n&&t.addIssue({code:"custom",message:`edit contentHash is ${e.contentHash}; expected ${n}`,path:["contentHash"]})}),dx=c({workspaceId:E,revision:Sa,sourceRevision:r().trim().min(1).max(500),channelRevision:Sa}).strict(),Do=c({id:E,revision:Sa,contentHash:Y}).strict(),c2=c({schemaVersion:S("openpond.harnessTurnSnapshot.v1"),workspaceId:E,workspaceRevision:Sa,sourceRevision:r().trim().min(1).max(500),channelName:E,channelRevision:Sa,harnessRelease:ee,toolCatalogHash:Y.nullable().optional(),overlay:Do.nullable().optional().default(null)}).strict(),d2=c({schemaVersion:S("openpond.harnessRunOverlay.v1"),id:E,runId:E,baseHarnessRelease:ee,workspace:dx,revision:Sa,status:b(["active","frozen","abandoned"]),edits:f(cx).max(1e3),createdAt:Pe,updatedAt:Pe,metadata:hs}).strict();d2.extend({contentHash:Y}).strict();const ux=c({kind:b(["tool_event","recovery","validation","user_turn","work_output","work_receipt"]),id:E,contentHash:Y.nullable()}).strict(),mx=c({id:E,kind:b(["dependency","schema","package","file_render","skill","prompt","business_formula","targeted_evaluation","observed_recovery","memory","component_activation"]),description:iu,required:A()}).strict(),u2=c({schemaVersion:S("openpond.harnessImprovementProposal.v1"),id:E,overlay:Do,baseHarnessRelease:ee,expectedWorkspace:dx,requestedScope:b(["personal","team","global"]),route:ts,risk:b(["low","review","restricted"]),effects:f(lx).min(1).max(20),evidence:f(ux).min(1).max(1e3),edits:f(cx).min(1).max(1e3),validationPlan:f(mx).min(1).max(100),expectedOutcome:iu,createdAt:Pe,metadata:hs}).strict().superRefine((e,t)=>{const n=new Set(e.effects);for(const[a,o]of e.edits.entries()){o.route!==e.route&&t.addIssue({code:"custom",message:"every edit route must match the proposal route",path:["edits",a,"route"]});for(const i of o.effects)n.has(i)||t.addIssue({code:"custom",message:`edit effect ${i} is missing from proposal effects`,path:["edits",a,"effects"]})}new Set(e.validationPlan.map(a=>a.id)).size!==e.validationPlan.length&&t.addIssue({code:"custom",message:"validation plan ids must be unique",path:["validationPlan"]})});u2.extend({contentHash:Y}).strict();const m2=c({schemaVersion:S("openpond.harnessTargetedValidationReceipt.v1"),id:E,proposal:ee,validationId:E,kind:mx.shape.kind,status:b(["passed","failed","blocked","skipped"]),summary:iu,evidenceRefs:f(ux).max(1e3),createdAt:Pe,metadata:hs}).strict();m2.extend({contentHash:Y}).strict();const p2=b(["advanced","retained","conflict","rolled_back"]),f2=c({schemaVersion:S("openpond.harnessAdvanceReceipt.v1"),id:E,workspaceId:E,ownerScope:sx,proposal:ee.nullable(),expectedWorkspaceRevision:Sa,observedWorkspaceRevision:Sa,previousChannelRevision:Sa,nextChannelRevision:Sa,previousRelease:ee.nullable(),nextRelease:ee.nullable(),validationReceipts:f(ee).max(100),decision:p2,reason:iu,rollbackOf:ee.nullable(),createdAt:Pe,metadata:hs}).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"]})});f2.extend({contentHash:Y}).strict();const h2=c({schemaVersion:S("openpond.harnessOverlayMergeReceipt.v1"),id:E,workspaceId:E,baseHarnessRelease:ee,leftOverlay:Do,rightOverlay:Do,decision:b(["merged","conflict"]),mergedOverlay:Do.nullable(),conflictTargets:f(r().trim().min(1).max(2e3)).max(1e3),requiresRevalidation:S(!0),createdAt:Pe,metadata:hs}).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"]})});h2.extend({contentHash:Y}).strict();const Lo=r().trim().min(1).max(1e5),g2=b(["no_action","harness_maintenance","runtime","product","taskset","model_improvement"]),v2=b(["none","runtime_service","product_team","human_review","evaluation_system","training_system"]),px=b(["observation","trigger","route_decision","refiner_outcome","proposal","validation","apply_receipt","harness_advance","rollback","work_outcome","taskset","evaluation","training_qualification","model_candidate"]),Yh=c({kind:b(["personal","team"]),id:E}).strict(),fx=c({policy:ee,state:b(["authorized","revoked","deleted","expired"]),checkedAt:Pe}).strict(),jl=c({evidence:ee,kind:px,sourceRef:E,sourcePolicy:fx,occurrenceKey:Y,occurredAt:Pe}).strict(),b2=c({evidence:ee,sourcePolicy:fx.nullable(),reason:b(["outside_scope","before_watermark","duplicate","resolved","revoked","deleted","expired","sensitive","unverified","budget"])}).strict(),Wb=c({cursor:Y,throughCreatedAt:Pe}).strict(),y2=c({fingerprint:Y,recurrenceFamily:r().trim().min(1).max(1e3),statement:Lo,candidateDisposition:b(["observe","confirm"]).optional(),independentOccurrences:u().int().positive().max(1e6),unresolvedOccurrences:u().int().positive().max(1e6)}).strict().refine(e=>e.unresolvedOccurrences<=e.independentOccurrences,"unresolved occurrences cannot exceed independent occurrences"),hx=b(["harness","runtime","product","retrieval","tools","evaluation","model"]),S2=c({layer:hx,status:b(["not_applicable","unresolved","resolved","blocked"]),reason:Lo,evidenceRefs:f(ee).max(1e3)}).strict(),k2=c({schemaVersion:S("openpond.harnessEvaluationReviewReceipt.v1"),id:E,ownerScope:Yh,workspaceRef:E,harnessRelease:ee,previousWatermark:Wb.nullable(),nextWatermark:Wb,selectedEvidence:f(jl).max(1e4),excludedEvidence:f(b2).max(1e4),claim:y2.nullable(),classification:g2,triage:f(S2).max(16),reason:Lo,nextAuthority:v2,maxEstimatedCostUsd:u().finite().nonnegative(),tasksetProposal:ee.nullable(),evaluation:ee.nullable(),trainingQualification:ee.nullable(),policyVersion:E,createdAt:Pe,metadata:Cn}).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"})});k2.extend({contentHash:Y}).strict();c({id:E,evidence:ee,kind:px,sourceRef:E,occurredAt:Pe,payload:ie(r(),ce())}).strict();const x2=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("no_action"),reason:Lo,ignoredEvidence:f(c({id:E,reason:r().trim().min(1).max(2e3)}).strict()).max(1e3)}).strict(),w2=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("review"),classification:b(["harness_maintenance","runtime","product","taskset"]),selectedEvidenceIds:f(E).min(1).max(1e3),ignoredEvidence:f(c({id:E,reason:r().trim().min(1).max(2e3)}).strict()).max(1e3),recurrenceFamily:r().trim().min(1).max(1e3),statement:Lo,triageLayer:hx,expectedOutcome:Lo,counterevidence:r().trim().max(1e4),confidence:u().min(0).max(1),candidateDisposition:b(["observe","confirm"]).nullable(),reason:Lo}).strict().superRefine((e,t)=>{e.classification==="harness_maintenance"!==(e.candidateDisposition!==null)&&t.addIssue({code:"custom",message:"Harness maintenance requires a candidate disposition; external routes require null",path:["candidateDisposition"]})}),I2=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("resolve_candidate"),candidateId:E,candidateFingerprint:Y,selectedEvidenceIds:f(E).min(1).max(1e3),ignoredEvidence:f(c({id:E,reason:r().trim().min(1).max(2e3)}).strict()).max(1e3),confidence:u().min(0).max(1),reason:Lo}).strict();Rt("decision",[x2,w2,I2]);c({schemaVersion:S("openpond.harnessEvaluationReviewNavigationDecision.v1"),selectedEvidenceIds:f(E).min(1).max(50),reason:Lo}).strict();const tc=c({name:r().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:r().trim().min(1).max(2e3),inputSchema:ie(r(),ce()),inputSchemaHash:Y,sideEffect:b(["read","write"]),timeoutMs:u().int().positive().max(36e5)}).strict(),Qh=c({id:E,required:A(),scopes:f(r().trim().min(1).max(500)).max(100).default([]),portability:b(["portable","host_adapter","local_only","hosted_only"])}).strict(),_2=c({portable:A(),blockers:f(r().trim().min(1).max(2e3)).max(1e3),localOnlyAssetRefs:f(E).max(1e4),hostPrivateAssetRefs:f(E).max(1e4)}).strict(),C2=c({schemaVersion:S("openpond.agentSnapshot.v2"),id:E,sourceRelease:ee.nullable(),instructions:f(dn).max(1e4),skills:f(dn).max(1e4),agents:f(dn).max(1e4),toolDeclarations:f(tc).max(200),capabilityRequirements:f(Qh).max(200),dependencyLock:dn,portability:_2,metadata:Cn}).strict(),R2=C2.extend({contentHash:Y}).strict(),gx=c({create:S(!0),reset:S(!0),step:S(!0),collect:S(!0),destroy:S(!0),resetScope:b(["task","attempt"])}).strict(),vx=c({visibleEvidence:f(E).max(1e3),privilegedEvidence:f(E).max(1e3),privateVerifierIsolation:A()}).strict(),P2=c({schemaVersion:S("openpond.harnessRelease.v2"),id:E,agentSnapshot:ee,program:dn,tools:f(tc).max(200),lifecycle:gx,graderInterface:vx,files:f(dn).max(1e5),metadata:Cn}).strict(),A2=P2.extend({contentHash:Y}).strict(),T2=c({id:E,turn:u().int().nonnegative(),kind:b(["message","tool_call","terminal"]),name:E.nullable(),arguments:ie(r(),ce()),content:r().max(1e6).nullable()}).strict(),E2=c({actionId:E,turn:u().int().nonnegative(),terminal:A(),output:ie(r(),ce()),artifactRefs:f(za).max(1e5)}).strict(),M2=c({sequence:u().int().nonnegative(),type:b(["created","reset","action","observation","terminal","failure","collected","destroyed"]),payloadHash:Y,metadata:Cn}).strict();c({schemaVersion:S("openpond.harnessTrace.v1"),manifest:ee,taskId:E,seed:r().trim().min(1).max(500),events:f(M2).max(1e6),actions:f(T2).max(1e5),observations:f(E2).max(1e5),terminal:A(),failureClass:Zl.nullable(),output:ie(r(),ce()),contentHash:Y}).strict();const su=r().trim().min(1).max(1e5),nc=ie(r(),ce()).default({}),j2=b(["completed_tool_batch","before_model_step","turn_completed","turn_paused"]),bx=c({kind:j2,eventSequence:u().int().nonnegative(),occurredAt:Pe}).strict(),yx=c({id:E,sequence:u().int().nonnegative().nullable(),contentHash:Y}).strict(),O2=b(["tool_failure","retry","recovery","validation","user_turn","reusable_success","completion_detour"]),$2=b(["open","recovered","terminal"]),N2=c({name:r().trim().min(1).max(500),invocationKey:Y}).strict(),D2=c({schemaVersion:S("openpond.improvementObservation.v1"),id:E,runRef:E,turnId:E,harnessRelease:ee,overlay:Do.nullable(),eventRefs:f(yx).min(1).max(100),kind:O2,state:$2,tool:N2.nullable(),deterministicClass:r().trim().min(1).max(500).nullable(),summary:su,createdAt:Pe,metadata:nc}).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"]})});D2.extend({contentHash:Y}).strict();const L2=c({schemaVersion:S("openpond.refinementTriggerPolicy.v1"),maxEstimatedCostUsd:u().finite().nonnegative(),cooldownMs:u().int().nonnegative(),maxPendingPlans:u().int().min(1).max(100),maxEvidenceEvents:u().int().min(1).max(1e3),maxProposalEdits:u().int().min(1).max(1e3),maxProposalBytes:u().int().min(1).max(1e7)}).strict(),U2=b(["no_action","route_deterministically","queue_refiner"]),z2=c({schemaVersion:S("openpond.refinementTriggerDecision.v1"),id:E,runRef:E,turnId:E,harnessRelease:ee,overlay:Do.nullable(),observations:f(ee).max(100),decision:U2,deterministicRoute:ts.nullable(),suggestedRoutes:f(ts).max(8),reason:su,deduplicationKey:Y,policy:L2,estimatedMaxCostUsd:u().finite().nonnegative(),pendingPlanCount:u().int().nonnegative(),boundary:bx,cooldownUntil:Pe.nullable(),createdAt:Pe,metadata:nc}).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"]})});z2.extend({contentHash:Y}).strict();const H2=b(["runtime_service","refiner_model","human_review","evaluation_system","training_system"]),q2=c({schemaVersion:S("openpond.improvementRouteDecision.v1"),id:E,trigger:ee,route:ts,authority:H2,automatic:A(),reason:su,createdAt:Pe,metadata:nc}).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"]})});q2.extend({contentHash:Y}).strict();const B2=c({schemaVersion:S("openpond.harnessRefinerOutcome.v1"),id:E,trigger:ee,decision:b(["no_action","proposed"]),proposal:ee.nullable(),reason:su,evidenceRefs:f(ee).max(100),estimatedCostUsd:u().finite().nonnegative(),createdAt:Pe,metadata:nc}).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"]})});B2.extend({contentHash:Y}).strict();const F2=b(["applied","retained","declined","conflict","rolled_back"]),V2=c({schemaVersion:S("openpond.improvementApplyReceipt.v1"),id:E,proposal:ee,beforeOverlay:Do,afterOverlay:Do.nullable(),decision:F2,boundary:bx,validationRefs:f(ee).max(100),outcomeEvidenceRefs:f(yx).max(1e3),rollbackOf:ee.nullable(),createdAt:Pe,metadata:nc}).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"]})});V2.extend({contentHash:Y}).strict();const K2=b(["memory","prompt","skill","agent"]),W2=b(["runtime","product","taskset","training"]),G2=c({id:r().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),text:r().trim().min(1).max(1e4)}).strict(),Sx=c({schemaVersion:S("openpond.refinerReviewProfile.v1"),id:r().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),version:r().trim().min(1).max(120),name:r().trim().min(1).max(200),objective:r().trim().min(1).max(1e4),instructions:f(G2).max(100),allowedProposalRoutes:f(K2).max(4),allowedExternalRoutes:f(W2).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"]})}),Gb=c({schemaVersion:S("openpond.refinerRelease.v1"),id:r().trim().min(1).max(240),coreVersion:r().trim().min(1).max(120),coreHash:Y,profile:Sx,profileHash:Y,composedPromptHash:Y,createdAt:Pe,contentHash:Y}).strict(),Z2=c({schemaVersion:S("openpond.refinerBinding.v1"),channel:S("active"),revision:u().int().nonnegative(),release:ee,updatedAt:Pe}).strict(),J2=c({schemaVersion:S("openpond.refinerTransitionReceipt.v1"),id:r().trim().min(1).max(240),operation:b(["initialize","update","activate","rollback"]),bindingChanged:A(),previousRelease:ee.nullable(),nextRelease:ee,actor:r().trim().min(1).max(240),reason:r().trim().min(1).max(1e4),authoringSkillHash:Y.nullable(),validation:c({valid:A(),messages:f(r().max(2e3)).max(100)}).strict(),createdAt:Pe,contentHash:Y}).strict(),Y2=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v1"),decision:S("no_action"),reason:r().trim().min(1).max(1e4)}).strip(),Q2=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v1"),decision:S("route"),route:b(["runtime","product","taskset","training"]),summary:r().trim().min(1).max(2e3),expectedOutcome:r().trim().min(1).max(1e4),reason:r().trim().min(1).max(1e4)}).strip(),X2=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v1"),decision:S("propose"),route:b(["memory","prompt","skill","agent"]),operation:b(["create","update","delete"]),target:r().trim().min(1).max(2e3),summary:r().trim().min(1).max(2e3),createContent:r().min(1).max(2e4).nullable(),find:r().min(1).max(8e3).nullable(),replace:r().max(8e3).nullable(),expectedOutcome:r().trim().min(1).max(1e4),reason:r().trim().min(1).max(1e4)}).strip().superRefine((e,t)=>{e.operation==="create"&&(e.createContent===null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"create proposals require createContent and null find/replace",path:["createContent"]}),e.operation==="update"&&(e.createContent!==null||e.find===null||e.replace===null)&&t.addIssue({code:"custom",message:"update proposals require one exact find/replace edit and null createContent",path:["find"]}),e.operation==="delete"&&(e.createContent!==null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"delete proposals require null createContent/find/replace",path:["createContent"]})}),e$=Rt("decision",[Y2,Q2,X2]),t$=e$,Xh=c({kind:b(["single_deterministic","recurrent_independent"]),supportingEvidenceIds:f(r().trim().min(1).max(2e3)).min(1).max(100),counterevidence:f(r().trim().min(1).max(2e3)).max(20)}).strict().superRefine((e,t)=>{new Set(e.supportingEvidenceIds).size!==e.supportingEvidenceIds.length&&t.addIssue({code:"custom",message:"supporting evidence IDs must be unique",path:["supportingEvidenceIds"]}),e.kind==="recurrent_independent"&&e.supportingEvidenceIds.length<2&&t.addIssue({code:"custom",message:"recurrent independent evidence requires at least two supplied incidents",path:["supportingEvidenceIds"]})}),n$=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("no_action"),reason:r().trim().min(1).max(1e4)}).strict(),a$=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("route"),route:b(["runtime","product","taskset","training"]),summary:r().trim().min(1).max(2e3),evidenceBasis:Xh,expectedOutcome:r().trim().min(1).max(1e4),reason:r().trim().min(1).max(1e4)}).strict(),o$=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("propose"),route:b(["memory","prompt","skill","agent"]),operation:b(["create","update","delete"]),target:r().trim().min(1).max(2e3),summary:r().trim().min(1).max(2e3),evidenceBasis:Xh,createContent:r().min(1).max(2e4).nullable(),find:r().min(1).max(8e3).nullable(),replace:r().max(8e3).nullable(),expectedOutcome:r().trim().min(1).max(1e4),reason:r().trim().min(1).max(1e4)}).strict().superRefine((e,t)=>{e.operation==="create"&&(e.createContent===null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"create proposals require createContent and null find/replace",path:["createContent"]}),e.operation==="update"&&(e.createContent!==null||e.find===null||e.replace===null)&&t.addIssue({code:"custom",message:"update proposals require one exact find/replace edit and null createContent",path:["find"]}),e.operation==="delete"&&(e.createContent!==null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"delete proposals require null createContent/find/replace",path:["createContent"]})}),kx=Rt("decision",[n$,a$,o$]);Dt([t$,kx]);const eg=c({memory:A(),prompt:A(),skill:A(),agent:A()}).strict(),xx=b(["memory","instruction","skill","agent"]),Zb=c({path:r().trim().min(1).max(2e3),kind:xx,content:r().max(6e4),loaded:A()}).strict(),Jb=c({path:r().trim().min(1).max(2e3),kind:xx,loaded:A()}).strict(),r$=c({capabilities:eg,trigger:ie(r(),ce()),observations:f(ie(r(),ce())).max(20),admissibleEvidenceIds:f(r().trim().min(1).max(2e3)).max(1e4),reviewPacket:c({currentTurn:c({id:r().trim().min(1).max(2e3),status:r().trim().min(1).max(100).nullable(),error:r().max(2100).nullable(),prompt:r().max(8100).nullable(),assistantOutput:r().max(8100).nullable(),assistantOutputLinkCount:u().int().nonnegative()}).strict(),priorConversation:f(c({turnId:r().trim().min(1).max(2e3),status:r().trim().min(1).max(100).nullable(),prompt:r().max(3100).nullable(),assistantOutput:r().max(3100).nullable()}).strict()).max(3),timeline:f(ie(r(),ce())).max(60),artifacts:f(ie(r(),ce())).max(30),artifactDiagnostics:f(ie(r(),ce())).max(20),executionProfile:c({modelRequestCount:u().int().nonnegative(),failedModelRequestCount:u().int().nonnegative(),promptTokens:u().int().nonnegative(),completionTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative(),toolFailureCount:u().int().nonnegative(),retryCount:u().int().nonnegative(),recoveryCount:u().int().nonnegative()}).strict(),priorIncidents:f(ie(r(),ce())).max(3),truncation:c({timelineEventCount:u().int().nonnegative(),includedTimelineEventCount:u().int().nonnegative(),timelineTruncated:A()}).strict()}).strict(),runtimeActivation:c({admittedRelease:ee,currentRelease:ee,rebasedOntoCurrent:A(),admittedSourceFiles:f(Zb).max(100),admittedSourceCatalog:f(Jb).max(1e3)}).strict(),sourceFiles:f(Zb).max(100),sourceCatalog:f(Jb).max(1e3),additionalEvidence:ce().nullable().optional()}).strict(),i$=c({id:r().trim().min(1).max(240),revision:u().int().nonnegative(),contentHash:Y}).strict();c({schemaVersion:S("openpond.hostedHarnessRefinerRequest.v2"),requestId:r().trim().min(1).max(240),idempotencyKey:r().trim().min(1).max(240),evidenceHash:Y,harness:c({admittedRelease:ee,currentRelease:ee,overlay:i$,workspace:c({id:r().trim().min(1).max(240),revision:u().int().nonnegative(),sourceRevision:Y,channelRevision:u().int().nonnegative()}).strict(),capabilities:eg}).strict(),evidence:r$}).strict();const s$=c({promptTokens:u().int().nonnegative(),completionTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative()}).strict();c({schemaVersion:S("openpond.hostedHarnessRefinerResponse.v2"),requestId:r().trim().min(1).max(240),evidenceHash:Y,admittedRelease:ee,currentRelease:ee,decision:kx,serviceRevision:r().trim().min(1).max(240),usage:s$}).strict();const l$=r().trim().min(1).max(2e3),tg=r().trim().min(1).max(1e5),c$=b(["create","update","delete"]),d$=b(["memory","prompt","skill","agent"]),u$=b(["runtime","product","taskset","training"]),m$=b(["no_action","routed","applied","retained","failed"]),p$=b(["not_applicable","pending","passed","rejected","failed"]),f$=b(["not_applicable","pending","passed","failed"]),h$=c({schemaVersion:S("openpond.harnessRefinerActivityReceipt.v1"),id:E,runRef:E,turnId:E,result:m$,decision:b(["no_action","route","propose"]).nullable(),route:ts.nullable(),operation:c$.nullable(),target:r().trim().min(1).max(2e3).nullable(),summary:l$,evidenceBasis:Xh.nullable(),critiqueStatus:p$,validationStatus:f$,trigger:ee,outcome:ee.nullable(),proposal:ee.nullable(),applyReceipt:ee.nullable(),inputHarness:ee,outputHarness:ee.nullable(),createdAt:Pe}).strict().superRefine((e,t)=>{const n=e.result==="applied"||e.result==="retained";e.result==="no_action"?Yb(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"||!u$.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"}),Yb(t,e,{critiqueStatus:"not_applicable",validationStatus:"not_applicable"})):n?((e.decision!=="propose"||!d$.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"]})});h$.extend({contentHash:Y}).strict();const g$=b(["unresolved","confirmed","resolved","rejected","expired"]),v$=c({kind:b(["applied_change","later_success","manual_rejection","source_revoked","expired"]),reason:tg,evidenceRefs:f(ee).max(1e3),resolvedAt:Pe}).strict(),b$=c({schemaVersion:S("openpond.harnessRefinementCandidate.v1"),id:E,ownerScope:Yh,workspaceRef:E,fingerprint:Y,recurrenceFamily:r().trim().min(1).max(1e3),statement:tg,status:g$,occurrences:f(jl).max(1e3),counterevidence:f(jl).max(1e3),sourceReviews:f(ee).min(1).max(100),relatedHarnessReleases:f(ee).max(100),firstSeenAt:Pe,lastSeenAt:Pe,lastReviewedAt:Pe,expiresAt:Pe,resolution:v$.nullable(),createdAt:Pe,updatedAt:Pe}).strict().superRefine((e,t)=>{$r(t,e.occurrences,"occurrences"),$r(t,e.counterevidence,"counterevidence"),$r(t,e.sourceReviews,"sourceReviews"),$r(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"]}),w$(t,e)});b$.extend({contentHash:Y}).strict();const y$=b(["created","merged","rejected","expired","reopened","resolved"]),S$=c({schemaVersion:S("openpond.harnessRefinementCandidateLifecycleReceipt.v1"),id:E,candidateId:E,decision:y$,beforeCandidate:ee.nullable(),afterCandidate:ee,review:ee,addedEvidence:f(jl).max(1e3),removedEvidence:f(ee).max(1e3),reason:tg,createdAt:Pe}).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"]}),$r(t,e.addedEvidence,"addedEvidence"),$r(t,e.removedEvidence,"removedEvidence");const n=new Set(e.removedEvidence.map(a=>Rf(a)));e.addedEvidence.some(a=>n.has(Rf(a.evidence)))&&t.addIssue({code:"custom",message:"candidate lifecycle evidence cannot be added and removed together",path:["removedEvidence"]})});S$.extend({contentHash:Y}).strict();const k$=c({schemaVersion:S("openpond.harnessCrossRunRefinementRequest.v1"),id:E,ownerScope:Yh,workspaceRef:E,candidate:ee,candidateFingerprint:Y,review:ee,admittedHarness:ee,evidence:f(jl).min(1).max(1e3),capabilities:eg,deduplicationKey:Y,createdAt:Pe}).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"]}),$r(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=x$(e);e.deduplicationKey!==n&&t.addIssue({code:"custom",message:`cross-run refinement deduplicationKey is ${e.deduplicationKey}; expected ${n}`,path:["deduplicationKey"]})});k$.extend({contentHash:Y}).strict();function x$(e){return rn({schemaVersion:"openpond.harnessCrossRunRefinementIdentity.v1",workspaceRef:e.workspaceRef,candidateFingerprint:e.candidateFingerprint,admittedHarness:e.admittedHarness})}function Yb(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 $r(e,t,n){const a=t.map(o=>Rf(o));new Set(a).size!==a.length&&e.addIssue({code:"custom",message:`${n} references must be unique`,path:[n]})}function Rf(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 w$(e,t){const n=[["firstSeenAt",t.firstSeenAt],["lastSeenAt",t.lastSeenAt],["lastReviewedAt",t.lastReviewedAt],["updatedAt",t.updatedAt],["expiresAt",t.expiresAt]];for(let a=1;a<n.length;a+=1){const o=n[a-1],i=n[a];Date.parse(o[1])<=Date.parse(i[1])||e.addIssue({code:"custom",message:`${i[0]} must not precede ${o[0]}`,path:[i[0]]})}Date.parse(t.createdAt)>Date.parse(t.updatedAt)&&e.addIssue({code:"custom",message:"updatedAt must not precede createdAt",path:["updatedAt"]})}const I$=25*1024*1024,_$=c({path:dn.shape.path,base64:r().max(Math.ceil(I$/3)*4)}).strict(),wx=c({schemaVersion:S("openpond.harnessSourcePackage.v1"),agentSnapshot:R2,harnessRelease:A2,files:f(_$).max(1e4)}).strict();wx.extend({contentHash:Y}).strict();wx.extend({schemaVersion:S("openpond.harnessPolicySourcePackage.v1"),contentHash:Y}).strict();c({schemaVersion:S("openpond.harnessSourceSelection.v1"),mode:b(["taskset_owned","selected_release"]),harnessRelease:ee,sourcePackageHash:Y.nullable()}).strict().superRefine((e,t)=>{e.mode==="selected_release"!=(e.sourcePackageHash!==null)&&t.addIssue({code:"custom",path:["sourcePackageHash"],message:"Only a selected release binds a source package."})});c({path:r().min(1).max(2e3),offset:u().int().nonnegative().default(0),length:u().int().positive().max(65536).default(16384)}).strict();const Ix=r().regex(/^[a-z][a-z0-9_-]{0,119}$/),_x=r().min(1).max(2e3).refine(e=>!e.includes("\\")&&!e.includes(":")&&!e.startsWith("/")&&e.split("/").every(t=>t!==""&&t!=="."&&t!==".."),"workflow references require portable relative paths"),C$=c({id:Ix,label:r().trim().min(1).max(240),description:r().max(4e3),inputSchema:ie(r(),ce()),invocation:Rt("kind",[c({kind:S("instructions"),instructions:r().min(1).max(1e5).refine(e=>!!e.trim())}).strict(),c({kind:S("agent_action"),actionId:r().trim().min(1).max(240)}).strict()]),skillPaths:f(_x).max(100)}).strict();c({schemaVersion:S("openpond.profileWorkflows.v1"),workflows:f(C$).max(1e3)}).strict();const R$=c({id:r().trim().min(1).max(240),agentId:r().regex(/^[a-zA-Z0-9_-]{1,240}$/),sourceActionId:r().trim().min(1).max(240),inputSchema:ie(r(),ce())}).strict();c({schemaVersion:S("openpond.profileWorkflowActions.v1"),actions:f(R$).max(200)}).strict();const P$=c({schemaVersion:S("openpond.profileWorkflowBinding.v1"),profileId:r().trim().min(1).max(240),sourceRevision:r().trim().min(1).max(240),harnessRelease:ee,catalogHash:Y,workflowId:Ix}).strict(),A$=c({schemaVersion:S("openpond.profileComponentBinding.v1"),profileId:r().trim().min(1).max(240),sourceRevision:r().trim().min(1).max(240),harnessRelease:ee,target:Rt("kind",[c({kind:S("profile")}).strict(),c({kind:S("skill"),skillPath:_x}).strict(),c({kind:S("agent_action"),actionId:r().trim().min(1).max(240)}).strict()])}).strict(),ng=Symbol.for("yaml.alias"),T$=Symbol.for("yaml.document"),Hr=Symbol.for("yaml.map"),Cx=Symbol.for("yaml.pair"),ag=Symbol.for("yaml.scalar"),ac=Symbol.for("yaml.seq"),bo=Symbol.for("yaml.node.type"),gs=e=>!!e&&typeof e=="object"&&e[bo]===ng,lu=e=>!!e&&typeof e=="object"&&e[bo]===T$,Rx=e=>!!e&&typeof e=="object"&&e[bo]===Hr,En=e=>!!e&&typeof e=="object"&&e[bo]===Cx,kn=e=>!!e&&typeof e=="object"&&e[bo]===ag,og=e=>!!e&&typeof e=="object"&&e[bo]===ac;function ca(e){if(e&&typeof e=="object")switch(e[bo]){case Hr:case ac:return!0}return!1}function Nn(e){if(e&&typeof e=="object")switch(e[bo]){case ng:case Hr:case ag:case ac:return!0}return!1}const Px=e=>(kn(e)||ca(e))&&!!e.anchor,Er=Symbol("break visit"),E$=Symbol("skip children"),kl=Symbol("remove node");function cu(e,t){const n=M$(t);lu(e)?Ni(null,e.contents,n,Object.freeze([e]))===kl&&(e.contents=null):Ni(null,e,n,Object.freeze([]))}cu.BREAK=Er;cu.SKIP=E$;cu.REMOVE=kl;function Ni(e,t,n,a){const o=j$(e,t,n,a);if(Nn(o)||En(o))return O$(e,a,o),Ni(e,o,n,a);if(typeof o!="symbol"){if(ca(t)){a=Object.freeze(a.concat(t));for(let i=0;i<t.items.length;++i){const s=Ni(i,t.items[i],n,a);if(typeof s=="number")i=s-1;else{if(s===Er)return Er;s===kl&&(t.items.splice(i,1),i-=1)}}}else if(En(t)){a=Object.freeze(a.concat(t));const i=Ni("key",t.key,n,a);if(i===Er)return Er;i===kl&&(t.key=null);const s=Ni("value",t.value,n,a);if(s===Er)return Er;s===kl&&(t.value=null)}}return o}function M$(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 j$(e,t,n,a){if(typeof n=="function")return n(e,t,a);if(Rx(t))return n.Map?.(e,t,a);if(og(t))return n.Seq?.(e,t,a);if(En(t))return n.Pair?.(e,t,a);if(kn(t))return n.Scalar?.(e,t,a);if(gs(t))return n.Alias?.(e,t,a)}function O$(e,t,n){const a=t[t.length-1];if(ca(a))a.items[e]=n;else if(En(a))e==="key"?a.key=n:a.value=n;else if(lu(a))a.contents=n;else{const o=gs(a)?"alias":"scalar";throw new Error(`Cannot replace node with ${o} parent`)}}function Ax(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 hl(e,t,n,a){if(a&&typeof a=="object")if(Array.isArray(a))for(let o=0,i=a.length;o<i;++o){const s=a[o],l=hl(e,a,String(o),s);l===void 0?delete a[o]:l!==s&&(a[o]=l)}else if(a instanceof Map)for(const o of Array.from(a.keys())){const i=a.get(o),s=hl(e,a,o,i);s===void 0?a.delete(o):s!==i&&a.set(o,s)}else if(a instanceof Set)for(const o of Array.from(a)){const i=hl(e,a,o,o);i===void 0?a.delete(o):i!==o&&(a.delete(o),a.add(i))}else for(const[o,i]of Object.entries(a)){const s=hl(e,a,o,i);s===void 0?delete a[o]:s!==i&&(a[o]=s)}return e.call(t,n,a)}function La(e,t,n){if(Array.isArray(e))return e.map((a,o)=>La(a,String(o),n));if(e&&typeof e.toJSON=="function"){if(!n||!Px(e))return e.toJSON(t,n);const a={aliasCount:0,count:1,res:void 0};n.anchors.set(e,a),n.onCreate=i=>{a.res=i,delete n.onCreate};const o=e.toJSON(t,n);return n.onCreate&&n.onCreate(o),o}return typeof e=="bigint"&&!n?.keep?Number(e):e}class rg{constructor(t){Object.defineProperty(this,bo,{value:t})}clone(){const t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:n,maxAliasCount:a,onAnchor:o,reviver:i}={}){if(!lu(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=La(this,"",s);if(typeof o=="function")for(const{count:m,res:d}of s.anchors.values())o(d,m);return typeof i=="function"?hl(i,{"":l},"",l):l}}class $$ extends rg{constructor(t){super(ng),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=[],cu(t,{Node:(i,s)=>{(gs(s)||Px(s))&&a.push(s)}}),n&&(n.aliasResolveCache=a));let o;for(const i of a){if(i===this)break;i.anchor===this.source&&(o=i)}return o}toJSON(t,n){if(!n)return{source:this.source};const{anchors:a,doc:o,maxAliasCount:i}=n,s=this.resolve(o,n);if(!s){const m=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(m)}let l=a.get(s);if(l||(La(s,null,n),l=a.get(s)),l?.res===void 0){const m="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(m)}if(i>=0&&(l.count+=1,l.aliasCount===0&&(l.aliasCount=rd(o,s,a)),l.count*l.aliasCount>i)){const m="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(m)}return l.res}toString(t,n,a){const o=`*${this.source}`;if(t){if(Ax(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){const i=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(i)}if(t.implicitKey)return`${o} `}return o}}function rd(e,t,n){if(gs(t)){const a=t.resolve(e),o=n&&a&&n.get(a);return o?o.count*o.aliasCount:0}else if(ca(t)){let a=0;for(const o of t.items){const i=rd(e,o,n);i>a&&(a=i)}return a}else if(En(t)){const a=rd(e,t.key,n),o=rd(e,t.value,n);return Math.max(a,o)}return 1}const Tx=e=>!e||typeof e!="function"&&typeof e!="object";class on extends rg{constructor(t){super(ag),this.value=t}toJSON(t,n){return n?.keep?this.value:La(this.value,t,n)}toString(){return String(this.value)}}on.BLOCK_FOLDED="BLOCK_FOLDED";on.BLOCK_LITERAL="BLOCK_LITERAL";on.PLAIN="PLAIN";on.QUOTE_DOUBLE="QUOTE_DOUBLE";on.QUOTE_SINGLE="QUOTE_SINGLE";function N$(e,t,n){return n.find(a=>a.identify?.(e)&&!a.format)}function Cd(e,t,n){if(lu(e)&&(e=e.contents),Nn(e))return e;if(En(e)){const v=n.schema[Hr].createNode?.(n.schema,null,n);return v.items.push(e),v}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());const{aliasDuplicateObjects:a,onAnchor:o,onTagObj:i,schema:s,sourceObjects:l}=n;let m;if(a&&e&&typeof e=="object"){if(m=l.get(e),m)return m.anchor??(m.anchor=o(e)),new $$(m.anchor);m={anchor:null,node:null},l.set(e,m)}let d=N$(e,t,s.tags);if(!d){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){const v=new on(e);return m&&(m.node=v),v}d=e instanceof Map?s[Hr]:Symbol.iterator in Object(e)?s[ac]:s[Hr]}i&&(i(d),delete n.onTagObj);const h=d?.createNode?d.createNode(n.schema,e,n):typeof d?.nodeClass?.from=="function"?d.nodeClass.from(n.schema,e,n):new on(e);return d.default||(h.tag=d.tag),m&&(m.node=h),h}function Qb(e,t,n){let a=n;for(let o=t.length-1;o>=0;--o){const i=t[o];if(typeof i=="number"&&Number.isInteger(i)&&i>=0){const s=[];s[i]=a,a=s}else a=new Map([[i,a]])}return Cd(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 D$=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done;class Ex extends rg{constructor(t,n){super(t),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(t){const n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(n.schema=t),n.items=n.items.map(a=>Nn(a)||En(a)?a.clone(t):a),this.range&&(n.range=this.range.slice()),n}addIn(t,n){if(D$(t))this.add(n);else{const[a,...o]=t,i=this.get(a,!0);if(ca(i))i.addIn(o,n);else if(i===void 0&&this.schema)this.set(a,Qb(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(ca(o))return o.deleteIn(a);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${a}`)}getIn(t,n){const[a,...o]=t,i=this.get(a,!0);return o.length===0?!n&&kn(i)?i.value:i:ca(i)?i.getIn(o,n):void 0}hasAllNullValues(t){return this.items.every(n=>{if(!En(n))return!1;const a=n.value;return a==null||t&&kn(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 ca(o)?o.hasIn(a):!1}setIn(t,n){const[a,...o]=t;if(o.length===0)this.set(a,n);else{const i=this.get(a,!0);if(ca(i))i.setIn(o,n);else if(i===void 0&&this.schema)this.set(a,Qb(this.schema,o,n));else throw new Error(`Expected YAML collection at ${a}. Remaining path: ${o}`)}}}const L$=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Ol(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}const Di=(e,t,n)=>e.endsWith(`
|
|
125
|
+
`)?Ol(n,t):n.includes(`
|
|
126
|
+
`)?`
|
|
127
|
+
`+Ol(n,t):(e.endsWith(" ")?"":" ")+n,Mx="flow",Pf="block",id="quoted";function du(e,t,n="flow",{indentAtStart:a,lineWidth:o=80,minContentWidth:i=20,onFold:s,onOverflow:l}={}){if(!o||o<0)return e;o<i&&(i=0);const m=Math.max(1+i,1+o-t.length);if(e.length<=m)return e;const d=[],h={};let v=o-t.length;typeof a=="number"&&(a>o-Math.max(2,i)?d.push(0):v=o-a);let y,w,I=!1,R=-1,M=-1,P=-1;n===Pf&&(R=Xb(e,R,t.length),R!==-1&&(v=R+m));for(let O;O=e[R+=1];){if(n===id&&O==="\\"){switch(M=R,e[R+1]){case"x":R+=3;break;case"u":R+=5;break;case"U":R+=9;break;default:R+=1}P=R}if(O===`
|
|
128
|
+
`)n===Pf&&(R=Xb(e,R,t.length)),v=R+t.length+m,y=void 0;else{if(O===" "&&w&&w!==" "&&w!==`
|
|
129
|
+
`&&w!==" "){const j=e[R+1];j&&j!==" "&&j!==`
|
|
130
|
+
`&&j!==" "&&(y=R)}if(R>=v)if(y)d.push(y),v=y+m,y=void 0;else if(n===id){for(;w===" "||w===" ";)w=O,O=e[R+=1],I=!0;const j=R>P+1?R-2:M-1;if(h[j])return e;d.push(j),h[j]=!0,v=j+m,y=void 0}else I=!0}w=O}if(I&&l&&l(),d.length===0)return e;s&&s();let N=e.slice(0,d[0]);for(let O=0;O<d.length;++O){const j=d[O],k=d[O+1]||e.length;j===0?N=`
|
|
131
|
+
${t}${e.slice(0,k)}`:(n===id&&h[j]&&(N+=`${e[j]}\\`),N+=`
|
|
132
|
+
${t}${e.slice(j+1,k)}`)}return N}function Xb(e,t,n){let a=t,o=t+1,i=e[o];for(;i===" "||i===" ";)if(t<o+n)i=e[++t];else{do i=e[++t];while(i&&i!==`
|
|
133
|
+
`);a=t,o=t+1,i=e[o]}return a}const uu=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),mu=e=>/^(%|---|\.\.\.)/m.test(e);function U$(e,t,n){if(!t||t<0)return!1;const a=t-n,o=e.length;if(o<=a)return!1;for(let i=0,s=0;i<o;++i)if(e[i]===`
|
|
134
|
+
`){if(i-s>a)return!0;if(s=i+1,o-s<=a)return!1}return!0}function xl(e,t){const n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;const{implicitKey:a}=t,o=t.options.doubleQuotedMinMultiLineLength,i=t.indent||(mu(e)?" ":"");let s="",l=0;for(let m=0,d=n[m];d;d=n[++m])if(d===" "&&n[m+1]==="\\"&&n[m+2]==="n"&&(s+=n.slice(l,m)+"\\ ",m+=1,l=m,d="\\"),d==="\\")switch(n[m+1]){case"u":{s+=n.slice(l,m);const h=n.substr(m+2,4);switch(h){case"0000":s+="\\0";break;case"0007":s+="\\a";break;case"000b":s+="\\v";break;case"001b":s+="\\e";break;case"0085":s+="\\N";break;case"00a0":s+="\\_";break;case"2028":s+="\\L";break;case"2029":s+="\\P";break;default:h.substr(0,2)==="00"?s+="\\x"+h.substr(2):s+=n.substr(m,6)}m+=5,l=m+1}break;case"n":if(a||n[m+2]==='"'||n.length<o)m+=1;else{for(s+=n.slice(l,m)+`
|
|
135
|
+
|
|
136
|
+
`;n[m+2]==="\\"&&n[m+3]==="n"&&n[m+4]!=='"';)s+=`
|
|
137
|
+
`,m+=2;s+=i,n[m+2]===" "&&(s+="\\"),m+=1,l=m+1}break;default:m+=1}return s=l?s+n.slice(l):n,a?s:du(s,i,id,uu(t,!1))}function Af(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
138
|
+
`)||/[ \t]\n|\n[ \t]/.test(e))return xl(e,t);const n=t.indent||(mu(e)?" ":""),a="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
139
|
+
${n}`)+"'";return t.implicitKey?a:du(a,n,Mx,uu(t,!1))}function Li(e,t){const{singleQuote:n}=t.options;let a;if(n===!1)a=xl;else{const o=e.includes('"'),i=e.includes("'");o&&!i?a=Af:i&&!o?a=xl:a=n?Af:xl}return a(e,t)}let Tf;try{Tf=new RegExp(`(^|(?<!
|
|
140
|
+
))
|
|
141
|
+
+(?!
|
|
142
|
+
|$)`,"g")}catch{Tf=/\n+(?!\n|$)/g}function sd({comment:e,type:t,value:n},a,o,i){const{blockQuote:s,commentString:l,lineWidth:m}=a.options;if(!s||/\n[\t ]+$/.test(n))return Li(n,a);const d=a.indent||(a.forceBlockIndent||mu(n)?" ":""),h=s==="literal"?!0:s==="folded"||t===on.BLOCK_FOLDED?!1:t===on.BLOCK_LITERAL?!0:!U$(n,m,d.length);if(!n)return h?`|
|
|
143
|
+
`:`>
|
|
144
|
+
`;let v,y;for(y=n.length;y>0;--y){const k=n[y-1];if(k!==`
|
|
145
|
+
`&&k!==" "&&k!==" ")break}let w=n.substring(y);const I=w.indexOf(`
|
|
146
|
+
`);I===-1?v="-":n===w||I!==w.length-1?(v="+",i&&i()):v="",w&&(n=n.slice(0,-w.length),w[w.length-1]===`
|
|
147
|
+
`&&(w=w.slice(0,-1)),w=w.replace(Tf,`$&${d}`));let R=!1,M,P=-1;for(M=0;M<n.length;++M){const k=n[M];if(k===" ")R=!0;else if(k===`
|
|
148
|
+
`)P=M;else break}let N=n.substring(0,P<M?P+1:M);N&&(n=n.substring(N.length),N=N.replace(/\n+/g,`$&${d}`));let j=(R?d?"2":"1":"")+v;if(e&&(j+=" "+l(e.replace(/ ?[\r\n]+/g," ")),o&&o()),!h){const k=n.replace(/\n+/g,`
|
|
149
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${d}`);let C=!1;const T=uu(a,!0);s!=="folded"&&t!==on.BLOCK_FOLDED&&(T.onOverflow=()=>{C=!0});const z=du(`${N}${k}${w}`,d,Pf,T);if(!C)return`>${j}
|
|
150
|
+
${d}${z}`}return n=n.replace(/\n+/g,`$&${d}`),`|${j}
|
|
151
|
+
${d}${N}${n}${w}`}function z$(e,t,n,a){const{type:o,value:i}=e,{actualString:s,implicitKey:l,indent:m,indentStep:d,inFlow:h}=t;if(l&&i.includes(`
|
|
152
|
+
`)||h&&/[[\]{},]/.test(i))return Li(i,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return l||h||!i.includes(`
|
|
153
|
+
`)?Li(i,t):sd(e,t,n,a);if(!l&&!h&&o!==on.PLAIN&&i.includes(`
|
|
154
|
+
`))return sd(e,t,n,a);if(mu(i)){if(m==="")return t.forceBlockIndent=!0,sd(e,t,n,a);if(l&&m===d)return Li(i,t)}const v=i.replace(/\n+/g,`$&
|
|
155
|
+
${m}`);if(s){const y=R=>R.default&&R.tag!=="tag:yaml.org,2002:str"&&R.test?.test(v),{compat:w,tags:I}=t.doc.schema;if(I.some(y)||w?.some(y))return Li(i,t)}return l?v:du(v,m,Mx,uu(t,!1))}function H$(e,t,n,a){const{implicitKey:o,inFlow:i}=t,s=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)});let{type:l}=e;l!==on.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(s.value)&&(l=on.QUOTE_DOUBLE);const m=h=>{switch(h){case on.BLOCK_FOLDED:case on.BLOCK_LITERAL:return o||i?Li(s.value,t):sd(s,t,n,a);case on.QUOTE_DOUBLE:return xl(s.value,t);case on.QUOTE_SINGLE:return Af(s.value,t);case on.PLAIN:return z$(s,t,n,a);default:return null}};let d=m(l);if(d===null){const{defaultKeyType:h,defaultStringType:v}=t.options,y=o&&h||v;if(d=m(y),d===null)throw new Error(`Unsupported default string type ${y}`)}return d}function q$(e,t){const n=Object.assign({blockQuote:!0,commentString:L$,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 B$(e,t){if(t.tag){const o=e.filter(i=>i.tag===t.tag);if(o.length>0)return o.find(i=>i.format===t.format)??o[0]}let n,a;if(kn(t)){a=t.value;let o=e.filter(i=>i.identify?.(a));if(o.length>1){const i=o.filter(s=>s.test);i.length>0&&(o=i)}n=o.find(i=>i.format===t.format)??o.find(i=>!i.format)}else a=t,n=e.find(o=>o.nodeClass&&a instanceof o.nodeClass);if(!n){const o=a?.constructor?.name??(a===null?"null":typeof a);throw new Error(`Tag not resolved for ${o} value`)}return n}function F$(e,t,{anchors:n,doc:a}){if(!a.directives)return"";const o=[],i=(kn(e)||ca(e))&&e.anchor;i&&Ax(i)&&(n.add(i),o.push(`&${i}`));const s=e.tag??(t.default?null:t.tag);return s&&o.push(a.directives.tagString(s)),o.join(" ")}function Rd(e,t,n,a){if(En(e))return e.toString(t,n,a);if(gs(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let o;const i=Nn(e)?e:t.doc.createNode(e,{onTagObj:m=>o=m});o??(o=B$(t.doc.schema.tags,i));const s=F$(i,o,t);s.length>0&&(t.indentAtStart=(t.indentAtStart??0)+s.length+1);const l=typeof o.stringify=="function"?o.stringify(i,t,n,a):kn(i)?H$(i,t,n,a):i.toString(t,n,a);return s?kn(i)||l[0]==="{"||l[0]==="["?`${s} ${l}`:`${s}
|
|
156
|
+
${t.indent}${l}`:l}function V$({key:e,value:t},n,a,o){const{allNullValues:i,doc:s,indent:l,indentStep:m,options:{commentString:d,indentSeq:h,simpleKeys:v}}=n;let y=Nn(e)&&e.comment||null;if(v){if(y)throw new Error("With simple keys, key nodes cannot have comments");if(ca(e)||!Nn(e)&&typeof e=="object"){const T="With simple keys, collection cannot be used as a key value";throw new Error(T)}}let w=!v&&(!e||y&&t==null&&!n.inFlow||ca(e)||(kn(e)?e.type===on.BLOCK_FOLDED||e.type===on.BLOCK_LITERAL:typeof e=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!w&&(v||!i),indent:l+m});let I=!1,R=!1,M=Rd(e,n,()=>I=!0,()=>R=!0);if(!w&&!n.inFlow&&M.length>1024){if(v)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");w=!0}if(n.inFlow){if(i||t==null)return I&&a&&a(),M===""?"?":w?`? ${M}`:M}else if(i&&!v||t==null&&w)return M=`? ${M}`,y&&!I?M+=Di(M,n.indent,d(y)):R&&o&&o(),M;I&&(y=null),w?(y&&(M+=Di(M,n.indent,d(y))),M=`? ${M}
|
|
157
|
+
${l}:`):(M=`${M}:`,y&&(M+=Di(M,n.indent,d(y))));let P,N,O;Nn(t)?(P=!!t.spaceBefore,N=t.commentBefore,O=t.comment):(P=!1,N=null,O=null,t&&typeof t=="object"&&(t=s.createNode(t))),n.implicitKey=!1,!w&&!y&&kn(t)&&(n.indentAtStart=M.length+1),R=!1,!h&&m.length>=2&&!n.inFlow&&!w&&og(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let j=!1;const k=Rd(t,n,()=>j=!0,()=>R=!0);let C=" ";if(y||P||N){if(C=P?`
|
|
158
|
+
`:"",N){const T=d(N);C+=`
|
|
159
|
+
${Ol(T,n.indent)}`}k===""&&!n.inFlow?C===`
|
|
160
|
+
`&&O&&(C=`
|
|
161
|
+
|
|
162
|
+
`):C+=`
|
|
163
|
+
${n.indent}`}else if(!w&&ca(t)){const T=k[0],z=k.indexOf(`
|
|
164
|
+
`),B=z!==-1,D=n.inFlow??t.flow??t.items.length===0;if(B||!D){let V=!1;if(B&&(T==="&"||T==="!")){let le=k.indexOf(" ");T==="&"&&le!==-1&&le<z&&k[le+1]==="!"&&(le=k.indexOf(" ",le+1)),(le===-1||z<le)&&(V=!0)}V||(C=`
|
|
165
|
+
${n.indent}`)}}else(k===""||k[0]===`
|
|
166
|
+
`)&&(C="");return M+=C+k,n.inFlow?j&&a&&a():O&&!j?M+=Di(M,n.indent,d(O)):R&&o&&o(),M}function K$(e,t){(e==="debug"||e==="warn")&&console.warn(t)}const Hc="<<",Pp={identify:e=>e===Hc||typeof e=="symbol"&&e.description===Hc,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new on(Symbol(Hc)),{addToJSMap:jx}),stringify:()=>Hc},W$=(e,t)=>(Pp.identify(t)||kn(t)&&(!t.type||t.type===on.PLAIN)&&Pp.identify(t.value))&&e?.doc.schema.tags.some(n=>n.tag===Pp.tag&&n.default);function jx(e,t,n){const a=Ox(e,n);if(og(a))for(const o of a.items)Ap(e,t,o);else if(Array.isArray(a))for(const o of a)Ap(e,t,o);else Ap(e,t,a)}function Ap(e,t,n){const a=Ox(e,n);if(!Rx(a))throw new Error("Merge sources must be maps or map aliases");const o=a.toJSON(null,e,Map);for(const[i,s]of o)t instanceof Map?t.has(i)||t.set(i,s):t instanceof Set?t.add(i):Object.prototype.hasOwnProperty.call(t,i)||Object.defineProperty(t,i,{value:s,writable:!0,enumerable:!0,configurable:!0});return t}function Ox(e,t){return e&&gs(t)?t.resolve(e.doc,e):t}function $x(e,t,{key:n,value:a}){if(Nn(n)&&n.addToJSMap)n.addToJSMap(e,t,a);else if(W$(e,n))jx(e,t,a);else{const o=La(n,"",e);if(t instanceof Map)t.set(o,La(a,o,e));else if(t instanceof Set)t.add(o);else{const i=G$(n,o,e),s=La(a,i,e);i in t?Object.defineProperty(t,i,{value:s,writable:!0,enumerable:!0,configurable:!0}):t[i]=s}}return t}function G$(e,t,n){if(t===null)return"";if(typeof t!="object")return String(t);if(Nn(e)&&n?.doc){const a=q$(n.doc,{});a.anchors=new Set;for(const i of n.anchors.keys())a.anchors.add(i.anchor);a.inFlow=!0,a.inStringifyKey=!0;const o=e.toString(a);if(!n.mapKeyWarned){let i=JSON.stringify(o);i.length>40&&(i=i.substring(0,36)+'..."'),K$(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${i}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return o}return JSON.stringify(t)}function ig(e,t,n){const a=Cd(e,void 0,n),o=Cd(t,void 0,n);return new Uo(a,o)}class Uo{constructor(t,n=null){Object.defineProperty(this,bo,{value:Cx}),this.key=t,this.value=n}clone(t){let{key:n,value:a}=this;return Nn(n)&&(n=n.clone(t)),Nn(a)&&(a=a.clone(t)),new Uo(n,a)}toJSON(t,n){const a=n?.mapAsMap?new Map:{};return $x(n,a,this)}toString(t,n,a){return t?.doc?V$(this,t,n,a):JSON.stringify(this)}}function Nx(e,t,n){return(t.inFlow??e.flow?J$:Z$)(e,t,n)}function Z$({comment:e,items:t},n,{blockItemPrefix:a,flowChars:o,itemIndent:i,onChompKeep:s,onComment:l}){const{indent:m,options:{commentString:d}}=n,h=Object.assign({},n,{indent:i,type:null});let v=!1;const y=[];for(let I=0;I<t.length;++I){const R=t[I];let M=null;if(Nn(R))!v&&R.spaceBefore&&y.push(""),Pd(n,y,R.commentBefore,v),R.comment&&(M=R.comment);else if(En(R)){const N=Nn(R.key)?R.key:null;N&&(!v&&N.spaceBefore&&y.push(""),Pd(n,y,N.commentBefore,v))}v=!1;let P=Rd(R,h,()=>M=null,()=>v=!0);M&&(P+=Di(P,i,d(M))),v&&M&&(v=!1),y.push(a+P)}let w;if(y.length===0)w=o.start+o.end;else{w=y[0];for(let I=1;I<y.length;++I){const R=y[I];w+=R?`
|
|
167
|
+
${m}${R}`:`
|
|
168
|
+
`}}return e?(w+=`
|
|
169
|
+
`+Ol(d(e),m),l&&l()):v&&s&&s(),w}function J$({items:e},t,{flowChars:n,itemIndent:a}){const{indent:o,indentStep:i,flowCollectionPadding:s,options:{commentString:l}}=t;a+=i;const m=Object.assign({},t,{indent:a,inFlow:!0,type:null});let d=!1,h=0;const v=[];for(let I=0;I<e.length;++I){const R=e[I];let M=null;if(Nn(R))R.spaceBefore&&v.push(""),Pd(t,v,R.commentBefore,!1),R.comment&&(M=R.comment);else if(En(R)){const N=Nn(R.key)?R.key:null;N&&(N.spaceBefore&&v.push(""),Pd(t,v,N.commentBefore,!1),N.comment&&(d=!0));const O=Nn(R.value)?R.value:null;O?(O.comment&&(M=O.comment),O.commentBefore&&(d=!0)):R.value==null&&N?.comment&&(M=N.comment)}M&&(d=!0);let P=Rd(R,m,()=>M=null);d||(d=v.length>h||P.includes(`
|
|
170
|
+
`)),I<e.length-1?P+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(d||(d=v.reduce((N,O)=>N+O.length+2,2)+(P.length+2)>t.options.lineWidth)),d&&(P+=",")),M&&(P+=Di(P,a,l(M))),v.push(P),h=v.length}const{start:y,end:w}=n;if(v.length===0)return y+w;if(!d){const I=v.reduce((R,M)=>R+M.length+2,2);d=t.options.lineWidth>0&&I>t.options.lineWidth}if(d){let I=y;for(const R of v)I+=R?`
|
|
171
|
+
${i}${o}${R}`:`
|
|
172
|
+
`;return`${I}
|
|
173
|
+
${o}${w}`}else return`${y}${s}${v.join(" ")}${s}${w}`}function Pd({indent:e,options:{commentString:t}},n,a,o){if(a&&o&&(a=a.replace(/^\n+/,"")),a){const i=Ol(t(a),e);n.push(i.trimStart())}}function Nr(e,t){const n=kn(t)?t.value:t;for(const a of e)if(En(a)&&(a.key===t||a.key===n||kn(a.key)&&a.key.value===n))return a}class Ai extends Ex{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Hr,t),this.items=[]}static from(t,n,a){const{keepUndefined:o,replacer:i}=a,s=new this(t),l=(m,d)=>{if(typeof i=="function")d=i.call(n,m,d);else if(Array.isArray(i)&&!i.includes(m))return;(d!==void 0||o)&&s.items.push(ig(m,d,a))};if(n instanceof Map)for(const[m,d]of n)l(m,d);else if(n&&typeof n=="object")for(const m of Object.keys(n))l(m,n[m]);return typeof t.sortMapEntries=="function"&&s.items.sort(t.sortMapEntries),s}add(t,n){let a;En(t)?a=t:!t||typeof t!="object"||!("key"in t)?a=new Uo(t,t?.value):a=new Uo(t.key,t.value);const o=Nr(this.items,a.key),i=this.schema?.sortMapEntries;if(o){if(!n)throw new Error(`Key ${a.key} already set`);kn(o.value)&&Tx(a.value)?o.value.value=a.value:o.value=a.value}else if(i){const s=this.items.findIndex(l=>i(a,l)<0);s===-1?this.items.push(a):this.items.splice(s,0,a)}else this.items.push(a)}delete(t){const n=Nr(this.items,t);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(t,n){const o=Nr(this.items,t)?.value;return(!n&&kn(o)?o.value:o)??void 0}has(t){return!!Nr(this.items,t)}set(t,n){this.add(new Uo(t,n),!0)}toJSON(t,n,a){const o=a?new a:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(o);for(const i of this.items)$x(n,o,i);return o}toString(t,n,a){if(!t)return JSON.stringify(this);for(const o of this.items)if(!En(o))throw new Error(`Map items must all be pairs; found ${JSON.stringify(o)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),Nx(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:a,onComment:n})}}class Dx extends Ex{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(ac,t),this.items=[]}add(t){this.items.push(t)}delete(t){const n=qc(t);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(t,n){const a=qc(t);if(typeof a!="number")return;const o=this.items[a];return!n&&kn(o)?o.value:o}has(t){const n=qc(t);return typeof n=="number"&&n<this.items.length}set(t,n){const a=qc(t);if(typeof a!="number")throw new Error(`Expected a valid index, not ${t}.`);const o=this.items[a];kn(o)&&Tx(n)?o.value=n:this.items[a]=n}toJSON(t,n){const a=[];n?.onCreate&&n.onCreate(a);let o=0;for(const i of this.items)a.push(La(i,String(o++),n));return a}toString(t,n,a){return t?Nx(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:a,onComment:n}):JSON.stringify(this)}static from(t,n,a){const{replacer:o}=a,i=new this(t);if(n&&Symbol.iterator in Object(n)){let s=0;for(let l of n){if(typeof o=="function"){const m=n instanceof Set?l:String(s++);l=o.call(n,m,l)}i.items.push(Cd(l,void 0,a))}}return i}}function qc(e){let t=kn(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}function Y$(e,t,n){const{replacer:a}=n,o=new Dx(e);o.tag="tag:yaml.org,2002:pairs";let i=0;if(t&&Symbol.iterator in Object(t))for(let s of t){typeof a=="function"&&(s=a.call(t,String(i++),s));let l,m;if(Array.isArray(s))if(s.length===2)l=s[0],m=s[1];else throw new TypeError(`Expected [key, value] tuple: ${s}`);else if(s&&s instanceof Object){const d=Object.keys(s);if(d.length===1)l=d[0],m=s[l];else throw new TypeError(`Expected tuple with one key, not ${d.length} keys`)}else l=s;o.items.push(ig(l,m,n))}return o}class sg extends Dx{constructor(){super(),this.add=Ai.prototype.add.bind(this),this.delete=Ai.prototype.delete.bind(this),this.get=Ai.prototype.get.bind(this),this.has=Ai.prototype.has.bind(this),this.set=Ai.prototype.set.bind(this),this.tag=sg.tag}toJSON(t,n){if(!n)return super.toJSON(t);const a=new Map;n?.onCreate&&n.onCreate(a);for(const o of this.items){let i,s;if(En(o)?(i=La(o.key,"",n),s=La(o.value,i,n)):i=La(o,"",n),a.has(i))throw new Error("Ordered maps must not include duplicate keys");a.set(i,s)}return a}static from(t,n,a){const o=Y$(t,n,a),i=new this;return i.items=o.items,i}}sg.tag="tag:yaml.org,2002:omap";class lg extends Ai{constructor(t){super(t),this.tag=lg.tag}add(t){let n;En(t)?n=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?n=new Uo(t.key,null):n=new Uo(t,null),Nr(this.items,n.key)||this.items.push(n)}get(t,n){const a=Nr(this.items,t);return!n&&En(a)?kn(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=Nr(this.items,t);a&&!n?this.items.splice(this.items.indexOf(a),1):!a&&n&&this.items.push(new Uo(t))}toJSON(t,n){return super.toJSON(t,n,Set)}toString(t,n,a){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),n,a);throw new Error("Set items must all have null values")}static from(t,n,a){const{replacer:o}=a,i=new this(t);if(n&&Symbol.iterator in Object(n))for(let s of n)typeof o=="function"&&(s=o.call(n,s,s)),i.items.push(ig(s,null,a));return i}}lg.tag="tag:yaml.org,2002:set";new Set("0123456789ABCDEFabcdef");new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()");new Set(",[]{}");new Set(` ,[]{}
|
|
174
|
+
\r `);const Ad=r().min(1).max(2e3).refine(e=>!e.includes("\\")&&!e.includes(":")&&!e.startsWith("/")&&e.split("/").every(t=>t!==""&&t!=="."&&t!==".."),"source paths must be portable relative paths");r().regex(/^[a-z][a-z0-9_-]{0,119}$/);const Q$={type:"object",properties:{},additionalProperties:!1};c({name:r().trim().min(1).max(240).optional(),description:r().max(4e3).optional(),skillPaths:f(Ad).max(100).optional(),assetPaths:f(Ad).max(100).optional()}).strict();c({actionId:r().trim().min(1).max(240),name:r().trim().min(1).max(240),description:r().max(4e3).default(""),inputSchema:ie(r(),ce()).default(Q$),skillPaths:f(Ad).max(100).default([]),assetPaths:f(Ad).max(100).default([])}).strict();const Lx=b(["openpond.lab"]),$l=c({id:r(),experience:Zh.default(UO),provider:fs,modelRef:mn.nullable().optional(),openPondCommandAccessMode:Ql.default(ou),systemKind:Lx.nullable().optional(),hiddenFromDefaultSidebar:A().optional(),parentSessionId:r().nullable().optional(),parentTurnId:r().nullable().optional(),subagentRunId:r().nullable().optional(),subagentRoleId:ps.nullable().optional(),subagentDelegationMode:tu.nullable().optional(),title:r(),appId:r().nullable(),appName:r().nullable(),workspaceKind:Xl.optional(),workspaceId:r().nullable().optional(),workspaceName:r().nullable().optional(),localProjectId:r().nullable().optional(),cloudProjectId:r().nullable().optional(),cloudTeamId:r().nullable().optional(),currentProfile:hr.nullable().optional(),profileWorkflowBinding:P$.nullable().optional(),profileComponentBinding:A$.nullable().optional(),metadata:ie(r(),ce()).optional(),cwd:r().nullable(),codexThreadId:r().nullable(),createdAt:r(),updatedAt:r(),status:b(["idle","active","failed","closed"]),runtimeSeconds:u().int().nonnegative().optional(),runtimeRunningSince:r().nullable().optional(),pinned:A(),savedForLater:A().optional(),archived:A(),order:u()});c({id:r(),sessionId:r(),providerTurnId:r().nullable(),modelRef:mn.nullable().optional(),prompt:r(),startedAt:r(),completedAt:r().nullable(),status:b(["in_progress","completed","failed","interrupted"]),error:r().nullable(),metadata:ie(r(),ce()).optional().default({}),createImproveRun:ec.nullable().optional().default(null),profileSnapshot:s2.nullable().optional(),harnessSnapshot:c2.nullable().optional()});const X$=c({id:r(),sessionId:r(),turnId:r().nullable(),providerRequestId:Dt([r(),u()]),kind:b(["command","file_change","permissions","user_input","create_plan","subagent_patch_apply","legacy_exec","legacy_patch"]),title:r(),detail:r(),status:b(["pending","accepted","accepted_for_session","declined","cancelled"]),createdAt:r()}),eN=c({key:b(["files","diffs","checks","deploys","sources","schedules","tool_runs","logs","app_config"]),label:r(),status:b(["placeholder","available","error"]),summary:r()}),Ux=c({id:r().trim().min(1).max(191),agentId:r().trim().min(1).max(191).optional().nullable(),sourcePath:r().trim().min(1).max(2e3).optional().nullable(),sourceActionId:r().trim().min(1).max(191).optional().nullable(),name:r().trim().min(1).max(191).optional().nullable(),label:r().trim().min(1).max(160).optional().nullable(),description:r().trim().max(1e3).optional().nullable(),visibility:r().trim().max(80).optional().nullable(),inputSchema:Dt([r().trim().max(191),ie(r(),ce())]).optional().nullable(),outputSchema:Dt([r().trim().max(191),ie(r(),ce())]).optional().nullable(),approvalPolicy:ie(r(),ce()).optional().nullable(),artifactPolicy:ie(r(),ce()).optional().nullable(),setupRequirements:f(ie(r(),ce())).optional(),mcp:ie(r(),ce()).optional().nullable(),schedulePolicy:ie(r(),ce()).optional().nullable(),trace:ie(r(),ce()).optional().nullable(),implementation:ie(r(),ce()).optional().nullable(),invokesModel:A().optional()}),tN=c({command:b(["inspect","build","validate","eval","traces","run"]),status:b(["passed","failed"]),checkedAt:r(),exitCode:u().nullable().optional(),sourceHead:r().nullable().optional()}),nN=c({id:r(),name:r(),path:r(),enabled:A()}),aN=c({name:r(),description:r(),path:r(),scope:S("profile"),enabled:A(),sourcePath:r(),charCount:u(),sourceHash:r(),validationStatus:b(["valid","warning","error"]),validationMessages:f(r()),resourceFiles:f(r()).optional().default([])}),oN=c({id:r(),name:r(),path:r(),agentId:r().nullable(),sourcePath:r()}),zx=c({path:r(),originalPath:r().nullable().optional(),indexStatus:r().nullable(),worktreeStatus:r().nullable(),status:r(),category:b(["added","modified","deleted","renamed","untracked","changed"])}),rN=c({isRepo:A(),branch:r().nullable(),head:r().nullable(),shortHead:r().nullable(),dirty:A(),upstream:r().nullable(),ahead:u().nullable(),behind:u().nullable(),remoteUrl:r().nullable(),files:f(zx),fileCount:u().int().nonnegative().optional(),error:r().nullable()}),iN=c({actionCount:u(),generatedAt:r().nullable(),manifestPath:r().nullable(),registryPath:r().nullable(),stale:A(),error:r().nullable()}),sN=c({skillCount:u(),generatedAt:r().nullable(),stale:A(),error:r().nullable()}),ey=c({ref:r(),source:b(["action_catalog","source_upload_metadata"]),actionId:r().nullable(),kind:r().nullable(),label:r(),status:r(),required:A(),blocking:A()}),lN=c({status:b(["ready","setup_required","blocked"]),requirementCount:u(),blockingCount:u(),optionalMissingCount:u(),readyCount:u(),requirements:f(ey),blockingRequirements:f(ey)}),cN=c({changedAgents:f(r()),newAgents:f(r()),deletedAgents:f(r()),changedSkills:f(r()).optional().default([]),changedActions:f(r()),changedExtensions:f(r()),setupChanges:f(r()),envRequirementChanges:f(r()),files:f(zx),fileCount:u().int().nonnegative().optional()}),dN=c({status:r(),agentId:r().nullable().optional(),deployPlanStatus:r().nullable().optional(),canRun:A().nullable().optional(),canDeploy:A().nullable().optional(),sourceRef:r().nullable().optional(),sourceCommitSha:r().nullable().optional(),manifestHash:r().nullable().optional(),manifestPath:r().nullable().optional(),setupCommands:f(r()).optional(),validationCommands:f(r()).optional(),requiredChecks:f(r()).optional(),evalNames:f(r()).optional(),blockedReasons:f(r()).optional(),staleReasons:f(r()).optional(),runtimeId:r().nullable().optional(),sandboxId:r().nullable().optional(),traceArtifactRefs:f(r()).optional(),evalResultArtifactRefs:f(r()).optional(),validatorArtifactRefs:f(r()).optional(),checkedAt:r().nullable().optional(),error:r().nullable().optional()}),uN=c({status:r(),agentId:r().nullable().optional(),runtimeAgentId:r().nullable().optional(),projectId:r().nullable().optional(),sourceRoot:r().nullable().optional(),sourceRef:r().nullable().optional(),sourceCommitSha:r().nullable().optional(),manifestHash:r().nullable().optional(),manifestPath:r().nullable().optional(),manifestSyncedAt:r().nullable().optional(),fileCount:u().nullable().optional(),totalBytes:u().nullable().optional(),generatedManifestPath:r().nullable().optional(),synthesizedOpenPondYaml:A().nullable().optional(),uploadMetadataPath:r().nullable().optional(),setupCommands:f(r()).optional(),validationCommands:f(r()).optional(),materializedAt:r().nullable().optional(),error:r().nullable().optional()}),mN=c({status:r(),agentId:r().nullable().optional(),snapshotId:r().nullable().optional(),sourceRef:r().nullable().optional(),sourceCommitSha:r().nullable().optional(),manifestHash:r().nullable().optional(),manifestPath:r().nullable().optional(),buildStatus:r().nullable().optional(),validationStatus:r().nullable().optional(),evalStatus:r().nullable().optional(),publishedAt:r().nullable().optional(),error:r().nullable().optional()}),pN=c({status:r(),agentId:r().nullable().optional(),runId:r().nullable().optional(),runtimeId:r().nullable().optional(),sandboxId:r().nullable().optional(),sourceRef:r().nullable().optional(),sourceCommitSha:r().nullable().optional(),manifestHash:r().nullable().optional(),setupGateStatus:r().nullable().optional(),setupRequirementRefs:f(r()).optional(),artifactRefs:f(r()).optional(),traceArtifactRefs:f(r()).optional(),evalArtifactRefs:f(r()).optional(),startedAt:r().nullable().optional(),completedAt:r().nullable().optional(),error:r().nullable().optional()}),fN=c({teamId:r().nullable(),projectId:r().nullable(),sourceRef:r().nullable(),sourceCommitSha:r().nullable(),lastPushedAt:r().nullable(),lastPushedLocalHead:r().nullable(),lastPushedHostedHead:r().nullable(),promotionStatus:r().nullable().optional().default(null),hostedRunStatus:r().nullable().optional().default(null),hostedRunAgentId:r().nullable().optional().default(null),hostedRunId:r().nullable().optional().default(null),hostedRunAt:r().nullable().optional().default(null),hostedSourceMaterialization:uN.nullable().optional().default(null),hostedSourceCheck:dN.nullable().optional().default(null),hostedPublish:mN.nullable().optional().default(null),hostedRun:pN.nullable().optional().default(null)}),hN=c({state:b(["none","ready","dirty","pending_commit","error"]),message:r(),agentCount:u(),actionCount:u(),defaultAction:r().nullable(),checkFresh:A(),checkStaleReason:r().nullable(),localHead:r().nullable(),hostedHead:r().nullable()}),Hx=c({mode:b(["none","local"]),repoPath:r().nullable(),activeProfile:r().nullable(),sourcePath:r().nullable(),manifestPath:r().nullable(),agents:f(nN),skills:f(aN).optional().default([]),evals:f(oN).optional().default([]),git:rN.nullable(),catalog:iN,skillCatalog:sN.optional().default({skillCount:0,generatedAt:null,stale:!0,error:null}),actionCatalog:f(Ux),sourceSetupRequirements:f(ie(r(),ce())),setupGate:lN,diff:cN,hosted:fN.nullable(),summary:hN,lastCheck:tN.nullable(),error:r().nullable()}),gN=c({ref:hr,name:r(),repoPath:r(),sourcePath:r().nullable(),state:Hx}),vN=c({lastUsed:hr.nullable(),profiles:f(gN)});function bN(){return{lastUsed:null,profiles:[]}}function yN(){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 SN=c({name:r(),description:r(),path:r(),sourcePath:r(),enabled:A(),charCount:u().int().nonnegative(),sourceHash:r(),validationStatus:b(["valid","error"]),validationMessages:f(r()),resourceFiles:f(r()),updatedAt:r().nullable()}),kN=b(["codex","profile","extension"]);c({skillName:r(),scope:kN,path:r(),byteSize:u().int().nonnegative(),isBinary:A(),content:r().nullable()});const xN=[{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"]}],wN=c({name:r(),description:r(),relativePath:r(),sourcePath:r(),charCount:u().int().nonnegative(),sourceHash:r(),resourceFiles:f(r()),validationStatus:b(["valid","error"]),validationMessages:f(r())}),qx=c({id:r(),source:S("github"),owner:r(),repo:r(),repositoryUrl:r().url(),requestedRef:r(),resolvedCommit:r(),sourcePath:r(),readmePath:r().nullable(),installedAt:r(),updatedAt:r(),packageHash:r(),skills:f(wN),validationStatus:b(["valid","error"]),validationMessages:f(r())});qx.omit({installedAt:!0,updatedAt:!0,sourcePath:!0}).extend({sourcePath:Xd()});const IN=c({rootPath:r(),registryPath:r(),extensions:f(qx),error:r().nullable()});c({source:r().trim().min(1),ref:r().trim().min(1).optional()});const _N=c({latestSequence:u().int().nonnegative(),oldestSequence:u().int().nonnegative(),totalEvents:u().int().nonnegative(),limit:u().int().nonnegative(),hasMoreBefore:A()});c({server:LO,account:PO,codex:AO,configuration:c({rawRevision:r(),effectiveRevision:r(),sources:f(c({layer:r(),path:r(),revision:r()})),provenance:ie(r(),c({layer:r(),path:r(),revision:r()}))}).optional(),preferences:Vb.optional().default(()=>Vb.parse({})),providers:pb.optional().default(()=>pb.parse({})),personalization:Kb.optional().default(()=>Kb.parse({soul:ax[0].content,soulPath:null,updatedAt:null})),apps:f(Dj),localProjects:f(qj).optional().default([]),cloudProjects:f(Hj).optional().default([]),profile:Hx.optional().default(yN),profileLibrary:vN.optional().default(bN),codexPersonalSkills:f(SN).optional().default([]),extensionCatalog:IN.optional().default({rootPath:"",registryPath:"",extensions:[],error:null}),codexHistorySessions:f($l).optional().default([]),sidebarAppPreferences:kO,sidebarFileBookmarks:f(tx).optional().default([]),appsError:r().nullable(),appsMeta:Fb,accountMeta:Fb,sessions:f($l),events:f(fb),eventWindow:_N.optional(),approvals:f(X$),placeholders:f(eN),diagnostics:f(fb)});const cg=b(["openpond_hosted","local_byok","codex_app_server","unknown"]),Bx=b(["provider_usage","codex_context_usage","missing"]),CN=b(["provider_usage_body","provider_response_headers"]),RN=b(["chat_turn","tool_loop","slash_command","create_improve_planner","harness_refiner","context_compaction","subagent","codex_context","other"]),PN=b(["foreground","tool_loop","compaction","subagent","refiner","other"]),Fx=b(["user_facing","background","system"]),Vx=b(["started","completed","failed","interrupted"]),dg=b(["composer_selection","prompt_parse","server_parser","model_tool","api"]),Kx=b(["chat","settings","goal","create_improve","compaction","system"]),Wx=b(["direct_chat","tool_loop","slash_command","planner","summary","scan","subagent","other"]),AN=c({surface:Kx,workflowKind:Wx,sessionId:r().trim().min(1).nullable().default(null),turnId:r().trim().min(1).nullable().default(null),goalId:r().trim().min(1).nullable().default(null),subagentRunId:r().trim().min(1).nullable().default(null),subagentRoleId:r().trim().min(1).nullable().default(null),createImproveRunId:r().trim().min(1).nullable().default(null),commandName:r().trim().min(1).max(160).nullable().default(null),commandSource:dg.nullable().default(null),appId:r().trim().min(1).nullable().default(null),workspaceKind:Xl.nullable().default(null),workspaceId:r().trim().min(1).nullable().default(null),localProjectId:r().trim().min(1).nullable().default(null),cloudProjectId:r().trim().min(1).nullable().default(null),sourceEventSequence:u().int().nonnegative().nullable().default(null)}),TN=c({surface:Kx.optional(),workflowKind:Wx.optional(),goalId:r().trim().min(1).nullable().optional(),subagentRunId:r().trim().min(1).nullable().optional(),subagentRoleId:r().trim().min(1).nullable().optional(),createImproveRunId:r().trim().min(1).nullable().optional(),commandName:r().trim().min(1).max(160).nullable().optional(),commandSource:dg.nullable().optional()}).strict(),Yr=r().trim().min(1).max(160),EN=c({id:r().trim().min(1),requestId:r().trim().min(1),requestOrdinal:u().int().nonnegative(),sessionId:r().trim().min(1).nullable(),turnId:r().trim().min(1).nullable(),provider:Yr,model:r().trim().min(1),route:cg,source:Bx,requestKind:RN,visibility:Fx,status:Vx,startedAt:r().trim().min(1),completedAt:r().trim().min(1).nullable(),durationMs:u().int().nonnegative().nullable(),firstTokenMs:u().int().nonnegative().nullable(),promptTokens:u().int().nonnegative().nullable(),cachedPromptTokens:u().int().nonnegative().nullable(),uncachedPromptTokens:u().int().nonnegative().nullable(),cacheWritePromptTokens:u().int().nonnegative().nullable(),cacheTelemetrySource:CN.nullable(),completionTokens:u().int().nonnegative().nullable(),totalTokens:u().int().nonnegative().nullable(),errorType:r().trim().min(1).max(160).nullable(),errorMessage:r().trim().min(1).max(2e3).nullable(),attribution:AN}),Gx=c({from:r().trim().min(1),to:r().trim().min(1),bucket:b(["day","all_time"])}),ug=Dt([S("all"),Fx]),mg=b(["all","started","completed","failed","interrupted","missing"]),MN=c({range:b(["7d","30d","90d","all"]).default("30d"),visibility:ug.default("all"),status:mg.default("all"),provider:Yr.optional(),model:r().trim().min(1).optional()});MN.extend({sessionId:r().trim().min(1).optional(),turnId:r().trim().min(1).optional(),limit:u().int().positive().max(500).default(100)});c({sessionId:r().trim().min(1)});const Qr=c({requests:u().int().nonnegative(),promptTokens:u().int().nonnegative().nullable(),cacheTelemetryRequests:u().int().nonnegative(),cacheHitRequests:u().int().nonnegative(),cachedPromptTokens:u().int().nonnegative().nullable(),uncachedPromptTokens:u().int().nonnegative().nullable(),cacheWritePromptTokens:u().int().nonnegative().nullable(),cacheHitRate:u().min(0).max(1).nullable(),cacheRequestHitRate:u().min(0).max(1).nullable(),cacheTelemetryCoverage:u().min(0).max(1),completionTokens:u().int().nonnegative().nullable(),totalTokens:u().int().nonnegative().nullable(),averageLatencyMs:u().nonnegative().nullable(),p95LatencyMs:u().nonnegative().nullable(),averageFirstTokenMs:u().nonnegative().nullable(),p95FirstTokenMs:u().nonnegative().nullable(),failures:u().int().nonnegative(),failureRate:u().nonnegative(),firstSeenAt:r().trim().min(1),lastSeenAt:r().trim().min(1)}),jN=Qr.extend({provider:Yr,model:r().trim().min(1),route:cg}),ON=Qr.extend({sessionId:r().trim().min(1),title:r().trim().min(1).nullable(),workspaceKind:Xl.nullable(),workspaceId:r().trim().min(1).nullable()}),$N=Qr.extend({commandName:r().trim().min(1),commandSource:dg.nullable()}),NN=Qr.extend({route:cg}),DN=Qr.extend({status:Vx}),LN=Qr.extend({source:Bx}),UN=Qr.extend({cohort:PN}),zN=c({date:r().trim().min(1),totalTokens:u().int().nonnegative(),requests:u().int().nonnegative(),models:f(c({provider:Yr,model:r().trim().min(1),totalTokens:u().int().nonnegative(),requests:u().int().nonnegative()}))}),HN=c({requests:u().int().nonnegative(),completedRequests:u().int().nonnegative(),failedRequests:u().int().nonnegative(),missingUsageRequests:u().int().nonnegative(),promptTokens:u().int().nonnegative().nullable(),cacheTelemetryRequests:u().int().nonnegative(),cacheHitRequests:u().int().nonnegative(),cachedPromptTokens:u().int().nonnegative().nullable(),uncachedPromptTokens:u().int().nonnegative().nullable(),cacheWritePromptTokens:u().int().nonnegative().nullable(),cacheHitRate:u().min(0).max(1).nullable(),cacheRequestHitRate:u().min(0).max(1).nullable(),cacheTelemetryCoverage:u().min(0).max(1),completionTokens:u().int().nonnegative().nullable(),totalTokens:u().int().nonnegative().nullable(),averageLatencyMs:u().nonnegative().nullable(),p95LatencyMs:u().nonnegative().nullable(),averageFirstTokenMs:u().nonnegative().nullable(),p95FirstTokenMs:u().nonnegative().nullable(),failureRate:u().nonnegative(),activeModelCount:u().int().nonnegative(),peakDailyTokens:u().int().nonnegative(),longestRequestMs:u().int().nonnegative().nullable(),activeDays:u().int().nonnegative(),currentStreakDays:u().int().nonnegative(),longestStreakDays:u().int().nonnegative()});c({generatedAt:r().trim().min(1),range:Gx,filters:c({visibility:ug,status:mg,provider:Yr.nullable(),model:r().trim().min(1).nullable()}),totals:HN,daily:f(zN),models:f(jN),threads:f(ON),commands:f($N),routes:f(NN),statuses:f(DN),sources:f(LN),cohorts:f(UN)});c({generatedAt:r().trim().min(1),range:Gx,filters:c({visibility:ug,status:mg,provider:Yr.nullable(),model:r().trim().min(1).nullable(),sessionId:r().trim().min(1).nullable(),turnId:r().trim().min(1).nullable()}),limit:u().int().positive(),hasMore:A(),records:f(EN)});const qN=c({turnId:r().trim().min(1),requests:u().int().nonnegative(),cacheTelemetryRequests:u().int().nonnegative(),cachedPromptTokens:u().int().nonnegative().nullable(),uncachedPromptTokens:u().int().nonnegative().nullable(),cacheWritePromptTokens:u().int().nonnegative().nullable(),cacheHitRate:u().min(0).max(1).nullable(),cacheTelemetryCoverage:u().min(0).max(1),providers:f(Yr)});c({generatedAt:r().trim().min(1),sessionId:r().trim().min(1),turns:f(qN)});const BN=b(["usage_spike","model_usage_spike","latency_regression","failure_cluster","missing_usage_frames"]);c({type:BN,title:r().trim().min(1),summary:r().trim().min(1),severity:b(["nit","concern","blocker"]),payload:ie(r(),ce()).default({})});const FN=b(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),VN=b(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),KN=b(["native_bot","oauth_connector","wallet_connector","mcp_endpoint"]),WN=c({kind:S("integration"),provider:FN,appIds:f(VN).min(1).max(4),setupSurfaces:f(KN).min(1).max(4),connectionIds:f(r().trim().min(1)).max(8).optional(),capabilities:f(r().trim().min(1)).max(64).optional()}).strict(),Dr={maxAttachments:10,maxAttachmentBytes:12*1024*1024,maxAttachmentBase64Chars:Math.ceil(12*1024*1024*4/3)+16,maxTextChars:2e5},GN=b(["image","text","file"]),ZN=c({sessionId:r().trim().min(1).max(200),turnId:r().trim().min(1).max(200),attachmentId:r().trim().min(1).max(200),storageName:r().trim().min(1).max(240),contentType:r().trim().min(1).max(160)}),JN=c({sessionId:r().trim().min(1).max(200),turnId:r().trim().min(1).max(200),attachmentId:r().trim().min(1).max(200),storageName:r().trim().min(1).max(1024),contentType:r().trim().min(1).max(160)}),Zx=c({id:r().trim().min(1),name:r().trim().min(1).max(240),mediaType:r().trim().min(1).max(160),sizeBytes:u().int().nonnegative().max(Dr.maxAttachmentBytes),kind:GN,lineCount:u().int().nonnegative().max(Dr.maxAttachmentBytes+1).optional(),relativePath:r().trim().min(1).max(1024).optional(),text:r().max(Dr.maxTextChars).optional(),contentsBase64:r().max(Dr.maxAttachmentBase64Chars).optional()}),YN=Zx.omit({text:!0,contentsBase64:!0}).extend({imagePreview:ZN.optional(),filePreview:JN.optional()});c({experience:Zh.optional(),provider:fs.default(Fr),modelRef:mn.optional(),openPondCommandAccessMode:Ql.optional(),systemKind:Lx.nullable().optional(),hiddenFromDefaultSidebar:A().optional(),parentSessionId:r().trim().min(1).max(200).nullable().optional(),parentTurnId:r().trim().min(1).max(200).nullable().optional(),subagentRunId:r().trim().min(1).max(200).nullable().optional(),subagentRoleId:ps.nullable().optional(),subagentDelegationMode:tu.nullable().optional(),appId:r().nullable().optional(),appName:r().nullable().optional(),workspaceKind:Xl.optional(),workspaceId:r().nullable().optional(),workspaceName:r().nullable().optional(),localProjectId:r().nullable().optional(),cloudProjectId:r().nullable().optional(),cloudTeamId:r().nullable().optional(),currentProfile:hr.nullable().optional(),profileWorkflowBinding:$l.shape.profileWorkflowBinding,profileComponentBinding:$l.shape.profileComponentBinding,metadata:ie(r(),ce()).optional(),cwd:r().nullable().optional(),title:r().optional(),autoTitlePrompt:r().trim().min(1).max(2e4).optional()});c({teamId:r().trim().min(1),projectName:r().trim().min(1).max(120).optional(),branch:r().trim().min(1).max(120).optional(),chatSessionId:r().trim().min(1).max(200).optional(),displayPrompt:r().trim().min(1).max(2e3).optional()});c({branch:r().trim().min(1).max(120).optional()});c({prompt:r().min(1),workflowInput:ce().optional(),metadata:ie(r(),ce()).optional(),usageAttribution:TN.optional().nullable(),cwd:r().nullable().optional(),model:r().nullable().optional(),modelRef:mn.optional(),mentionedAppIds:f(r().trim().min(1)).max(8).optional(),mentionedConnectedApps:f(WN).max(8).optional(),openPondActionCatalog:f(Ux).max(100).optional(),attachments:f(Zx).max(Dr.maxAttachments).optional(),createImproveRun:ec.optional().nullable(),approvalPolicy:b(["untrusted","on-failure","on-request","never"]).default("on-request"),sandbox:b(["read-only","workspace-write","danger-full-access"]).default("workspace-write"),codexPermissionMode:Wh.default("default"),codexReasoningEffort:ru.optional()});c({prompt:r().min(1),error:r().min(1),target:b(["cloud_workspace","hybrid_sandbox"])});c({reason:b(["manual"]).default("manual"),model:r().nullable().optional(),modelRef:mn.optional()});c({experience:Zh.optional(),provider:fs.optional(),modelRef:mn.nullable().optional(),openPondCommandAccessMode:Ql.optional(),pinned:A().optional(),savedForLater:A().optional(),archived:A().optional(),order:u().optional(),title:r().optional(),parentSessionId:r().trim().min(1).max(200).nullable().optional(),parentTurnId:r().trim().min(1).max(200).nullable().optional(),subagentRunId:r().trim().min(1).max(200).nullable().optional(),subagentRoleId:ps.nullable().optional(),subagentDelegationMode:tu.nullable().optional(),appId:r().nullable().optional(),appName:r().nullable().optional(),workspaceKind:Xl.optional(),workspaceId:r().nullable().optional(),workspaceName:r().nullable().optional(),localProjectId:r().nullable().optional(),cloudProjectId:r().nullable().optional(),cloudTeamId:r().nullable().optional(),currentProfile:hr.nullable().optional(),metadata:ie(r(),ce()).optional(),cwd:r().nullable().optional()});c({command:r().trim().min(1),cwd:r().trim().min(1).max(4096).nullable().optional(),timeoutSeconds:u().int().min(1).max(3600).optional()});c({appIds:f(r()).min(1)});c({expectedRevision:r().optional(),defaultChatProvider:fs.optional(),defaultChatModel:r().min(1).optional(),defaultChatModelRef:mn.nullable().optional(),subagents:Tl.optional(),codexPermissionMode:Wh.optional(),codexReasoningEffort:ru.optional(),openPondCommandAccessMode:Ql.optional(),defaultBranchPrefix:r().trim().max(48).optional(),defaultNewProjectDirectory:r().trim().max(4096).optional(),defaultTeamId:r().trim().max(191).nullable().optional(),advancedWorkspaceControls:A().optional(),steerActiveResponses:A().optional(),contextCompaction:If.optional(),training:_f.optional(),sidebarWidth:u().int().min(244).max(560).optional(),diffPanelWidth:u().int().min(320).max(2400).optional(),sidebarSectionsCollapsed:wf.optional(),editor:_d.optional()});c({message:r().trim().min(1).max(4e3),surface:r().trim().min(1).max(120).default("app"),stack:r().max(12e3).nullable().optional(),context:ie(r(),ce()).optional()}).strict();c({activeTemplateId:Gh,templateName:r().trim().min(1).max(80),soul:r().trim().min(1).max(8e3),saveAsNew:A().optional().default(!1)});c({decision:b(["accept","acceptForSession","decline","cancel"])});c({branch:r().trim().min(1).max(240).nullable().optional(),surface:b(["desktop","terminal"])});c({handle:r().min(1),baseUrl:r().nullable().optional()});c({handle:r().min(1),baseUrl:r().nullable().optional()});c({handle:r().min(1).optional(),apiKey:r().min(1),baseUrl:r().nullable().optional(),apiBaseUrl:r().nullable().optional(),chatApiBaseUrl:r().nullable().optional(),environment:r().nullable().optional(),setActive:A().optional()});c({handle:r().min(1),currentBaseUrl:r().nullable().optional(),baseUrl:r().nullable().optional(),apiBaseUrl:r().nullable().optional(),chatApiBaseUrl:r().nullable().optional(),environment:r().nullable().optional(),setActive:A().optional()});c({appId:r(),exists:A(),configPath:r().nullable().optional(),envVar:r().nullable(),toolName:r().nullable(),version:Dt([r(),u()]).nullable(),source:b(["hosted_env","local_file","defaults","missing"]),currentConfig:ie(r(),ce()).nullable(),defaults:ie(r(),ce()).nullable(),schema:ie(r(),ce()).nullable(),error:r().nullable().optional(),updatedAt:r()}).passthrough();const Td=b(["create_sandbox_template_scaffold","resource_read","resource_search","list_files","read_files","search_files","preview_write_files","preview_write_file","preview_edit_file","preview_delete_file","write_files","write_file","edit_file","delete_file","workspace_status","validate_sandbox_template","build_sandbox_template","run_sandbox_template","git_init","git_status","git_diff","git_fetch","git_commit","git_push","publish_openpond_repo","sandbox_create","sandbox_templates","sandbox_template_launch","sandbox_status","sandbox_start","sandbox_list_files","sandbox_read_file","sandbox_search_files","sandbox_upload_file","sandbox_write_file","sandbox_edit_file","sandbox_delete_file","sandbox_mkdir","sandbox_move_file","sandbox_exec","sandbox_git_status","sandbox_git_diff","sandbox_git_export_patch","sandbox_git_apply_patch_local","sandbox_git_branch","sandbox_git_commit","sandbox_git_pull","sandbox_git_push","sandbox_preserve_source","sandbox_promote_source","sandbox_run_action","sandbox_open_port","sandbox_snapshot_catalog","sandbox_snapshot_create","sandbox_snapshot_update","sandbox_snapshot_validate","sandbox_snapshot_publish","sandbox_replays","sandbox_replay_start","sandbox_replay_get","sandbox_replay_logs","sandbox_replay_artifacts","sandbox_replay_cancel","sandbox_logs","sandbox_receipts","sandbox_prepare_agent","sandbox_save_agent_package","sandbox_save_output","work_agent_package_install","work_output_delete","work_output_read","sandbox_schedule_create","sandbox_stop"]);c({action:Td,args:ie(r(),ce()).optional().default({}),source:b(["ui_button","chat_action","terminal_command","hook"]).default("chat_action")});c({ok:A(),action:Td,appId:r().nullable().optional(),output:r(),data:ce().optional()});const oc=c({id:r().trim().min(1).max(200),title:r().trim().min(1).max(240),sourceTaskId:r().trim().min(1).max(200),sourceTurnId:r().trim().min(1).max(200),revision:u().int().positive().default(1),createdAt:r().datetime()}),rc=c({kind:b(["structural","visual","test","user_review"]),status:b(["passed","failed","not_run"]),label:r().trim().min(1).max(240),detail:r().trim().max(4e3).nullable().optional(),ref:r().trim().max(4096).nullable().optional()}),Jx=c({kind:S("local"),path:r().trim().min(1).max(4096),deviceId:r().trim().min(1).max(200)}),Yx=c({kind:S("managed"),fileId:r().trim().min(1).max(200),downloadPath:r().trim().min(1).max(4096)}),QN=c({kind:S("external"),provider:r().trim().min(1).max(120),resourceId:r().trim().min(1).max(500),url:r().url().nullable()}),Qx=oc.extend({kind:S("file"),contentType:r().trim().min(1).max(200),sizeBytes:u().int().nonnegative(),sha256:r().regex(/^[a-f0-9]{64}$/),location:Rt("kind",[Jx,Yx,QN]),validation:f(rc).max(32).default([])}),XN=oc.extend({kind:S("source_change"),projectId:r().trim().min(1).max(200),ref:r().trim().min(1).max(500),url:r().url().nullable(),validation:f(rc).max(32).default([])}),eD=oc.extend({kind:S("deployment"),deploymentId:r().trim().min(1).max(200),url:r().url(),validation:f(rc).max(32).default([])}),tD=oc.extend({kind:S("external_resource"),provider:r().trim().min(1).max(120),resourceId:r().trim().min(1).max(500),url:r().url(),contentType:r().trim().min(1).max(200).nullable(),validation:f(rc).max(32).default([])}),Xx=c({id:r().trim().min(1).max(191),label:r().trim().min(1).max(160).nullable(),description:r().trim().max(1e3).nullable(),inputSchema:ie(r(),ce()).nullable(),outputSchema:ie(r(),ce()).nullable(),schedulePolicy:ie(r(),ce()).nullable()}),ew=c({base:r().trim().min(1).max(200),resources:ie(r(),ce()),modelPolicy:ie(r(),ce()).nullable(),setup:ie(r(),ce()).nullable()}),nD=c({id:r().trim().min(1).max(200),kind:b(["sdk_validation","sdk_eval"]),status:b(["passed","failed"]),summary:r().trim().min(1).max(2e3),artifactPath:r().trim().min(1).max(4096),artifactSha256:r().regex(/^[a-f0-9]{64}$/)}),aD=c({path:r().trim().min(1).max(4096),sizeBytes:u().int().nonnegative(),sha256:r().regex(/^[a-f0-9]{64}$/),contentsBase64:r()});c({schema:S("openpond.agent-package.v1"),agentId:r().trim().min(1).max(191),versionId:r().trim().min(1).max(200),digest:r().regex(/^[a-f0-9]{64}$/),title:r().trim().min(1).max(240),source:c({files:f(aD).min(1).max(1e3),totalSizeBytes:u().int().nonnegative()}),manifest:ie(r(),ce()),actions:f(Xx).min(1).max(256),runtimeRequirements:ew,receipts:f(nD).min(2).max(64)});const oD=oc.extend({kind:S("agent_package"),agentId:r().trim().min(1).max(191),versionId:r().trim().min(1).max(200),digest:r().regex(/^[a-f0-9]{64}$/),packageFileId:r().trim().min(1).max(200),manifestFileId:r().trim().min(1).max(200),actions:f(Xx).min(1).max(256),runtimeRequirements:ew,validationReceiptIds:f(r().trim().min(1).max(200)).min(1).max(32),evalReceiptIds:f(r().trim().min(1).max(200)).min(1).max(32),sourceFileCount:u().int().positive(),sourceSizeBytes:u().int().nonnegative(),location:Rt("kind",[Jx,Yx]),validation:f(rc).max(32).default([])}),dY=Rt("kind",[Qx,XN,eD,tD,oD]);c({outputs:f(Qx)});const rD=b(["sandbox_template","sandbox","generic_git","plain_folder"]),iD=b(["sandbox_template"]).nullable();c({productKind:rD,actions:c({files:A(),git:A(),sandboxRuntime:A(),sandboxTemplate:A()}),checks:c({validate:Td.nullable(),build:Td.nullable(),postEdit:iD}),ui:c({showSandboxTemplateActions:A(),showSandboxRuntimeActions:A()})});const sD=c({id:r(),name:r(),dnsName:r().nullable(),os:r().nullable(),online:A(),active:A(),isSelf:A(),tailscaleIps:f(r()),lastSeen:r().nullable()}),lD=c({installed:A(),running:A(),version:r().nullable(),backendState:r().nullable(),tailnetName:r().nullable(),magicDnsSuffix:r().nullable(),machineName:r().nullable(),dnsName:r().nullable(),authUrl:r().nullable(),tailscaleIps:f(r()),health:f(r()),error:r().nullable(),peers:f(sD)}),cD=c({enabled:A(),reachable:A(),targetUrl:r().nullable(),httpsUrl:r().nullable(),httpsHost:r().nullable(),httpsPort:u().nullable(),setupUrl:r().nullable(),configText:r().nullable(),error:r().nullable()}),dD=c({localUrl:r(),localWebUrl:r(),remoteUrl:r().nullable(),remoteWebUrl:r().nullable(),tokenHash:r(),tailscaleUpCommand:r(),serveCommand:r(),disableCommand:r(),operatorCommand:r(),webUiAvailable:A(),updatedAt:r(),tailscale:lD,serve:cD});c({message:r(),status:dD});const tw=b(["github","openpond_git"]),nw=b(["private","public"]),uD=b(["actions","workflows","instructions","prompts","goals","evals","examples","tasksets","extensions"]),mD=c({agentIds:f(r().trim().min(1)).max(100),skillNames:f(r().trim().min(1)).max(200),optionalContent:f(uD).max(20).default([])}),aw=c({provider:tw,owner:r().trim().min(1).max(191).nullable().optional(),repository:r().trim().min(1).max(191),visibility:nw.default("private")}),pD=c({ref:hr,selection:mD,target:aw}),fD=c({path:r(),sizeBytes:u().int().nonnegative(),category:r()});c({sourceHash:r(),sourceRevision:r().nullable(),clean:A(),blockedReasons:f(r()),warnings:f(r()),files:f(fD),excludedFiles:f(r()),target:aw,replacesExisting:A()});pD.extend({expectedSourceHash:r().trim().min(1),confirmed:S(!0)});c({provider:tw,owner:r(),repository:r(),visibility:nw,remoteUrl:r(),webUrl:r(),revision:r()});const hD=b(["cron","rate"]),ow=b(["queued","running","succeeded","failed","skipped"]),pg=c({id:r(),localProjectId:r(),localProjectName:r(),agentRootPath:r(),agentName:r(),scheduleName:r(),scheduleType:hD,scheduleExpression:r(),timezone:r().nullable(),targetAction:r(),input:ie(r(),ce()).optional().default({}),enabledByDefault:A(),enabled:A(),sourceHash:r(),manifestHash:r().nullable(),agentVersionId:r().nullable().optional(),agentPackageDigest:r().nullable().optional(),nextRunAt:r().nullable(),lastRunAt:r().nullable(),lastRunStatus:ow.nullable(),lastRunId:r().nullable(),lastError:r().nullable(),createdAt:r(),updatedAt:r()}),rw=c({id:r(),scheduleId:r(),definitionSnapshot:pg.optional(),configurationSnapshot:ie(r(),ce()).optional(),inputSnapshot:ie(r(),ce()).optional(),localProjectId:r(),scheduleName:r(),scheduledFor:r(),trigger:b(["schedule","manual"]),status:ow,targetAction:r(),agentVersionId:r().nullable().optional(),agentPackageDigest:r().nullable().optional(),startedAt:r().nullable(),completedAt:r().nullable(),exitCode:u().int().nullable(),stdout:r().nullable(),stderr:r().nullable(),result:ie(r(),ce()).nullable(),traceArtifactRef:r().nullable(),error:r().nullable(),createdAt:r(),updatedAt:r()});c({schedules:f(pg),scheduler:c({running:A(),nextTickAt:r().nullable(),lastSyncAt:r().nullable(),scanRunning:A()})});c({runs:f(rw)});c({enabled:A().optional()});c({input:ie(r(),ce()).optional()});c({schedule:pg,run:rw});const gD=b(["sunday","monday","tuesday","wednesday","thursday","friday","saturday"]),vs=c({version:S(1),kind:b(["once","daily","weekdays","weekly","monthly"]),timeZone:r().trim().min(1).max(100),startDate:r().regex(/^\d{4}-\d{2}-\d{2}$/),localTime:r().regex(/^([01]\d|2[0-3]):([0-5]\d)$/),weekdays:f(gD).min(1).max(7).optional(),dayOfMonth:u().int().min(1).max(31).optional(),end:Rt("kind",[c({kind:S("never")}),c({kind:S("on_date"),date:r().regex(/^\d{4}-\d{2}-\d{2}$/)}),c({kind:S("after_occurrences"),occurrences:u().int().min(1).max(1e5)})])}).superRefine((e,t)=>{e.kind==="weekly"&&!e.weekdays?.length&&t.addIssue({code:"custom",message:"Weekly recurrence requires at least one weekday.",path:["weekdays"]}),e.kind==="monthly"&&e.dayOfMonth===void 0&&t.addIssue({code:"custom",message:"Monthly recurrence requires a day of month.",path:["dayOfMonth"]})}),vD=c({id:r(),expression:r().nullable(),timeZone:r(),recurrence:vs.nullable(),configurationVersion:u().int(),enabled:A(),nextRunAt:r().nullable(),lastTriggeredAt:r().nullable(),delivery:ie(r(),ce()).default({})}),bD=c({id:r(),definitionKey:r(),version:u().int(),name:r(),prompt:r(),modelId:r(),schedules:f(vD)}),yD=c({id:r(),definitionId:r(),scheduleId:r().nullable(),definitionName:r(),definitionVersion:u().int(),conversationId:r(),triggerKind:b(["manual","schedule","webhook","retry"]),status:r(),notificationStatus:r(),deliveryStatus:r(),deliveryError:r().nullable(),createdAt:r()});c({definitions:f(bD),runs:f(yD),asOf:r(),webBaseUrl:r().url().optional()});c({clientRequestId:r().trim().min(1).max(191),sourceTurnId:r().trim().min(1).max(191).nullable().optional(),targetSessionId:r().trim().min(1).max(191).nullable().optional(),name:r().trim().min(1).max(180),prompt:r().trim().min(1).max(2e4),recurrence:vs,modelId:r().trim().min(1).max(191).default("openpond-chat")});Dt([c({enabled:A()}),c({name:r().trim().min(1).max(180),prompt:r().trim().min(1).max(2e4),recurrence:vs})]);const iw=b(["queued","running","succeeded","failed"]),sw=c({id:r(),sessionId:r(),sessionTitle:r(),sourceTurnId:r().nullable(),name:r(),prompt:r(),profileRef:hr.optional(),profileWorkflowId:r().optional(),profileMigrationError:r().nullable().optional(),recurrence:vs,enabled:A(),nextRunAt:r().nullable(),lastRunAt:r().nullable(),lastRunStatus:iw.nullable(),lastRunId:r().nullable(),lastError:r().nullable(),scheduledRunCount:u().int().nonnegative(),createdAt:r(),updatedAt:r()}),SD=c({definitionSnapshot:sw.optional(),configurationSnapshot:ie(r(),ce()).optional(),id:r(),workflowId:r(),sessionId:r(),scheduledFor:r(),trigger:b(["schedule","manual"]),status:iw,turnId:r().nullable(),error:r().nullable(),createdAt:r(),startedAt:r().nullable(),completedAt:r().nullable(),updatedAt:r()});c({sessionId:r().trim().min(1).max(191),sourceTurnId:r().trim().min(1).max(191).nullable().optional(),name:r().trim().min(1).max(180),prompt:r().trim().min(1).max(2e4),recurrence:vs});Dt([c({enabled:A()}),c({name:r().trim().min(1).max(180),prompt:r().trim().min(1).max(2e4),recurrence:vs})]);c({workflows:f(sw),runs:f(SD),asOf:r()});const fg=ie(r(),ce());c({userId:r(),role:b(["owner","admin","member"]),name:r(),handle:r().nullable(),image:r().nullable()});const kD=c({userId:r(),role:b(["owner","admin","member"]),name:r(),handle:r().nullable(),image:r().nullable(),lastReadSequence:u().int().nonnegative()}),xD=c({id:r(),messageId:r(),refType:b(["hosted_ai_thread","goal","openpond_session","project","agent_run","message_reply"]),refId:r(),preview:fg,createdAt:r()}),lw=c({id:r(),messageId:r().nullable(),clientAttachmentId:r(),kind:S("image"),name:r(),mediaType:b(["image/png","image/jpeg","image/webp","image/gif"]),sizeBytes:u().int().positive(),status:b(["pending","ready","failed"]),createdAt:r(),readyAt:r().nullable()});c({attachment:lw,uploadUrl:r().url().nullable(),uploadHeaders:ie(r(),r()),expiresAt:r().nullable()});c({url:r().url(),expiresAt:r()});const hg=c({id:r(),threadId:r(),teamId:r(),clientRequestId:r().nullable(),authorType:b(["user","agent","system"]),authorUserId:r().nullable(),authorAgentId:r().nullable(),sequence:u().int().nonnegative(),kind:b(["text","system","command_result"]),body:r(),metadata:fg,editedAt:r().nullable(),deletedAt:r().nullable(),createdAt:r(),refs:f(xD),attachments:f(lw)}),wD=c({id:r(),teamId:r(),kind:b(["general","dm","group","channel"]),title:r().nullable(),createdByUserId:r(),lastMessageId:r().nullable(),lastMessageSequence:u().int().nonnegative(),lastMessageAt:r(),createdAt:r(),updatedAt:r(),unreadCount:u().int().nonnegative(),pinnedAt:r().nullable(),mutedAt:r().nullable(),archivedAt:r().nullable(),participants:f(kD),lastMessage:hg.nullable()});c({thread:wD,messages:f(hg),hasMoreBefore:A()});c({threadId:r(),mutedAt:r().nullable()});const ID=b(["pending","running","completed","failed","interrupted","cancelled"]),ty=c({id:r(),conversationId:r(),threadId:r(),teamId:r(),requestedByUserId:r(),executorUserId:r().nullable(),providerId:r(),modelId:r(),clientRequestId:r(),baseMessageSequence:u().int().nonnegative(),status:ID,partialBody:r().nullable(),userMessageId:r(),assistantMessageId:r().nullable(),errorCode:r().nullable(),cancelledByUserId:r().nullable(),leaseExpiresAt:r().nullable(),heartbeatAt:r().nullable(),createdAt:r(),updatedAt:r()}),_D=c({id:r(),conversationId:r(),sequence:u().int().nonnegative(),role:b(["user","assistant","system","action"]),body:r(),createdByUserId:r().nullable(),createdAt:r()});c({conversationId:r(),parentThreadId:r(),parentMessageId:r(),teamId:r(),title:r().nullable(),providerId:r().nullable(),modelId:r(),createdByUserId:r(),messages:f(_D),turns:f(ty),activeTurn:ty.nullable(),createdAt:r(),updatedAt:r()});const cw=c({id:u().int().nonnegative(),teamId:r(),threadId:r(),conversationId:r().nullable(),type:b(["thread.created","message.created","message.updated","message.deleted","read.updated","ai_thread.created","ai_turn.updated"]),payload:fg,createdAt:r()});c({events:f(cw),cursor:u().int().nonnegative(),hasMore:A()});c({httpUrl:r().min(1),realtimeUrl:r().min(1),region:r().min(1),token:r().min(1),expiresAt:r().min(1),teamId:r().min(1),userId:r().min(1)});const gg=ie(r(),ce()),xa=r().nullable(),CD=b(["draft","published","archived"]),vg=b(["owner","admin","member"]),dw=b(["active","left"]),uw=b(["mentions","all","none"]),mw=b(["public_preview","members"]),RD=b(["members","admins"]),PD=c({canPreview:A(),canJoin:A(),canLeave:A(),canRead:A(),canPost:A(),canUpload:A(),canMention:A(),canManage:A(),requiresRulesAcceptance:A(),currentRulesVersionId:r().nullable()}),pw=c({id:r(),communityId:r(),version:u().int().positive(),title:r(),requiresReacceptance:A(),publishedAt:r()}),AD=pw.extend({bodyMarkdown:r(),contentHash:r()}),TD=c({role:vg,status:dw,notificationMode:uw}),ED=c({id:r(),communityId:r(),userId:r(),role:vg,status:dw,notificationMode:uw,joinedAt:r(),leftAt:xa,createdAt:r(),updatedAt:r()}),fw=c({id:r(),slug:r(),displayName:r(),description:r(),imageUrl:r().nullable(),status:CD,visibility:b(["public","private"]),joinPolicy:b(["open","closed"]),historyVisibility:mw,featuredAt:xa,publishedAt:xa,archivedAt:xa,memberCount:u().int().nonnegative(),membership:TD.nullable(),capabilities:PD,currentRules:pw.nullable()});c({items:f(fw),nextCursor:r().nullable()});const hw=c({lastReadSequence:u().int().nonnegative(),lastReadAt:xa.optional(),mutedAt:xa,pinnedAt:xa}),bg=c({id:r(),communityId:r(),chatThreadId:r().nullable(),slug:r(),displayName:r(),topic:r(),position:u().int().nonnegative(),visibility:mw,postingPolicy:RD,isDefault:A(),archivedAt:xa,lastMessageSequence:u().int().nonnegative(),unreadCount:u().int().nonnegative(),readState:hw.nullable()});fw.omit({currentRules:!0}).extend({currentRules:AD.nullable(),channels:f(bg),previewMessageLimit:u().int().positive()});const MD=c({id:r(),messageId:r(),refType:b(["hosted_ai_thread","goal","openpond_session","project","agent_run","message_reply"]),refId:r(),preview:gg,createdAt:r()}),gw=c({id:r(),messageId:r().nullable(),clientAttachmentId:r(),kind:S("image"),name:r(),mediaType:b(["image/png","image/jpeg","image/webp","image/gif"]),sizeBytes:u().int().positive(),status:b(["pending","ready","failed"]),createdAt:r(),readyAt:xa});c({attachment:gw,uploadUrl:r().url().nullable(),uploadHeaders:ie(r(),r()),expiresAt:xa});c({url:r().url(),expiresAt:r()});const vw=c({id:r(),threadId:r(),teamId:Xd(),clientRequestId:r().nullable(),authorType:b(["user","agent","system"]),authorUserId:r().nullable(),authorAgentId:r().nullable(),sequence:u().int().nonnegative(),kind:b(["text","system","command_result"]),body:r(),metadata:gg,editedAt:xa,deletedAt:xa,createdAt:r(),refs:f(MD),attachments:f(gw)});c({messages:f(vw),hasMoreBefore:A(),channelId:r(),readState:hw.omit({lastReadAt:!0}).nullable(),preview:A()});const jD=c({userId:r(),handle:r().nullable(),name:r().nullable(),role:vg});c({items:f(jD),nextCursor:r().nullable()});const bw=c({id:u().int().nonnegative(),communityId:r(),channelId:r(),threadId:r(),type:b(["thread.created","message.created","message.updated","message.deleted","read.updated"]),payload:gg,createdAt:r()});c({events:f(bw),cursor:u().int().nonnegative(),hasMore:A()});c({httpUrl:r().min(1),realtimeUrl:r().min(1),region:r().min(1),token:r().min(1),expiresAt:r().min(1),communityId:r().min(1),userId:r().min(1),channel:r().min(1)});c({membership:ED,channels:f(bg)});c({channels:f(bg)});var OD=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),$D=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function ND(e){const t=typeof e=="string"?new TextEncoder().encode(e):e,n=Math.ceil((t.byteLength+9)/64)*64,a=new Uint8Array(n);a.set(t),a[t.byteLength]=128;const o=t.byteLength*8,i=new DataView(a.buffer);i.setUint32(n-8,Math.floor(o/4294967296),!1),i.setUint32(n-4,o>>>0,!1);const s=new Uint32Array(OD),l=new Uint32Array(64);for(let m=0;m<n;m+=64){for(let P=0;P<16;P+=1)l[P]=i.getUint32(m+P*4,!1);for(let P=16;P<64;P+=1){const N=l[P-15],O=l[P-2],j=oo(N,7)^oo(N,18)^N>>>3,k=oo(O,17)^oo(O,19)^O>>>10;l[P]=l[P-16]+j+l[P-7]+k>>>0}let d=s[0],h=s[1],v=s[2],y=s[3],w=s[4],I=s[5],R=s[6],M=s[7];for(let P=0;P<64;P+=1){const N=w&I^~w&R,O=d&h^d&v^h&v,j=oo(d,2)^oo(d,13)^oo(d,22),k=oo(w,6)^oo(w,11)^oo(w,25),C=M+k+N+$D[P]+l[P]>>>0,T=j+O>>>0;M=R,R=I,I=w,w=y+C>>>0,y=v,v=h,h=d,d=C+T>>>0}s[0]=s[0]+d>>>0,s[1]=s[1]+h>>>0,s[2]=s[2]+v>>>0,s[3]=s[3]+y>>>0,s[4]=s[4]+w>>>0,s[5]=s[5]+I>>>0,s[6]=s[6]+R>>>0,s[7]=s[7]+M>>>0}return Array.from(s,m=>m.toString(16).padStart(8,"0")).join("")}function oo(e,t){return e>>>t|e<<32-t}var DD=2e3,yw=25e7,He=r().trim().min(1).max(240),Ye=r().regex(/^[a-f0-9]{64}$/),_t=r().datetime({offset:!0}),pu=ie(r(),ce()).default({}),Je=c({id:He,contentHash:Ye}).strict(),LD=Je.extend({revision:u().int().positive()}).strict(),sr=c({id:He,path:r().trim().min(1).max(DD).refine(qD),contentHash:Ye,sizeBytes:u().int().nonnegative().max(yw),mediaType:r().trim().min(1).max(200),visibility:b(["policy","verifier","host_private"])}).strict(),UD=c({id:He,contentHash:Ye,mediaType:r().trim().min(1).max(200).nullable().default(null),sizeBytes:u().int().nonnegative().max(yw).nullable().default(null)}).strict(),zD=b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]);function HD(e){return`${JSON.stringify(Ef(e),null,2)}
|
|
175
|
+
`}function Sw(e){return ND(e)}function qr(e){return Sw(HD(e))}function qD(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function Ef(e){return Array.isArray(e)?e.map(Ef):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,Ef(n)]))}var BD=b(["memory","prompt","skill","agent"]),FD=b(["runtime","product","taskset","training"]),VD=c({id:r().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),text:r().trim().min(1).max(1e4)}).strict(),KD=c({schemaVersion:S("openpond.refinerReviewProfile.v1"),id:r().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),version:r().trim().min(1).max(120),name:r().trim().min(1).max(200),objective:r().trim().min(1).max(1e4),instructions:f(VD).max(100),allowedProposalRoutes:f(BD).max(4),allowedExternalRoutes:f(FD).max(4)}).strict().superRefine((e,t)=>{const n=e.instructions.map(a=>a.id);new Set(n).size!==n.length&&t.addIssue({code:"custom",message:"instruction IDs must be unique",path:["instructions"]}),new Set(e.allowedProposalRoutes).size!==e.allowedProposalRoutes.length&&t.addIssue({code:"custom",message:"proposal routes must be unique",path:["allowedProposalRoutes"]}),new Set(e.allowedExternalRoutes).size!==e.allowedExternalRoutes.length&&t.addIssue({code:"custom",message:"external routes must be unique",path:["allowedExternalRoutes"]})});c({schemaVersion:S("openpond.refinerRelease.v1"),id:r().trim().min(1).max(240),coreVersion:r().trim().min(1).max(120),coreHash:Ye,profile:KD,profileHash:Ye,composedPromptHash:Ye,createdAt:_t,contentHash:Ye}).strict();c({schemaVersion:S("openpond.refinerBinding.v1"),channel:S("active"),revision:u().int().nonnegative(),release:Je,updatedAt:_t}).strict();c({schemaVersion:S("openpond.refinerTransitionReceipt.v1"),id:r().trim().min(1).max(240),operation:b(["initialize","update","activate","rollback"]),bindingChanged:A(),previousRelease:Je.nullable(),nextRelease:Je,actor:r().trim().min(1).max(240),reason:r().trim().min(1).max(1e4),authoringSkillHash:Ye.nullable(),validation:c({valid:A(),messages:f(r().max(2e3)).max(100)}).strict(),createdAt:_t,contentHash:Ye}).strict();var WD=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v1"),decision:S("no_action"),reason:r().trim().min(1).max(1e4)}).strip(),GD=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v1"),decision:S("route"),route:b(["runtime","product","taskset","training"]),summary:r().trim().min(1).max(2e3),expectedOutcome:r().trim().min(1).max(1e4),reason:r().trim().min(1).max(1e4)}).strip(),ZD=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v1"),decision:S("propose"),route:b(["memory","prompt","skill","agent"]),operation:b(["create","update","delete"]),target:r().trim().min(1).max(2e3),summary:r().trim().min(1).max(2e3),createContent:r().min(1).max(2e4).nullable(),find:r().min(1).max(8e3).nullable(),replace:r().max(8e3).nullable(),expectedOutcome:r().trim().min(1).max(1e4),reason:r().trim().min(1).max(1e4)}).strip().superRefine((e,t)=>{e.operation==="create"&&(e.createContent===null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"create proposals require createContent and null find/replace",path:["createContent"]}),e.operation==="update"&&(e.createContent!==null||e.find===null||e.replace===null)&&t.addIssue({code:"custom",message:"update proposals require one exact find/replace edit and null createContent",path:["find"]}),e.operation==="delete"&&(e.createContent!==null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"delete proposals require null createContent/find/replace",path:["createContent"]})}),JD=Rt("decision",[WD,GD,ZD]),YD=JD,yg=c({kind:b(["single_deterministic","recurrent_independent"]),supportingEvidenceIds:f(r().trim().min(1).max(2e3)).min(1).max(100),counterevidence:f(r().trim().min(1).max(2e3)).max(20)}).strict().superRefine((e,t)=>{new Set(e.supportingEvidenceIds).size!==e.supportingEvidenceIds.length&&t.addIssue({code:"custom",message:"supporting evidence IDs must be unique",path:["supportingEvidenceIds"]}),e.kind==="recurrent_independent"&&e.supportingEvidenceIds.length<2&&t.addIssue({code:"custom",message:"recurrent independent evidence requires at least two supplied incidents",path:["supportingEvidenceIds"]})}),QD=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("no_action"),reason:r().trim().min(1).max(1e4)}).strict(),XD=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("route"),route:b(["runtime","product","taskset","training"]),summary:r().trim().min(1).max(2e3),evidenceBasis:yg,expectedOutcome:r().trim().min(1).max(1e4),reason:r().trim().min(1).max(1e4)}).strict(),eL=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("propose"),route:b(["memory","prompt","skill","agent"]),operation:b(["create","update","delete"]),target:r().trim().min(1).max(2e3),summary:r().trim().min(1).max(2e3),evidenceBasis:yg,createContent:r().min(1).max(2e4).nullable(),find:r().min(1).max(8e3).nullable(),replace:r().max(8e3).nullable(),expectedOutcome:r().trim().min(1).max(1e4),reason:r().trim().min(1).max(1e4)}).strict().superRefine((e,t)=>{e.operation==="create"&&(e.createContent===null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"create proposals require createContent and null find/replace",path:["createContent"]}),e.operation==="update"&&(e.createContent!==null||e.find===null||e.replace===null)&&t.addIssue({code:"custom",message:"update proposals require one exact find/replace edit and null createContent",path:["find"]}),e.operation==="delete"&&(e.createContent!==null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"delete proposals require null createContent/find/replace",path:["createContent"]})}),kw=Rt("decision",[QD,XD,eL]);Dt([YD,kw]);var Sg=c({memory:A(),prompt:A(),skill:A(),agent:A()}).strict(),xw=b(["memory","instruction","skill","agent"]),ny=c({path:r().trim().min(1).max(2e3),kind:xw,content:r().max(6e4),loaded:A()}).strict(),ay=c({path:r().trim().min(1).max(2e3),kind:xw,loaded:A()}).strict(),tL=c({capabilities:Sg,trigger:ie(r(),ce()),observations:f(ie(r(),ce())).max(20),admissibleEvidenceIds:f(r().trim().min(1).max(2e3)).max(1e4),reviewPacket:c({currentTurn:c({id:r().trim().min(1).max(2e3),status:r().trim().min(1).max(100).nullable(),error:r().max(2100).nullable(),prompt:r().max(8100).nullable(),assistantOutput:r().max(8100).nullable(),assistantOutputLinkCount:u().int().nonnegative()}).strict(),priorConversation:f(c({turnId:r().trim().min(1).max(2e3),status:r().trim().min(1).max(100).nullable(),prompt:r().max(3100).nullable(),assistantOutput:r().max(3100).nullable()}).strict()).max(3),timeline:f(ie(r(),ce())).max(60),artifacts:f(ie(r(),ce())).max(30),artifactDiagnostics:f(ie(r(),ce())).max(20),executionProfile:c({modelRequestCount:u().int().nonnegative(),failedModelRequestCount:u().int().nonnegative(),promptTokens:u().int().nonnegative(),completionTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative(),toolFailureCount:u().int().nonnegative(),retryCount:u().int().nonnegative(),recoveryCount:u().int().nonnegative()}).strict(),priorIncidents:f(ie(r(),ce())).max(3),truncation:c({timelineEventCount:u().int().nonnegative(),includedTimelineEventCount:u().int().nonnegative(),timelineTruncated:A()}).strict()}).strict(),runtimeActivation:c({admittedRelease:Je,currentRelease:Je,rebasedOntoCurrent:A(),admittedSourceFiles:f(ny).max(100),admittedSourceCatalog:f(ay).max(1e3)}).strict(),sourceFiles:f(ny).max(100),sourceCatalog:f(ay).max(1e3),additionalEvidence:ce().nullable().optional()}).strict(),nL=c({id:r().trim().min(1).max(240),revision:u().int().nonnegative(),contentHash:Ye}).strict();c({schemaVersion:S("openpond.hostedHarnessRefinerRequest.v2"),requestId:r().trim().min(1).max(240),idempotencyKey:r().trim().min(1).max(240),evidenceHash:Ye,harness:c({admittedRelease:Je,currentRelease:Je,overlay:nL,workspace:c({id:r().trim().min(1).max(240),revision:u().int().nonnegative(),sourceRevision:Ye,channelRevision:u().int().nonnegative()}).strict(),capabilities:Sg}).strict(),evidence:tL}).strict();var aL=c({promptTokens:u().int().nonnegative(),completionTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative()}).strict();c({schemaVersion:S("openpond.hostedHarnessRefinerResponse.v2"),requestId:r().trim().min(1).max(240),evidenceHash:Ye,admittedRelease:Je,currentRelease:Je,decision:kw,serviceRevision:r().trim().min(1).max(240),usage:aL}).strict();var ww=c({name:r().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:r().trim().min(1).max(2e3),inputSchema:ie(r(),ce()),inputSchemaHash:Ye,sideEffect:b(["read","write"]),timeoutMs:u().int().positive().max(36e5)}).strict(),oL=c({id:He,required:A(),scopes:f(r().trim().min(1).max(500)).max(100).default([]),portability:b(["portable","host_adapter","local_only","hosted_only"])}).strict(),rL=c({portable:A(),blockers:f(r().trim().min(1).max(2e3)).max(1e3),localOnlyAssetRefs:f(He).max(1e4),hostPrivateAssetRefs:f(He).max(1e4)}).strict(),iL=c({schemaVersion:S("openpond.agentSnapshot.v2"),id:He,sourceRelease:Je.nullable(),instructions:f(sr).max(1e4),skills:f(sr).max(1e4),agents:f(sr).max(1e4),toolDeclarations:f(ww).max(200),capabilityRequirements:f(oL).max(200),dependencyLock:sr,portability:rL,metadata:pu}).strict(),sL=iL.extend({contentHash:Ye}).strict(),lL=c({create:S(!0),reset:S(!0),step:S(!0),collect:S(!0),destroy:S(!0),resetScope:b(["task","attempt"])}).strict(),cL=c({visibleEvidence:f(He).max(1e3),privilegedEvidence:f(He).max(1e3),privateVerifierIsolation:A()}).strict(),dL=c({schemaVersion:S("openpond.harnessRelease.v2"),id:He,agentSnapshot:Je,program:sr,tools:f(ww).max(200),lifecycle:lL,graderInterface:cL,files:f(sr).max(1e5),metadata:pu}).strict(),uL=dL.extend({contentHash:Ye}).strict(),mL=c({id:He,turn:u().int().nonnegative(),kind:b(["message","tool_call","terminal"]),name:He.nullable(),arguments:ie(r(),ce()),content:r().max(1e6).nullable()}).strict(),pL=c({actionId:He,turn:u().int().nonnegative(),terminal:A(),output:ie(r(),ce()),artifactRefs:f(UD).max(1e5)}).strict(),fL=c({sequence:u().int().nonnegative(),type:b(["created","reset","action","observation","terminal","failure","collected","destroyed"]),payloadHash:Ye,metadata:pu}).strict();c({schemaVersion:S("openpond.harnessTrace.v1"),manifest:Je,taskId:He,seed:r().trim().min(1).max(500),events:f(fL).max(1e6),actions:f(mL).max(1e5),observations:f(pL).max(1e5),terminal:A(),failureClass:zD.nullable(),output:ie(r(),ce()),contentHash:Ye}).strict();var hL=25*1024*1024,gL=c({path:sr.shape.path,base64:r().max(Math.ceil(hL/3)*4)}).strict(),Iw=c({schemaVersion:S("openpond.harnessSourcePackage.v1"),agentSnapshot:sL,harnessRelease:uL,files:f(gL).max(1e4)}).strict();Iw.extend({contentHash:Ye}).strict();Iw.extend({schemaVersion:S("openpond.harnessPolicySourcePackage.v1"),contentHash:Ye}).strict();c({schemaVersion:S("openpond.harnessSourceSelection.v1"),mode:b(["taskset_owned","selected_release"]),harnessRelease:Je,sourcePackageHash:Ye.nullable()}).strict().superRefine((e,t)=>{e.mode==="selected_release"!=(e.sourcePackageHash!==null)&&t.addIssue({code:"custom",path:["sourcePackageHash"],message:"Only a selected release binds a source package."})});var zo=r().trim().min(1).max(1e5),vL=b(["no_action","harness_maintenance","runtime","product","taskset","model_improvement"]),bL=b(["none","runtime_service","product_team","human_review","evaluation_system","training_system"]),_w=b(["observation","trigger","route_decision","refiner_outcome","proposal","validation","apply_receipt","harness_advance","rollback","work_outcome","taskset","evaluation","training_qualification","model_candidate"]),kg=c({kind:b(["personal","team"]),id:He}).strict(),Cw=c({policy:Je,state:b(["authorized","revoked","deleted","expired"]),checkedAt:_t}).strict(),Nl=c({evidence:Je,kind:_w,sourceRef:He,sourcePolicy:Cw,occurrenceKey:Ye,occurredAt:_t}).strict(),yL=c({evidence:Je,sourcePolicy:Cw.nullable(),reason:b(["outside_scope","before_watermark","duplicate","resolved","revoked","deleted","expired","sensitive","unverified","budget"])}).strict(),oy=c({cursor:Ye,throughCreatedAt:_t}).strict(),SL=c({fingerprint:Ye,recurrenceFamily:r().trim().min(1).max(1e3),statement:zo,candidateDisposition:b(["observe","confirm"]).optional(),independentOccurrences:u().int().positive().max(1e6),unresolvedOccurrences:u().int().positive().max(1e6)}).strict().refine(e=>e.unresolvedOccurrences<=e.independentOccurrences,"unresolved occurrences cannot exceed independent occurrences"),Rw=b(["harness","runtime","product","retrieval","tools","evaluation","model"]),kL=c({layer:Rw,status:b(["not_applicable","unresolved","resolved","blocked"]),reason:zo,evidenceRefs:f(Je).max(1e3)}).strict(),xL=c({schemaVersion:S("openpond.harnessEvaluationReviewReceipt.v1"),id:He,ownerScope:kg,workspaceRef:He,harnessRelease:Je,previousWatermark:oy.nullable(),nextWatermark:oy,selectedEvidence:f(Nl).max(1e4),excludedEvidence:f(yL).max(1e4),claim:SL.nullable(),classification:vL,triage:f(kL).max(16),reason:zo,nextAuthority:bL,maxEstimatedCostUsd:u().finite().nonnegative(),tasksetProposal:Je.nullable(),evaluation:Je.nullable(),trainingQualification:Je.nullable(),policyVersion:He,createdAt:_t,metadata:pu}).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"})});xL.extend({contentHash:Ye}).strict();c({id:He,evidence:Je,kind:_w,sourceRef:He,occurredAt:_t,payload:ie(r(),ce())}).strict();var wL=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("no_action"),reason:zo,ignoredEvidence:f(c({id:He,reason:r().trim().min(1).max(2e3)}).strict()).max(1e3)}).strict(),IL=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("review"),classification:b(["harness_maintenance","runtime","product","taskset"]),selectedEvidenceIds:f(He).min(1).max(1e3),ignoredEvidence:f(c({id:He,reason:r().trim().min(1).max(2e3)}).strict()).max(1e3),recurrenceFamily:r().trim().min(1).max(1e3),statement:zo,triageLayer:Rw,expectedOutcome:zo,counterevidence:r().trim().max(1e4),confidence:u().min(0).max(1),candidateDisposition:b(["observe","confirm"]).nullable(),reason:zo}).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"]})}),_L=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("resolve_candidate"),candidateId:He,candidateFingerprint:Ye,selectedEvidenceIds:f(He).min(1).max(1e3),ignoredEvidence:f(c({id:He,reason:r().trim().min(1).max(2e3)}).strict()).max(1e3),confidence:u().min(0).max(1),reason:zo}).strict();Rt("decision",[wL,IL,_L]);c({schemaVersion:S("openpond.harnessEvaluationReviewNavigationDecision.v1"),selectedEvidenceIds:f(He).min(1).max(50),reason:zo}).strict();var bs=ie(r(),ce()).default({}),ka=u().int().nonnegative(),fu=r().trim().min(1).max(1e5),Pw=c({kind:b(["personal","team"]),id:He}).strict(),CL=c({name:He,release:Je.nullable(),revision:ka}).strict();c({schemaVersion:S("openpond.harnessWorkspace.v1"),id:He,ownerScope:Pw,name:r().trim().min(1).max(240),location:b(["local","hosted"]),sourceRevision:r().trim().min(1).max(500),revision:ka,dirty:A(),currentChannel:CL,createdAt:_t,updatedAt:_t,metadata:bs}).strict();var ns=b(["runtime","memory","prompt","skill","agent","product","taskset","training"]),Aw=b(["text_instruction","memory","dependency_selection","executable_code","business_logic","financial_logic","permission","connected_app","publication","deployment","training","model_binding","team_or_global"]),Tw=c({id:He,route:ns,operation:b(["create","update","delete"]),target:r().trim().min(1).max(2e3),summary:r().trim().min(1).max(2e3),content:r().max(1e6).nullable(),contentHash:Ye.nullable(),effects:f(Aw).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=qr(e.content);e.contentHash!==n&&t.addIssue({code:"custom",message:`edit contentHash is ${e.contentHash}; expected ${n}`,path:["contentHash"]})}),Ew=c({workspaceId:He,revision:ka,sourceRevision:r().trim().min(1).max(500),channelRevision:ka}).strict(),Ho=c({id:He,revision:ka,contentHash:Ye}).strict();c({schemaVersion:S("openpond.harnessTurnSnapshot.v1"),workspaceId:He,workspaceRevision:ka,sourceRevision:r().trim().min(1).max(500),channelName:He,channelRevision:ka,harnessRelease:Je,toolCatalogHash:Ye.nullable().optional(),overlay:Ho.nullable().optional().default(null)}).strict();var RL=c({schemaVersion:S("openpond.harnessRunOverlay.v1"),id:He,runId:He,baseHarnessRelease:Je,workspace:Ew,revision:ka,status:b(["active","frozen","abandoned"]),edits:f(Tw).max(1e3),createdAt:_t,updatedAt:_t,metadata:bs}).strict();RL.extend({contentHash:Ye}).strict();var Mw=c({kind:b(["tool_event","recovery","validation","user_turn","work_output","work_receipt"]),id:He,contentHash:Ye.nullable()}).strict(),jw=c({id:He,kind:b(["dependency","schema","package","file_render","skill","prompt","business_formula","targeted_evaluation","observed_recovery","memory","component_activation"]),description:fu,required:A()}).strict(),PL=c({schemaVersion:S("openpond.harnessImprovementProposal.v1"),id:He,overlay:Ho,baseHarnessRelease:Je,expectedWorkspace:Ew,requestedScope:b(["personal","team","global"]),route:ns,risk:b(["low","review","restricted"]),effects:f(Aw).min(1).max(20),evidence:f(Mw).min(1).max(1e3),edits:f(Tw).min(1).max(1e3),validationPlan:f(jw).min(1).max(100),expectedOutcome:fu,createdAt:_t,metadata:bs}).strict().superRefine((e,t)=>{const n=new Set(e.effects);for(const[a,o]of e.edits.entries()){o.route!==e.route&&t.addIssue({code:"custom",message:"every edit route must match the proposal route",path:["edits",a,"route"]});for(const i of o.effects)n.has(i)||t.addIssue({code:"custom",message:`edit effect ${i} is missing from proposal effects`,path:["edits",a,"effects"]})}new Set(e.validationPlan.map(a=>a.id)).size!==e.validationPlan.length&&t.addIssue({code:"custom",message:"validation plan ids must be unique",path:["validationPlan"]})});PL.extend({contentHash:Ye}).strict();var AL=c({schemaVersion:S("openpond.harnessTargetedValidationReceipt.v1"),id:He,proposal:Je,validationId:He,kind:jw.shape.kind,status:b(["passed","failed","blocked","skipped"]),summary:fu,evidenceRefs:f(Mw).max(1e3),createdAt:_t,metadata:bs}).strict();AL.extend({contentHash:Ye}).strict();var TL=b(["advanced","retained","conflict","rolled_back"]),EL=c({schemaVersion:S("openpond.harnessAdvanceReceipt.v1"),id:He,workspaceId:He,ownerScope:Pw,proposal:Je.nullable(),expectedWorkspaceRevision:ka,observedWorkspaceRevision:ka,previousChannelRevision:ka,nextChannelRevision:ka,previousRelease:Je.nullable(),nextRelease:Je.nullable(),validationReceipts:f(Je).max(100),decision:TL,reason:fu,rollbackOf:Je.nullable(),createdAt:_t,metadata:bs}).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"]})});EL.extend({contentHash:Ye}).strict();var ML=c({schemaVersion:S("openpond.harnessOverlayMergeReceipt.v1"),id:He,workspaceId:He,baseHarnessRelease:Je,leftOverlay:Ho,rightOverlay:Ho,decision:b(["merged","conflict"]),mergedOverlay:Ho.nullable(),conflictTargets:f(r().trim().min(1).max(2e3)).max(1e3),requiresRevalidation:S(!0),createdAt:_t,metadata:bs}).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"]})});ML.extend({contentHash:Ye}).strict();var hu=r().trim().min(1).max(1e5),ic=ie(r(),ce()).default({}),jL=b(["completed_tool_batch","before_model_step","turn_completed","turn_paused"]),Ow=c({kind:jL,eventSequence:u().int().nonnegative(),occurredAt:_t}).strict(),$w=c({id:He,sequence:u().int().nonnegative().nullable(),contentHash:Ye}).strict(),OL=b(["tool_failure","retry","recovery","validation","user_turn","reusable_success","completion_detour"]),$L=b(["open","recovered","terminal"]),NL=c({name:r().trim().min(1).max(500),invocationKey:Ye}).strict(),DL=c({schemaVersion:S("openpond.improvementObservation.v1"),id:He,runRef:He,turnId:He,harnessRelease:Je,overlay:Ho.nullable(),eventRefs:f($w).min(1).max(100),kind:OL,state:$L,tool:NL.nullable(),deterministicClass:r().trim().min(1).max(500).nullable(),summary:hu,createdAt:_t,metadata:ic}).strict().superRefine((e,t)=>{new Set(e.eventRefs.map(n=>n.id)).size!==e.eventRefs.length&&t.addIssue({code:"custom",message:"observation event refs must be unique",path:["eventRefs"]}),["tool_failure","retry","recovery","completion_detour"].includes(e.kind)&&e.tool===null&&t.addIssue({code:"custom",message:`${e.kind} observations require a tool identity`,path:["tool"]})});DL.extend({contentHash:Ye}).strict();var LL=c({schemaVersion:S("openpond.refinementTriggerPolicy.v1"),maxEstimatedCostUsd:u().finite().nonnegative(),cooldownMs:u().int().nonnegative(),maxPendingPlans:u().int().min(1).max(100),maxEvidenceEvents:u().int().min(1).max(1e3),maxProposalEdits:u().int().min(1).max(1e3),maxProposalBytes:u().int().min(1).max(1e7)}).strict(),UL=b(["no_action","route_deterministically","queue_refiner"]),zL=c({schemaVersion:S("openpond.refinementTriggerDecision.v1"),id:He,runRef:He,turnId:He,harnessRelease:Je,overlay:Ho.nullable(),observations:f(Je).max(100),decision:UL,deterministicRoute:ns.nullable(),suggestedRoutes:f(ns).max(8),reason:hu,deduplicationKey:Ye,policy:LL,estimatedMaxCostUsd:u().finite().nonnegative(),pendingPlanCount:u().int().nonnegative(),boundary:Ow,cooldownUntil:_t.nullable(),createdAt:_t,metadata:ic}).strict().superRefine((e,t)=>{e.estimatedMaxCostUsd>e.policy.maxEstimatedCostUsd&&t.addIssue({code:"custom",message:"estimated Refiner cost exceeds the trigger policy budget",path:["estimatedMaxCostUsd"]}),e.pendingPlanCount>e.policy.maxPendingPlans&&t.addIssue({code:"custom",message:"pending plan count exceeds the trigger policy limit",path:["pendingPlanCount"]}),e.observations.length>e.policy.maxEvidenceEvents&&t.addIssue({code:"custom",message:"trigger observations exceed the evidence budget",path:["observations"]}),e.decision==="route_deterministically"&&e.deterministicRoute===null&&t.addIssue({code:"custom",message:"deterministic decisions require a route",path:["deterministicRoute"]}),e.decision!=="route_deterministically"&&e.deterministicRoute!==null&&t.addIssue({code:"custom",message:"only deterministic decisions may declare a deterministic route",path:["deterministicRoute"]}),e.decision==="no_action"&&e.suggestedRoutes.length>0&&t.addIssue({code:"custom",message:"no-action decisions cannot suggest routes",path:["suggestedRoutes"]}),e.decision!=="no_action"&&e.observations.length===0&&t.addIssue({code:"custom",message:"actionable trigger decisions require observations",path:["observations"]})});zL.extend({contentHash:Ye}).strict();var HL=b(["runtime_service","refiner_model","human_review","evaluation_system","training_system"]),qL=c({schemaVersion:S("openpond.improvementRouteDecision.v1"),id:He,trigger:Je,route:ns,authority:HL,automatic:A(),reason:hu,createdAt:_t,metadata:ic}).strict().superRefine((e,t)=>{e.automatic&&["human_review","evaluation_system","training_system"].includes(e.authority)&&t.addIssue({code:"custom",message:`${e.authority} routes cannot be marked automatic`,path:["automatic"]}),e.route==="training"&&e.automatic&&e.authority!=="training_system"&&t.addIssue({code:"custom",message:"automatic training routes require training-system authority",path:["authority"]})});qL.extend({contentHash:Ye}).strict();var BL=c({schemaVersion:S("openpond.harnessRefinerOutcome.v1"),id:He,trigger:Je,decision:b(["no_action","proposed"]),proposal:Je.nullable(),reason:hu,evidenceRefs:f(Je).max(100),estimatedCostUsd:u().finite().nonnegative(),createdAt:_t,metadata:ic}).strict().superRefine((e,t)=>{e.decision==="proposed"!=(e.proposal!==null)&&t.addIssue({code:"custom",message:"proposed Refiner outcomes require a proposal; no-action outcomes cannot include one",path:["proposal"]})});BL.extend({contentHash:Ye}).strict();var FL=b(["applied","retained","declined","conflict","rolled_back"]),VL=c({schemaVersion:S("openpond.improvementApplyReceipt.v1"),id:He,proposal:Je,beforeOverlay:Ho,afterOverlay:Ho.nullable(),decision:FL,boundary:Ow,validationRefs:f(Je).max(100),outcomeEvidenceRefs:f($w).max(1e3),rollbackOf:Je.nullable(),createdAt:_t,metadata:ic}).strict().superRefine((e,t)=>{e.decision==="applied"!=(e.afterOverlay!==null)&&t.addIssue({code:"custom",message:"applied receipts require an after-overlay; other decisions cannot include one",path:["afterOverlay"]}),e.decision==="rolled_back"!=(e.rollbackOf!==null)&&t.addIssue({code:"custom",message:"only rollback receipts require rollbackOf",path:["rollbackOf"]})});VL.extend({contentHash:Ye}).strict();c({provider:He,model:He,revision:r().trim().min(1).max(500).nullable().default(null),artifactHash:Ye.nullable().default(null),tokenizerRevision:r().trim().min(1).max(500).nullable().default(null),chatTemplateHash:Ye.nullable().default(null)}).strict();var KL=["openpond","codex","anthropic","openai","xai","google","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],WL=b(KL),Nw=c({providerId:WL,modelId:r().trim().min(1).max(300)}),GL=r().trim().min(1).max(2e3),xg=r().trim().min(1).max(1e5),ZL=b(["create","update","delete"]),JL=b(["memory","prompt","skill","agent"]),YL=b(["runtime","product","taskset","training"]),QL=b(["no_action","routed","applied","retained","failed"]),XL=b(["not_applicable","pending","passed","rejected","failed"]),eU=b(["not_applicable","pending","passed","failed"]),tU=c({schemaVersion:S("openpond.harnessRefinerActivityReceipt.v1"),id:He,runRef:He,turnId:He,result:QL,decision:b(["no_action","route","propose"]).nullable(),route:ns.nullable(),operation:ZL.nullable(),target:r().trim().min(1).max(2e3).nullable(),summary:GL,evidenceBasis:yg.nullable(),critiqueStatus:XL,validationStatus:eU,trigger:Je,outcome:Je.nullable(),proposal:Je.nullable(),applyReceipt:Je.nullable(),inputHarness:Je,outputHarness:Je.nullable(),createdAt:_t}).strict().superRefine((e,t)=>{const n=e.result==="applied"||e.result==="retained";e.result==="no_action"?ry(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"||!YL.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"}),ry(t,e,{critiqueStatus:"not_applicable",validationStatus:"not_applicable"})):n?((e.decision!=="propose"||!JL.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"]})});tU.extend({contentHash:Ye}).strict();var nU=b(["unresolved","confirmed","resolved","rejected","expired"]),aU=c({kind:b(["applied_change","later_success","manual_rejection","source_revoked","expired"]),reason:xg,evidenceRefs:f(Je).max(1e3),resolvedAt:_t}).strict(),oU=c({schemaVersion:S("openpond.harnessRefinementCandidate.v1"),id:He,ownerScope:kg,workspaceRef:He,fingerprint:Ye,recurrenceFamily:r().trim().min(1).max(1e3),statement:xg,status:nU,occurrences:f(Nl).max(1e3),counterevidence:f(Nl).max(1e3),sourceReviews:f(Je).min(1).max(100),relatedHarnessReleases:f(Je).max(100),firstSeenAt:_t,lastSeenAt:_t,lastReviewedAt:_t,expiresAt:_t,resolution:aU.nullable(),createdAt:_t,updatedAt:_t}).strict().superRefine((e,t)=>{Lr(t,e.occurrences,"occurrences"),Lr(t,e.counterevidence,"counterevidence"),Lr(t,e.sourceReviews,"sourceReviews"),Lr(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"]}),cU(t,e)});oU.extend({contentHash:Ye}).strict();var rU=b(["created","merged","rejected","expired","reopened","resolved"]),iU=c({schemaVersion:S("openpond.harnessRefinementCandidateLifecycleReceipt.v1"),id:He,candidateId:He,decision:rU,beforeCandidate:Je.nullable(),afterCandidate:Je,review:Je,addedEvidence:f(Nl).max(1e3),removedEvidence:f(Je).max(1e3),reason:xg,createdAt:_t}).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"]}),Lr(t,e.addedEvidence,"addedEvidence"),Lr(t,e.removedEvidence,"removedEvidence");const n=new Set(e.removedEvidence.map(a=>Mf(a)));e.addedEvidence.some(a=>n.has(Mf(a.evidence)))&&t.addIssue({code:"custom",message:"candidate lifecycle evidence cannot be added and removed together",path:["removedEvidence"]})});iU.extend({contentHash:Ye}).strict();var sU=c({schemaVersion:S("openpond.harnessCrossRunRefinementRequest.v1"),id:He,ownerScope:kg,workspaceRef:He,candidate:Je,candidateFingerprint:Ye,review:Je,admittedHarness:Je,evidence:f(Nl).min(1).max(1e3),capabilities:Sg,deduplicationKey:Ye,createdAt:_t}).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"]}),Lr(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=lU(e);e.deduplicationKey!==n&&t.addIssue({code:"custom",message:`cross-run refinement deduplicationKey is ${e.deduplicationKey}; expected ${n}`,path:["deduplicationKey"]})});sU.extend({contentHash:Ye}).strict();function lU(e){return qr({schemaVersion:"openpond.harnessCrossRunRefinementIdentity.v1",workspaceRef:e.workspaceRef,candidateFingerprint:e.candidateFingerprint,admittedHarness:e.admittedHarness})}function ry(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 Lr(e,t,n){const a=t.map(o=>Mf(o));new Set(a).size!==a.length&&e.addIssue({code:"custom",message:`${n} references must be unique`,path:[n]})}function Mf(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 cU(e,t){const n=[["firstSeenAt",t.firstSeenAt],["lastSeenAt",t.lastSeenAt],["lastReviewedAt",t.lastReviewedAt],["updatedAt",t.updatedAt],["expiresAt",t.expiresAt]];for(let a=1;a<n.length;a+=1){const o=n[a-1],i=n[a];Date.parse(o[1])<=Date.parse(i[1])||e.addIssue({code:"custom",message:`${i[0]} must not precede ${o[0]}`,path:[i[0]]})}Date.parse(t.createdAt)>Date.parse(t.updatedAt)&&e.addIssue({code:"custom",message:"updatedAt must not precede createdAt",path:["updatedAt"]})}c({path:r().min(1).max(2e3),offset:u().int().nonnegative().default(0),length:u().int().positive().max(65536).default(16384)}).strict();var Dw=r().regex(/^[a-z][a-z0-9_-]{0,119}$/),Lw=r().min(1).max(2e3).refine(e=>!e.includes("\\")&&!e.includes(":")&&!e.startsWith("/")&&e.split("/").every(t=>t!==""&&t!=="."&&t!==".."),"workflow references require portable relative paths"),dU=c({id:Dw,label:r().trim().min(1).max(240),description:r().max(4e3),inputSchema:ie(r(),ce()),invocation:Rt("kind",[c({kind:S("instructions"),instructions:r().min(1).max(1e5).refine(e=>!!e.trim())}).strict(),c({kind:S("agent_action"),actionId:r().trim().min(1).max(240)}).strict()]),skillPaths:f(Lw).max(100)}).strict();c({schemaVersion:S("openpond.profileWorkflows.v1"),workflows:f(dU).max(1e3)}).strict();var uU=c({id:r().trim().min(1).max(240),agentId:r().regex(/^[a-zA-Z0-9_-]{1,240}$/),sourceActionId:r().trim().min(1).max(240),inputSchema:ie(r(),ce())}).strict();c({schemaVersion:S("openpond.profileWorkflowActions.v1"),actions:f(uU).max(200)}).strict();c({schemaVersion:S("openpond.profileWorkflowBinding.v1"),profileId:r().trim().min(1).max(240),sourceRevision:r().trim().min(1).max(240),harnessRelease:Je,catalogHash:Ye,workflowId:Dw}).strict();c({schemaVersion:S("openpond.profileComponentBinding.v1"),profileId:r().trim().min(1).max(240),sourceRevision:r().trim().min(1).max(240),harnessRelease:Je,target:Rt("kind",[c({kind:S("profile")}).strict(),c({kind:S("skill"),skillPath:Lw}).strict(),c({kind:S("agent_action"),actionId:r().trim().min(1).max(240)}).strict()])}).strict();var Ed=r().min(1).max(2e3).refine(e=>!e.includes("\\")&&!e.includes(":")&&!e.startsWith("/")&&e.split("/").every(t=>t!==""&&t!=="."&&t!==".."),"source paths must be portable relative paths");r().regex(/^[a-z][a-z0-9_-]{0,119}$/);var mU={type:"object",properties:{},additionalProperties:!1};c({name:r().trim().min(1).max(240).optional(),description:r().max(4e3).optional(),skillPaths:f(Ed).max(100).optional(),assetPaths:f(Ed).max(100).optional()}).strict();c({actionId:r().trim().min(1).max(240),name:r().trim().min(1).max(240),description:r().max(4e3).default(""),inputSchema:ie(r(),ce()).default(mU),skillPaths:f(Ed).max(100).default([]),assetPaths:f(Ed).max(100).default([])}).strict();const iy=r().trim().min(1).max(240),pU=r().trim().min(1).max(1e3).refine(e=>!/[\\:\0]/.test(e)&&e.split("/").every(t=>t&&t!=="."&&t!==".."&&!t.startsWith(".env")),"Metric modules must use a safe relative path."),gu=c({schemaVersion:S("openpond.tasksetMetricPolicy.v1"),primaryMetric:iy,aggregation:b(["mean_score","pass_rate","weighted_mean","custom"]),missingReward:b(["zero","exclude"]),taskWeights:ie(iy,u().positive().max(1e6)).optional(),customAggregator:c({module:pU,exportName:r().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),contentHash:Y,timeoutMs:u().int().positive().max(3e5),networkPolicy:S("none")}).strict().nullable()}).strict().superRefine((e,t)=>{e.aggregation==="custom"!=(e.customAggregator!==null)&&t.addIssue({code:"custom",path:["customAggregator"],message:"Only custom aggregation requires a content-hashed module."}),(e.aggregation==="weighted_mean"?!e.taskWeights||!Object.keys(e.taskWeights).length:e.taskWeights!==void 0)&&t.addIssue({code:"custom",path:["taskWeights"],message:"Only weighted means require explicit positive task weights."})}),fU=c({schemaVersion:S("openpond.tasksetMetricResult.v1"),runManifest:ee,tasksetRelease:ee,policy:gu,policyHash:Y,receiptRefs:f(ee).min(1).max(1e6),includedCount:u().int().nonnegative(),missingRewardCount:u().int().nonnegative(),excludedCount:u().int().nonnegative(),value:u().min(0).max(1).nullable()}).strict(),hU=fU.extend({contentHash:Y}).strict(),Zo=b(["train","validation","test","frozen_eval"]),gU=c({path:r().trim().min(1).max(2e3).refine(bU),mediaType:r().trim().min(1).max(200),schemaRef:dn.nullable().default(null),maxBytes:u().int().positive().max(25e7).nullable().default(null),metadata:Cn}).strict(),vU=c({policyVisibleFields:f(E).max(1e3).default([]),privilegedFields:f(E).max(1e3).default([]),hiddenGraderRefs:f(E).max(1e3).default([]),connectedAppScopes:f(E).max(100).default([])}).strict(),Uw=c({protocolVersion:S("openpond.environment.v1"),kind:b(["text","agent","work","custom_program"]),entrypoint:r().trim().min(1).max(1e3),stateful:A(),deterministicSeeds:A(),lifecycle:f(b(["create","reset","step","collect","destroy"])).min(5).max(5),networkPolicy:b(["none","declared_read_only","declared_scoped"]),defaultTimeoutMs:u().int().positive().max(36e5)}).strict(),vu=c({id:E,version:r().trim().min(1).max(100),weight:u().nonnegative().max(1e3).default(1),hardGate:A().default(!1),rewardEligible:A().default(!1),privileged:A().default(!1)}),zw=vu.extend({kind:b(["content","schema","artifact","runtime_event","state"]),config:ie(r(),ce())}).strict(),Hw=vu.extend({kind:S("model_judge"),rubricRef:dn,calibrationStatus:b(["pending","passed","failed"]),model:c({providerId:E,modelId:E,revision:r().trim().min(1).max(500).nullable()}).strict().optional(),temperature:u().min(0).max(2).optional()}).strict(),qw=b(["isolated_javascript","sandbox_process"]),Bw=vu.extend({kind:S("custom_verifier"),runtime:qw.optional(),verifierRef:dn,exportName:r().trim().min(1).max(240).optional(),timeoutMs:u().int().positive().max(3e5),networkPolicy:S("none")}).strict(),Fw=vu.extend({kind:S("human"),rubricRef:dn,reviewerRole:r().trim().min(1).max(500)}).strict(),Vw=Dt([zw,Hw,Bw,Fw]),wg=c({id:E,clusterKey:E,split:Zo,input:ie(r(),ce()),expectedOutput:ie(r(),ce()).nullable(),policyVisibleContext:ie(r(),ce()).default({}),privilegedContextRef:E.nullable(),artifactRefs:f(dn).max(1e3).default([]),requiredOutputs:f(gU).max(1e3).optional(),tags:f(E).max(100).default([])}).strict(),Kw=c({schemaVersion:S("openpond.tasksetRelease.v2"),id:E,revision:u().int().positive(),policy:vU,environment:Uw,environmentRelease:c({id:E,contentHash:Y}).strict().optional(),tools:f(tc).max(200),capabilities:f(Qh).max(200),tasks:f(wg).min(1).max(1e6),graders:f(Vw).min(1).max(1e3),verifierSetRelease:c({id:E,contentHash:Y}).strict().optional(),metrics:gu.optional(),metadata:Cn}).strict(),Ww=Kw.extend({contentHash:Y}).strict();function bU(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}const yU=c({adapterId:E,placement:b(["local","remote","colocated","provider_native"]),runtimeVersion:r().trim().min(1).max(200),capabilityReceipt:Y}).strict(),SU=c({maxTurns:u().int().positive().max(1e5),timeoutMs:u().int().positive().max(864e5),maxOutputBytes:u().int().positive().max(25e7),maximumSpendUsd:u().nonnegative().nullable()}).strict(),kU=c({schemaVersion:S("openpond.runManifest.v1"),id:E,harnessRelease:ee,tasksetRelease:ee,model:Mh,runtimeTarget:yU,limits:SU,approval:c({id:E,contentHash:Y}).strict().nullable(),createdAt:Pe,metadata:Cn}).strict();kU.extend({contentHash:Y}).strict();const xU=c({schemaVersion:S("openpond.attemptReceipt.v1"),id:E,runManifest:ee,taskId:E,seed:r().trim().min(1).max(500),terminal:A(),failureClass:Zl.nullable(),outputHash:Y.nullable(),traceHash:Y,artifactRefs:f(za).max(1e5),graderEvidenceRefs:f(za).max(1e4),startedAt:Pe,completedAt:Pe,latencyMs:u().int().nonnegative(),costUsd:u().nonnegative().nullable(),legacyAttemptRef:E.nullable().default(null),metadata:Cn}).strict();xU.extend({contentHash:Y}).strict();const wU=c({schemaVersion:S("openpond.evaluationResult.v1"),id:E,runManifest:ee,harnessRelease:ee,tasksetRelease:ee,model:Mh,receiptRefs:f(ee).min(1).max(1e6),attemptCount:u().int().positive(),rewardEligibleCount:u().int().nonnegative(),terminalCount:u().int().nonnegative(),meanScore:u().min(0).max(1).nullable(),failureCounts:ie(Zl,u().int().nonnegative()),authoredMetric:hU.optional(),metadata:Cn}).strict(),IU=wU.extend({contentHash:Y}).strict(),_U=c({schemaVersion:S("openpond.harnessCompatibility.v1"),id:E,baseHarnessRelease:ee,candidateHarnessRelease:ee,tasksetRelease:ee,environmentHash:Y,toolContractHash:Y,policyHash:Y,graderInterfaceHash:Y,metadata:Cn}).strict();_U.extend({contentHash:Y}).strict();var wa=r().trim().min(1).max(240),qo=r().trim().min(1),ur=r().trim().min(8).max(256),Gw=r().trim().min(1).max(1e3).refine(e=>!e.startsWith("/")&&!e.startsWith("\\")&&!e.split(/[\\/]/).includes(".."),"Artifact paths must be relative and stay inside the Dataset."),gr=b(["train","validation","test","frozen_eval"]),CU=c({name:r().trim().min(1).max(500),semanticRole:b(["row_id","cluster_id","prompt","messages","demonstration","chosen","rejected","expected_output","privileged_context","reward","feedback","tag","metadata"]),logicalType:b(["string","integer","float","boolean","json","messages"]),nullable:A(),policy:b(["visible","privileged","metadata"])}),RU=c({schemaVersion:S("openpond.datasetSemanticSchema.v1"),fields:f(CU).min(1).max(1e4),schemaHash:ur}),PU=c({id:wa,split:gr,path:Gw,contentHash:ur,schemaHash:ur,sizeBytes:u().int().nonnegative(),rowCount:u().int().positive(),rowGroupCount:u().int().positive()}),Ig=c({schemaVersion:S("openpond.datasetArtifact.v1"),id:wa,tasksetId:wa,tasksetRevision:u().int().positive(),contentHash:ur,format:S("parquet"),schema:RU,shards:f(PU).min(1).max(1e5),rowCount:u().int().positive(),splitCounts:ie(gr,u().int().nonnegative()),sourceReceiptRefs:f(wa).min(1).max(1e5),mappingHash:ur,qualityReportHash:ur,createdAt:qo}),AU=c({schemaVersion:S("openpond.datasetArtifactSummary.v1"),artifactId:wa,tasksetId:wa,tasksetRevision:u().int().positive(),format:S("parquet"),rowCount:u().int().positive(),splitCounts:ie(gr,u().int().nonnegative()),sizeBytes:u().int().nonnegative(),contentHash:ur,available:A(),unavailableReason:r().trim().min(1).max(2e3).nullable(),createdAt:qo}),TU=c({schemaVersion:S("openpond.datasetCatalogItem.v1"),tasksetId:wa,tasksetRevision:u().int().positive(),artifactId:wa.nullable(),name:r().trim().min(1).max(500),status:b(["draft","awaiting_disclosure_approval","awaiting_materialization_approval","materializing","validating","needs_review","baselining","ready","blocked","failed","archived"]),storageKind:b(["inline","parquet"]),rowCount:u().int().nonnegative(),splitCounts:ie(gr,u().int().nonnegative()),sizeBytes:u().int().nonnegative().nullable(),available:A(),unavailableReason:r().trim().min(1).max(2e3).nullable(),createdAt:qo,updatedAt:qo});c({schemaVersion:S("openpond.datasetCatalog.v1"),profileId:wa,datasets:f(TU),generatedAt:qo});c({schemaVersion:S("openpond.datasetArtifactRegistry.v1"),manifest:Ig,profileId:wa,storageRoot:r().trim().min(1).max(4e3),relativeManifestPath:Gw,available:A(),unavailableReason:r().trim().min(1).max(2e3).nullable(),verifiedAt:qo.nullable(),createdAt:qo,updatedAt:qo});c({split:gr.nullable().default(null),cursor:r().trim().min(1).max(2e3).nullable().default(null),limit:u().int().min(1).max(100).default(25),columns:f(r().trim().min(1).max(500)).max(100).default([])});c({schemaVersion:S("openpond.datasetRowPage.v1"),tasksetId:wa,tasksetRevision:u().int().positive(),artifactHash:ur,split:gr.nullable(),rows:f(ie(r(),ce())).max(100),nextCursor:r().max(2e3).nullable(),totalRows:u().int().nonnegative(),returnedRows:u().int().nonnegative()});var EU=c({schemaVersion:S("openpond.datasetStorageSettings.v1"),datasetStorePath:r().trim().min(1).max(4e3),updatedAt:qo}),MU=c({id:wa,label:r().trim().min(1).max(500),path:r().trim().min(1).max(4e3),datasetStorePath:r().trim().min(1).max(4e3),kind:b(["local","network","removable","cache"]),configured:A(),mounted:A(),writable:A(),totalBytes:u().int().nonnegative().nullable(),freeBytes:u().int().nonnegative().nullable()});c({schemaVersion:S("openpond.datasetStorageState.v1"),settings:EU,storageRoots:f(MU)});c({datasetStorePath:r().trim().min(1).max(4e3)});var Wi=r().trim().min(1).max(240),jU=r().trim().min(1),as=r().trim().min(8).max(256),OU=ie(r(),ce()).default({}),$U=r().trim().min(7).max(256),NU=b(["pending","approved","review","blocked"]),bu=c({id:Wi,profileId:Wi,title:r().trim().min(1).max(500),sourceHash:as,occurredAt:jU,licensingStatus:NU,secretScanStatus:b(["pending","passed","blocked"]),piiScanStatus:b(["pending","passed","review","blocked"]),metadata:OU}),DU=bu.extend({schemaVersion:S("openpond.huggingFaceDatasetSource.v1"),kind:S("huggingface"),repositoryId:r().trim().regex(/^[^/\s]+\/[^/\s]+$/).max(500),repositoryUrl:r().url().max(2e3),revision:$U,configuration:r().trim().min(1).max(500),upstreamSplits:f(r().trim().min(1).max(500)).min(1).max(1e3),gated:A(),private:A(),declaredLicense:r().trim().min(1).max(500).nullable(),sourceFileHashes:f(as).min(1).max(1e5)}),LU=bu.extend({schemaVersion:S("openpond.uploadedFileDatasetSource.v1"),kind:S("uploaded_file"),originalFileNames:f(r().trim().min(1).max(500)).min(1).max(1e3),mediaTypes:f(r().trim().min(1).max(200)).min(1).max(1e3),sourceFileHashes:f(as).min(1).max(1e3),totalBytes:u().int().nonnegative(),parserVersion:r().trim().min(1).max(200)}),UU=bu.extend({schemaVersion:S("openpond.generatedDatasetSource.v1"),kind:S("generated"),generatorId:Wi,generatorVersion:r().trim().min(1).max(200),seed:u().int(),generatorHash:as}),zU=bu.extend({schemaVersion:S("openpond.learningBatchDatasetSource.v1"),kind:S("learning_batch"),batch:c({id:Wi,revision:u().int().positive(),contentHash:as}).strict(),taskDefinition:c({id:Wi,revision:u().int().positive(),contentHash:as}).strict(),admittedBy:Wi}),HU=Rt("kind",[DU,LU,UU,zU]),qU=c({schemaVersion:S("openpond.harnessActionBinding.v1"),actionId:He,modelToolName:r().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:r().trim().min(1).max(1e3),inputSchema:ie(r(),ce()),actionSchemaHash:Ye,agentRelease:Je,implementationHash:Ye,runtimeBindingId:He,capabilityReceiptHash:Ye,sideEffect:b(["read","write"]),studentVisible:A(),timeoutMs:u().int().positive().max(36e5),episodeArgumentBindings:f(c({argument:He,source:S("case_id")}).strict()).max(20).default([])}).strict(),At=r().trim().min(1).max(240),_g=r().trim().min(1),BU=r().trim().min(8).max(256),Cg=r().trim().regex(/^[a-f0-9]{64}$/),FU=r().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),qa=ie(r(),ce()).default({}),yu=At.nullable();function sc(e){const t=e.trim().replaceAll("\\","/");return!t||t.startsWith("/")||t==="."||t===".."?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function VU(e){const t=e.trim();return t.length>0&&t!=="."&&t!==".."&&!t.includes("/")&&!t.includes("\\")&&!t.includes("\0")}var os=gr,Zw=b(["general","benchmark"]),Jw=c({schemaVersion:S("openpond.tasksetBenchmark.v1"),definitionId:At,releaseId:At,releaseHash:Cg,managedReleasePath:r().trim().min(1).max(1e3).refine(sc,"Benchmark release paths must remain relative."),adaptationSplit:os,evaluationSplit:os,primaryMetric:b(["foreground_tokens","success_rate","latency_ms","cost_usd"]),qualityGate:b(["none","non_regression","all_pass"]),source:b(["builtin","imported"]),metadata:qa}),Yw=c({schemaVersion:S("openpond.tasksetPreferenceComparisonBinding.v1"),releaseId:At,releaseHash:Cg,publishedAt:_g,metadata:qa}),KU=c({status:b(["pending","granted","denied","revoked"]),scope:b(["metadata_only","selected_turns","full_session"]),grantedBy:yu,grantedAt:_g.nullable(),purpose:S("task_authoring_and_evaluation")}),Qw=c({schemaVersion:S("openpond.trainingSource.v1"),id:At,profileId:At,sessionId:At,turnIds:f(At).max(1e3).default([]),workspaceId:yu,sourceHash:BU,clusterKey:At,title:r().trim().min(1).max(500),occurredAt:_g,consent:KU,connectedAppIds:f(At).max(100).default([]),secretScanStatus:b(["pending","passed","blocked"]),piiScanStatus:b(["pending","passed","review","blocked"]),licensingStatus:b(["pending","approved","review","blocked"]),metadata:qa}),Xw=Dt([Qw,HU]),Rg=c({policyVisibleFields:f(At).max(1e3).default([]),privilegedFields:f(At).max(1e3).default([]),hiddenGraderRefs:f(At).max(100).default([]),connectedAppScopes:f(At).max(100).default([])}),WU=c({id:At,sourceRefId:At,artifactRef:r().trim().min(1).max(4e3).refine(sc,"Task asset references must be safe relative paths."),fileName:r().trim().min(1).max(500).refine(VU,"Task asset file names must not contain path separators."),mediaType:r().trim().min(1).max(200),sha256:Cg,sizeBytes:u().int().nonnegative().max(25e7),split:os,metadata:qa}),GU=c({path:r().trim().min(1).max(1e3).refine(sc,"Required output paths must stay inside the Work output directory."),mediaType:r().trim().min(1).max(200),schemaRef:At.nullable().optional(),maxBytes:u().int().positive().max(1e7).optional(),metadata:qa}),Pg=c({schemaVersion:S("openpond.taskData.v1"),id:At,clusterKey:At,split:os,input:ie(r(),ce()),expectedOutput:ie(r(),ce()).nullable(),policyVisibleContext:ie(r(),ce()).default({}),privilegedContextRef:yu,sourceRefs:f(At).min(1).max(100),assets:f(WU).max(1e3).optional(),resourceRefs:f(At).max(1e3).optional(),requiredOutputs:f(GU).max(100).optional(),tags:f(At).max(100).default([]),metadata:qa}),ZU=c({id:At,kind:b(["file","catalog","configuration","code_module"]),path:r().trim().min(1).max(1e3).refine(sc,"Environment resource paths must remain relative."),mediaType:r().trim().min(1).max(200).nullable().optional(),visibility:b(["policy_visible","policy_hidden","privileged"]),required:A(),metadata:qa}),ys=c({id:At,taskId:yu,sourceRefs:f(At).min(1).max(100),artifactRef:At,approved:A(),confidence:u().min(0).max(1),metadata:qa}),e1=ys.extend({kind:S("demonstration"),prompt:r().max(1e5).nullable().default(null),response:r().max(2e5).nullable().default(null)}),t1=ys.extend({kind:S("preference"),prompt:r().max(1e5),chosen:r().max(2e5),rejected:r().max(2e5),rationale:r().max(1e5).nullable().default(null)}),n1=ys.extend({kind:S("correction"),original:r().max(2e5),corrected:r().max(2e5),rationale:r().max(1e5).nullable().default(null)}),a1=ys.extend({kind:S("feedback"),feedback:r().max(1e5),polarity:b(["positive","negative","mixed","neutral"])}),o1=ys.extend({kind:S("reward"),task:r().max(1e5),rules:f(c({id:At,points:u().finite(),condition:r().trim().min(1).max(1e5)})).min(1).max(1e3),otherwisePoints:u().finite(),executable:A()}),r1=ys.extend({kind:S("label"),labelKind:S("rubric"),task:r().max(1e5),criteria:f(c({id:At,label:r().trim().min(1).max(500),description:r().trim().min(1).max(1e5)})).min(1).max(1e3),calibrationExamples:c({positive:r().trim().min(1).max(2e5),negative:r().trim().min(1).max(2e5),boundary:r().trim().min(1).max(2e5)})});Rt("kind",[e1,t1,n1,a1,o1,r1]);var i1=c({demonstrations:f(e1).max(1e5).default([]),preferences:f(t1).max(1e5).default([]),corrections:f(n1).max(1e5).default([]),feedback:f(a1).max(1e5).default([]),rewards:f(o1).max(1e5).default([]),labels:f(r1).max(1e5).default([])}),s1=c({protocolVersion:S("openpond.taskEnvironment.v1"),kind:b(["chat","agent","program","stateful_harness","work"]),entrypoint:r().trim().min(1).max(1e3),stateful:A(),deterministicSeeds:A(),toolNames:f(At).max(200).default([]),actionBindings:f(qU).max(200).optional(),lifecycle:f(b(["create","reset","step","grade","cleanup"])).min(1),defaultTimeoutMs:u().int().positive().max(36e5),networkPolicy:b(["none","declared_read_only","declared_scoped"]),resources:f(ZU).max(1e4).optional(),metadata:qa}),Ag=c({schemaVersion:S("openpond.tasksetCapabilities.v1"),taskKind:b(["chat","single_agent","multi_agent","custom_program"]),supportedSignals:f(b(["demonstration","preference","correction","feedback","reward","label"])),compatibleMethods:f(b(["none","retrieval","sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"])),rewardKinds:f(b(["none","exact","deterministic","model_judge","human"])),requiresTools:A(),requiresState:A(),requiresPrivilegedGrading:A(),environmentPlacements:f(b(["local","remote","colocated","provider_native"])),exportable:A(),portabilityBlockers:f(r().trim().min(1).max(2e3)).default([])}),Su=c({id:At,version:r().trim().min(1).max(100),label:r().trim().min(1).max(500),weight:u().min(0).max(1e3).default(1),hardGate:A().default(!1),rewardEligible:A().default(!1),privileged:A().default(!1),metadata:qa}),JU=Su.extend({kind:b(["content","schema","file","diff","test","runtime_event","state"]),config:ie(r(),ce())}),YU=Su.extend({kind:S("model_judge"),rubric:r().trim().min(1).max(5e4),judge:Nw,calibrationFixtureRefs:f(At).min(1).max(500),calibrationStatus:b(["pending","passed","failed"]),temperature:u().min(0).max(2).default(0)}),QU=Su.extend({kind:S("human"),rubric:r().trim().min(1).max(5e4),reviewerRole:r().trim().min(1).max(500)}),XU=Su.extend({kind:S("custom_verifier"),runtime:qw.optional(),module:r().trim().min(1).max(1e3).refine(sc,"Custom verifier modules must use a safe relative path."),exportName:FU,timeoutMs:u().int().positive().max(3e5),networkPolicy:S("none")}),ku=Dt([JU,YU,QU,XU]),Tg=b(["positive","negative","boundary","adversarial","prompt_injection","infrastructure_failure"]),l1=c({id:At,taskId:At,label:Tg,output:ie(r(),ce()),infrastructureError:r().trim().min(1).max(1e4).nullable(),expectedPassed:A(),expectedRewardEligible:A(),metadata:qa}),co=r().trim().min(1).max(240),Dl=r().trim().min(1),Md=r().trim().min(8).max(256),c1=ie(r(),ce()).default({}),ez=co.nullable(),tz=b(["draft","awaiting_disclosure_approval","awaiting_materialization_approval","materializing","validating","needs_review","baselining","ready","blocked","failed","archived"]),d1=b(["demonstrations","preferences","verifiable_reward","rubric","discovery"]),Hn=r().trim().max(1e5),u1=Rt("kind",[c({kind:S("demonstrations"),behavior:Hn,examples:f(c({id:co,prompt:Hn,response:Hn})).max(1e3).default([])}),c({kind:S("preferences"),preference:Hn,pairs:f(c({id:co,prompt:Hn,chosen:Hn,rejected:Hn,rationale:Hn})).max(1e3).default([])}),c({kind:S("verifiable_reward"),task:Hn,rules:f(c({id:co,points:u().finite(),condition:Hn})).max(1e3).default([]),otherwisePoints:u().finite().default(0)}),c({kind:S("rubric"),task:Hn,criteria:f(c({id:co,label:r().trim().max(500),description:Hn})).max(1e3).default([]),positiveExample:Hn,negativeExample:Hn,boundaryExample:Hn})]),nz=c({path:r().trim().min(1).max(1e3),role:b(["environment","verifier","fixture"]),content:r().max(25e4)}),m1=c({primaryMethod:b(["sft","dpo","grpo","ppo","sdft","opsd","sdpo"]),bootstrap:c({method:S("sft"),purpose:S("trajectory_bootstrap"),demonstrationRefs:f(co).min(1).max(1e5),limitations:f(r().trim().min(1).max(5e3)).min(1).max(100)}).nullable()}),p1=b(["taskset_not_ready","demonstrations_missing","preference_pairs_missing","preference_pairs_invalid","executable_reward_missing","reward_not_calibrated","reward_model_missing","value_model_required","frozen_eval_missing"]),az=c({method:b(["sft","dpo","grpo","ppo"]),status:b(["recommended","compatible","needs_dataset_work"]),reasonCodes:f(p1).default([]),reasons:f(r().trim().min(1).max(5e3)).default([])}),sy=c({code:co,message:r().trim().min(1).max(5e3),path:r().trim().max(2e3).nullable()}),f1=c({schemaVersion:S("openpond.tasksetReadiness.v1"),tasksetId:co,tasksetHash:Md,ready:A(),recommendedMethod:b(["none","retrieval","sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),trainingPath:m1.nullable().default(null),methodReadiness:f(az).default([]),compatibleDestinationClasses:f(b(["export","custom","hosted_managed"])),blockers:f(sy).default([]),advisories:f(sy).default([]),warnings:f(r().trim().min(1).max(5e3)).default([]),generatedAt:Dl}),h1=c({attempt:u().int().positive(),summary:r().trim().min(1).max(5e3),createdAt:Dl}),oz=c({schemaVersion:S("openpond.taskAuthoringProvenance.v1"),model:Nw.nullable(),modelConfig:c1,skillHash:Md,promptTemplateVersion:r().trim().min(1).max(200),buildIntent:d1.default("demonstrations"),buildSpecification:u1.nullable().default(null),evidenceHashes:f(Md).max(1e5),tasksetSdkVersion:r().trim().min(1).max(100),sourceCommit:r().trim().min(1).max(256).nullable(),repairHistory:f(h1).max(1e3),createdAt:Dl}),ly=c({schemaVersion:S("openpond.taskset.v1"),id:co,revision:u().int().positive().default(1),profileId:co,profileRelease:LD.nullable().optional(),createImproveRunId:ez.default(null),name:r().trim().min(1).max(500),objective:r().trim().max(2e4),purpose:Zw.default("general"),benchmark:Jw.nullable().default(null),preferenceComparison:Yw.nullable().default(null),status:tz,sourceRefs:f(Xw).min(1).max(1e5),datasetArtifact:Ig.nullable().optional(),policy:Rg,environment:s1,capabilities:Ag,metrics:gu.optional(),tasks:f(Pg).max(1e6),graders:f(ku).min(1).max(1e3),graderFixtures:f(l1).max(1e5),learningSignals:i1,authoringProvenance:oz,readiness:f1.nullable(),contentHash:Md,createdAt:Dl,updatedAt:Dl,metadata:c1}).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 rz(e){return e.schemaVersion==="openpond.trainingSource.v1"}class g1 extends Error{code;status;constructor(t,n=422,a){super(a?`${t}: ${a}`:t),this.code=t,this.status=n,this.name="LearningDomainError"}}var v1=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},iz=v1((e,t)=>{"use strict";t.exports=function n(a,o){if(a===o)return!0;if(a&&o&&typeof a=="object"&&typeof o=="object"){if(a.constructor!==o.constructor)return!1;var i,s,l;if(Array.isArray(a)){if(i=a.length,i!=o.length)return!1;for(s=i;s--!==0;)if(!n(a[s],o[s]))return!1;return!0}if(a.constructor===RegExp)return a.source===o.source&&a.flags===o.flags;if(a.valueOf!==Object.prototype.valueOf)return a.valueOf()===o.valueOf();if(a.toString!==Object.prototype.toString)return a.toString()===o.toString();if(l=Object.keys(a),i=l.length,i!==Object.keys(o).length)return!1;for(s=i;s--!==0;)if(!Object.prototype.hasOwnProperty.call(o,l[s]))return!1;for(s=i;s--!==0;){var m=l[s];if(!n(a[m],o[m]))return!1}return!0}return a!==a&&o!==o}}),sz=v1(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var t=iz();t.code='require("ajv/dist/runtime/equal").default',e.default=t}),cy=Ot,dy={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"}}},lz=Object.prototype.hasOwnProperty,cz=sz().default,It={validate:Ot};function la(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:i={}}={}){let s=null,l=0,m=la.evaluated;if(m.dynamicProps&&(m.props=void 0),m.dynamicItems&&(m.items=void 0),l===0)if(e&&typeof e=="object"&&!Array.isArray(e))for(let h in e){let v=l;It.validate(e[h],{instancePath:t+"/"+h.replace(/~/g,"~0").replace(/\//g,"~1"),parentData:e,parentDataProperty:h,rootData:o,dynamicAnchors:i})||(s=s===null?It.validate.errors:s.concat(It.validate.errors),l=s.length);var d=v===l;if(!d)break}else return la.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"object"}}],!1;return la.errors=s,l===0}la.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};function _n(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:i={}}={}){let s=null,l=0,m=_n.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 _n.errors=[{instancePath:t,schemaPath:"#/maxItems",keyword:"maxItems",params:{limit:32}}],!1;if(e.length<1)return _n.errors=[{instancePath:t,schemaPath:"#/minItems",keyword:"minItems",params:{limit:1}}],!1;{var d=!0;let h=e.length;for(let v=0;v<h;v++){let y=l;It.validate(e[v],{instancePath:t+"/"+v,parentData:e,parentDataProperty:v,rootData:o,dynamicAnchors:i})||(s=s===null?It.validate.errors:s.concat(It.validate.errors),l=s.length);var d=y===l;if(!d)break}}}else return _n.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"array"}}],!1;return _n.errors=s,l===0}_n.evaluated={items:!0,dynamicProps:!1,dynamicItems:!1};var dz={enum:["array","boolean","integer","null","number","object","string"]};function lo(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:i={}}={}){let s=null,l=0,m=lo.evaluated;return m.dynamicProps&&(m.props=void 0),m.dynamicItems&&(m.items=void 0),e==="array"||e==="boolean"||e==="integer"||e==="null"||e==="number"||e==="object"||e==="string"?(lo.errors=s,l===0):(lo.errors=[{instancePath:t,schemaPath:"#/enum",keyword:"enum",params:{allowedValues:dz.enum}}],!1)}lo.evaluated={dynamicProps:!1,dynamicItems:!1};function $t(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:i={}}={}){let s=null,l=0,m=$t.evaluated;return m.dynamicProps&&(m.props=void 0),m.dynamicItems&&(m.items=void 0),typeof e=="number"&&!(e%1)&&!isNaN(e)&&isFinite(e)?typeof e=="number"&&isFinite(e)&&(e<0||isNaN(e))?($t.errors=[{instancePath:t,schemaPath:"#/minimum",keyword:"minimum",params:{comparison:">=",limit:0}}],!1):($t.errors=s,l===0):($t.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"integer"}}],!1)}$t.evaluated={dynamicProps:!1,dynamicItems:!1};function ya(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:i={}}={}){let s=null,l=0,m=ya.evaluated;if(m.dynamicProps&&(m.props=void 0),m.dynamicItems&&(m.items=void 0),l===0)if(Array.isArray(e)){var d=!0;let h=e.length;for(let v=0;v<h;v++){let y=l;if(typeof e[v]!="string")return ya.errors=[{instancePath:t+"/"+v,schemaPath:"#/items/type",keyword:"type",params:{type:"string"}}],!1;var d=y===l;if(!d)break}if(d){let v=e.length,y;if(v>1){let w={};for(;v--;){let I=e[v];if(typeof I=="string"){if(typeof w[I]=="number")return y=w[I],ya.errors=[{instancePath:t,schemaPath:"#/uniqueItems",keyword:"uniqueItems",params:{i:v,j:y}}],!1;w[I]=v}}}}}else return ya.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"array"}}],!1;return ya.errors=s,l===0}ya.evaluated={items:!0,dynamicProps:!1,dynamicItems:!1};function Ot(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:i={}}={}){let s=null,l=0,m=Ot.evaluated;if(m.dynamicProps&&(m.props=void 0),m.dynamicItems&&(m.items=void 0),!(e&&typeof e=="object"&&!Array.isArray(e))&&typeof e!="boolean")return Ot.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:dy.type}}],!1;if(l===0&&e&&typeof e=="object"&&!Array.isArray(e)){let w=l;for(let I in e)if(!lz.call(dy.properties,I))return Ot.errors=[{instancePath:t,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:I}}],!1;if(w===l){if(e.$schema!==void 0){let I=l;if(e.$schema!=="https://json-schema.org/draft/2020-12/schema")return Ot.errors=[{instancePath:t+"/$schema",schemaPath:"#/properties/%24schema/const",keyword:"const",params:{allowedValue:"https://json-schema.org/draft/2020-12/schema"}}],!1;var d=I===l}else var d=!0;if(d){if(e.$ref!==void 0){let R=l;if(typeof e.$ref!="string")return Ot.errors=[{instancePath:t+"/$ref",schemaPath:"#/properties/%24ref/type",keyword:"type",params:{type:"string"}}],!1;var d=R===l}else var d=!0;if(d){if(e.$comment!==void 0){let M=l;if(typeof e.$comment!="string")return Ot.errors=[{instancePath:t+"/$comment",schemaPath:"#/properties/%24comment/type",keyword:"type",params:{type:"string"}}],!1;var d=M===l}else var d=!0;if(d){if(e.$defs!==void 0){let P=l;la(e.$defs,{instancePath:t+"/$defs",parentData:e,parentDataProperty:"$defs",rootData:o,dynamicAnchors:i})||(s=s===null?la.errors:s.concat(la.errors),l=s.length);var d=P===l}else var d=!0;if(d){if(e.properties!==void 0){let N=l;la(e.properties,{instancePath:t+"/properties",parentData:e,parentDataProperty:"properties",rootData:o,dynamicAnchors:i})||(s=s===null?la.errors:s.concat(la.errors),l=s.length);var d=N===l}else var d=!0;if(d){if(e.dependentSchemas!==void 0){let O=l;la(e.dependentSchemas,{instancePath:t+"/dependentSchemas",parentData:e,parentDataProperty:"dependentSchemas",rootData:o,dynamicAnchors:i})||(s=s===null?la.errors:s.concat(la.errors),l=s.length);var d=O===l}else var d=!0;if(d){if(e.allOf!==void 0){let j=l;_n(e.allOf,{instancePath:t+"/allOf",parentData:e,parentDataProperty:"allOf",rootData:o,dynamicAnchors:i})||(s=s===null?_n.errors:s.concat(_n.errors),l=s.length);var d=j===l}else var d=!0;if(d){if(e.anyOf!==void 0){let k=l;_n(e.anyOf,{instancePath:t+"/anyOf",parentData:e,parentDataProperty:"anyOf",rootData:o,dynamicAnchors:i})||(s=s===null?_n.errors:s.concat(_n.errors),l=s.length);var d=k===l}else var d=!0;if(d){if(e.oneOf!==void 0){let C=l;_n(e.oneOf,{instancePath:t+"/oneOf",parentData:e,parentDataProperty:"oneOf",rootData:o,dynamicAnchors:i})||(s=s===null?_n.errors:s.concat(_n.errors),l=s.length);var d=C===l}else var d=!0;if(d){if(e.prefixItems!==void 0){let T=l;_n(e.prefixItems,{instancePath:t+"/prefixItems",parentData:e,parentDataProperty:"prefixItems",rootData:o,dynamicAnchors:i})||(s=s===null?_n.errors:s.concat(_n.errors),l=s.length);var d=T===l}else var d=!0;if(d){if(e.items!==void 0){let z=l;It.validate(e.items,{instancePath:t+"/items",parentData:e,parentDataProperty:"items",rootData:o,dynamicAnchors:i})||(s=s===null?It.validate.errors:s.concat(It.validate.errors),l=s.length);var d=z===l}else var d=!0;if(d){if(e.additionalProperties!==void 0){let B=l;It.validate(e.additionalProperties,{instancePath:t+"/additionalProperties",parentData:e,parentDataProperty:"additionalProperties",rootData:o,dynamicAnchors:i})||(s=s===null?It.validate.errors:s.concat(It.validate.errors),l=s.length);var d=B===l}else var d=!0;if(d){if(e.not!==void 0){let D=l;It.validate(e.not,{instancePath:t+"/not",parentData:e,parentDataProperty:"not",rootData:o,dynamicAnchors:i})||(s=s===null?It.validate.errors:s.concat(It.validate.errors),l=s.length);var d=D===l}else var d=!0;if(d){if(e.if!==void 0){let V=l;It.validate(e.if,{instancePath:t+"/if",parentData:e,parentDataProperty:"if",rootData:o,dynamicAnchors:i})||(s=s===null?It.validate.errors:s.concat(It.validate.errors),l=s.length);var d=V===l}else var d=!0;if(d){if(e.then!==void 0){let le=l;It.validate(e.then,{instancePath:t+"/then",parentData:e,parentDataProperty:"then",rootData:o,dynamicAnchors:i})||(s=s===null?It.validate.errors:s.concat(It.validate.errors),l=s.length);var d=le===l}else var d=!0;if(d){if(e.else!==void 0){let te=l;It.validate(e.else,{instancePath:t+"/else",parentData:e,parentDataProperty:"else",rootData:o,dynamicAnchors:i})||(s=s===null?It.validate.errors:s.concat(It.validate.errors),l=s.length);var d=te===l}else var d=!0;if(d){if(e.contains!==void 0){let Ie=l;It.validate(e.contains,{instancePath:t+"/contains",parentData:e,parentDataProperty:"contains",rootData:o,dynamicAnchors:i})||(s=s===null?It.validate.errors:s.concat(It.validate.errors),l=s.length);var d=Ie===l}else var d=!0;if(d){if(e.unevaluatedProperties!==void 0){let ke=l;It.validate(e.unevaluatedProperties,{instancePath:t+"/unevaluatedProperties",parentData:e,parentDataProperty:"unevaluatedProperties",rootData:o,dynamicAnchors:i})||(s=s===null?It.validate.errors:s.concat(It.validate.errors),l=s.length);var d=ke===l}else var d=!0;if(d){if(e.unevaluatedItems!==void 0){let Z=l;It.validate(e.unevaluatedItems,{instancePath:t+"/unevaluatedItems",parentData:e,parentDataProperty:"unevaluatedItems",rootData:o,dynamicAnchors:i})||(s=s===null?It.validate.errors:s.concat(It.validate.errors),l=s.length);var d=Z===l}else var d=!0;if(d){if(e.propertyNames!==void 0){let Ae=l;It.validate(e.propertyNames,{instancePath:t+"/propertyNames",parentData:e,parentDataProperty:"propertyNames",rootData:o,dynamicAnchors:i})||(s=s===null?It.validate.errors:s.concat(It.validate.errors),l=s.length);var d=Ae===l}else var d=!0;if(d){if(e.type!==void 0){let he=e.type,ue=l,be=l,ne=!1,ge=l;lo(he,{instancePath:t+"/type",parentData:e,parentDataProperty:"type",rootData:o,dynamicAnchors:i})||(s=s===null?lo.errors:s.concat(lo.errors),l=s.length);var v=ge===l;ne=ne||v;let xe=l;if(l===xe)if(Array.isArray(he))if(he.length<1){let Se={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf/1/minItems",keyword:"minItems",params:{limit:1}};s===null?s=[Se]:s.push(Se),l++}else{var h=!0;let Se=he.length;for(let se=0;se<Se;se++){let we=l;lo(he[se],{instancePath:t+"/type/"+se,parentData:he,parentDataProperty:se,rootData:o,dynamicAnchors:i})||(s=s===null?lo.errors:s.concat(lo.errors),l=s.length);var h=we===l;if(!h)break}if(h){let se=he.length,we;if(se>1){e:for(;se--;)for(we=se;we--;)if(cz(he[se],he[we])){let Oe={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf/1/uniqueItems",keyword:"uniqueItems",params:{i:se,j:we}};s===null?s=[Oe]:s.push(Oe),l++;break e}}}}else{let Se={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf/1/type",keyword:"type",params:{type:"array"}};s===null?s=[Se]:s.push(Se),l++}var v=xe===l;if(ne=ne||v,ne)l=be,s!==null&&(be?s.length=be:s=null);else{let Se={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf",keyword:"anyOf",params:{}};return s===null?s=[Se]:s.push(Se),l++,Ot.errors=s,!1}var d=ue===l}else var d=!0;if(d){if(e.enum!==void 0){let ue=e.enum,be=l;if(l===be)if(Array.isArray(ue)){if(ue.length<1)return Ot.errors=[{instancePath:t+"/enum",schemaPath:"#/properties/enum/minItems",keyword:"minItems",params:{limit:1}}],!1}else return Ot.errors=[{instancePath:t+"/enum",schemaPath:"#/properties/enum/type",keyword:"type",params:{type:"array"}}],!1;var d=be===l}else var d=!0;if(d){if(e.title!==void 0){let be=l;if(typeof e.title!="string")return Ot.errors=[{instancePath:t+"/title",schemaPath:"#/properties/title/type",keyword:"type",params:{type:"string"}}],!1;var d=be===l}else var d=!0;if(d){if(e.description!==void 0){let ne=l;if(typeof e.description!="string")return Ot.errors=[{instancePath:t+"/description",schemaPath:"#/properties/description/type",keyword:"type",params:{type:"string"}}],!1;var d=ne===l}else var d=!0;if(d){if(e.examples!==void 0){let ge=l;if(!Array.isArray(e.examples))return Ot.errors=[{instancePath:t+"/examples",schemaPath:"#/properties/examples/type",keyword:"type",params:{type:"array"}}],!1;var d=ge===l}else var d=!0;if(d){if(e.readOnly!==void 0){let xe=l;if(typeof e.readOnly!="boolean")return Ot.errors=[{instancePath:t+"/readOnly",schemaPath:"#/properties/readOnly/type",keyword:"type",params:{type:"boolean"}}],!1;var d=xe===l}else var d=!0;if(d){if(e.writeOnly!==void 0){let qe=l;if(typeof e.writeOnly!="boolean")return Ot.errors=[{instancePath:t+"/writeOnly",schemaPath:"#/properties/writeOnly/type",keyword:"type",params:{type:"boolean"}}],!1;var d=qe===l}else var d=!0;if(d){if(e.deprecated!==void 0){let Se=l;if(typeof e.deprecated!="boolean")return Ot.errors=[{instancePath:t+"/deprecated",schemaPath:"#/properties/deprecated/type",keyword:"type",params:{type:"boolean"}}],!1;var d=Se===l}else var d=!0;if(d){if(e.multipleOf!==void 0){let se=e.multipleOf,we=l;if(l===we)if(typeof se=="number"&&isFinite(se)){if(se<=0||isNaN(se))return Ot.errors=[{instancePath:t+"/multipleOf",schemaPath:"#/properties/multipleOf/exclusiveMinimum",keyword:"exclusiveMinimum",params:{comparison:">",limit:0}}],!1}else return Ot.errors=[{instancePath:t+"/multipleOf",schemaPath:"#/properties/multipleOf/type",keyword:"type",params:{type:"number"}}],!1;var d=we===l}else var d=!0;if(d){if(e.maximum!==void 0){let we=e.maximum,Oe=l;if(!(typeof we=="number"&&isFinite(we)))return Ot.errors=[{instancePath:t+"/maximum",schemaPath:"#/properties/maximum/type",keyword:"type",params:{type:"number"}}],!1;var d=Oe===l}else var d=!0;if(d){if(e.exclusiveMaximum!==void 0){let Oe=e.exclusiveMaximum,Qe=l;if(!(typeof Oe=="number"&&isFinite(Oe)))return Ot.errors=[{instancePath:t+"/exclusiveMaximum",schemaPath:"#/properties/exclusiveMaximum/type",keyword:"type",params:{type:"number"}}],!1;var d=Qe===l}else var d=!0;if(d){if(e.minimum!==void 0){let Qe=e.minimum,Ge=l;if(!(typeof Qe=="number"&&isFinite(Qe)))return Ot.errors=[{instancePath:t+"/minimum",schemaPath:"#/properties/minimum/type",keyword:"type",params:{type:"number"}}],!1;var d=Ge===l}else var d=!0;if(d){if(e.exclusiveMinimum!==void 0){let Ge=e.exclusiveMinimum,st=l;if(!(typeof Ge=="number"&&isFinite(Ge)))return Ot.errors=[{instancePath:t+"/exclusiveMinimum",schemaPath:"#/properties/exclusiveMinimum/type",keyword:"type",params:{type:"number"}}],!1;var d=st===l}else var d=!0;if(d){if(e.maxLength!==void 0){let st=l;$t(e.maxLength,{instancePath:t+"/maxLength",parentData:e,parentDataProperty:"maxLength",rootData:o,dynamicAnchors:i})||(s=s===null?$t.errors:s.concat($t.errors),l=s.length);var d=st===l}else var d=!0;if(d){if(e.minLength!==void 0){let Le=l;$t(e.minLength,{instancePath:t+"/minLength",parentData:e,parentDataProperty:"minLength",rootData:o,dynamicAnchors:i})||(s=s===null?$t.errors:s.concat($t.errors),l=s.length);var d=Le===l}else var d=!0;if(d){if(e.maxItems!==void 0){let Fe=l;$t(e.maxItems,{instancePath:t+"/maxItems",parentData:e,parentDataProperty:"maxItems",rootData:o,dynamicAnchors:i})||(s=s===null?$t.errors:s.concat($t.errors),l=s.length);var d=Fe===l}else var d=!0;if(d){if(e.minItems!==void 0){let De=l;$t(e.minItems,{instancePath:t+"/minItems",parentData:e,parentDataProperty:"minItems",rootData:o,dynamicAnchors:i})||(s=s===null?$t.errors:s.concat($t.errors),l=s.length);var d=De===l}else var d=!0;if(d){if(e.maxContains!==void 0){let L=l;$t(e.maxContains,{instancePath:t+"/maxContains",parentData:e,parentDataProperty:"maxContains",rootData:o,dynamicAnchors:i})||(s=s===null?$t.errors:s.concat($t.errors),l=s.length);var d=L===l}else var d=!0;if(d){if(e.minContains!==void 0){let $=l;$t(e.minContains,{instancePath:t+"/minContains",parentData:e,parentDataProperty:"minContains",rootData:o,dynamicAnchors:i})||(s=s===null?$t.errors:s.concat($t.errors),l=s.length);var d=$===l}else var d=!0;if(d){if(e.maxProperties!==void 0){let H=l;$t(e.maxProperties,{instancePath:t+"/maxProperties",parentData:e,parentDataProperty:"maxProperties",rootData:o,dynamicAnchors:i})||(s=s===null?$t.errors:s.concat($t.errors),l=s.length);var d=H===l}else var d=!0;if(d){if(e.minProperties!==void 0){let Q=l;$t(e.minProperties,{instancePath:t+"/minProperties",parentData:e,parentDataProperty:"minProperties",rootData:o,dynamicAnchors:i})||(s=s===null?$t.errors:s.concat($t.errors),l=s.length);var d=Q===l}else var d=!0;if(d){if(e.uniqueItems!==void 0){let me=l;if(typeof e.uniqueItems!="boolean")return Ot.errors=[{instancePath:t+"/uniqueItems",schemaPath:"#/properties/uniqueItems/type",keyword:"type",params:{type:"boolean"}}],!1;var d=me===l}else var d=!0;if(d){if(e.required!==void 0){let _e=l;ya(e.required,{instancePath:t+"/required",parentData:e,parentDataProperty:"required",rootData:o,dynamicAnchors:i})||(s=s===null?ya.errors:s.concat(ya.errors),l=s.length);var d=_e===l}else var d=!0;if(d){if(e.dependentRequired!==void 0){let $e=e.dependentRequired,Xe=l;if(l===Xe)if($e&&typeof $e=="object"&&!Array.isArray($e))for(let rt in $e){let it=l;ya($e[rt],{instancePath:t+"/dependentRequired/"+rt.replace(/~/g,"~0").replace(/\//g,"~1"),parentData:$e,parentDataProperty:rt,rootData:o,dynamicAnchors:i})||(s=s===null?ya.errors:s.concat(ya.errors),l=s.length);var y=it===l;if(!y)break}else return Ot.errors=[{instancePath:t+"/dependentRequired",schemaPath:"#/properties/dependentRequired/type",keyword:"type",params:{type:"object"}}],!1;var d=Xe===l}else var d=!0;if(d){if(e.contentEncoding!==void 0){let Xe=l;if(typeof e.contentEncoding!="string")return Ot.errors=[{instancePath:t+"/contentEncoding",schemaPath:"#/properties/contentEncoding/type",keyword:"type",params:{type:"string"}}],!1;var d=Xe===l}else var d=!0;if(d)if(e.contentMediaType!==void 0){let Xe=l;if(typeof e.contentMediaType!="string")return Ot.errors=[{instancePath:t+"/contentMediaType",schemaPath:"#/properties/contentMediaType/type",keyword:"type",params:{type:"string"}}],!1;var d=Xe===l}else var d=!0}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}return Ot.errors=s,l===0}Ot.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};const uy="https://json-schema.org/draft/2020-12/schema",uz=1048576,mz=32768,pz=new Set(["properties","$defs","dependentSchemas"]),fz=new Set(["allOf","anyOf","oneOf","prefixItems"]),hz=new Set(["items","additionalProperties","not","if","then","else","contains","unevaluatedProperties","unevaluatedItems","propertyNames"]);function Jo(e,t=uz){const n=[{value:e,depth:0}],a=new Set;let o=0;for(;n.length;){const i=n.pop();if(i.exit){a.delete(i.value);continue}if(++o>1e5||i.depth>48)throw new Error("task_json_complexity_exceeded");if(i.value===null||typeof i.value=="string"||typeof i.value=="boolean"||typeof i.value=="number"&&Number.isFinite(i.value))continue;if(typeof i.value!="object")throw new Error("task_json_value_invalid");if(a.has(i.value))throw new Error("task_json_cycle");a.add(i.value),n.push({...i,exit:!0});const s=Object.getPrototypeOf(i.value);if(!Array.isArray(i.value)&&s!==Object.prototype&&s!==null)throw new Error("task_json_object_invalid");if(Object.getOwnPropertySymbols(i.value).length)throw new Error("task_json_symbol_invalid");if(Object.hasOwn(i.value,"toJSON"))throw new Error("task_json_serializer_invalid");if(Array.isArray(i.value)&&(i.value.length>1e4||Object.keys(i.value).length!==i.value.length))throw new Error("task_json_array_invalid");for(const[l,m]of Object.entries(Object.getOwnPropertyDescriptors(i.value))){if(m.get||m.set)throw new Error("task_json_accessor_invalid");if(Array.isArray(i.value)&&l!=="length"&&(!/^(0|[1-9]\d*)$/u.test(l)||Number(l)>=i.value.length))throw new Error("task_json_array_invalid");m.enumerable&&n.push({value:m.value,depth:i.depth+1})}}if(new TextEncoder().encode(JSON.stringify(e)).byteLength>t)throw new Error("task_json_size_exceeded")}function Eg(e){try{return gz(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 gz(e){if(Jo(e,mz),gl(e,e,new Set,0,{remaining:2048}),!cy(e)){const t=cy.errors?.[0];throw new Error(`Task schema ${t?.instancePath||"/"} violates ${t?.keyword??"schema"}.`)}}function gl(e,t,n,a,o){if(--o.remaining<0)throw new Error("Task schema reference expansion exceeds the validation budget.");if(typeof e=="boolean")return;if(!e||typeof e!="object"||Array.isArray(e))throw new Error("A task schema must be an object or boolean.");if(a>24||n.has(e))throw new Error("Recursive or deeply nested task schemas are not supported.");const i=new Set(n).add(e),s=e;if(s.$schema!==void 0&&s.$schema!==uy)throw new Error(`Task schemas must use ${uy}.`);for(const[l,m]of Object.entries(s))if(l==="$ref"){if(typeof m!="string"||!m.startsWith("#/$defs/"))throw new Error("Task schema references must be local JSON pointers into $defs.");let d=t;for(const h of m.slice(2).split("/")){if(/~(?![01])/u.test(h))throw new Error("Invalid task schema JSON pointer.");const v=h.replaceAll("~1","/").replaceAll("~0","~");if(!d||typeof d!="object"||!Object.hasOwn(d,v))throw new Error(`Task schema reference ${m} is missing.`);d=d[v]}gl(d,t,i,a+1,o)}else if(pz.has(l)){if(!m||typeof m!="object"||Array.isArray(m))throw new Error(`Invalid schema map ${l}.`);for(const d of Object.values(m))gl(d,t,i,a+1,o)}else if(fz.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)gl(d,t,i,a+1,o)}else hz.has(l)&&gl(m,t,i,a+1,o)}const vz=c({schemaVersion:S("openpond.modelJudgeReceipt.v1"),providerId:r().trim().min(1).max(200),modelId:r().trim().min(1).max(500),modelRevision:r().trim().min(1).max(500).nullable(),responseId:r().trim().min(1).max(500).nullable(),requestHash:Y,responseHash:Y,inputTokens:u().int().nonnegative().nullable(),outputTokens:u().int().nonnegative().nullable(),costUsd:u().finite().nonnegative().nullable()}).strict(),bz=c({schemaVersion:S("openpond.graderEvidence.v1"),graderId:E,graderVersion:r().trim().min(1).max(100),score:u().min(0).max(1).nullable(),passed:A(),rewardEligible:A(),failureClass:Zl.nullable(),feedback:f(r().max(2e4)).max(1e3),visibleEvidenceRefs:f(E).max(1e4),privilegedEvidenceRefs:f(E).max(1e4),modelJudgeReceipt:vz.optional()}).strict(),yz=bz.extend({contentHash:Y}).strict();c({score:u().min(0).max(1).nullable(),passed:A(),rewardEligible:A(),failureClass:Zl.nullable(),gradingStatus:b(["scored","unscorable","not_configured"])}).strict();const Bc={id:!0,version:!0,weight:!0,hardGate:!0,rewardEligible:!0,privileged:!0},Sz=Dt([zw.omit(Bc),Hw.omit(Bc),Bw.omit(Bc),Fw.omit(Bc),c({kind:S("learned_model"),modelVersion:ee,inputContract:dn}).strict()]),b1=c({schemaVersion:S("openpond.rewardRelease.v1"),id:E,revision:u().int().positive(),name:r().trim().min(1).max(500),description:r().max(1e4),implementation:Sz,rawScore:c({minimum:u().finite(),maximum:u().finite()}).strict(),assets:f(dn).max(1e3),fixtureSetRef:dn.optional(),calibrationCheckRef:ee.extend({revision:u().int().positive()}).optional()}).strict().superRefine((e,t)=>{if(e.fixtureSetRef&&(e.fixtureSetRef.visibility!=="verifier"||!e.assets.some(n=>rn(n)===rn(e.fixtureSetRef)))&&t.addIssue({code:"custom",path:["fixtureSetRef"],message:"Reward fixtures must be included as a private verifier asset."}),e.rawScore.minimum>=e.rawScore.maximum&&t.addIssue({code:"custom",path:["rawScore"],message:"A raw score contract requires minimum < maximum."}),e.implementation.kind!=="learned_model"&&(e.rawScore.minimum!==0||e.rawScore.maximum!==1)&&t.addIssue({code:"custom",path:["rawScore"],message:"Portable graders currently return scores in [0, 1]."}),e.implementation.kind==="schema"){const n=Eg(e.implementation.config.jsonSchema);n.valid||t.addIssue({code:"custom",path:["implementation","config","jsonSchema"],message:n.issues[0].message})}}),xu=b1.safeExtend({contentHash:Y}).strict(),lc=ee.extend({revision:u().int().positive()}).strict(),kz=Rt("kind",[c({kind:S("identity")}).strict(),c({kind:S("linear"),minimum:u().finite(),maximum:u().finite(),direction:b(["higher","lower"])}).strict()]),xz=c({graderId:E,reward:lc,role:b(["training","evaluation"]),normalization:kz,weight:u().nonnegative().max(1e3),required:A(),hardGate:A(),privileged:A(),fixtureRefs:f(ee).max(1e3)}).strict(),wz=c({schemaVersion:S("openpond.rewardBinding.v1"),id:E,revision:u().int().positive(),name:r().trim().min(1).max(500).optional(),description:r().max(1e4).optional(),recipeRef:lc.optional(),sources:f(xz).max(100),aggregation:S("weighted_mean"),unscorable:S("exclude_optional_require_all_required")}).strict().superRefine((e,t)=>{new Set(e.sources.map(n=>n.graderId)).size!==e.sources.length&&t.addIssue({code:"custom",path:["sources"],message:"Bound grader identities must be unique."}),e.sources.length&&!e.sources.some(n=>n.weight>0)&&t.addIssue({code:"custom",path:["sources"],message:"A configured binding needs at least one positively weighted source."});for(const[n,a]of e.sources.entries())a.hardGate&&!a.required&&t.addIssue({code:"custom",path:["sources",n],message:"A hard gate must be required."}),a.normalization.kind==="linear"&&a.normalization.minimum>=a.normalization.maximum&&t.addIssue({code:"custom",path:["sources",n,"normalization"],message:"Linear normalization requires minimum < maximum."})}),wu=wz.safeExtend({contentHash:Y}).strict(),Iz=c({graderId:E,reward:lc,role:b(["training","evaluation"]),status:b(["scored","pending","unavailable","failed"]),rawScore:u().finite().nullable(),normalizedScore:u().min(0).max(1).nullable(),passed:A().nullable(),evidenceHashes:f(Y).max(1e3),graderEvidence:yz.optional(),message:r().max(2e4).nullable()}).strict(),_z=c({schemaVersion:S("openpond.rewardComposition.v1"),binding:lc,taskHash:Y,outputHash:Y,results:f(Iz).max(100),training:c({status:b(["scored","unscorable","not_configured"]),score:u().min(0).max(1).nullable(),passed:A().nullable()}).strict(),evaluation:c({status:b(["scored","unscorable","not_configured"]),score:u().min(0).max(1).nullable(),passed:A().nullable()}).strict()}).strict(),jd=_z.extend({contentHash:Y}).strict();function uY(e){Jo(e);const t=b1.parse(e);return xu.parse({...t,contentHash:rn(t)})}const Cz=c({text:r().max(1e5),modelId:r().trim().min(1).max(500),modelRevision:r().trim().min(1).max(500).nullable(),responseId:r().trim().min(1).max(500).nullable(),inputTokens:u().int().nonnegative().nullable(),outputTokens:u().int().nonnegative().nullable(),costUsd:u().finite().nonnegative().nullable()}).strict(),Rz=c({id:E,requestHash:Y,reservedUsd:u().finite().positive(),status:b(["reserved","settled","not_dispatched"]),response:Cz.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."})}),y1=c({localTime:r().regex(/^(?:[01]\d|2[0-3]):[0-5]\d$/),timeZone:r().min(1).max(200).refine(e=>{try{return new Intl.DateTimeFormat("en",{timeZone:e}),!0}catch{return!1}},"Choose a valid IANA timezone.")}).strict(),Vt=ie(r(),Br()),wt=lc,nr=r().max(2e3).refine(e=>e===""||e.startsWith("/")&&!/~(?![01])/u.test(e),"Use an RFC 6901 JSON pointer."),Pz=c({schemaVersion:S("openpond.taskDefinition.v1"),id:E,revision:u().int().positive(),name:r().trim().min(1).max(500),description:r().max(1e4),instructions:r().trim().min(1).max(2e4),category:b(["structured","question_answering","coding","tool_workflow","custom"]),familyNamespace:E,inputSchema:ie(r(),ce()),outputSchema:ie(r(),ce()),requiredOutputs:wg.shape.requiredOutputs,contextRequirements:f(r().trim().min(1).max(2e3)).max(100).optional(),rewardBinding:wt,harness:ee.nullable(),execution:Kw.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=Eg(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."})}),Iu=Pz.safeExtend({contentHash:Y}).strict(),Az=c({schemaVersion:S("openpond.taskSourceMapping.v1"),exampleId:nr,attemptId:nr,occurredAt:nr,input:nr,observedOutput:nr.nullable(),expected:nr.nullable(),evaluatorContext:nr.nullable(),familyKey:nr,split:Zo}).strict(),Tz=c({modelId:E,packageHash:Y,taskset:wt,batch:wt,rewardBinding:wt}).strict(),Ez=c({schemaVersion:S("openpond.learningSource.v1"),id:E,revision:u().int().positive(),name:r().trim().min(1).max(500),kind:b(["direct","benchmark","work","opentelemetry","provider"]),taskDefinition:wt,enabled:A(),allowedSplits:f(Zo).min(1).max(4),mapping:Az.nullable(),adapterVersion:r().trim().min(1).max(200).nullable(),reviewOrigin:Tz.optional()}).strict().superRefine((e,t)=>{e.kind!=="direct"&&!e.mapping&&t.addIssue({code:"custom",path:["mapping"],message:"Mapped sources require an explicit mapping."}),e.mapping&&!e.allowedSplits.includes(e.mapping.split)&&t.addIssue({code:"custom",path:["allowedSplits"],message:"The mapping split must be allowed by this source."}),["opentelemetry","provider"].includes(e.kind)&&!e.adapterVersion&&t.addIssue({code:"custom",path:["adapterVersion"],message:"Trace adapters require a pinned version."})}),Mg=Ez.safeExtend({contentHash:Y}).strict(),Mz=c({schemaVersion:S("openpond.taskExample.v1"),sourceId:E,idempotencyKey:E,taskDefinition:wt,exampleId:E,attemptId:E,occurredAt:Pe,familyKey:E.nullable(),split:Zo,input:Vt,observedOutput:Vt.nullable(),expected:Vt.nullable(),evaluatorContext:Vt.nullable(),assets:f(dn).max(1e3),requiredOutputs:wg.shape.requiredOutputs,provenance:c({sourceRecordRef:r().max(2e3).nullable(),mappingHash:Y.nullable()}).strict()}).strict(),jz=c({schemaVersion:S("openpond.taskEvidence.v1"),id:E,revision:u().int().positive(),source:wt,submission:Mz,supersedes:wt.nullable(),correctionFeedbackId:E.nullable(),receivedAt:Pe}).strict(),_u=jz.extend({contentHash:Y}).strict(),Oz=c({schemaVersion:S("openpond.taskRating.v1"),criteria:r().trim().min(1).max(2e4),scale:c({minimum:u().finite(),maximum:u().finite()}).strict(),score:u().finite(),evidence:r().max(2e4),explanation:r().max(2e4)}).strict().superRefine((e,t)=>{e.scale.minimum>=e.scale.maximum&&t.addIssue({code:"custom",path:["scale"],message:"The score scale must have an increasing range."}),(e.score<e.scale.minimum||e.score>e.scale.maximum)&&t.addIssue({code:"custom",path:["score"],message:"The score must be within its declared scale."})}),$z=c({schemaVersion:S("openpond.taskFeedback.v1"),sourceId:E,idempotencyKey:E,exampleId:E,attemptId:E,expectedEvidenceHash:Y.nullable(),occurredAt:Pe,kind:b(["outcome","target_correction","ground_truth_correction","input_correction","family_resolution"]),value:Vt,note:r().max(2e4)}).strict().superRefine((e,t)=>{if(e.value.schemaVersion!=="openpond.taskRating.v1")return;e.expectedEvidenceHash===null&&t.addIssue({code:"custom",path:["expectedEvidenceHash"],message:"A rating must identify the exact evidence revision."}),e.kind!=="outcome"&&t.addIssue({code:"custom",path:["kind"],message:"Ratings must be submitted as outcomes."});const n=Oz.safeParse(e.value);if(!n.success)for(const a of n.error.issues)t.addIssue({code:"custom",path:["value",...a.path],message:a.message})}),S1=c({schemaVersion:S("openpond.taskFeedbackRecord.v1"),id:E,submission:$z,status:b(["pending_example","pending_review","applied","superseded","rejected"]),evidence:wt.nullable(),createdAt:Pe,revision:u().int().positive(),submittedBy:c({id:E,role:b(["editor","reviewer","source"]),sourceId:E.nullable()}).strict().nullable().default(null),review:c({actorId:E,decision:wt.nullable(),note:r().max(2e4),resolvedAt:Pe}).strict().nullable().default(null)}).strict(),Nz=c({schemaVersion:S("openpond.taskAdmissionDecision.v1"),id:E,revision:u().int().positive(),evidence:wt,supersedes:wt.nullable(),actor:c({kind:b(["human","qualified_policy"]),id:E,policy:wt.nullable()}).strict(),evidenceValidity:b(["valid","invalid","pending"]),taskAdmissibility:b(["approved","rejected","pending"]),observedQuality:b(["passed","failed","unscored","unavailable"]),targetApproval:b(["approved","rejected","pending","not_required"]),approvedTarget:Vt.nullable(),grade:jd.nullable(),targetGrade:jd.nullable(),note:r().max(2e4),decidedAt:Pe}).strict().superRefine((e,t)=>{e.targetApproval==="approved"&&e.approvedTarget===null&&t.addIssue({code:"custom",path:["approvedTarget"],message:"Target approval requires an actual target."}),e.targetApproval!=="approved"&&e.approvedTarget!==null&&t.addIssue({code:"custom",path:["approvedTarget"],message:"Only approved targets may be selected for supervised learning."}),e.actor.kind==="qualified_policy"&&!e.actor.policy&&t.addIssue({code:"custom",path:["actor"],message:"Automatic admission must pin its qualified policy."}),e.taskAdmissibility==="approved"&&e.evidenceValidity!=="valid"&&t.addIssue({code:"custom",path:["taskAdmissibility"],message:"Only valid evidence can produce an approved task."})}),jg=Nz.safeExtend({contentHash:Y}).strict(),Dz=c({schemaVersion:S("openpond.taskBatch.v1"),id:E,revision:S(1),taskDefinition:wt,rewardBinding:wt,purpose:b(["supervised_training","reward_training","evaluation"]),examples:f(c({evidence:wt,decision:wt,familyKey:E,inputHash:Y,split:Zo}).strict()).min(1).max(1e4),sealedAt:Pe,sealedBy:E}).strict().superRefine((e,t)=>{new Set(e.examples.map(a=>a.evidence.id)).size!==e.examples.length&&t.addIssue({code:"custom",path:["examples"],message:"Each evidence identity can occur only once in a batch."});const n=new Map;for(const[a,o]of e.examples.entries()){e.purpose==="evaluation"==(o.split==="train")&&t.addIssue({code:"custom",path:["examples",a,"split"],message:"Training uses train examples; evaluation uses held-out examples."});for(const i of[`family:${o.familyKey}`,`input:${o.inputHash}`])n.has(i)&&n.get(i)!==o.split&&t.addIssue({code:"custom",path:["examples",a],message:"A task family or identical input cannot cross splits."}),n.set(i,o.split)}}),k1=Dz.safeExtend({contentHash:Y}).strict(),Lz=c({schemaVersion:S("openpond.learningPolicy.v1"),id:E,revision:u().int().positive(),modelProjectId:E,executionOwner:b(["local","hosted"]),enabled:A(),sources:f(wt).min(1).max(100),taskDefinition:wt,rewardBinding:wt,admission:c({mode:b(["human","qualified_automatic"]),qualification:ee.nullable(),minimumApprovedExamples:u().int().positive().max(1e5)}).strict(),trigger:Rt("kind",[c({kind:S("manual")}).strict(),c({kind:S("approved_count")}).strict(),c({kind:S("schedule"),intervalSeconds:u().int().min(60).max(31536e3)}).strict(),y1.extend({kind:S("nightly")}).strict(),c({kind:S("upstream_accepted"),modelProjectId:E}).strict()]),trainingParent:ee,teacher:ee.nullable(),training:c({method:b(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),recipe:ee,retentionEvaluation:ee,replayBatches:f(ee).max(100)}).strict(),limits:c({maxIterationSpendUsd:u().positive().max(1e5),maxDailySpendUsd:u().positive().max(1e6),cooldownSeconds:u().int().nonnegative().max(31536e3),maxRetries:u().int().nonnegative().max(10),maxBatchExamples:u().int().positive().max(1e4),maxBacklogExamples:u().int().positive().max(1e6)}).strict(),automation:c({collect:A(),train:A(),accept:A(),serve:A()}).strict(),acceptance:c({minimumScore:u().min(0).max(1),maximumRetentionRegression:u().min(0).max(1),requireImprovement:A(),rollbackVersion:ee.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."})}),Uz=Lz.safeExtend({contentHash:Y}).strict(),zz=c({iterationId:E,iterationRevision:u().int().positive(),candidate:ee,decision:wt,decidedAt:Pe}).strict(),Hz=b(["waiting_for_data","waiting_for_review","ready","dispatching","training","evaluating","candidate_ready","accepted","rejected","paused","failed","cancelling","cancelled","completed_without_candidate"]),qz=c({schemaVersion:S("openpond.learningIteration.v1"),id:E,revision:u().int().positive(),policy:wt,status:Hz,triggerIdentity:E,batch:wt.nullable(),sourceWatermarks:ie(E,u().int().nonnegative()),trainingParent:ee,trainingParentSelection:zz.nullable().optional(),teacher:ee.nullable(),upstreamEvent:ee.nullable(),trainingJob:ee.nullable(),evaluationJob:ee.nullable(),candidateVersion:ee.nullable(),candidateDecision:wt.nullable().default(null),candidateDecisionAt:Pe.nullable().optional(),dispatchId:E,retryCount:u().int().nonnegative(),spendUsd:u().nonnegative(),failure:c({code:E,message:r().max(2e4)}).strict().nullable(),createdAt:Pe,updatedAt:Pe}).strict(),Bz=c({schemaVersion:S("openpond.taskGradeRun.v1"),id:E,revision:u().int().positive(),evidence:wt,binding:wt,target:b(["observed","proposed_target"]),output:Vt,status:b(["queued","running","completed","failed","cancelling","cancelled"]),composition:jd.nullable(),leaseOwner:E.nullable(),leaseExpiresAt:Pe.nullable(),attemptCount:u().int().nonnegative(),timeoutMs:u().int().min(100).max(3e5),maximumSpendUsd:u().nonnegative().max(1e3),judgeCalls:f(Rz).max(1e4).optional(),requestedBy:E.optional(),failure:r().max(2e4).nullable(),createdAt:Pe,updatedAt:Pe}).strict();Dt([Iu,xu,wu,Mg,_u,S1,jg,k1,Uz,qz,Bz]);function Fz(e){return wt.parse({id:e.id,revision:e.revision,contentHash:e.contentHash})}function mY(e,t){return e.id===t.id&&e.revision===t.revision&&e.contentHash===t.contentHash}function pY(e){return Jo(e,16777216),{...e,contentHash:rn(e)}}function fY(e){const{contentHash:t,...n}=e;if(Jo(n,16777216),rn(n)!==t)throw new g1("learning_content_hash_mismatch",422)}const x1=c({schemaVersion:S("openpond.learningTextAsset.v1"),id:E,revision:S(1),asset:dn,text:r().max(524288)}).strict().superRefine((e,t)=>{e.asset.id!==e.id&&t.addIssue({code:"custom",path:["asset","id"],message:"Asset identity must match the stored resource."}),(e.asset.sizeBytes!==new TextEncoder().encode(e.text).byteLength||e.asset.sizeBytes>524288)&&t.addIssue({code:"custom",path:["asset","sizeBytes"],message:"Authored source must match its byte count and fit within 512 KiB."}),e.asset.contentHash!==Eh(e.text)&&t.addIssue({code:"custom",path:["asset","contentHash"],message:"Asset source does not match its SHA-256."})}),Cu=x1.safeExtend({contentHash:Y}).strict();function hY(e){Jo(e);const{text:t,...n}=e,a=Eh(t),o=`asset-${a}-${rn(n).slice(0,16)}`,i=x1.parse({schemaVersion:"openpond.learningTextAsset.v1",id:o,revision:1,asset:{...n,id:o,contentHash:a,sizeBytes:new TextEncoder().encode(t).byteLength},text:t});return Cu.parse({...i,contentHash:rn(i)})}function gY(e,t){const{contentHash:n,...a}=Cu.parse(e);if(rn(a)!==n||rn(a.asset)!==rn(t))throw new g1("learning_asset_reference_mismatch",409);return a.text}const Na={bytes:5*1024*1024,records:1e3,files:100,messages:2e3},w1=b(["json","jsonl","csv","hermes","openclaw"]),Vz=c({path:r().min(1).max(500),text:r()}).strict(),Og=c({id:r().min(1).max(200),familyKey:r().min(1).max(200),split:Zo,kind:b(["task","attempt"]),input:Vt,observedOutput:Vt.nullable(),expected:Vt.nullable(),sourceId:r().min(1).max(2e3),sourceHash:r().length(64),occurredAt:r().datetime().nullable(),metadata:Vt,warnings:f(r().max(2e3)).max(100),needsContext:A()}).strict(),I1=c({schemaVersion:S("openpond.taskIntakePreview.v1"),format:w1,contentHash:r().length(64),records:f(Og).max(Na.records),issues:f(c({file:r(),row:u().int().positive().nullable(),message:r()}).strict()).max(1e3)}).strict();function Od(e,t){return`${e}-${rn(t)}`}function _1(e){if(typeof e!="string"&&typeof e!="number")return null;const t=new Date(typeof e=="number"?e*1e3:e);return Number.isFinite(t.getTime())?t.toISOString():null}function Kz(e){const t=[];let n=[],a="",o=!1,i=!1;const s=()=>{n.push(a),a="",i=!1},l=()=>{if(s(),n.some(h=>h.length)&&t.push(n),n=[],t.length>Na.records+1)throw new Error("CSV exceeds the 1,000-record limit.")};for(let h=0;h<e.length;h++){const v=e[h];if(o)v==='"'&&e[h+1]==='"'?(a+='"',h++):v==='"'?(o=!1,i=!0):a+=v;else if(v===",")s();else if(v===`
|
|
176
|
+
`||v==="\r")v==="\r"&&e[h+1]===`
|
|
177
|
+
`&&h++,l();else if(v==='"'&&!a&&!i)o=!0;else{if(i||v==='"')throw new Error("CSV has an invalid quoted field.");a+=v}}if(o)throw new Error("CSV has an unterminated quoted field.");(a||n.length||i)&&l();const m=t.shift()?.map(h=>h.trim().replace(/^\uFEFF/u,""));if(!m?.includes("instruction"))throw new Error("CSV requires an instruction column.");const d=new Set(["instruction","context","reference","labels","id","familyKey","split"]);if(m.some(h=>!d.has(h))||new Set(m).size!==m.length)throw new Error("CSV has duplicate or unsupported columns. Use instruction, context, reference, labels, id, familyKey and split.");return t.map((h,v)=>{if(h.length!==m.length)throw new Error(`CSV record ${v+2} has a different number of columns from its header.`);return Object.fromEntries(m.map((y,w)=>[y,h[w]]).filter(([,y])=>y!==""))})}function vY(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 C1(e){return e.startsWith("\uFEFF")?e.slice(1):e}const R1=c({role:r().min(1),content:Br().nullable().optional()}).catchall(Br()),Wz=c({id:r().min(1),messages:f(R1).min(1).max(Na.messages),lineage_session_ids:f(r()).optional(),parent_session_id:r().nullable().optional()}).catchall(Br());function Gz(e){const t=Wz.parse(e),n=t.lineage_session_ids?.[0]??t.parent_session_id??t.id,{messages:a,segments:o,...i}=t;return P1("hermes",t.id,n,t.messages,{sourceHash:rn(e),metadata:{session:i},warnings:["Imported session context and tools need review before this can become an executable task."]})}const Zz=c({traceSchema:S("openclaw-trajectory"),schemaVersion:S(1),traceId:r().min(1),sessionId:r().min(1),leafId:r().nullable(),eventCount:u().int().nonnegative(),warnings:f(Vt).optional()}).catchall(Br()),Jz=c({traceSchema:S("openclaw-trajectory"),schemaVersion:S(1),traceId:r(),sessionId:r(),seq:u().int().nonnegative(),type:r(),ts:r()}).catchall(Br()),Yz=c({header:Vt.nullable(),leafId:r().nullable(),entries:f(c({id:r().min(1),type:r().min(1),parentId:r().nullable().optional(),message:R1.optional()}).catchall(Br())).max(Na.messages)}).strict();function Qz(e){const t=l=>{const m=e.find(d=>d.path===l);if(!m)throw new Error(`OpenClaw bundle is missing ${l}.`);return C1(m.text)},n=Zz.parse(JSON.parse(t("manifest.json"))),a=Yz.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=>Jz.parse(JSON.parse(l)));if(o.length!==n.eventCount||o.some(l=>l.traceId!==n.traceId||l.sessionId!==n.sessionId))throw new Error("OpenClaw events do not match the manifest identity or count.");if(a.header&&a.header.id!==n.sessionId)throw new Error("OpenClaw session header does not match the manifest.");const i=new Set;for(const[l,m]of a.entries.entries()){if(i.has(m.id))throw new Error("OpenClaw branch contains duplicate entry IDs.");if(l&&m.parentId!==a.entries[l-1].id)throw new Error("OpenClaw branch is incomplete or out of order.");i.add(m.id)}if(a.entries.length&&a.entries.at(-1).id!==a.leafId)throw new Error("OpenClaw branch does not reach its declared leaf.");const s=a.entries.filter(l=>l.type==="message"&&l.message).map(l=>({...l.message,entryId:l.id,timestamp:typeof l.timestamp=="string"?l.timestamp:typeof l.message.timestamp=="number"?new Date(l.message.timestamp).toISOString():null}));return P1("openclaw",n.sessionId,n.sessionId,s,{sourceHash:rn(e),metadata:{manifest:n,sourceFiles:e.map(l=>l.path)},warnings:["Imported trajectory context and tools need review before this can become an executable task.",...(n.warnings??[]).map(l=>typeof l.message=="string"?l.message.slice(0,2e3):"The source exporter reported incomplete context.")]})}function P1(e,t,n,a,o){const i=a.flatMap((l,m)=>l.role==="user"?[m]:[]);if(!i.length)throw new Error("This history contains no user request. Supply a session with its request context.");let s=0;return i.map((l,m)=>{const d=i[m+1]??a.length,h=a.slice(l+1,d),v=h.filter(R=>R.role==="assistant").at(-1),y=a[l],w=y.entryId??y.message_id??y.id??rn({start:l,request:y}),I={id:Od(e,[t,w]),familyKey:Od(e,n),split:"train",kind:"attempt",input:{request:y.content??null,messages:a.slice(0,l+1)},observedOutput:v?{response:v.content??null,messages:h}:null,expected:null,sourceId:`${e}:${t}:${String(w)}`,sourceHash:o.sourceHash,occurredAt:_1(v?.timestamp??y.timestamp),metadata:o.metadata,warnings:[...o.warnings,...v?[]:["No assistant response was recorded for this request."]],needsContext:!0};if(Jo(I),s+=new TextEncoder().encode(JSON.stringify(I)).length,s>Na.bytes)throw new Error("Expanded history exceeds the 5 MiB preview limit. Export a smaller session selection.");return Og.parse(I)})}const Xz=c({instruction:r().trim().min(1).max(1e5),context:Dt([r(),Vt]).optional(),reference:Dt([r(),Vt]).optional(),labels:Dt([r(),f(r()),Vt]).optional(),id:r().min(1).max(200).optional(),familyKey:r().min(1).max(200).optional(),split:Zo.optional()}).strict(),eH=c({input:Vt,observedOutput:Vt.nullable().optional(),expectedOutput:Vt.nullable().optional(),id:r().min(1).max(200).optional(),familyKey:r().min(1).max(200).optional(),split:Zo.optional(),occurredAt:r().datetime().optional(),labels:Vt.optional()}).strict();function tH(e){const t=w1.parse(e.format),n=f(Vz).min(1).max(Na.files).parse(e.files);if(n.reduce((d,h)=>d+new TextEncoder().encode(h.text).length,0)>Na.bytes)throw new Error("Import exceeds the 5 MiB size limit.");if(n.some(d=>d.path.startsWith("/")||d.path.includes("\\")||d.path.split("/").some(h=>!h||h==="."||h===".."))||new Set(n.map(d=>d.path)).size!==n.length)throw new Error("Import contains an unsafe or duplicate file path.");const a=[],o=[],i=new Map,s=new Map;let l=0;function m(d,h,v){try{const y=v();if(a.length+y.length>Na.records)throw new Error("Import exceeds the 1,000-record limit.");const w=new Map(i),I=new Map(s);let R=0;for(const M of y){Jo(M);const P=rn(M),N=w.get(M.id);if(N&&N!==P)throw new Error("The same record identity has different content in this upload.");N||(R+=new TextEncoder().encode(JSON.stringify(M)).length),w.set(M.id,P);for(const O of[`family:${M.familyKey}`,`input:${rn(M.input)}`]){if(I.has(O)&&I.get(O)!==M.split)throw new Error("The same task family or request occurs in different splits.");I.set(O,M.split)}}if(l+R>Na.bytes*2)throw new Error("Expanded import exceeds the 10 MiB preview limit. Select fewer source files.");for(const M of y)i.has(M.id)||a.push(M),i.set(M.id,rn(M));for(const[M,P]of I)s.set(M,P);l+=R}catch(y){o.push({file:d,row:h,message:y instanceof bE?`Unsupported record fields or values (${y.issues.slice(0,3).map(w=>w.path.join(".")||"record").join(", ")}).`:y instanceof SyntaxError?"Invalid JSON.":y instanceof Error?y.message:"Invalid import record."})}}if(t==="openclaw")m("manifest.json",null,()=>Qz(n));else for(const d of n){const h=C1(d.text);if(t==="jsonl"||t==="hermes"){for(const[v,y]of h.split(/\r?\n/u).entries())if(y.trim()){if(o.length>=Na.records)break;m(d.path,v+1,()=>t==="hermes"?Gz(JSON.parse(y)):[my(JSON.parse(y))])}}else{let v;try{const y=t==="csv"?Kz(h):JSON.parse(h);v=Array.isArray(y)?y:[y]}catch(y){m(d.path,null,()=>{throw y});continue}if(v.length>Na.records){m(d.path,null,()=>{throw new Error("Import exceeds the 1,000-record limit.")});continue}v.forEach((y,w)=>m(d.path,w+(t==="csv"?2:1),()=>[my(y)]))}}return I1.parse({schemaVersion:"openpond.taskIntakePreview.v1",format:t,contentHash:rn({format:t,files:n}),records:a,issues:o.slice(0,1e3)})}function my(e){const t=Dt([Xz,eH]).parse(e),n="instruction"in t,a=n?{instruction:t.instruction,...t.context===void 0?{}:{context:t.context}}:t.input,o=n?t.reference===void 0?null:typeof t.reference=="string"?{text:t.reference}:t.reference:t.expectedOutput??null,i=n?null:t.observedOutput??null,s=t.familyKey??Od("family",a),l=t.id??Od("task",{input:a,expected:o,observedOutput:i});return Og.parse({id:l,familyKey:s,split:t.split??"train",kind:i?"attempt":"task",input:a,expected:o,observedOutput:i,sourceId:l,sourceHash:rn(e),occurredAt:n?null:_1(t.occurredAt),metadata:t.labels===void 0?{}:{importedLabels:t.labels,labelOrigin:"unverified_import"},warnings:[],needsContext:!1})}var Vr=wt.shape.id,Ll=r().regex(/^[a-f0-9]{64}$/),nH=c({scopeId:Vr,modelId:Vr}).strict(),aH=c({schemaVersion:S("openpond.modelTasksetAuthoring.v1"),owner:nH,root:wt,parent:wt}).strict(),bY=c({schemaVersion:S("openpond.modelTasksetDraftRequest.v1"),operationId:Vr,modelId:Vr,expectedModelRevision:u().int().positive(),sourcePackageHash:Ll}).strict(),oH=c({schemaVersion:S("openpond.modelTasksetDraftPreparation.v1"),draftId:Vr,requestHash:Ll,sourcePackageHash:Ll,sourceTasksetRef:wt,tasksetId:Vr,tasksetRevision:u().int().positive(),lineage:aH,authoringGraph:S("bound").optional()}).strict(),Ru=r().min(1).max(1024).refine(e=>!e.includes("\\")&&!e.includes(":")&&!e.includes("\0")&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."||t.startsWith(".env")),"Use a relative Taskset file path without environment files."),A1=c({path:Ru,sizeBytes:u().int().nonnegative(),writable:A()}).strict(),T1=c({encoding:b(["utf8","base64"]),data:r().max(8e6)}).strict(),rH=A1.extend({contentHash:Ll,content:T1}).strict();c({draftId:Vr,expectedDraftRevision:u().int().positive(),path:Ru,expectedFileHash:Ll.nullable(),content:T1.nullable()}).strict();var iH=y1.extend({mode:b(["nightly","approved_count"]),minimumTasks:u().int().min(1).max(1e4),maximumSpendUsd:u().positive().max(1e5),maximumDailySpendUsd:u().positive().max(1e6)}).strict().superRefine((e,t)=>{e.maximumDailySpendUsd<e.maximumSpendUsd&&t.addIssue({code:"custom",path:["maximumDailySpendUsd"],message:"The daily budget must cover one update."})}),sH=67108864,jf=524288,vl=class extends Error{code;constructor(e,t){super(t),this.name="OpenPondProtocolError",this.code=e}};function E1(e){return JSON.stringify(Of(e))}function lH(e){return new TextEncoder().encode(E1(e)).byteLength}async function cH(e){const t=new TextEncoder().encode(E1(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 dH(e,t,n){const a=lH(e);if(a>t)throw new vl("payload_too_large",`${n} is ${a} bytes; the maximum is ${t} bytes.`)}function Of(e){if(e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number"){if(!Number.isFinite(e))throw new vl("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=>Of(t));if(typeof e=="object"){const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)throw new vl("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 vl("non_json_value",`Canonical JSON cannot contain ${typeof o} at ${a}.`);n[a]=Of(o)}return n}throw new vl("non_json_value",`Canonical JSON cannot contain ${typeof e}.`)}var Mt=r().trim().min(1).max(500),uo=r().regex(/^[a-f0-9]{64}$/),Ia=r().datetime({offset:!0}),Nt=c({id:Mt,contentHash:uo}).strict(),mr=Nt.extend({revision:u().int().positive()}).strict(),Xr=c({schemaVersion:S("openpond.baseModelPreference.v1"),modelId:Mt,revision:r().trim().min(1).max(256).nullable(),tokenizerRevision:r().trim().min(1).max(256).nullable(),chatTemplateHash:r().trim().min(8).max(256).nullable(),modelAssetId:Mt.nullable(),source:b(["managed","local","builtin"])}).strict(),M1=b(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),j1=c({schemaVersion:r().regex(/^openpond\.[A-Za-z0-9]+Recipe\.v\d+$/),method:M1,parameterization:b(["lora","full"])}).catchall(ce()),uH=c({profileProjectId:Mt,sourceRevision:r().regex(/^[a-f0-9]{40,64}$/),harnessRelease:Nt}).strict(),mH=c({profileProjectId:Mt,sourceRevision:r().regex(/^[a-f0-9]{40,64}$/),catalogHash:uo,definitionId:Mt,harnessRelease:Nt,tasksetRelease:Nt}).strict(),O1=c({tasksetRef:mr.nullable().default(null),evaluationTasksetRef:mr.nullable().optional(),profileSource:uH.nullable().optional(),profileEvaluation:mH.nullable().optional(),rewardBindingRef:mr.nullable().optional(),tasksetRelease:Nt.nullable().default(null),harnessRelease:Nt.nullable().default(null),baseModel:Xr.nullable().default(null),method:M1.nullable().default(null),destinationId:Mt.nullable().default(null),managedRolloutPlacement:b(["local","remote"]).default("remote"),managedGpuPlacementObjective:b(["fast","balanced","economical"]).default("balanced"),managedGpuRequirement:b(["any","h100_hbm3"]).default("any"),runPreset:b(["small","standard","custom","small_experiment"]).nullable().default(null),recipe:j1.nullable().default(null),preferredMaximumSpendUsd:u().nonnegative().nullable().default(null),preferredRetentionDays:u().int().nonnegative().nullable().default(null)}).strict(),$g=O1.omit({managedGpuRequirement:!0}),pH=c({schemaVersion:S("openpond.hostedModelProjectLink.v1"),apiOrigin:r().url().refine(e=>new URL(e).origin===e,"Use a canonical API origin.").nullable().default(null),teamId:Mt,projectId:Mt,portableProjectId:Mt,revision:u().int().positive(),etag:uo,syncedSourceRevision:u().int().positive(),syncedAt:Ia,tasksets:f(c({localTasksetId:Mt,localTasksetHash:uo.nullable().default(null),releaseId:Mt,releaseRevision:u().int().positive(),releaseHash:uo,packageHash:uo.nullable().default(null),hostedTasksetId:Mt,syncedAt:Ia}).strict()).max(1e4).default([])}).strict(),fH=c({localTasksetId:Mt,releaseId:Mt,releaseRevision:u().int().positive(),releaseHash:uo,state:b(["syncing","synced","sync_failed"]),hostedTasksetId:Mt.nullable().default(null),lastAttemptAt:Ia,syncedAt:Ia.nullable().default(null),lastError:r().trim().min(1).max(5e3).nullable().default(null)}).strict(),$1=c({schemaVersion:S("openpond.modelProject.v2"),id:Mt,profileId:Mt,revision:u().int().positive().default(1),name:r().trim().min(1).max(200),objective:r().trim().max(5e3).nullable(),defaultBaseModel:Xr.nullable(),defaultDestinationId:Mt.nullable(),trainingSetup:O1,hosted:pH.nullable().default(null),tasksetSyncs:f(fH).max(1e4).default([]),createdAt:Ia,updatedAt:Ia}).strict(),N1=$1.pick({id:!0,profileId:!0,name:!0,objective:!0,defaultBaseModel:!0,defaultDestinationId:!0,trainingSetup:!0}),hH=c({schemaVersion:S("openpond.modelProjectSave.v1"),operationId:Mt,expectedRevision:u().int().nonnegative(),project:N1,learning:iH.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."})}),D1=c({schemaVersion:S("openpond.modelProjectConfigurationCheck.v1"),configurationHash:uo,projectId:Mt,expectedRevision:u().int().nonnegative(),checkedAt:Ia,canSave:A(),deferred:f(b(["base_model","taskset"])).max(2),findings:f(c({code:Mt,severity:b(["error","warning"]),message:r().min(1).max(5e3),field:r().min(1).max(500).nullable()}).strict()).max(100)}).strict();c({id:Mt,name:r().min(1).max(500),available:A(),preference:Xr}).strict();function gH(e){try{Jo(e,jf)}catch{throw new SH(400,{schemaVersion:"openpond.modelProjectApiError.v2",code:"model_configuration_json_invalid",message:"Model configuration must be bounded JSON data.",retryable:!1,requestId:null,details:{}})}return hH.parse(e)}async function vH(e,t,n){Jo(e,jf);const a=N1.parse(e);dH(a,jf,"Model configuration");const o=await cH({project:a,expectedRevision:t});return gH({schemaVersion:"openpond.modelProjectSave.v1",operationId:`model-save:${o}`,expectedRevision:t,project:a})}var bH=c({schemaVersion:S("openpond.hostedModelProjectSync.v2"),portableProjectId:Mt,name:r().trim().min(1).max(200),objective:r().trim().max(5e3).nullable(),defaultBaseModel:Xr.nullable(),defaultDestinationId:Mt.nullable(),trainingSetup:$g,sourceRevision:u().int().positive(),sourceUpdatedAt:Ia,expectedEtag:uo.nullable().default(null)}).strict(),L1=c({id:Mt,teamId:Mt,portableProjectId:Mt,name:r().trim().min(1).max(200),objective:r().trim().max(5e3).nullable(),defaultBaseModel:Xr.nullable(),defaultDestinationId:Mt.nullable(),trainingSetup:$g,sourceRevision:u().int().positive(),sourceUpdatedAt:Ia,revision:u().int().positive(),etag:uo,createdAt:Ia,updatedAt:Ia}).strict(),yH=c({kind:b(["taskset_release","harness_release","dataset_release","evidence_set","model_version","reward_model_version","evaluation_receipt"]),ref:Nt,role:r().trim().min(1).max(200).nullable().default(null),updatedAt:Ia}).strict();c({project:L1,resources:f(yH).max(1e4),jobCount:u().int().nonnegative(),latestJobIds:f(Mt).max(100)}).strict();c({schemaVersion:S("openpond.modelProjectApiError.v2"),code:r().trim().min(1).max(200),message:r().trim().min(1).max(5e3),retryable:A().default(!1),requestId:r().trim().min(1).max(500).nullable().default(null),details:ie(r(),ce()).default({})}).strict();var SH=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}};const Ng=b(["scored","unscorable"]),Pu=b(["policy","environment","collector","verifier","provider","host","user","scheduler"]),U1=b(["completed","policy_failure","incomplete_output","task_deadline","environment_failure","collector_failure","verifier_failure","provider_failure","host_failure","infrastructure_timeout","cancelled"]),kH=c({schemaVersion:S("openpond.environmentRelease.v1"),id:E,revision:u().int().positive(),contract:Uw,actionSchemaRef:dn.nullable(),observationSchemaRef:dn.nullable(),stateSchemaRef:dn.nullable(),artifactCollection:c({maxArtifacts:u().int().positive().max(1e5),maxTotalBytes:u().int().positive().max(1e10)}).strict(),adapterConformanceHashes:ie(E,Y),metadata:Cn}).strict(),Dg=kH.extend({contentHash:Y}).strict(),xH=b(["collected","missing","skipped","failed"]),py=b(["not_requested","passed","failed"]),wH=c({requiredOutputPath:r().trim().min(1).max(2e3).nullable(),collectedPath:r().trim().min(1).max(4e3).nullable(),declaredMediaType:r().trim().min(1).max(200).nullable(),detectedMediaType:r().trim().min(1).max(200).nullable(),artifact:za.nullable(),status:xH,parseStatus:py,schemaStatus:py,errorCode:E.nullable(),failureOwner:Pu.nullable(),evidenceRefs:f(za).max(1e4),metadata:Cn}).strict(),IH=c({schemaVersion:S("openpond.artifactManifest.v1"),id:E,attemptRef:ee,entries:f(wH).max(1e5),createdAt:Pe,metadata:Cn}).strict();IH.extend({contentHash:Y}).strict();const _H=c({schemaVersion:S("openpond.verifierSetRelease.v1"),id:E,revision:u().int().positive(),graders:f(Vw).min(1).max(1e3),isolation:c({processBoundary:b(["same_process","isolated_process","container"]),networkPolicy:S("none"),defaultTimeoutMs:u().int().positive().max(3e5)}).strict(),calibrationReceiptRefs:f(ee).max(1e4),metadata:Cn}).strict(),Lg=_H.extend({contentHash:Y}).strict(),CH=c({verifierId:E,verifierVersion:r().trim().min(1).max(100),status:Ng,rawScore:u().finite().nullable(),normalizedScore:u().min(0).max(1).nullable(),weight:u().nonnegative().max(1e3),passed:A(),hardGate:A(),rewardEligible:A(),rewardContribution:u().min(0).max(1).nullable(),failureOwner:Pu.nullable(),feedback:f(r().max(2e4)).max(1e3),visibleEvidenceRefs:f(za).max(1e4),privilegedEvidenceRefs:f(za).max(1e4),metadata:Cn}).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"]})}),z1=c({schemaVersion:S("openpond.rewardReceipt.v1"),id:E,attemptRef:ee,verifierSetRef:ee,artifactManifestRef:ee,status:Ng,reward:u().min(0).max(1).nullable(),learningEligible:A(),passed:A(),outcomeClass:U1,failureOwner:Pu.nullable(),components:f(CH).min(1).max(1e4),visibleEvidenceRefs:f(za).max(1e5),privilegedEvidenceRefs:f(za).max(1e5),supersedes:ee.nullable(),createdAt:Pe,metadata:Cn}).strict();function H1(e,t){e.status==="scored"&&(e.reward===null||!e.learningEligible)&&t.addIssue({code:"custom",message:"A scored receipt requires a reward and is learning-eligible.",path:["status"]}),e.status==="unscorable"&&(e.reward!==null||e.learningEligible)&&t.addIssue({code:"custom",message:"An unscorable receipt has null reward and is not learning-eligible.",path:["status"]})}z1.superRefine(H1);z1.extend({contentHash:Y}).strict().superRefine(H1);const q1=c({schemaVersion:S("openpond.optimizerTrainingSample.v1"),tokenIds:f(u().int().nonnegative()).min(2).max(32768),mask:f(A()).min(2).max(32768),logprobs:f(u().finite()).min(2).max(32768),temperatures:f(u().positive().finite()).min(2).max(32768),envName:r().trim().min(1).max(200),modelRequestId:r().trim().min(1).max(1e3),promptTokenCount:u().int().positive(),completionTokenCount:u().int().positive(),servedPolicyVersion:u().int().nonnegative()}).strict().superRefine((e,t)=>{const n=e.tokenIds.length;for(const[a,o]of[["mask",e.mask],["logprobs",e.logprobs],["temperatures",e.temperatures]])o.length!==n&&t.addIssue({code:"custom",path:[a],message:`${a} must align with tokenIds`});e.promptTokenCount+e.completionTokenCount!==n&&t.addIssue({code:"custom",path:["completionTokenCount"],message:"prompt and completion token counts must span tokenIds"}),e.mask.filter(a=>!a).length!==e.promptTokenCount&&t.addIssue({code:"custom",path:["mask"],message:"promptTokenCount must equal the non-trainable mask count"}),e.mask.filter(Boolean).length!==e.completionTokenCount&&t.addIssue({code:"custom",path:["mask"],message:"completionTokenCount must equal the trainable mask count"})}),RH=c({id:E,environmentRelease:ee,status:b(["completed","failed","timed_out","cancelled"]),startedAt:Pe,completedAt:Pe,traceRefs:f(za).max(1e4),metadata:Cn}).strict(),PH=c({receiptRef:ee,status:Ng,value:u().min(0).max(1).nullable(),learningEligible:A(),passed:A(),outcomeClass:U1,failureOwner:Pu.nullable(),components:ie(E,u().min(0).max(1).nullable())}).strict(),B1=c({schemaVersion:S("openpond.canonicalRolloutRecord.v1"),id:E,attemptRef:ee,artifactManifestRef:ee,tasksetRelease:ee,environmentRelease:ee,verifierSetRelease:ee,harnessRelease:ee,taskId:E,split:Zo,model:Mh,seed:r().trim().min(1).max(500),reward:PH,traceRef:za,optimizerSample:q1.nullable(),environmentExecutions:f(RH).min(1).max(1e5),startedAt:Pe,completedAt:Pe,metadata:Cn}).strict();function F1(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."})}B1.superRefine(F1);c({...B1.shape,contentHash:Y}).strict().superRefine(F1);const AH=r().regex(/^(0|-?[1-9][0-9]*)$/).max(20).refine(e=>{if(e.length>20||!/^(0|-?[1-9][0-9]*)$/.test(e))return!1;const t=BigInt(e);return t>=-(1n<<63n)&&t<1n<<63n},"SQL integers must fit signed 64-bit storage."),V1=Dt([Xd(),r().max(262144),u().finite(),c({integer:AH}).strict(),c({blobBase64:r().max(349528).regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/)}).strict()]),fy=r().min(1).max(128).refine(e=>!e.includes("\0")),TH=c({tables:f(c({name:fy,columns:f(c({name:fy,type:b(["INTEGER","REAL","TEXT","BLOB"])}).strict()).min(1).max(128),rows:f(f(V1).max(128)).max(4096)}).strict()).max(64)}).strict().superRefine((e,t)=>{const n=new Set;for(const[a,o]of e.tables.entries()){const i=o.name.toLowerCase();(n.has(i)||i.startsWith("sqlite_"))&&t.addIssue({code:"custom",path:["tables",a,"name"],message:"Table names must be unique and outside SQLite's reserved namespace."}),n.add(i),new Set(o.columns.map(s=>s.name.toLowerCase())).size!==o.columns.length&&t.addIssue({code:"custom",path:["tables",a,"columns"],message:"Column names must be unique."}),o.rows.some(s=>s.length!==o.columns.length)&&t.addIssue({code:"custom",path:["tables",a,"rows"],message:"Each row must match the declared columns."})}}),hy=c({schemaVersion:S("openpond.sqlExecution.v1"),snapshot:TH,sql:r().min(1).max(65536).refine(e=>!e.includes("\0")),maxRows:u().int().min(1).max(4096),maxResultBytes:u().int().min(256).max(262144)}).strict();Rt("status",[c({status:S("completed"),columns:f(r()).max(128),rows:f(f(V1).max(128)).max(4096)}).strict(),c({status:S("rejected"),code:b(["invalid_query","multiple_statements","result_too_large","memory_limit"])}).strict()]);const Fc=c({scope:b(["input","initialState","state","arguments"]),path:f(r().min(1).max(256)).max(16)}).strict(),gy={id:r().min(1).max(128),operation:b(["step","collect"]),toolName:r().min(1).max(500).optional(),timeoutMs:u().int().min(1).max(2e4)},EH=Rt("kind",[c({...gy,kind:S("sqlite.v1"),sql:Fc,snapshot:Fc,maxRows:hy.shape.maxRows,maxResultBytes:hy.shape.maxResultBytes}).strict(),c({...gy,kind:S("javascript.v1"),source:Fc,cases:Fc,exportName:r().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/).max(128),maxCases:u().int().min(1).max(32),maxResultBytes:u().int().min(256).max(262144)}).strict()]).superRefine((e,t)=>{e.operation==="step"!=(e.toolName!==void 0)&&t.addIssue({code:"custom",path:["toolName"],message:"Only step services require a declared tool name."}),e.operation==="collect"&&(e.kind==="sqlite.v1"?[e.sql,e.snapshot]:[e.source,e.cases]).some(a=>a.scope==="arguments")&&t.addIssue({code:"custom",message:"Collection has no tool arguments."})}),MH=c({schemaVersion:S("openpond.javascriptEnvironment.v1"),id:r().trim().min(1).max(500),revision:u().int().positive(),module:dn.refine(e=>e.visibility==="host_private","Environment code belongs to the execution owner."),tools:f(tc).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:f(EH).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)=>{Eg(a.inputSchema).valid||t.addIssue({code:"custom",path:["tools",o,"inputSchema"],message:"Environment tools require a supported JSON schema."}),a.inputSchemaHash!==rn(a.inputSchema)&&t.addIssue({code:"custom",path:["tools",o,"inputSchemaHash"],message:"Tool schema identity differs from its declared schema."})});const n=e.executionServices??[];new Set(n.map(a=>a.id)).size!==n.length&&t.addIssue({code:"custom",path:["executionServices"],message:"Execution service identities must be unique."}),n.forEach((a,o)=>{const i=e.tools.find(s=>s.name===a.toolName);a.operation==="step"&&!i&&t.addIssue({code:"custom",path:["executionServices",o,"toolName"],message:"Execution services must target a declared tool."}),a.timeoutMs>=Math.min(e.operationTimeoutMs,i?.timeoutMs??e.operationTimeoutMs)&&t.addIssue({code:"custom",path:["executionServices",o,"timeoutMs"],message:"Service budgets must leave time for the authored controller."})})}),jH=MH.safeExtend({contentHash:r().regex(/^[a-f0-9]{64}$/)});b(["create","reset","step","collect","destroy"]);c({state:ie(r(),ce()),observation:ie(r(),ce())}).strict();r().regex(/^[a-f0-9]{64}$/);var OH=c({environment:Dg,verifierSet:Lg,javascript:jH}).strict();c({actions:f(c({name:r().min(1).max(64),arguments:ie(r(),ce())}).strict()).max(1e3)}).strict();var $H=c({environment:Dg,verifierSet:Lg}).strict(),NH=c({scopeId:r().trim().min(1).max(500),modelId:r().trim().min(1).max(500)}).strict();c({schemaVersion:S("openpond.modelTasksetDerivation.v1"),owner:NH,root:mr,parent:mr}).strict();var DH=c({taskset:Ww,taskDefinition:Iu,rewardBinding:wu,rewards:f(xu).min(1).max(100),assets:f(Cu).max(1e3),executionResources:$H.optional(),execution:OH.optional(),instructionMode:S("per_task").optional()}).strict(),LH=c({batch:k1,evidence:f(_u).min(1).max(1e4),decisions:f(jg).min(1).max(1e4),sources:f(Mg).min(1).max(1e4),assets:f(Cu).max(1e3)}).strict(),UH=64*1024*1024,zH=c({asset:sr,base64:r().max(Math.ceil(UH/3)*4)}).strict(),HH=DH.omit({taskset:!0,executionResources:!0}),qH=c({schemaVersion:S("openpond.tasksetPackage.v1"),taskset:Ww,environment:Dg,verifierSet:Lg,files:f(zH).max(1e4),modelResources:HH.optional(),learningResources:LH.optional()}).strict(),$f=qH.extend({contentHash:r().regex(/^[a-f0-9]{64}$/)}).strict(),rs=r().trim().min(1).max(500),BH=r().regex(/^[a-f0-9]{64}$/),Nf=c({id:rs,revision:u().int().positive(),contentHash:BH}).strict(),FH=c({schemaVersion:S("openpond.hostedTasksetSummary.v1"),id:rs,teamId:rs,release:Nf,name:r().min(1).max(500),description:r().max(2e4),taskCount:u().int().nonnegative(),buildIntent:r().min(1).max(100),methodHint:r().min(1).max(100).nullable(),packageBytes:u().int().nonnegative().nullable(),storedBytes:u().int().nonnegative().nullable(),createdAt:r().datetime({offset:!0})}).strict();c({afterId:rs.optional(),limit:u().int().min(1).max(100).default(30),modelProjectId:rs.optional()}).strict();c({items:f(FH).max(100),nextCursor:rs.nullable()}).strict();c({code:r().min(1),message:r().min(1)}).strict();var jo=r().trim().min(1).max(500),ld=r().regex(/^[a-f0-9]{64}$/),VH=bH.pick({portableProjectId:!0,name:!0,objective:!0,defaultBaseModel:!0,defaultDestinationId:!0,sourceRevision:!0,sourceUpdatedAt:!0}).extend({trainingSetup:$g.omit({tasksetRef:!0,rewardBindingRef:!0,tasksetRelease:!0})}).strict();c({schemaVersion:S("openpond.tasksetPackagePublication.v1"),operationId:jo,modelProjectId:jo,expectedProjectEtag:ld.nullable(),name:r().trim().min(1).max(200),description:r().max(5e3),buildIntent:b(["demonstrations","preferences","verifiable_reward","rubric","discovery"]),methodHint:b(["sft","dpo","grpo","ppo"]).nullable(),package:$f,modelConfiguration:VH.optional(),evaluationPackage:$f.optional(),selection:b(["select","attach"]).optional()}).strict().refine(e=>e.selection!=="attach"||e.modelConfiguration===void 0,"Attachment-only publication cannot replace Model configuration.").refine(e=>!e.evaluationPackage||e.modelConfiguration!==void 0&&e.modelConfiguration.trainingSetup.evaluationTasksetRef!=null&&qr(e.modelConfiguration.trainingSetup.evaluationTasksetRef)===qr(Fz(e.evaluationPackage.taskset)),"Evaluation package must match the selected immutable evaluation in Model configuration.");c({schemaVersion:S("openpond.tasksetPackageReceipt.v1"),teamId:jo,modelProjectId:jo,operationId:jo,taskset:Nf,packageHash:ld,hostedTasksetId:jo,projectEtag:ld,project:L1.optional(),selection:b(["select","attach"]).optional(),evaluation:c({taskset:Nf,packageHash:ld,hostedTasksetId:jo}).strict().optional()}).strict();c({schemaVersion:S("openpond.tasksetPackageReadback.v1"),teamId:jo,modelProjectId:jo,package:$f}).strict();var Ui=r().trim().min(1).max(240),vy=r().trim().min(1),KH=r().trim().min(8).max(256),WH=r().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),GH=ie(r(),ce()).default({});function by(e){const t=e.trim().replaceAll("\\","/");return!t||t.startsWith("/")||t==="."||t===".."?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}var K1=Pg.extend({sourceRefs:f(Ui).max(100).default([])}),W1=b(["draft","validating","needs_review","published"]),ZH=c({enabled:A(),candidateCount:u().int().min(2).max(4),minimumSamples:u().int().min(1).max(1e4).default(100),allowTies:A(),allowRejectAll:A(),rubric:r().trim().max(5e4),criteria:f(c({id:Ui,label:r().trim().min(1).max(500),description:r().trim().max(1e4),weight:u().nonnegative().max(1e3)})).max(100)}),JH=c({mode:b(["text","structured_json","artifacts"]),jsonSchema:ie(r(),ce()).nullable(),renderer:c({module:r().trim().min(1).max(1e3).refine(by,"Renderer modules must use a safe relative path."),exportName:WH,configRef:r().trim().min(1).max(1e3).refine(by,"Renderer configuration must use a safe relative path.").nullable().default(null)}).nullable()}).superRefine((e,t)=>{e.mode==="structured_json"&&!e.jsonSchema&&t.addIssue({code:"custom",message:"Structured JSON output requires a JSON Schema.",path:["jsonSchema"]}),e.mode==="text"&&e.renderer&&t.addIssue({code:"custom",message:"Text output cannot configure an artifact renderer.",path:["renderer"]})}),fo=c({schemaVersion:S("openpond.tasksetDraft.v1"),id:Ui,revision:u().int().positive(),profileId:Ui,modelScope:c({modelId:Ui,expectedModelRevision:u().int().positive(),source:oH.optional()}).strict().nullable().default(null),name:r().trim().max(500),objective:r().trim().max(2e4),purpose:Zw.default("general"),benchmark:Jw.nullable().default(null),preferenceComparison:Yw.nullable().default(null),status:W1,sourceRefs:f(Xw).max(1e5).default([]),datasetArtifact:Ig.nullable().optional(),policy:Rg,environment:s1,output:JH.default({mode:"text",jsonSchema:null,renderer:null}),capabilities:Ag,metrics:gu,review:ZH,tasks:f(K1).max(1e6).default([]),graders:f(ku).max(1e3).default([]),graderFixtures:f(l1).max(1e5).default([]),learningSignals:i1,publishedTasksetRef:c({id:Ui,revision:u().int().positive(),contentHash:KH}).nullable(),createdAt:vy,updatedAt:vy,metadata:GH}).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"]})}),YH=6e6,QH=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 XH(e){const t=Ru.parse(e);return!QH.has(t)&&!t.startsWith("source-artifacts/")}function yy(e,t){const n=XH(e);if(t.byteLength>YH)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)?Sy(t):{encoding:"utf8",data:o}}catch{a=Sy(t)}return{path:e,writable:n,content:a,sizeBytes:t.byteLength,contentHash:Sw(t)}}function Sy(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 ky=64*1024*1024,G1=r().regex(/^[a-f0-9]{64}$/),eq=c({path:Ru,contentHash:G1,sizeBytes:u().int().nonnegative().max(ky),base64:r().max(ky)}).strict(),tq=c({schemaVersion:S("openpond.tasksetDraftWorkspace.v1"),draft:fo,files:f(eq).max(1e4)}).strict();tq.extend({contentHash:G1}).strict();c({schemaVersion:S("openpond.trainingHarnessSourcePublication.v1"),harnessRelease:Je,sourcePackageHash:r().regex(/^[a-f0-9]{64}$/),sizeBytes:u().int().positive().max(sH)}).strict();f(c({id:r().trim().min(1)}).catchall(ce())).min(1).max(1e3);c({binding:wu,rewards:f(xu).min(1).max(100)}).strict();var nq=c({id:r().trim().min(1),clusterKey:r().trim().min(1),split:b(["train","validation","frozen_eval"])}).passthrough();c({schemaVersion:S("openpond.trainingEvaluationSource.v1"),taskset:mr,tasks:f(nq).min(1).max(1e4),assets:f(c({path:r().trim().min(1).max(2e3),sha256:r().regex(/^[a-f0-9]{64}$/),sizeBytes:u().int().nonnegative(),encoding:S("base64"),content:r().max(32*1024*1024)}).strict()).max(1e4)}).strict().superRefine((e,t)=>{const n=new Set;e.tasks.forEach((a,o)=>{a.split==="train"&&t.addIssue({code:"custom",path:["tasks",o,"split"],message:"Evaluation sources require held-out tasks."}),n.has(a.id)&&t.addIssue({code:"custom",path:["tasks",o,"id"],message:"Evaluation task identities must be unique."}),n.add(a.id)})});var Tn=r().trim().min(1).max(500),da=r().regex(/^[a-f0-9]{64}$/),Ua=r().datetime({offset:!0});c({schemaVersion:S("openpond.trainingInputArtifactUpload.v2"),kind:b(["portable_training_bundle","reward_model_dataset"]),idempotencyKey:r().trim().min(1).max(500),sourceManifest:Nt,payload:ce(),contentHash:da}).strict();c({schemaVersion:S("openpond.trainingInputArtifact.v2"),kind:b(["portable_training_bundle","reward_model_dataset"]),sourceManifest:Nt,artifactRef:r().trim().min(1).max(2e3),contentHash:da,sizeBytes:u().int().positive(),createdAt:Ua}).strict();var Z1=b(["reward_model_train","policy_optimize"]),aq=b(["queued","admitting","provisioning","running","stopping","cancelling","succeeded","failed","cancelled"]),oq=c({id:Tn,version:r().trim().min(1).max(200).nullable().default(null),required:A().default(!0)}).strict(),rq=c({modelProject:c({id:Tn,portableProjectId:Tn,revision:u().int().positive(),contentHash:da}).strict(),harnessRunManifest:Nt,harnessRelease:Nt,taskset:mr,tasksetRelease:Nt,evaluation:c({taskset:mr,dataset:Nt}).strict().nullable().optional(),dataset:Nt,evidenceSets:f(Nt).max(1e4)}).strict(),iq=c({kind:S("reward_model_train"),baseModel:Xr,preferenceDatasetRelease:Nt,processorRelease:Nt,recipe:c({schemaVersion:S("openpond.rewardModelRecipe.v1"),method:S("reward_model"),parameterization:S("lora_with_scalar_head")}).catchall(ce())}).strict(),sq=c({kind:S("deterministic"),grader:Nt,composer:Nt.nullable().default(null)}).strict(),lq=c({kind:S("learned_reward"),rewardModelVersion:Nt,qualificationReport:Nt.nullable().default(null),evaluationReferences:f(Nt).max(1e3).default([]),scorerArtifact:c({artifactRef:r().trim().min(1).max(2e3),contentHash:da,executionReceipt:Nt}).strict(),processorRelease:Nt,rewardComposerRelease:Nt}).strict(),cq=c({kind:S("policy_optimize"),baseModel:Xr,recipe:j1,rewardSource:Rt("kind",[sq,lq]),resumeFrom:Nt.nullable().default(null)}).strict(),dq=Rt("kind",[iq,cq]),uq=c({approvalHash:da,approvedAt:Ua,exportApproved:A(),maximumSpendUsd:u().nonnegative(),retentionDays:u().int().nonnegative().nullable(),region:r().trim().min(1).max(200).nullable().default(null)}).strict();c({schemaVersion:S("openpond.trainingJobSubmission.v2"),idempotencyKey:r().trim().min(1).max(500),name:r().trim().min(1).max(200),source:rq,job:dq,requestedCapabilities:f(oq).max(1e3),placementObjective:b(["fast","balanced","economical"]),budget:c({maximumSpendUsd:u().nonnegative(),maximumWallSeconds:u().int().positive()}).strict(),approval:uq,contentHash:da}).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 mq=c({schemaVersion:S("openpond.trainingJob.v2"),id:Tn,teamId:Tn,kind:Z1,modelProjectId:Tn,portableProjectId:Tn,sourceProjectRevision:u().int().positive(),submissionHash:da,state:aq,phase:r().trim().min(1).max(200),version:u().int().nonnegative(),progress:u().min(0).max(1),rolloutProgress:c({groupsCompleted:u().int().nonnegative(),groupsTarget:u().int().nonnegative(),optimizerUpdatesApplied:u().int().nonnegative(),optimizerUpdatesSkipped:u().int().nonnegative()}).strict(),accruedSpendUsd:u().nonnegative(),terminalReason:r().trim().min(1).max(5e3).nullable(),createdAt:Ua,updatedAt:Ua,completedAt:Ua.nullable()}).strict();c({schemaVersion:S("openpond.trainingJobPage.v2"),jobs:f(mq).max(1e3),nextCursor:r().trim().min(1).max(2e3).nullable()}).strict();c({schemaVersion:S("openpond.trainingJobEvent.v2"),id:Tn,jobId:Tn,sequence:u().int().nonnegative(),type:Tn,phase:r().trim().min(1).max(200),message:r().trim().min(1).max(5e3).nullable(),data:ie(r(),ce()).default({}),createdAt:Ua}).strict();c({schemaVersion:S("openpond.trainingJobLog.v2"),jobId:Tn,sequence:u().int().nonnegative(),level:b(["debug","info","warning","error"]),message:r().max(2e4),createdAt:Ua}).strict();c({expectedVersion:u().int().nonnegative()}).strict();var pq=c({schemaVersion:S("openpond.trainingJobOutput.v2"),id:Tn,jobId:Tn,kind:b(["checkpoint","adapter","scorer","metrics","evaluation","trace","receipt"]),artifactRef:r().trim().min(1).max(2e3),contentHash:da,sizeBytes:u().int().nonnegative(),metadata:ie(r(),ce()).default({}),createdAt:Ua}).strict(),fq=c({schemaVersion:S("openpond.trainingExecutionReceipt.v2"),id:Tn,teamId:Tn,jobId:Tn,submissionHash:da,manifestHash:da,recipeHash:da,capabilityHash:da,runtimeRelease:Nt,inputs:f(Nt).max(1e4),outputs:f(Nt).max(1e4),spendUsd:u().nonnegative(),durationSeconds:u().nonnegative(),cleanupComplete:A(),issuer:Tn,issuedAt:Ua,signature:r().trim().min(1).max(1e4).nullable()}).strict();c({schemaVersion:S("openpond.trainingJobOutputs.v2"),outputs:f(pq).max(1e4),receipt:fq.nullable()}).strict();c({schemaVersion:S("openpond.trainingApiError.v2"),code:r().trim().min(1).max(200),message:r().trim().min(1).max(5e3),retryable:A().default(!1),requestId:r().trim().min(1).max(500).nullable().default(null),details:ie(r(),ce()).default({})}).strict();c({schemaVersion:S("openpond.trainingCapabilities.v2"),capabilityHash:da,jobKinds:f(Z1),methods:f(r().trim().min(1).max(200)),placements:f(b(["local","remote","colocated","provider_native"])),controls:c({cancel:A(),stopAfterGroup:A(),resumeFromCheckpoint:A()}).strict(),limits:c({maximumSpendUsd:u().nonnegative(),maximumWallSeconds:u().int().positive(),maximumArtifactBytes:u().int().positive()}).strict(),checkedAt:Ua,expiresAt:Ua}).strict();var ho=fo.shape.id,Ha=u().int().positive(),Kr=r().regex(/^[a-f0-9]{64}$/),ei={teamId:ho,modelId:ho};c({schemaVersion:S("openpond.tasksetDraftCreate.v1"),operationId:ho,modelId:ho,expectedModelRevision:Ha,name:fo.shape.name}).strict();c({schemaVersion:S("openpond.tasksetDraftSourceDescriptor.v1"),...ei,expectedModelRevision:Ha,sourcePackageHash:Kr}).strict();c({schemaVersion:S("openpond.tasksetDraftReadback.v1"),...ei,draft:fo,workspaceHash:Kr,projectEtag:Kr}).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 hq=c({id:ho,revision:Ha,name:fo.shape.name,status:W1,updatedAt:fo.shape.updatedAt,sourceTasksetRef:wt.nullable()}).strict();c({schemaVersion:S("openpond.tasksetDraftList.v1"),...ei,drafts:f(hq).max(100),nextCursor:r().min(1).max(2e3).nullable()}).strict();c({expectedDraftRevision:Ha,draft:fo}).strict();c({expectedDraftRevision:Ha,expectedModelRevision:Ha}).strict();var gq=c({expectedDraftRevision:Ha,expectedWorkspaceHash:Kr}).strict();c({schemaVersion:S("openpond.tasksetDraftValidation.v1"),...ei,draftId:ho,draftRevision:Ha,workspaceHash:Kr,valid:A(),issues:f(c({code:r().min(1),severity:b(["warning","error"]),message:r(),path:r().nullable()}).strict()),packageHash:Kr.nullable(),tasksetRef:wt.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.");gq.extend({operationId:ho,expectedPackageHash:Kr,expectedTasksetRef:wt}).strict();c({schemaVersion:S("openpond.tasksetDraftFileList.v1"),...ei,draftId:ho,draftRevision:Ha,files:f(A1).max(10020)}).strict();c({schemaVersion:S("openpond.tasksetDraftFileReadback.v1"),...ei,draftId:ho,draftRevision:Ha,file:rH}).strict();c({schemaVersion:S("openpond.tasksetDraftDeletion.v1"),...ei,draftId:ho,revision:Ha,deleted:S(!0)}).strict();fo.shape.id;u().int().positive();var No=r().trim().min(1).max(500),vq=c({projectId:No.optional(),tasksetId:No.optional(),draftId:No.optional(),taskId:No.optional(),query:r().trim().max(1e3).default(""),split:b(["train","validation","test","frozen_eval"]).optional(),after:r().min(1).max(2e3).optional(),limit:u().int().min(1).max(100).default(30)}).strict(),bq=c({id:No,method:b(["code","judge","human"]),required:A()}),J1=c({tasksetId:No,tasksetName:r(),tasksetRevision:u().int().positive(),tasksetHash:r(),taskId:No,ordinal:u().int().nonnegative(),title:r(),description:r(),split:r(),scoring:f(bq),configuration:b(["configured","needs_reward","needs_checks"]),draftId:No.nullable().default(null),modelId:No.nullable().default(null)}),yq=c({items:f(J1).max(100),nextCursor:r().nullable()});function yY(e,t){if(tH({format:e.format,files:t}).contentHash!==e.contentHash)throw new Error("The source files differ from the import preview.");const n=`private/intake/${e.contentHash}`,a=t.map((i,s)=>({file:i,path:`${n}/${String(s).padStart(4,"0")}.txt`})),o={schemaVersion:"openpond.taskIntakeSources.v1",format:e.format,previewHash:e.contentHash,files:a.map(({file:i,path:s})=>({originalPath:i.path,retainedPath:s}))};return[...a.map(({file:i,path:s})=>yy(s,new TextEncoder().encode(i.text))),yy(`${n}/manifest.json`,new TextEncoder().encode(JSON.stringify(o)))]}function SY(e,t,n){const a=I1.parse(t);if(!n.length||new Set(n).size!==n.length)throw new Error("Select unique task records to import.");const o=[...e.tasks];for(const s of n){const l=a.records.find(h=>h.id===s);if(!l||l.kind!=="task"||l.needsContext)throw new Error("Recorded attempts and incomplete histories must be imported into Labeling for review.");const m=K1.parse({schemaVersion:"openpond.taskData.v1",id:l.id,clusterKey:l.familyKey,split:l.split,input:l.input,expectedOutput:l.expected,privilegedContextRef:null,metadata:{intake:{format:a.format,uploadHash:a.contentHash,sourceId:l.sourceId,sourceHash:l.sourceHash,metadata:l.metadata}}}),d=o.find(h=>h.id===m.id);if(d&&qr(d)!==qr(m))throw new Error(`Task ${m.id} already exists with different content. Import will not replace saved edits.`);d||o.push(m)}const i=new Map;for(const s of o)for(const l of[`family:${s.clusterKey}`,`input:${qr(s.input)}`]){if(i.has(l)&&i.get(l)!==s.split)throw new Error("The imported task family or request already occurs in another split.");i.set(l,s.split)}return fo.parse({...e,tasks:o})}const ta=r().trim().min(1).max(240),lr=r().trim().min(1),Y1=ie(r(),ce()).default({}),Q1=b(["nominated","needs_review","approved_for_creation","creating","needs_task_review","baselining","ready_for_export","rejected","dismissed","retired","blocked"]),X1=b(["no_training","prompting","retrieval","sft","preference","grpo_rft","sdft_opsd","sdpo","agentic_rl"]),Sq=c({id:ta,kind:b(["repeated_success","accepted_correction","agent_action_recurrence","outcome_linked_change","frontier_cost","expert_label","runtime_feedback"]),sourceRefIds:f(ta).min(1).max(1e4),occurredAt:lr,signature:r().trim().min(1).max(2e3),summary:r().trim().min(1).max(5e3),confidence:u().min(0).max(1),consented:A(),metadata:Y1}),kq=c({frequency:u().min(0).max(1),businessValue:u().min(0).max(1),frontierCost:u().min(0).max(1),signalQuality:u().min(0).max(1),verifiability:u().min(0).max(1),repeatability:u().min(0).max(1),privacyRisk:u().min(0).max(1),overall:u().min(0).max(1)}),xq=c({tactic:X1,eligible:A(),reasons:f(r().trim().min(1).max(5e3)).min(1).max(100),blockers:f(r().trim().min(1).max(5e3)).max(100).default([]),requiredSignals:f(r().trim().min(1).max(500)).max(100).default([]),generatedBy:b(["decision_table","baseline_reassessment"])}),eI=c({schemaVersion:S("openpond.taskCandidate.v1"),id:ta,profileId:ta,status:Q1,fingerprint:r().trim().min(1).max(512),title:r().trim().min(1).max(500),summary:r().trim().min(1).max(1e4),workflowSignature:r().trim().min(1).max(2e3),evidence:f(Sq).min(1).max(1e5),scorecard:kq,recommendation:xq,mergedIntoId:ta.nullable(),createdAt:lr,updatedAt:lr,metadata:Y1}),Au=c({schemaVersion:S("openpond.taskMinerConfig.v1"),enabled:A().default(!1),localOnly:A().default(!0),observationWindowDays:u().int().min(1).max(365).default(30),minimumRecurrence:u().int().min(2).max(100).default(3),clustering:S("hybrid_deterministic_first").default("hybrid_deterministic_first"),consentRequired:A().default(!0)});c({items:f(eI),generatedAt:lr,config:Au});c({status:Q1.optional(),mergeIntoId:ta.nullable().optional()});c({profileId:ta,sourceIds:f(ta).max(1e5).default([]),sessionIds:f(ta).max(1e5).default([]),config:Au.optional()});const wq=c({schemaVersion:S("openpond.taskMinerRun.v1"),id:ta,profileId:ta,status:b(["queued","running","cancelling","cancelled","succeeded","failed"]),config:Au,sourceIds:f(ta).max(1e5),sessionIds:f(ta).max(1e5).default([]),progress:c({stage:b(["queued","ingesting","preparing","clustering","persisting","complete"]),processedSources:u().int().nonnegative(),totalSources:u().int().nonnegative(),candidatesFound:u().int().nonnegative(),skippedSources:u().int().nonnegative().default(0)}),candidateIds:f(ta).max(1e5),cancelRequested:A(),error:r().trim().min(1).max(2e4).nullable(),createdAt:lr,startedAt:lr.nullable(),completedAt:lr.nullable(),updatedAt:lr});var Iq=c({id:He,purpose:r().trim().min(1).max(500),audience:b(["orchestrator","environment","privileged_scorer","trainer","infrastructure"]),required:A(),ttlSeconds:u().int().positive().max(86400),scopes:f(r().trim().min(1).max(500)).max(100).default([])}).strict(),_q=c({declarationId:He,leaseRef:r().trim().min(8).max(1e3),audience:Iq.shape.audience,expiresAt:_t}).strict(),Ug=c({adapterId:He,placement:b(["local","remote","colocated","provider_native"]),capabilityReceipt:Ye,runtimeVersion:r().trim().min(1).max(200),dataPlane:c({provider:He,dataPlaneId:He,cellId:He,runnerPoolId:He,runtimeImageDigest:r().regex(/^sha256:[a-f0-9]{64}$/),capabilityReceipt:Ye}).strict().nullable()}).strict(),zg=c({adapterId:He,kind:b(["local","ssh","managed","custom"]),deviceOrPool:r().trim().min(1).max(1e3),capabilityReceipt:Ye,provider:He.nullable()}).strict(),Hg=c({adapterId:He,workerVersion:r().trim().min(1).max(200),workerImageDigest:r().regex(/^sha256:[a-f0-9]{64}$/).nullable(),upstreamRevision:r().trim().min(1).max(500),capabilityReceipt:Ye}).strict(),Cq=c({schemaVersion:S("openpond.harnessRunManifest.v1"),id:He,harnessRelease:Je,datasetRelease:Je,evidenceSets:f(Je).max(1e4),model:c({source:r().trim().min(1).max(200),revision:r().trim().min(1).max(500),artifactHash:Ye.nullable(),tokenizerRevision:r().trim().min(1).max(500),chatTemplateHash:Ye}).strict(),recipe:c({method:r().trim().min(1).max(100),version:r().trim().min(1).max(200),configHash:Ye}).strict(),runtimeTarget:Ug,computeTarget:zg,engine:Hg,resolvedBundleHash:Ye,secretLeaseRefs:f(_q).max(1e3),approval:c({approvalHash:Ye,approvedAt:_t,maximumSpendUsd:u().nonnegative().nullable()}).strict(),createdAt:_t}).strict(),Rq=Cq.extend({contentHash:Ye}).strict(),Pq=c({schemaVersion:S("openpond.resolvedTrainingBundle.v1"),projection:S("trainer"),harnessRelease:Je,datasetRelease:Je,evidenceSetRelease:Je.nullable(),files:f(c({path:r().trim().min(1).max(2e3),sha256:Ye,sizeBytes:u().int().nonnegative()}).strict()).max(1e5)}).strict();Pq.extend({contentHash:Ye}).strict();var tI=c({name:S("adamw").default("adamw"),weightDecay:u().nonnegative().max(1).default(0),beta1:u().positive().lt(1).default(.9),beta2:u().positive().lt(1).default(.999),epsilon:u().positive().max(.01).default(1e-8)}).strict().default({name:"adamw",weightDecay:0,beta1:.9,beta2:.999,epsilon:1e-8});const ft=r().trim().min(1).max(240),na=r().trim().min(1),is=r().trim().min(8).max(256),qg=ie(r(),ce()).default({}),mo=ft.nullable(),Aq=b(["slash_train","session_menu","bulk_selection","training_page","task_candidate"]),Tq=b(["defaults","customize"]),Eq=b(["automated","manual"]);c({schemaVersion:S("openpond.trainingSourceEstimate.v1"),sessionId:ft,messageCount:u().int().nonnegative(),estimatedTokens:u().int().nonnegative(),textBytes:u().int().nonnegative()});c({query:r().max(500).default(""),offset:u().int().nonnegative().default(0),limit:u().int().min(1).max(100).default(20),candidates:f(c({sessionId:ft,title:r().trim().min(1).max(500),updatedAt:na})).max(500).default([])});const Mq=c({sessionId:ft,title:r().trim().min(1).max(500),updatedAt:na,snippet:r().max(2e3).nullable()});c({schemaVersion:S("openpond.trainingChatSearchResult.v1"),query:r(),offset:u().int().nonnegative(),limit:u().int().positive(),total:u().int().nonnegative(),hasMore:A(),indexedChats:u().int().nonnegative(),totalChats:u().int().nonnegative(),indexing:A(),entries:f(Mq)});const Bg=b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]),jq=c({graderId:ft.nullable(),path:r().trim().min(1).max(1e3),language:b(["javascript","typescript","python","json","text"]),content:r().max(2e6),sha256:is,declaredSha256:is.nullable(),integrity:b(["verified","unverified","mismatch"])}),Oq=c({protocolVersion:r().trim().min(1).max(200),module:r().trim().min(1).max(1e3),moduleSha256:is,command:f(r().max(2e3)).max(100),cwd:r().trim().min(1).max(4e3),maxTurns:u().int().positive().max(100)});c({schemaVersion:S("openpond.tasksetGraderDetails.v1"),taskset:Kt,sourceTasksetId:ft,graders:f(ku).max(1e3),runtime:Oq.nullable(),sources:f(jq).max(1e3),unavailableReason:r().max(2e3).nullable()});const $q=c({id:ft,taskIndex:u().int().nonnegative(),label:Tg,output:ie(r(),ce()),infrastructureError:r().trim().min(1).max(1e4).nullable(),expectedPassed:A(),expectedRewardEligible:A(),metadata:qg}),Nq=c({schemaVersion:S("openpond.taskAttempt.v1"),id:ft,tasksetId:ft,taskId:ft,split:os,attempt:u().int().nonnegative(),seed:u().int(),modelRef:mn.nullable(),startedAt:na,completedAt:na,output:ie(r(),ce()),runtimeEventRefs:f(ft).max(1e4).default([]),artifactRefs:f(ft).max(1e4).default([]),privilegedOutcomeRef:mo,infrastructureError:r().trim().min(1).max(1e4).nullable(),costUsd:u().nonnegative().nullable(),latencyMs:u().int().nonnegative(),userInterventions:u().int().nonnegative().default(0),metadata:qg}),Dq=c({schemaVersion:S("openpond.taskAttemptArtifact.v1"),id:ft,tasksetId:ft,taskId:ft,attemptId:ft,kind:b(["raw_model_response","runtime_trace","environment_state","grader_evidence","output_artifact"]),path:r().trim().min(1).max(4e3),mediaType:r().trim().min(1).max(200).nullable().optional(),sha256:is,sizeBytes:u().int().nonnegative(),createdAt:na,metadata:qg}),Lq=c({graderId:ft,graderVersion:r().trim().min(1).max(100),score:u().min(0).max(1).nullable(),passed:A(),hardGate:A(),rewardEligible:A(),feedback:r().trim().max(2e4).nullable(),evidenceRefs:f(ft).max(1e4).default([]),judge:mn.nullable().optional().default(null),calibrationStatus:b(["not_applicable","pending","passed","failed"])}),Uq=c({schemaVersion:S("openpond.gradeResult.v1"),id:ft,attemptId:ft,graderSetHash:is,score:u().min(0).max(1).nullable(),passed:A(),components:f(Lq).min(1).max(1e3),failureClass:Bg.nullable(),feedback:f(r().trim().min(1).max(2e4)).max(1e3).default([]),rewardEligible:A(),rewardComposition:jd.optional(),createdAt:na});b(["stable_hash_top_n","rft_easy_curriculum_v1"]);const zq=c({schemaVersion:S("openpond.graderAuditReport.v1"),id:ft,tasksetId:ft,tasksetHash:is,fixtureRefs:f(ft).min(1).max(1e5),gradeRefs:f(ft).min(1).max(1e5),passed:A(),hackingChecksPassed:A(),leakageChecksPassed:A(),infrastructureSafetyPassed:A(),failures:f(c({fixtureId:ft,label:Tg,gradeId:ft,reason:r().trim().min(1).max(5e3)})).max(1e5),createdAt:na}),Hq=c({schemaVersion:S("openpond.capabilityDiagnosis.v1"),summary:r().trim().min(1).max(1e4),stableBehavior:f(r().trim().min(1).max(5e3)).max(100).default([]),changingKnowledge:f(r().trim().min(1).max(5e3)).max(100).default([]),requiredContext:f(r().trim().min(1).max(5e3)).max(100).default([]),requiredTools:f(ft).max(100).default([]),intervention:X1,trainingEligible:A(),rationale:f(r().trim().min(1).max(5e3)).min(1).max(100),confidence:u().min(0).max(1)}),qq=c({id:ft,sourceId:ft,sourceTurnId:mo,split:os,origin:b(["extracted","corrected","synthetic","expert_authored"]),inputPrompt:r().trim().min(1).max(1e5),expectedOutputText:r().trim().min(1).max(2e5).nullable(),rationale:r().trim().min(1).max(5e3)}),Bq=c({schemaVersion:S("openpond.taskDesignProposal.v1"),id:ft,name:r().trim().min(1).max(500),objective:r().trim().min(1).max(2e4),diagnosis:Hq.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:Ag.shape.taskKind,sourceIds:f(ft).min(1).max(1e5),assumptions:f(r().trim().min(1).max(5e3)).max(1e3),successCriteria:f(r().trim().min(1).max(5e3)).min(1).max(1e3),proposedGraders:f(ku).max(1e3).default([]),graderFixtures:f($q).max(1e5).default([]),generatedFiles:f(nz).max(1e3).default([]),proposedExamples:f(qq).max(1e5).default([]),proposedMethod:f1.shape.recommendedMethod,trainingPath:m1.nullable().default(null),policy:Rg,warnings:f(r().trim().min(1).max(5e3)).default([]),createdAt:na}),Fq=5;function kY(e,t="New model"){const n=e?.trim().split(/\s+/).filter(Boolean)??[];return n.length===0?t:n.slice(0,Fq).join(" ")}const cc=c({schemaVersion:S("openpond.baseModelPreference.v1"),modelId:ft,revision:r().trim().min(1).max(256).nullable(),tokenizerRevision:r().trim().min(1).max(256).nullable(),chatTemplateHash:r().trim().min(8).max(256).nullable(),modelAssetId:mo,source:b(["managed","local","builtin"])}),Vq=c({schemaVersion:S("openpond.taskCreationRequest.v1"),id:ft,profileId:ft,surface:Aq,mode:Tq,entryMode:Eq.default("manual"),resourceIntent:b(["workproduct","dataset"]).default("workproduct"),buildIntent:d1.default("demonstrations"),buildSpecification:u1.nullable().default(null),objective:r().trim().min(1).max(2e4).nullable(),methodHint:b(["sft","dpo","grpo","ppo"]).nullable().default(null),preferredBaseModelId:ft.nullable().default(null),preferredBaseModel:cc.nullable().default(null),sourceIds:f(ft).max(1e5),candidateId:mo,analysisModel:mn.nullable(),analysisReasoningEffort:ru.nullable().default(null),createImproveRunId:mo.default(null),targetIntent:c({kind:b(["agent","skill","extension","model","configuration"]).nullable(),id:mo,displayName:r().trim().min(1).max(500).nullable(),operation:b(["create","improve"])}).default({kind:"model",id:null,displayName:null,operation:"create"}),disclosure:c({status:b(["not_required","pending","approved","declined"]),content:S("raw_excerpts"),sourceIds:f(ft).max(1e5),providerModel:mn.nullable(),approvalId:mo,approvedAt:na.nullable()}).default({status:"not_required",content:"raw_excerpts",sourceIds:[],providerModel:null,approvalId:null,approvedAt:null}),createdAt:na}),nI=c({schemaVersion:S("openpond.taskCreationSnapshot.v1"),id:ft,request:Vq,state:b(["planning","awaiting_disclosure_approval","awaiting_questions","recommendation_ready","awaiting_materialization_approval","materializing","validating","ready","blocked","failed","cancelled"]),proposal:Bq.nullable(),materializedTasksetId:mo,disclosureApprovalId:mo,materializationApprovalId:mo,blockingQuestions:f(c({id:ft,kind:b(["objective","consent","success_signal","privacy_licensing","interpretation"]),prompt:r().trim().min(1).max(5e3),answer:r().trim().min(1).max(2e4).nullable()})).default([]),transcript:f(c({id:ft,role:b(["user","assistant","system","tool"]),text:r().max(1e5),createdAt:na})).max(1e4).default([]),repairHistory:f(h1).max(1e3).default([]),blockedReason:r().trim().min(1).max(1e4).nullable(),createdAt:na,updatedAt:na});c({schemaVersion:S("openpond.taskCreationTranscript.v1"),creationId:ft,profileId:ft,messages:nI.shape.transcript,updatedAt:na});const zi=r().trim().min(1).max(240),cd=r().trim().min(1),Df=r().trim().min(8).max(256),aI=ie(r(),ce()).default({}),Kq=b(["created","inspecting","awaiting_source_review","awaiting_mapping","awaiting_materialization_approval","materializing","validating","ready","cancelling","cancelled","failed"]),oI=c({schemaVersion:S("openpond.huggingFaceDatasetLocator.v1"),repositoryId:r().trim().regex(/^[^/\s]+\/[^/\s]+$/).max(500),repositoryUrl:r().url().max(2e3),requestedRevision:r().trim().min(1).max(256).nullable()}),Wq=c({path:r().trim().min(1).max(1e3),logicalType:r().trim().min(1).max(500),nullable:A(),sampleValues:f(ce()).max(5)}),Gq=c({configuration:r().trim().min(1).max(500),split:r().trim().min(1).max(500),rowCount:u().int().nonnegative().nullable(),sizeBytes:u().int().nonnegative().nullable()}),Zq=c({schemaVersion:S("openpond.huggingFaceDatasetInspection.v1"),id:zi,locator:oI,resolvedRevision:r().trim().min(7).max(256),title:r().trim().min(1).max(500),description:r().max(2e4).nullable(),declaredLicense:r().trim().min(1).max(500).nullable(),gated:A(),private:A(),configurations:f(r().trim().min(1).max(500)).min(1).max(1e3),splits:f(Gq).min(1).max(1e4),columns:f(Wq).min(1).max(1e4),previewRows:f(ie(r(),ce())).max(25),sourceFiles:f(c({path:r().trim().min(1).max(2e3),configuration:r().trim().min(1).max(500),split:r().trim().min(1).max(500),revision:r().trim().min(7).max(256),sizeBytes:u().int().nonnegative().nullable(),contentHash:Df.nullable()})).max(1e5),inspectedAt:cd,metadata:aI}),Jq=b(["row_id","cluster_id","prompt","messages","demonstration","chosen","rejected","expected_output","privileged_context","reward","feedback","tag","metadata"]),Yq=c({sourcePath:r().trim().min(1).max(1e3),target:Jq,transform:b(["identity","string","json","messages","numeric","math_final_answer"]),policy:b(["visible","privileged","metadata"]),required:A()}),rI=c({schemaVersion:S("openpond.datasetImportMapping.v1"),sourceSchemaHash:Df,configuration:r().trim().min(1).max(500),upstreamSplits:f(r().trim().min(1).max(500)).min(1).max(1e3),preset:b(["prompt_only","prompt_completion","messages","preference","prompt_expected_answer","prompt_privileged_solution","prompt_feedback"]),bindings:f(Yq).min(1).max(1e4),nullPolicy:b(["reject","drop","preserve"]),invalidRowPolicy:b(["reject_import","drop_with_receipt"]),splitPolicy:c({seed:u().int(),assignments:ie(r(),gr),validationPercent:u().min(0).max(100),frozenEvalPercent:u().min(0).max(100)}),importerVersion:r().trim().min(1).max(200),mappingHash:Df}),Qq=c({phase:b(["idle","metadata","download","mapping","parquet_write","verification","publish"]),completedBytes:u().int().nonnegative(),totalBytes:u().int().nonnegative().nullable(),completedRows:u().int().nonnegative(),totalRows:u().int().nonnegative().nullable(),message:r().trim().min(1).max(2e3).nullable()}),Xq=c({schemaVersion:S("openpond.datasetImportJob.v1"),id:zi,profileId:zi,sourceKind:b(["huggingface","uploaded_file"]),status:Kq,locator:oI.nullable(),inspection:Zq.nullable(),mapping:rI.nullable(),progress:Qq,targetStorageRoot:r().trim().min(1).max(4e3).nullable(),tasksetId:zi.nullable(),tasksetRevision:u().int().positive().nullable(),artifactId:zi.nullable(),error:r().trim().min(1).max(2e4).nullable(),cancellationRequested:A(),createdAt:cd,updatedAt:cd,completedAt:cd.nullable(),metadata:aI});c({profileId:zi,url:r().trim().min(1).max(2e3)});c({name:r().trim().min(1).max(500),objective:r().trim().min(1).max(2e4),mapping:rI,targetStorageRoot:r().trim().min(1).max(4e3).nullable(),licenseApproved:A().default(!1)});const ar=E.nullable(),Po=u().int().nonnegative(),eB=r().regex(/^[a-f0-9]{40}$/),tB=c({name:r().trim().min(1).max(160),startedAt:Pe,completedAt:Pe,durationMs:u().nonnegative(),clock:b(["monotonic","provider","wall"]),outcome:b(["succeeded","failed","cancelled"])}).strict(),nB=c({schemaVersion:S("openpond.correlatedTelemetryReceipt.v1"),stage:b(["training","evaluation","deployment","inference"]),correlation:c({modelRunId:ar,modelVersionId:ar,policyVersion:Po.nullable(),taskId:ar,rolloutGroupId:ar,providerResourceId:ar,deploymentId:ar,inferenceRequestId:ar}).strict(),spans:f(tB).max(1e4),usage:c({promptTokens:Po.nullable(),generatedTokens:Po.nullable(),gpuSeconds:u().nonnegative().nullable(),workerActiveSeconds:u().nonnegative().nullable(),optimizerSteps:Po.nullable(),rolloutGroups:Po.nullable(),successfulTrajectories:Po.nullable(),failedTrajectories:Po.nullable(),peakGpuMemoryBytes:Po.nullable(),peakGpuUtilizationPercent:u().min(0).max(100).nullable()}).strict(),resource:c({provider:E,resourceIds:f(E).max(1e3),gpuType:r().trim().min(1).max(300).nullable(),gpuCount:Po.nullable(),baseProfileId:ar,baseRepository:r().trim().min(1).max(512).nullable(),baseRevision:eB.nullable(),adapterContentHash:Y.nullable()}).strict(),cost:c({currency:S("USD"),providerReportedUsd:u().nonnegative().nullable(),quotedHourlyUsd:u().nonnegative().nullable(),estimatedUsd:u().nonnegative().nullable(),methodologyVersion:r().trim().min(1).max(160),pricingInputs:ie(r().trim().min(1).max(160),u().finite()),unitEstimates:ie(r().trim().min(1).max(160),u().nonnegative())}).strict(),recordedAt:Pe,contentHash:Y}).strict(),gn=r().trim().min(1).max(240),Bo=r().regex(/^[a-f0-9]{64}$/),rr=r().datetime({offset:!0}),Sn=c({id:gn,contentHash:Bo}).strict(),aB=Sn.extend({revision:u().int().positive()}).strict(),iI=c({providerId:gn,modelId:r().trim().min(1).max(300)}).strict(),Tu=b(["correction","sibling_verification","cumulative_known","development","retained","frozen_final","training_eligible"]),oB=c({taskId:gn,taskContentHash:Bo,panelRole:Tu,passLabel:gn.nullable(),optimizerEligible:A(),criticalInvariantIds:f(gn).max(100).default([])}).strict().superRefine((e,t)=>{e.optimizerEligible!==(e.panelRole==="correction")&&t.addIssue({code:"custom",path:["optimizerEligible"],message:"Only correction cases may be optimizer eligible."})}),rB=c({schemaVersion:S("openpond.continualBenchIssuePacket.v1"),id:gn,revision:u().int().positive(),contentHash:Bo,familyId:gn,familyLabel:r().trim().min(1).max(500),severity:b(["low","medium","high","critical"]),cases:f(oB).min(2).max(1e4),duplicateEvidence:Sn,leakageEvidence:Sn,priorExposureEvidence:Sn,observedAt:rr,reviewedAt:rr,queuedAt:rr.nullable(),runAt:rr.nullable(),createdBy:gn,createdAt:rr}).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."})}),iB=c({id:gn,role:Tu,passLabel:gn.nullable(),taskset:aB,familyIds:f(gn).min(1).max(1e5),taskCount:u().int().positive().max(1e6),sealedAt:rr}).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."})}),Tp=Rt("kind",[c({kind:S("base_model"),id:gn,revision:r().trim().min(1).max(500),contentHash:Bo}).strict(),c({kind:S("model_version"),id:gn,contentHash:Bo}).strict(),c({kind:S("external_reference"),id:gn,model:iI,providerRevision:r().trim().min(1).max(500),contentHash:Bo}).strict()]),sB=c({scheduleEntryId:gn,ordinal:u().int().nonnegative(),label:gn,role:b(["seed","daily_residual","rank_candidate","weekly_rollup","full_refresh"]),parentRule:b(["base_model","previous_release","seed_release","accepted_daily_head","accepted_seed"]),trainableRank:u().int().positive().max(1024),correctionPanelIds:f(gn).min(1).max(1e3),optimizerGroupsPerTask:u().int().positive().max(1e3),trajectoriesPerGroup:u().int().min(4).max(1e3)}).strict(),lB=c({revision:u().int().positive(),requireAllAttemptsTerminal:S(!0),criticalCorrectionPassRate:u().min(0).max(1),siblingPassRate:u().min(0).max(1),behavioralRetentionRate:u().min(0).max(1),maximumRetainedRegressionPoints:u().min(0).max(100),blockCriticalPriorRegression:A(),authorizedClaims:f(b(["systems_complete","correction_absorbed","issue_generalized","continually_current","frontier_pareto_result"])).min(1).max(5)}).strict(),cB=c({schemaVersion:S("openpond.continualBenchmarkProtocol.v1"),id:gn,revision:u().int().positive(),contentHash:Bo,ownerId:gn,createdAt:rr,sealedAt:rr,creationReceipt:Sn,predecessorSeries:c({id:gn,revision:u().int().positive(),contentHash:Bo}).strict().nullable(),scenarioPack:Sn,issueFamilyLedger:Sn,issuePacketRelease:Sn,panels:f(iB).min(6).max(1e4),grader:Sn,judge:c({release:Sn,rubricRelease:Sn,calibrationRelease:Sn,model:iI}).strict().nullable(),policies:c({base:Tp,master:Tp.nullable(),externalReferences:f(Tp).min(1).max(20)}).strict(),invariants:c({systemPromptHash:Bo,toolSchema:Sn,application:Sn,harness:Sn,runtime:Sn,workerImage:Sn,autoRefiner:c({enabled:A(),release:Sn.nullable()}).strict()}).strict(),schedule:f(sB).min(1).max(1e3),evaluation:c({seeds:f(u().int()).min(3).max(100),repetitions:u().int().min(3).max(20),powerRule:Sn,pairedBootstrapSamples:u().int().min(1e3).max(1e6),confidenceLevel:S(.95)}).strict(),resources:c({maximumTrainingGpuSeconds:u().int().positive(),maximumEvaluationGpuSeconds:u().int().positive(),maximumProviderSpendUsd:u().positive(),maximumTotalSpendUsd:u().positive(),maximumConcurrentGroups:u().int().positive().max(1e3)}).strict(),currencyThresholds:lB}).strict().superRefine((e,t)=>{const n=e.panels.map(i=>i.id);new Set(n).size!==n.length&&t.addIssue({code:"custom",path:["panels"],message:"Protocol panel ids must be unique."});for(const i of["development","retained","frozen_final","training_eligible"])e.panels.filter(s=>s.role===i).length!==1&&t.addIssue({code:"custom",path:["panels"],message:`A protocol requires exactly one ${i} panel.`});[...e.schedule].sort((i,s)=>i.ordinal-s.ordinal).some((i,s)=>i.ordinal!==s)&&t.addIssue({code:"custom",path:["schedule"],message:"Protocol schedule ordinals must be contiguous from zero."});const o=new Set(n);e.schedule.some(i=>i.correctionPanelIds.some(s=>!o.has(s)))&&t.addIssue({code:"custom",path:["schedule"],message:"Every scheduled correction panel must belong to the protocol."})}),dB=b(["draft","active","completed","archived"]),uB=b(["draft","ready","queued","running","candidate","accepted","rejected","no_signal","failed","cancelled"]),sI=b(["seed","daily_residual","rank_candidate","weekly_rollup","full_refresh"]),mB=b(["base_model","previous_release","seed_release","accepted_daily_head","accepted_seed"]),pB=b(["seed_taskset","nightly_selection","daily_cohort_union","eligible_task_pool"]),fB=b(["live_client","evaluation_attempt","replay_evidence","manual"]),hB=c({id:E,ordinal:u().int().nonnegative(),label:r().trim().min(1).max(100),role:sI,parentRule:mB,taskSource:pB,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."})}),gB=c({id:E,version:u().int().positive(),requireCheckpoint:A(),requireAppliedOptimizerUpdate:A(),minimumCurrentCohortMeanImprovement:u().finite(),maximumRetainedMeanRegression:u().finite().nonnegative(),blockCriticalInvariantRegression:A(),automaticDailyAdvancement:A()}).strict(),vB=c({schemaVersion:S("openpond.modelComparisonSeries.v1"),id:E,profileId:E,modelProjectId:E,name:r().trim().min(1).max(500),objective:r().trim().min(1).max(2e4),status:dB,revision:u().int().positive(),productionBinding:c({role:S("chat_manual"),roleTargetId:E}).strict(),baseModel:c({id:E,revision:r().trim().min(1).max(256)}).strict(),seedTaskset:Kt,eligibleTaskPool:Kt,evaluationTasksets:c({development:Kt,retained:Kt,frozenFinal:Kt}).strict(),grader:ee,benchmarkProtocol:cB.nullable().default(null),automaticEvaluation:c({enabled:A()}).strict().default({enabled:!1}),residualProfile:c({profileId:E,serializedEnvelopeRank:u().int().positive().max(1024),maximumEnabledRank:u().int().positive().max(1024),topology:S("uniform_block_masked")}).strict(),schedule:f(hB).min(1).max(1e3),scheduleSealedAt:Pe.nullable(),advancementPolicy:gB,executionPolicy:c({startWhenReady:S(!1)}).strict(),acceptedSeedEntryId:E.nullable(),acceptedDailyHeadEntryId:E.nullable(),promotedBindingId:E.nullable(),createdBy:E,createdAt:Pe,updatedAt:Pe}).strict().superRefine((e,t)=>{[...e.schedule].sort((m,d)=>m.ordinal-d.ordinal).some((m,d)=>m.ordinal!==d)&&t.addIssue({code:"custom",path:["schedule"],message:"Schedule ordinals must be unique and contiguous from zero."}),(new Set(e.schedule.map(m=>m.id)).size!==e.schedule.length||new Set(e.schedule.map(m=>m.label)).size!==e.schedule.length)&&t.addIssue({code:"custom",path:["schedule"],message:"Schedule ids and labels must be unique."}),e.residualProfile.maximumEnabledRank>e.residualProfile.serializedEnvelopeRank&&t.addIssue({code:"custom",path:["residualProfile"],message:"Maximum enabled rank cannot exceed the serialized envelope."});const a=Object.values(e.evaluationTasksets);new Set(a.map(m=>`${m.id}:${m.revision}:${m.contentHash}`)).size!==a.length&&t.addIssue({code:"custom",path:["evaluationTasksets"],message:"Development, retained, and frozen-final cohorts require distinct immutable Taskset releases."});const o=e.schedule.find(m=>m.role==="seed");if(!o||e.schedule.filter(m=>m.role==="seed").length!==1){t.addIssue({code:"custom",path:["schedule"],message:"A series requires exactly one seed entry."});return}const i=e.schedule.filter(m=>m.role==="rank_candidate");i.length===1&&t.addIssue({code:"custom",path:["schedule"],message:"A causal rank comparison requires at least two rank candidates."}),new Set(i.map(m=>m.trainableRank)).size!==i.length&&t.addIssue({code:"custom",path:["schedule"],message:"Causal rank candidates must use distinct trainable ranks."}),[o.trainableRank+e.schedule.filter(m=>m.role==="daily_residual").reduce((m,d)=>m+d.trainableRank,0),...e.schedule.filter(m=>m.role==="weekly_rollup").map(m=>o.trainableRank+m.trainableRank),...e.schedule.filter(m=>m.role==="rank_candidate").map(m=>o.trainableRank+m.trainableRank),...e.schedule.filter(m=>m.role==="full_refresh").map(m=>m.trainableRank)].some(m=>m>e.residualProfile.maximumEnabledRank)&&t.addIssue({code:"custom",path:["schedule"],message:"A declared branch exceeds the maximum enabled rank."})}),lI=c({source:fB,taskIds:f(E).min(1).max(1e5),observedFrom:Pe,observedTo:Pe,reviewedAt:Pe,reviewedBy:E,sourceTaskset:Kt}).strict(),bB=lI.extend({derivedFamilyKeys:f(E).min(1).max(1e5),familyDerivation:c({algorithm:E,sourceTasksetHash:Y}).strict(),selectionHash:Y}).strict(),cI=Rt("kind",[c({kind:S("base_model"),id:E,revision:r().trim().min(1).max(256)}).strict(),c({kind:S("model_version"),id:E,contentHash:Y}).strict()]),yB=c({id:E,branchOrdinal:u().int().nonnegative(),rank:u().int().positive().max(1024),offsetStart:u().int().nonnegative(),offsetEnd:u().int().positive(),optimizationRole:b(["frozen","trainable"]),artifactLineageId:E.nullable()}).strict().superRefine((e,t)=>{e.offsetEnd-e.offsetStart!==e.rank&&t.addIssue({code:"custom",path:["offsetEnd"],message:"Block offsets must span exactly the declared rank."})}),SB=c({disposition:b(["advance","hold","no_signal"]),policy:c({id:E,version:u().int().positive()}).strict(),reasonCodes:f(E).min(1).max(100),summary:r().trim().min(1).max(5e3),decidedBy:E,decidedAt:Pe}).strict(),kB=c({evaluationRunId:E,modelVersionId:E,taskset:Kt,grader:ee,cohortRole:b(["current","correction","sibling_verification","cumulative_known","development","retained","prior_disclosed","frozen_final"]),panelId:E.nullable().default(null),protocol:c({id:E,revision:u().int().positive(),contentHash:Y}).strict().nullable().default(null)}).strict(),xB=c({attemptOrdinal:u().int().positive(),trainingPlanId:E.nullable(),modelRunId:E.nullable(),terminalStatus:b(["failed","cancelled"]),queuedAt:Pe.nullable(),startedAt:Pe.nullable(),completedAt:Pe}).strict(),ss=c({seriesId:E,entryId:E,scheduleEntryId:E,ordinal:u().int().nonnegative(),releaseHash:Y}).strict(),wB=c({schemaVersion:S("openpond.modelComparisonSeriesEntry.v1"),id:E,seriesId:E,profileId:E,modelProjectId:E,scheduleEntryId:E,releaseHash:Y,ordinal:u().int().nonnegative(),label:r().trim().min(1).max(100),role:sI,branch:b(["daily","rank_candidate","weekly_rollup","full_refresh"]),status:uB,parent:cI,taskset:Kt,sourceTasksets:f(Kt).min(1).max(1e3),taskSelection:bB.nullable(),trainableRank:u().int().positive().max(1024),serializedEnvelopeRank:u().int().positive().max(1024),enabledCumulativeRank:u().int().positive().max(1024),trainableBlockId:E,residualBlocks:f(yB).min(1).max(1024),attemptOrdinal:u().int().positive().default(1),priorRunAttempts:f(xB).max(100).default([]),trainingPlanId:E.nullable(),modelRunId:E.nullable(),modelVersionId:E.nullable(),evaluations:f(kB).max(1e5),decision:SB.nullable(),promotionBindingId:E.nullable(),queuedAt:Pe.nullable(),startedAt:Pe.nullable(),completedAt:Pe.nullable(),createdAt:Pe,updatedAt:Pe}).strict().superRefine((e,t)=>{const n=[...e.residualBlocks].sort((s,l)=>s.offsetStart-l.offsetStart);n.some((s,l)=>s.offsetStart!==(l===0?0:n[l-1].offsetEnd))&&t.addIssue({code:"custom",path:["residualBlocks"],message:"Residual block offsets must be contiguous from zero."});const a=n.at(-1)?.offsetEnd??0;(a!==e.enabledCumulativeRank||a>e.serializedEnvelopeRank)&&t.addIssue({code:"custom",path:["enabledCumulativeRank"],message:"Enabled rank must match the block inventory and fit the envelope."});const o=e.residualBlocks.filter(s=>s.optimizationRole==="trainable");(o.length!==1||o[0]?.id!==e.trainableBlockId||o[0]?.rank!==e.trainableRank)&&t.addIssue({code:"custom",path:["trainableBlockId"],message:"Exactly one block must be trainable during the Run and match trainableRank."});const i=e.priorRunAttempts.map(s=>s.attemptOrdinal);(e.priorRunAttempts.length!==e.attemptOrdinal-1||i.some((s,l)=>s!==l+1))&&t.addIssue({code:"custom",path:["priorRunAttempts"],message:"Prior Run attempts must be a contiguous history before the active attempt."})});c({seriesId:E,scheduleEntryId:E,taskSelection:lI.nullable(),expectedSeriesRevision:u().int().positive()}).strict();const IB=b(["base_reference","lora_adapter"]),dI=c({baseModel:c({source:S("huggingface"),repoId:E,revision:r().regex(/^[a-f0-9]{40}$/),configHash:Y,tokenizerHash:Y,licenseId:E,gated:A()}).strict(),processor:c({repository:E,revision:r().regex(/^[a-f0-9]{40}$/),configHash:Y}).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."})}),_B=c({schemaVersion:S("openpond.modelVersion.v1"),id:E,modelId:E,profileId:E,version:u().int().nonnegative(),kind:IB,status:b(["available","failed"]),baseModel:cc,taskset:Kt,comparisonSeriesEntry:ss.nullable().optional(),evaluationTasksetRef:Kt.nullable().optional(),releaseGraph:c({resolvedBundleHash:Y,profileRelease:Kt,harnessRelease:ee,agentRelease:ee.nullable(),grader:c({id:E,contentHash:Y}).strict()}).strict(),artifactLineageId:E.nullable(),adapterStatus:b(["not_trained","trained"]),createdAt:Pe,contentHash:Y}).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."})}),CB=c({schemaVersion:S("openpond.rewardModelVersion.v1"),id:E,modelId:E,profileId:E,version:u().int().positive(),role:S("reward"),status:b(["available","failed"]),scope:b(["synthetic_smoke","human_preference"]),baseModel:cc,runtime:dI.nullable().default(null),taskset:Kt,preferenceDatasetRelease:ee,releaseGraph:c({resolvedBundleHash:Y,profileRelease:Kt,harnessRelease:ee,grader:c({id:E,contentHash:Y}).strict()}).strict(),artifacts:c({checkpoint:ee.extend({objectRef:r().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/),files:f(c({path:r().trim().min(1).max(512),sizeBytes:u().int().positive(),sha256:Y}).strict()).min(4).max(128)}).strict(),adapter:ee,scalarHead:ee,bucketHead:ee.nullable(),processorRelease:ee}).strict(),qualificationReport:ee.nullable(),createdAt:Pe,contentHash:Y}).strict(),RB=c({schemaVersion:S("openpond.rewardModelRunReceipt.v1"),provider:E,providerRunId:E,resolvedBundleHash:Y,finalCheckpoint:ee.extend({objectRef:r().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/)}).strict(),adapter:ee,scalarHead:ee,bucketHead:ee.nullable(),processorRelease:ee,optimizerEvidence:ee,managedExecutionReceipt:ee.nullable().default(null),parameterDeltaHash:Y,cleanup:c({computeReleased:A(),providerTerminalObserved:A()}).strict(),contentHash:Y}).strict(),PB=wM(e=>{if(!e||typeof e!="object"||Array.isArray(e))return e;const t=e;if(t.tasksetRelease!==void 0)return e;const n=t.taskset;if(!n||typeof n!="object"||Array.isArray(n))return e;const a=n;return typeof a.id!="string"||typeof a.contentHash!="string"?e:{...t,tasksetRelease:{id:a.id,contentHash:a.contentHash}}},c({schemaVersion:S("openpond.rewardModelRun.v1"),id:E,rewardModelId:E,rewardModelVersionId:E.nullable(),profileId:E,role:S("reward"),scope:b(["synthetic_smoke","human_preference"]),status:b(["prepared","running","succeeded","failed","cancelled"]),taskset:Kt,tasksetRelease:ee,preferenceDatasetRelease:ee,recipeRelease:ee,destinationId:E,quote:c({maximumSpendUsd:u().positive(),hourlyCostUsd:u().nonnegative().nullable()}).strict(),managedRunId:E.nullable(),progress:c({completedSteps:u().int().nonnegative(),totalSteps:u().int().positive(),latestLoss:u().finite().nullable()}).strict(),receipt:RB.nullable(),qualificationReport:ee.nullable(),accruedSpendUsd:u().nonnegative().nullable(),failureOwner:b(["authoring","admission","provider","runner","artifact","qualification","cleanup"]).nullable(),failure:r().trim().min(1).max(5e3).nullable(),startedAt:Pe,completedAt:Pe.nullable(),updatedAt:Pe}).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."})}),AB=c({schemaVersion:S("openpond.modelRunReceipt.v1"),provider:E,providerRunId:E,assignmentHash:Y,resultHash:Y,transcriptHash:Y,traceHash:Y.nullable(),resolvedBundleHash:Y,artifactPath:r().trim().min(1).max(2e3),cleanup:c({computeReleased:A(),tunnelClosed:A()}).strict(),telemetry:nB.nullable().default(null),contentHash:Y}).strict(),or=c({inputTokens:u().int().nonnegative(),outputTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative(),costUsd:u().nonnegative().nullable()}).strict(),xy=r().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),Fg=c({phase:b(["baseline","adaptation","candidate_adaptation","candidate"]),taskId:E,attemptId:E,sessionId:E.nullable(),turnId:E.nullable(),passed:A(),score:u().min(0).max(1).nullable(),failureClass:Bg.nullable(),inputTokens:u().int().nonnegative(),outputTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative(),latencyMs:u().int().nonnegative(),costUsd:u().nonnegative().nullable(),startedAt:Pe}).strict(),wy=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(),uI=c({target:S("all_tasks_lower"),targetTaskCount:u().int().nonnegative(),comparedTaskCount:u().int().nonnegative(),passedTaskCount:u().int().nonnegative(),failedTaskCount:u().int().nonnegative(),lowerTaskCount:u().int().nonnegative(),higherTaskCount:u().int().nonnegative(),unchangedTaskCount:u().int().nonnegative(),baselineTokens:u().int().nonnegative(),refinedTokens:u().int().nonnegative(),tokenDelta:u().int(),tokenDeltaPercent:u().finite().nullable(),complete:A(),passed:A(),cohorts:c({adaptation:wy,heldOut:wy}).strict()}).strict(),Vg=c({baseline:or,adaptation:or,candidateAdaptation:or,candidate:or,refiner:or,grader:or}).strict(),TB=c({usage:Vg,observedSpendUsd:u().nonnegative(),attempts:f(Fg).max(1e4)}).strict(),EB=c({id:E,contentHash:Y,artifactPath:r().trim().min(1).max(2e3)}).strict(),MB=c({schemaVersion:S("openpond.modelEvaluationReceipt.v1"),benchmarkId:E,resultManifest:c({id:E,contentHash:Y,artifactPath:r().trim().min(1).max(2e3)}).strict(),stages:c({baseline:ee,adaptation:ee,refiner:ee,candidateAdaptation:ee,candidate:ee,comparison:ee}).strict(),usage:Vg,quality:c({baselinePassRate:u().min(0).max(1),candidatePassRate:u().min(0).max(1),adaptationBaselinePassRate:u().min(0).max(1),adaptationCandidatePassRate:u().min(0).max(1),adaptationCandidatePassed:A(),heldOutCandidatePassed:A(),passed:A()}).strict(),foregroundTokenDelta:u().int(),foregroundTokenDeltaPercent:u().finite().nullable(),taskEfficiency:uI.optional(),efficiency:c({grossForegroundTokenSavings:u().int(),overheadTokens:u().int().nonnegative(),firstPassNetTokenSavings:u().int(),breakEvenReuseCount:u().int().nonnegative().nullable(),amortizedTokenSavings:u().int(),amortizedReuseCount:u().int().positive()}).strict(),budget:c({maximumSpendUsd:u().nonnegative(),observedSpendUsd:u().nonnegative(),enforced:A()}).strict(),evidenceSnapshot:ee,lineage:c({adaptationEvidenceHash:Y,refinerInputHash:Y,refinerOutcomeHash:Y,validationHash:Y,applyReceiptHash:Y,candidateRelease:ee,valid:A()}).strict(),invalidReasons:f(r().trim().min(1).max(2e3)).max(100),attempts:f(Fg).max(1e4).default([]),terminalClassification:b(["improved","no_improvement","regressed","inconclusive","cancelled","infrastructure_failure"]),profileGit:c({ref:r().trim().min(1).max(2e3),commit:xy,baseCommit:xy}).strict().nullable(),contentHash:Y}).strict(),jB=c({schemaVersion:S("openpond.modelEvaluationStopReceipt.v1"),benchmarkId:E,terminalClassification:S("inconclusive"),stopReason:b(["candidate_harness_unchanged","candidate_lineage_invalid"]),reason:r().trim().min(1).max(5e3),stoppedAfter:S("refiner"),baselineHarness:ee,candidateHarness:ee,refiner:c({id:E,contentHash:Y,outcomeCount:u().int().nonnegative()}).strict(),usage:Vg,budget:c({maximumSpendUsd:u().nonnegative(),observedSpendUsd:u().nonnegative(),enforced:A()}).strict(),evidenceSnapshot:ee,attempts:f(Fg).max(1e4),contentHash:Y}).strict(),Iy=c({level:S(.95),lower:u().finite(),upper:u().finite()}).strict().superRefine((e,t)=>{e.lower>e.upper&&t.addIssue({code:"custom",message:"A confidence interval's lower bound cannot exceed its upper bound."})}),OB=c({schemaVersion:S("openpond.modelComparisonBenchmarkReceipt.v1"),benchmarkId:S("model-comparison"),target:c({kind:b(["base_model","model_version","external_reference"]),label:r().trim().min(1).max(300),modelVersionId:E.nullable(),model:mn.nullable()}).strict(),taskset:Kt,grader:ee,sampling:c({seeds:f(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:Iy.nullable()}).strict(),judge:c({judgeModel:mn,judgeRelease:ee,rubricRelease:ee,calibrationRelease:ee,score:u().min(0).max(100),scoreCi95:Iy,comparisonCount:u().int().positive(),wins:u().int().nonnegative(),ties:u().int().nonnegative(),losses:u().int().nonnegative(),referenceLabel:r().trim().min(1).max(300)}).strict().superRefine((e,t)=>{e.wins+e.ties+e.losses!==e.comparisonCount&&t.addIssue({code:"custom",message:"Judge win, tie, and loss counts must equal comparisonCount."})}).nullable(),attempts:f(c({attemptId:E.nullable().default(null),taskId:E,seed:u().int(),repetition:u().int().nonnegative(),status:b(["succeeded","failed"]),deterministicScore:u().finite().nullable(),passed:A().nullable(),judgeScore:u().min(0).max(100).nullable(),judgePreference:b(["win","tie","loss"]).nullable(),transcriptHash:Y.nullable(),traceHash:Y.nullable(),transcriptArtifact:c({artifactPath:r().trim().min(1).max(2e3),jsonPointer:r().trim().min(1).max(1e3)}).strict().nullable().default(null),traceArtifact:c({artifactPath:r().trim().min(1).max(2e3),jsonPointer:r().trim().min(1).max(1e3)}).strict().nullable().default(null),latencyMs:u().int().nonnegative().nullable().default(null),failureClass:Bg.nullable()}).strict()).max(1e5),usage:c({policy:or.nullable(),judge:or.nullable(),observedSpendUsd:u().nonnegative().nullable(),evaluationGpuSeconds:u().nonnegative().nullable().default(null)}).strict(),managedServing:c({jobId:E,terminalState:b(["completed","cancelled","failed","budget_exhausted"]),sourcePolicyVersion:u().int().nonnegative(),sourceAdapterSha256:Y.nullable(),servedPolicyVersion:u().int().nonnegative().nullable(),servedAdapterSha256:Y.nullable(),accruedSpendUsd:u().nonnegative(),cleanupAttestationHash:Y,resourceCount:u().int().nonnegative(),activeResourceCount:S(0)}).strict().nullable().default(null),evidenceSnapshot:c({id:E,contentHash:Y,artifactPath:r().trim().min(1).max(2e3)}).strict(),completedAt:Pe,contentHash:Y}).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."})}),$B=c({benchmarkId:S("harness-refiner"),model:mn,upstreamModel:c({providerId:E,modelId:r().trim().min(1).max(300),revision:r().trim().min(1).max(300),pricing:c({version:r().trim().min(1).max(300),source:r().trim().min(1).max(300),effectiveAt:Pe,inputUsdPerMillionTokens:u().nonnegative(),cachedInputUsdPerMillionTokens:u().nonnegative(),outputUsdPerMillionTokens:u().nonnegative()}).strict().optional()}).strict(),reasoningEffort:r().trim().min(1).max(100).nullable(),seeds:f(u().int()).min(1).max(100),repetitions:u().int().positive().max(20),maximumSpendUsd:u().nonnegative(),attemptPlan:f(c({stage:b(["baseline","adaptation","candidate_adaptation","candidate"]),split:r().trim().min(1).max(100),taskIds:f(E).min(1).max(1e5),attemptCount:u().int().positive()}).strict()).length(4)}).strict(),NB=c({benchmarkId:S("model-comparison"),target:c({kind:b(["base_model","model_version","external_reference"]),label:r().trim().min(1).max(300),modelVersionId:E.nullable(),model:mn.nullable()}).strict(),grader:ee,judge:c({model:mn,release:ee,rubricRelease:ee,calibrationRelease:ee,referenceLabel:r().trim().min(1).max(300)}).strict().nullable(),seeds:f(u().int()).min(1).max(100),repetitions:u().int().positive().max(20),maximumSpendUsd:u().nonnegative(),series:c({id:E,protocol:c({id:E,revision:u().int().positive(),contentHash:Y}).strict()}).strict().nullable().default(null),panel:c({id:E,role:b(["correction","sibling_verification","cumulative_known","development","retained","frozen_final"]),passLabel:E.nullable()}).strict().nullable().default(null),comparisonPair:c({entryId:E,parent:cI,candidateModelVersionId:E}).strict().nullable().default(null),attemptPlan:f(c({stage:S("comparison"),split:r().trim().min(1).max(100),taskIds:f(E).min(1).max(1e5),attemptCount:u().int().positive()}).strict()).length(1)}).strict(),DB=Dt([$B,NB]),LB=c({schemaVersion:S("openpond.modelRun.v1"),id:E,modelId:E,modelVersionId:E.nullable(),profileId:E,kind:b(["rollout_smoke","training","evaluation"]),status:b(["prepared","running","succeeded","failed","cancelled"]),method:b(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]).nullable(),destinationId:E.nullable(),taskset:Kt,comparisonSeriesEntry:ss.nullable().optional(),evaluationTasksetRef:Kt.nullable().optional(),harnessRelease:ee.nullable().optional(),quote:c({maximumSpendUsd:u().nonnegative(),hourlyCostUsd:u().nonnegative().nullable()}).strict().nullable(),evaluation:DB.nullable().default(null),evaluationProgress:c({stage:b(["baseline","adaptation","refiner","candidate_adaptation","candidate","comparison"]),completedAttempts:u().int().nonnegative(),totalAttempts:u().int().positive(),accounting:TB.nullable().default(null),evidenceSnapshot:EB.nullable().default(null)}).strict().nullable().default(null),reward:c({raw:u(),components:ie(r(),u())}).strict().nullable(),receipt:Dt([AB,MB,jB,OB]).nullable(),adapterArtifactLineageId:E.nullable(),failure:r().trim().min(1).max(5e3).nullable(),startedAt:Pe,completedAt:Pe.nullable(),updatedAt:Pe}).strict().superRefine((e,t)=>{e.status==="succeeded"&&!e.receipt&&t.addIssue({code:"custom",message:"A successful Model Run requires a canonical receipt."}),e.kind==="evaluation"&&(e.method!==null||e.destinationId!==null||!e.evaluation||e.adapterArtifactLineageId!==null)&&t.addIssue({code:"custom",message:"An evaluation Model Run requires evaluation configuration and cannot claim training method, destination, or adapter lineage."}),e.kind==="evaluation"&&e.receipt&&e.receipt.schemaVersion!=="openpond.modelEvaluationReceipt.v1"&&e.receipt.schemaVersion!=="openpond.modelEvaluationStopReceipt.v1"&&e.receipt.schemaVersion!=="openpond.modelComparisonBenchmarkReceipt.v1"&&t.addIssue({code:"custom",message:"An evaluation Model Run requires an evaluation receipt."}),e.kind!=="evaluation"&&(e.method===null||e.destinationId===null||e.quote===null)&&t.addIssue({code:"custom",message:"A training or rollout Model Run requires method, destination, and quote."}),e.kind==="rollout_smoke"&&e.adapterArtifactLineageId!==null&&t.addIssue({code:"custom",message:"A rollout smoke cannot claim adapter artifacts."})});function xY(e){const t=new Map;for(const I of e.attempts){const R=`${I.phase}\0${I.taskId}`,M=t.get(R);(!M||I.startedAt>M.startedAt||I.startedAt===M.startedAt&&I.attemptId>M.attemptId)&&t.set(R,I)}const n=[...t.values()],a=[["adaptation","adaptation","candidate_adaptation"],["held_out","baseline","candidate"]].flatMap(([I,R,M])=>{const P=new Map(n.filter(N=>N.phase===M).map(N=>[N.taskId,N]));return n.filter(N=>N.phase===R).flatMap(N=>{const O=P.get(N.taskId);return O?[{cohort:I,taskId:N.taskId,baseline:N,refined:O,tokenDelta:O.totalTokens-N.totalTokens}]:[]})}),o=new Set(n.filter(I=>I.phase==="baseline"||I.phase==="adaptation").map(I=>I.taskId)).size,i=e.targetTaskCount??o;if(!Number.isInteger(i)||i<0)throw new Error("Benchmark task-efficiency target must be a non-negative integer.");const s={adaptation:new Set(n.filter(I=>I.phase==="adaptation").map(I=>I.taskId)).size,held_out:new Set(n.filter(I=>I.phase==="baseline").map(I=>I.taskId)).size},l=(I,R)=>({targetTaskCount:R,comparedTaskCount:I.length,passedTaskCount:I.filter(M=>M.tokenDelta<0).length,failedTaskCount:I.filter(M=>M.tokenDelta>=0).length,lowerTaskCount:I.filter(M=>M.tokenDelta<0).length,higherTaskCount:I.filter(M=>M.tokenDelta>0).length,unchangedTaskCount:I.filter(M=>M.tokenDelta===0).length}),m=l(a,i),d=a.reduce((I,R)=>I+R.baseline.totalTokens,0),h=a.reduce((I,R)=>I+R.refined.totalTokens,0),v=h-d,y=a.length===i;return{summary:uI.parse({target:"all_tasks_lower",...m,baselineTokens:d,refinedTokens:h,tokenDelta:v,tokenDeltaPercent:d>0?v/d*100:null,complete:y,passed:y&&m.passedTaskCount===i,cohorts:{adaptation:l(a.filter(I=>I.cohort==="adaptation"),s.adaptation),heldOut:l(a.filter(I=>I.cohort==="held_out"),s.held_out)}}),pairs:a}}const UB=b(["measuring","up_to_date","needs_attention"]),zB=b(["fixed","retained","regressed","unresolved","unavailable"]),_y=c({evaluationRunId:E,attemptKey:E,artifactPath:r().trim().min(1).max(2e3),jsonPointer:r().trim().min(1).max(1e3),transcriptHash:Y.nullable(),traceHash:Y.nullable()}).strict(),Lf=c({level:S(.95),lower:u().finite(),upper:u().finite()}).strict(),HB=c({panelId:E,panelRole:Tu,passLabel:E.nullable(),taskset:Kt,attempted:u().int().nonnegative(),available:u().int().nonnegative(),passed:u().int().nonnegative(),strictSuccess:u().min(0).max(1).nullable(),strictSuccessCi95:Lf.nullable(),judgeScore:u().min(0).max(100).nullable(),judgeScoreCi95:Lf.nullable()}).strict(),qB=c({schemaVersion:S("openpond.modelCurrencySnapshot.v1"),id:E,contentHash:Y,seriesId:E,protocol:c({id:E,revision:u().int().positive(),contentHash:Y}).strict(),entryId:E,passLabel:E,parent:Rt("kind",[c({kind:S("base_model"),id:E,revision:r().trim().min(1).max(500)}).strict(),c({kind:S("model_version"),id:E,contentHash:Y}).strict()]),candidate:c({kind:S("model_version"),id:E,contentHash:Y}).strict(),sources:c({evaluationRunIds:f(E).max(1e5),attemptIds:f(E).max(1e6),tasksets:f(Kt).max(1e4),grader:ee,judge:ee.nullable(),calibration:ee.nullable()}).strict(),matches:f(c({key:E,panelId:E,panelRole:Tu,taskId:E,issueFamilyId:E,seed:u().int(),repetition:u().int().nonnegative(),classification:zB,parentPassed:A().nullable(),candidatePassed:A().nullable(),parentAttempt:_y.nullable(),candidateAttempt:_y.nullable()}).strict()).max(1e6),taskIds:c({fixed:f(E).max(1e6),retained:f(E).max(1e6),regressed:f(E).max(1e6),unresolved:f(E).max(1e6),unavailable:f(E).max(1e6)}).strict(),panels:f(HB).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:Lf.nullable(),exactPairedBinaryPValue:u().min(0).max(1).nullable(),pairedBootstrapSamples:u().int().positive()}).strict(),criteria:c({allRequiredAttemptsTerminal:A(),criticalCorrectionPassRate:u().min(0).max(1).nullable(),siblingPassRate:u().min(0).max(1).nullable(),behavioralRetentionRate:u().min(0).max(1).nullable(),retainedRegressionPoints:u().finite().nullable(),criticalPriorRegressionCount:u().int().nonnegative(),thresholdRelease:ee}).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:Y,toolSchema:ee,application:ee,harness:ee,runtime:ee,grader:ee,autoRefinerEnabled:A()}).strict(),evidenceState:UB,evidenceReasons:f(E).max(100),projectedAt:Pe}).strict(),dd=Rt("kind",[c({kind:S("base_model"),id:E,revision:r().trim().min(1).max(500),label:r().trim().min(1).max(300)}).strict(),c({kind:S("model_version"),id:E,label:r().trim().min(1).max(300)}).strict(),c({kind:S("captured_model"),id:E,label:r().trim().min(1).max(300)}).strict()]),wl=Dt([c({source:S("evaluation_run").default("evaluation_run"),evaluationRunId:E,attemptId:E,modelLabel:r().trim().min(1).max(300).nullable().default(null),modelVersionId:E.nullable().default(null),reward:u().finite().nullable(),components:ie(r(),u().finite()).default({})}).strict(),c({source:S("imported_response"),modelLabel:r().trim().min(1).max(300),modelVersionId:E.nullable().default(null),response:ce().refine(e=>e!==void 0,"An imported model response is required."),reward:u().finite().nullable().default(null),components:ie(r(),u().finite()).default({})}).strict()]),BB=Dt([c({taskId:E,target:dd,attempt:wl}).strict(),c({taskId:E,target:b(["base","current"]).default("current"),attempt:wl}).strict(),c({taskId:E,target:b(["base","current"]).default("current"),evaluationRunId:E,attemptId:E,reward:u().finite().nullable(),components:ie(r(),u().finite()).default({})}).strict().transform(({taskId:e,target:t,...n})=>({taskId:e,target:t,attempt:{source:"evaluation_run",modelLabel:null,modelVersionId:null,...n}}))]);c({schemaVersion:S("openpond.continualLearningDailyBatchManifest.v1"),id:E,seriesId:E,scheduleEntryId:E,dayOrdinal:u().int().positive().max(1e4),sourceTaskset:Kt,taskIds:f(E).min(1).max(1e3),observedAttempts:f(BB).max(1e3).default([]),sourceFileName:r().trim().min(1).max(500).nullable().default(null),availableAt:Pe}).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}:${KB(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 FB=c({schemaVersion:S("openpond.continualLearningDailyBatch.v1"),id:E,seriesId:E,scheduleEntryId:E,dayOrdinal:u().int().positive().max(1e4),label:r().trim().min(1).max(100),runMode:b(["automatic","manual"]).optional(),source:b(["json_upload","sealed_fixture"]),sourceFileName:r().trim().min(1).max(500).nullable(),sourceTaskset:Kt,tasks:f(c({taskId:E,taskContentHash:Y,familyKey:E,disposition:b(["include","defer","exclude"]).nullable(),oracleReview:b(["pending","confirmed","needs_correction"]),note:r().trim().max(2e3),observedAttempt:wl.nullable(),baselineAttempt:wl.nullable().default(null),responses:f(c({target:dd,attempt:wl}).strict()).max(100).default([]),stagedAt:Pe.nullable().default(null),queuedEntry:ss.nullable().default(null)}).strict()).min(1).max(1e3),intakeEvaluation:c({status:b(["awaiting","running","ready","failed"]),requestedTargets:f(b(["base","current"])).max(2).default(["base","current"]),requestedPolicies:f(dd).max(100).default([]),runs:f(c({target:dd,runId:E}).strict()).max(100).default([]),baselineRunId:E.nullable(),currentRunId:E.nullable(),currentPolicy:Rt("kind",[c({kind:S("base_model"),id:E}).strict(),c({kind:S("model_version"),id:E}).strict()]).nullable(),failure:r().trim().min(1).max(2e3).nullable()}).strict().default({status:"awaiting",requestedTargets:["base","current"],requestedPolicies:[],runs:[],baselineRunId:null,currentRunId:null,currentPolicy:null,failure:null}),status:b(["pending","reviewed","queued"]),queuedEntry:ss.nullable(),reviewedBy:E.nullable(),reviewedAt:Pe.nullable(),availableAt:Pe,revision:u().int().positive(),createdAt:Pe,updatedAt:Pe}).strict().superRefine((e,t)=>{new Set(e.tasks.map(a=>a.taskId)).size!==e.tasks.length&&t.addIssue({code:"custom",path:["tasks"],message:"A daily batch cannot repeat a task."});for(const[a,o]of e.tasks.entries()){const i=o.responses.map(s=>mI(s.target));new Set(i).size!==i.length&&t.addIssue({code:"custom",path:["tasks",a,"responses"],message:"A task cannot repeat a model response target."})}const n=e.tasks.every(a=>a.disposition!==null&&a.oracleReview!=="pending"&&(a.oracleReview!=="needs_correction"||a.note.length>0));e.status!=="pending"&&!n&&t.addIssue({code:"custom",path:["tasks"],message:"Every task requires a decision and oracle review before the day completes."}),e.status==="queued"!=(e.queuedEntry!==null)&&t.addIssue({code:"custom",path:["queuedEntry"],message:"Only a queued day carries an exact series-entry reference."}),e.status==="pending"&&(e.reviewedAt!==null||e.reviewedBy!==null)&&t.addIssue({code:"custom",path:["reviewedAt"],message:"A pending day cannot carry reviewer completion identity."}),e.status!=="pending"&&(e.reviewedAt===null||e.reviewedBy===null)&&t.addIssue({code:"custom",path:["reviewedAt"],message:"Reviewed identity is required after a day review completes."})}),VB=c({schemaVersion:S("openpond.continualBenchIssueReview.v1"),id:E,seriesId:E,scheduleEntryId:E,passLabel:E,packet:rB,splitManifest:c({id:E,contentHash:Y}).strict(),decisions:f(c({taskId:E,disposition:b(["include","defer","exclude"]).nullable(),note:r().trim().max(2e3)}).strict()).min(2).max(1e4),status:b(["pending","reviewed","queued"]),queuedEntry:ss.nullable(),reviewedBy:E.nullable(),reviewedAt:Pe.nullable(),revision:u().int().positive(),createdAt:Pe,updatedAt:Pe}).strict().superRefine((e,t)=>{const n=[...e.packet.cases.map(i=>i.taskId)].sort(),a=[...e.decisions.map(i=>i.taskId)].sort();JSON.stringify(n)!==JSON.stringify(a)&&t.addIssue({code:"custom",path:["decisions"],message:"Review decisions must cover the exact issue-packet cases."});const o=e.decisions.every(i=>i.disposition!==null&&i.note.length>0);e.status!=="pending"&&!o&&t.addIssue({code:"custom",path:["decisions"],message:"Every case requires a disposition and note before review completes."}),e.status==="queued"!=(e.queuedEntry!==null)&&t.addIssue({code:"custom",path:["queuedEntry"],message:"Only a queued review carries an exact series-entry reference."})}).readonly();function mI(e){return`${e.kind}:${e.id}`}function KB(e){return typeof e=="string"?e:mI(e)}const Oa=r().trim().min(1).max(240),va=r().trim().min(8).max(256),pI=b(["grpo","dapo","gspo-token"]),Ul=c({id:Oa,revision:r().trim().min(1).max(256),tokenizerRevision:r().trim().min(1).max(256),chatTemplateHash:va}),WB=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()}),GB=c({method:S("grpo"),groupSize:u().int().min(2).max(128),normalization:S("group_standardized"),advantageEpsilon:u().positive().max(.01).default(1e-8),loss:pI,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:tI}),fI=c({method:S("ppo"),valueModel:Ul,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)}),ZB=Rt("method",[GB,fI]),hI=c({rewardModelVersion:c({id:Oa,contentHash:va}).strict(),qualificationReport:c({id:Oa,contentHash:va}).strict().nullable().default(null),evaluationReferences:f(c({id:Oa,contentHash:va}).strict()).max(1e3).default([]),checkpoint:c({id:Oa,contentHash:va,objectRef:r().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/),files:f(c({path:r().trim().min(1).max(512),sizeBytes:u().int().positive(),sha256:va}).strict()).min(4).max(128)}).strict(),runtime:dI,processorRelease:c({id:Oa,contentHash:va}).strict(),rewardComposerRelease:c({id:Oa,contentHash:va}).strict(),executionReceipt:c({id:Oa,contentHash:va}).strict()}).strict(),gI=c({schemaVersion:S("openpond.policyOptimization.v1"),policyModel:Ul,referenceModel:Ul,dataset:c({tasksetId:Oa,tasksetHash:va,split:S("train"),selectionStrategy:b(["stable_hash_top_n","rft_easy_curriculum_v1"]),selectionSeed:u().int(),maxExamples:u().int().positive().max(1e5)}),sampler:c({temperature:u().min(0).max(2),topP:u().min(0).max(1),maxOutputTokens:u().int().positive().max(32768),maxTurns:u().int().positive().max(1e3),concurrency:u().int().positive().max(1e3)}),environment:c({id:Oa,version:r().trim().min(1).max(256),toolContractHash:va}),reward:c({graderId:Oa,graderHash:va,learnedPreference:hI.nullable().default(null)}),kl:c({coefficient:u().nonnegative().nullable(),referenceConstraint:S("fixed_reference")}),budgets:WB,checkpointEverySteps:u().int().positive(),seed:u().int(),evaluationSplit:S("frozen_eval"),optimizer:ZB}),Re=r().trim().min(1).max(240),Tt=r().trim().min(1),pt=r().trim().min(8).max(256),dc=ie(r(),ce()).default({}),vI=c({schemaVersion:S("openpond.localModelChatConfiguration.v1").default("openpond.localModelChatConfiguration.v1"),profile:b(["efficient","full_harness","custom"]).default("efficient"),systemPromptMode:b(["lean","full_harness","custom"]).default("lean"),customSystemPrompt:r().max(2e4).nullable().default(null),contextWindowTokens:u().int().min(128).max(32768).default(1024),maxOutputTokens:u().int().min(1).max(512).default(64),temperature:u().min(0).max(2).default(0),repetitionPenalty:u().min(.5).max(2).default(1.1),noRepeatNgramSize:u().int().min(0).max(10).default(3),compaction:b(["off","when_needed"]).default("when_needed"),keepWarmSeconds:u().int().min(0).max(3600).default(300),updatedAt:Tt.nullable().default(null)}),JB=vI.parse({}),YB=c({schemaVersion:S("openpond.managedAdapterServingProjection.v1"),teamId:Re.nullable().default(null),source:S("sandbox_managed_rl"),sourceRef:Re,canonicalArtifactId:Re.nullable(),canonicalArtifactState:b(["imported_unvalidated","evaluating","promotable","rejected","deleted"]).nullable(),canonicalDeploymentId:Re.nullable(),canonicalDeploymentState:b(["requested","deploying","ready","degraded","deleting","deleted","failed"]).nullable(),state:b(["pending","imported","ready","failed"]),customerBindingAllowed:A().default(!1),artifactContentHash:pt.nullable().default(null),baseProfileId:Re.nullable().default(null),publishedAt:Tt.nullable(),lastSyncedAt:Tt,lastError:r().trim().min(1).max(5e3).nullable()});function wY(e){const t=e.managedServing;return!!(t?.source==="sandbox_managed_rl"&&t.canonicalArtifactState==="promotable"&&t.customerBindingAllowed)}function bI(e){return e.state==="ready"&&e.canonicalArtifactState==="promotable"&&e.canonicalDeploymentState==="ready"&&e.customerBindingAllowed&&!!e.teamId&&!!e.canonicalArtifactId&&!!e.canonicalDeploymentId}function IY(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"&&bI(t)&&t.canonicalArtifactId&&t.canonicalDeploymentId?{kind:"sandbox_customer_binding",evaluationArtifactId:null,canonicalArtifactId:t.canonicalArtifactId,canonicalDeploymentId:t.canonicalDeploymentId}:null}function _Y(e){const t=e.managedServing;return t?bI(t)&&t.canonicalArtifactId&&t.canonicalDeploymentId?{kind:"sandbox_serving",canonicalArtifactId:t.canonicalArtifactId,canonicalDeploymentId:t.canonicalDeploymentId}:null:{kind:"source_artifact",canonicalArtifactId:null,canonicalDeploymentId:null}}const Kg="openpond.crossSystemOperations.v1",CY="1.0.0",yI="openpond.crossSystemTools.v1",QB=["search_crm","query_billing","search_support","run_python"],XB=b(["train","validation","frozen_eval"]),eF=b(["easy","medium","hard"]),tF=b(["renewal_risk_v2"]);b(["renewal_exposure","collections_prioritization","invoice_reconciliation","sla_escalation","contract_billing_mismatch"]);c({seed:u().int().nonnegative(),split:XB,difficulty:eF,scenarioProfile:tF.optional()});const Ep={anyOf:[{type:"string",minLength:1,maxLength:256},{type:"null"}],default:null},Mp={type:"integer",minimum:1,maximum:50,default:25},SI=[{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:Ep,limit:Mp}}},{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:Ep,limit:Mp}}},{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:Ep,limit:Mp}}},{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}}}}],uc=mF({schemaVersion:yI,tools:SI}),nF=[`Use only the four registered synthetic Cross-System Operations tools. Contract ${uc}.`,"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(" "),aF=15;function oF(e="auto"){return[nF,"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: ${aF}.`,`Registered tool signatures: ${SI.map(rF).join("; ")}`].join(`
|
|
178
|
+
`)}oF();function rF(e){const t=$d(e.parameters),n=$d(t.properties),a=kI(t.required),o=Object.fromEntries(a.map(i=>[i,ud(n[i])]));return`${e.name}(${JSON.stringify(o)})`}function ud(e){const t=$d(e),n=Uf(t.anyOf);if(n.length)return n.map(ud).join("|");const a=Uf(t.enum);if(a.length)return a.join("|");if(t.type==="array")return[ud(t.items)];if(t.type==="object"){const o=$d(t.properties),i=kI(t.required);return Object.fromEntries(i.map(s=>[s,ud(o[s])]))}return typeof t.type=="string"?t.type:"unknown"}function $d(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Uf(e){return Array.isArray(e)?e:[]}function kI(e){return Uf(e).filter(t=>typeof t=="string")}const Nd=b(QB),iF=Rt("kind",[c({kind:S("model"),turn:u().int().nonnegative(),content:r().max(1e5)}),c({kind:S("tool_call"),turn:u().int().nonnegative(),callId:r().trim().min(1).max(240),name:Nd,arguments:ie(r(),ce())}),c({kind:S("tool_result"),turn:u().int().nonnegative(),callId:r().trim().min(1).max(240),name:Nd,ok:A(),result:ce(),rows:u().int().nonnegative(),bytes:u().int().nonnegative(),durationMs:u().int().nonnegative(),error:r().trim().min(1).max(2e4).nullable()}),c({kind:S("final"),turn:u().int().nonnegative(),content:r().max(1e5)})]),sF=c({schemaVersion:S(Kg),id:r().trim().min(1).max(240),worldId:r().trim().min(1).max(240),taskId:r().trim().min(1).max(240),toolContractHash:S(uc),modelRef:c({providerId:r().trim().min(1),modelId:r().trim().min(1)}).nullable(),status:b(["completed","budget_exhausted","cancelled","infrastructure_failure"]),steps:f(iF).max(1e3),startedAt:r().trim().min(1),completedAt:r().trim().min(1),infrastructureError:r().trim().min(1).max(2e4).nullable(),metadata:ie(r(),ce()).default({})}),lF=c({schemaVersion:S(Kg),trajectoryId:r().trim().min(1).max(240),outcome:b(["correct","incorrect","parse_failure","budget_exhausted","tool_schema_violation","infrastructure_failure","cancelled"]),reward:u().min(0).max(1.15).nullable(),rewardEligible:A(),exactAnswer:A(),components:c({exactAnswer:u().min(0).max(1),efficiency:u().min(0).max(.1),conciseOutput:u().min(0).max(.05)}),metrics:c({toolCalls:u().int().nonnegative(),rowsRead:u().int().nonnegative(),bytesRead:u().int().nonnegative(),consecutiveRetrievalCalls:u().int().nonnegative(),wallTimeMs:u().int().nonnegative(),parseFailures:u().int().nonnegative(),budgetExhausted:A()}),parsedAnswer:ce().nullable(),feedback:f(r().trim().min(1).max(5e3)).max(100)}),cF=c({id:r().trim().min(1).max(240),type:S("function"),function:c({name:Nd,arguments:r().max(2e4)})}),xI=c({role:b(["system","user","assistant","tool"]),content:r().max(2e5).nullable(),tool_call_id:r().trim().min(1).max(240).optional(),tool_calls:f(cF).max(4).optional()});c({schemaVersion:S(Kg),id:r().trim().min(1).max(240),taskId:r().trim().min(1).max(240),worldId:r().trim().min(1).max(240),trajectoryId:r().trim().min(1).max(240),toolContractHash:S(uc),approval:c({status:S("approved"),approvedBy:r().trim().min(1).max(240),approvedAt:r().trim().min(1)}),messages:f(xI).min(3).max(1e3)});const dF=c({tasksetTaskId:r().trim().min(1).max(240),environmentTaskId:r().trim().min(1).max(240),family:b(["renewal_exposure","collections_prioritization","invoice_reconciliation","sla_escalation","contract_billing_mismatch"]),prompt:r().trim().min(1).max(1e5),finalAnswer:r().trim().min(1).max(2e5),trajectoryId:r().trim().min(1).max(240),trajectoryHash:r().trim().min(8).max(256),toolNames:f(Nd).min(1).max(100),toolCallCount:u().int().positive(),messageCount:u().int().min(3),reward:u().min(0).max(1.15),messages:f(xI).min(3).max(1e3)}),uF=c({status:S("approved"),approvedBy:r().trim().min(1).max(240),approvedAt:r().trim().min(1),previewHash:r().trim().min(8).max(256),trajectoryCount:u().int().positive()});c({schemaVersion:S("openpond.crossSystemExpertBootstrapPreview.v1"),tasksetId:r().trim().min(1).max(240),tasksetHash:r().trim().min(8).max(256),tasksetRevision:u().int().positive(),previewHash:r().trim().min(8).max(256),toolContractHash:S(uc),status:b(["ready_for_review","approved"]),approval:uF.nullable(),tasks:f(dF).min(1).max(100)});function mF(e){const t=zf(e);let n=2166136261,a=2654435769;for(let o=0;o<t.length;o+=1){const i=t.charCodeAt(o);n=Math.imul(n^i,16777619),a=Math.imul(a^i,2246822507)}return`${yI}:${Cy(n)}${Cy(a)}`}function zf(e){return Array.isArray(e)?`[${e.map(zf).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${zf(n)}`).join(",")}}`:JSON.stringify(e)}function Cy(e){return(e>>>0).toString(16).padStart(8,"0")}const pF=c({schemaVersion:S("openpond.singleTurnPolicyTrajectory.v1"),id:Re,taskId:Re,status:b(["completed","infrastructure_failure"]),promptHash:pt,responseText:r().max(2e6),infrastructureError:r().trim().min(1).max(1e4).nullable(),startedAt:Tt,completedAt:Tt,metadata:dc}),fF=c({schemaVersion:S("openpond.ppoTrajectory.v1"),id:Re,taskId:Re,policyModelId:Re,referenceModelId:Re,valueModelId:Re,steps:f(c({index:u().int().nonnegative(),observationHash:pt,actionTokenIds:f(u().int().nonnegative()).min(1),terminated:A(),truncated:A(),reward:u(),policyLogProbability:u(),referenceLogProbability:u(),valuePrediction:u(),return:u(),advantage:u(),mask:u().min(0).max(1)})).min(1).max(1e5),createdAt:Tt}),hF=c({schemaVersion:S("openpond.exactAnswerVerifierResult.v1"),outcome:b(["correct","incorrect","parse_failure","infrastructure_failure"]),graderSetHash:pt,score:u().min(0).max(1).nullable(),passed:A(),rewardEligible:A(),expectedAnswerHash:pt,extractedAnswer:r().max(2e4).nullable(),feedback:f(r().trim().min(1).max(2e4)).max(1e3)}),gF=c({schemaVersion:S("openpond.rolloutTrajectoryReceipt.v1"),id:Re,jobId:Re,planId:Re,tasksetId:Re,tasksetHash:pt,taskId:Re,split:S("train"),correlationId:Re,provider:Re,providerTrace:c({invocationId:Re,experimentId:Re,rolloutId:Re,runId:Re,rowId:Re}),optimizerMethod:b(["grpo","ppo"]).default("grpo"),evidenceLevels:c({requested:b(["trajectory","aggregate","provider_reported"]),observed:b(["trajectory","aggregate","provider_reported"]),providerReported:b(["trajectory","aggregate","provider_reported"])}).default({requested:"trajectory",observed:"trajectory",providerReported:"provider_reported"}),budgetUsage:c({rollouts:u().int().nonnegative(),environmentExecutions:u().int().nonnegative(),inputTokens:u().int().nonnegative(),outputTokens:u().int().nonnegative(),optimizerSteps:u().int().nonnegative(),costUsd:u().nonnegative()}).default({rollouts:0,environmentExecutions:0,inputTokens:0,outputTokens:0,optimizerSteps:0,costUsd:0}),environment:c({id:Re,version:r().trim().min(1).max(256),worldId:Re,worldHash:pt,toolContractHash:pt}),policy:c({modelId:Re,checkpointId:Re.nullable(),completionParametersHash:pt}),status:b(["received","running","succeeded","failed"]),failureClass:b(["policy_failure","parse_failure","tool_schema_violation","budget_exhausted","cancelled","environment_failure","infrastructure_failure"]).nullable(),reward:c({eligible:A(),raw:u().min(0).max(1.15).nullable(),normalized:u().min(0).max(1).nullable(),components:ie(r(),u())}),trajectory:Dt([sF,pF,fF]).nullable(),verifier:Dt([lF,hF]).nullable(),providerStatus:ie(r(),ce()).default({}),receivedAt:Tt,startedAt:Tt.nullable(),completedAt:Tt.nullable(),updatedAt:Tt}),RY="dataset-exact-answer",PY="dataset-exact-answer-v1",AY="no-tools-v1",vr=b(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),Eu=b(["lora","full"]),ti=b(["openpond_managed"]),vF=c({schemaVersion:S("openpond.sftRecipe.v1"),method:S("sft"),parameterization:S("lora"),baseModel:c({id:Re,revision:r().trim().min(1).max(256),tokenizerRevision:r().trim().min(1).max(256),chatTemplateHash:pt}),dataset:c({trainSplit:S("train"),validationSplit:b(["validation","frozen_eval"]),completionOnly:A(),maxSequenceLength:u().int().positive().max(32768),maxExamples:u().int().positive().max(1e5).default(1e3),selectionStrategy:S("stable_hash_top_n").default("stable_hash_top_n"),selectionSeed:u().int().default(17)}),lora:c({rank:u().int().positive().max(256),alpha:u().positive().max(1024),dropout:u().min(0).max(1),targetModules:f(Re).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:Re,input:ie(r(),ce()),expectedOutput:ie(r(),ce()),tags:f(Re).max(100).default([])});c({id:Re,prompt:r().min(1).max(5e5),chosen:r().min(1).max(5e5),rejected:r().min(1).max(5e5),sourceRefs:f(Re).min(1).max(1e4)});c({id:Re,input:ie(r(),ce()),tags:f(Re).max(100).default([])});c({schemaVersion:S("openpond.rewardModelRecipe.v1"),method:S("reward_model"),parameterization:S("lora_with_scalar_head"),runScope:b(["synthetic_smoke","human_preference"]),baseModel:c({id:Re,revision:r().trim().min(1).max(256),tokenizerRevision:r().trim().min(1).max(256),processorRevision:r().trim().min(1).max(256),chatTemplateHash:pt}).strict(),tasksetRelease:ee,preferenceDatasetRelease:ee,processorRelease:ee,input:c({kind:S("structured_text"),serialization:b(["scenario_input_and_candidate_json_v1","visible_agent_trajectory_v1"]),maxCharacters:u().int().positive().max(5e5)}).strict().default({kind:"structured_text",serialization:"scenario_input_and_candidate_json_v1",maxCharacters:32e3}),lora:c({rank:u().int().positive().max(256),alpha:u().positive().max(1024),dropout:u().min(0).max(1),targetModules:f(Re).min(1).max(100)}).strict(),heads:c({scalar:S("pooled_hidden_state_linear"),bucket:b(["none","three_class"]).default("three_class")}).strict(),loss:c({ranking:S("bradley_terry"),rankingWeight:u().positive(),bucketWeight:u().nonnegative(),tieWeight:u().nonnegative()}).strict(),optimizer:c({learningRate:u().positive(),maxSteps:u().int().positive().max(1e5),batchSize:u().int().positive().max(1e4),gradientAccumulationSteps:u().int().positive().max(1e4),seed:u().int(),checkpointEverySteps:u().int().positive().max(1e5)}).strict(),resourceLimits:c({wallTimeMs:u().int().positive().max(1440*60*1e3),maxExamples:u().int().positive().max(1e5),maxInputCharacters:u().int().positive().max(5e5).default(32e3),maxImagePixels:u().int().positive().max(1e8).optional(),maximumSpendUsd:u().nonnegative().max(1e5)}).strict()}).superRefine((e,t)=>{e.runScope==="synthetic_smoke"&&(e.optimizer.maxSteps>100||e.resourceLimits.maximumSpendUsd>10)&&t.addIssue({code:"custom",path:["resourceLimits"],message:"Synthetic-smoke Reward Model runs are limited to 100 steps and USD 10."})});const bF=c({schemaVersion:S("openpond.rftRecipe.v1"),method:S("grpo"),parameterization:S("lora"),baseModel:c({id:Re,revision:r().trim().min(1).max(256),tokenizerRevision:r().trim().min(1).max(256),chatTemplateHash:pt}),dataset:c({trainSplit:S("train"),validationSplit:b(["validation","frozen_eval"]),maxPromptTokens:u().int().positive().max(32768),maxExamples:u().int().positive().max(1e5).default(1e3),selectionStrategy:b(["stable_hash_top_n","rft_easy_curriculum_v1"]).default("stable_hash_top_n")}),lora:c({rank:u().int().positive().max(256)}),rollout:c({groupSize:u().int().min(2).max(64),concurrency:u().int().positive().max(32),maxTurns:u().int().positive().max(100),maxOutputTokens:u().int().positive().max(8192),temperature:u().min(0).max(2),topP:u().positive().max(1),seed:u().int()}),optimizer:c({learningRate:u().positive(),maxSteps:u().int().positive().max(1e5),clipRange:u().positive().max(1).default(.2),iterations:u().int().min(2).max(16).default(2),microbatchSize:u().int().positive().max(64).default(1),gradientAccumulationSteps:u().int().positive().max(64).default(1),advantageEpsilon:u().positive().max(.01).default(1e-8),adamw:tI}),loss:c({method:pI.default("grpo"),klBeta:u().min(0).nullable().default(null)}).default({method:"grpo",klBeta:null}),reward:c({graderId:Re,graderHash:pt,environmentId:Re,environmentVersion:r().trim().min(1).max(256),toolContractHash:pt,learnedPreference:hI.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:gI.nullable().default(null),continuation:c({schemaVersion:S("openpond.crossJobContinuationRequest.v1"),parentArtifact:ee,sourceArtifact:c({jobId:Re,artifactId:Re,checkpointId:Re,contentHash:pt}).strict(),optimizerMode:b(["continue","reset"])}).strict().optional()}),yF=c({schemaVersion:S("openpond.dpoRecipe.v1"),method:S("dpo"),parameterization:S("lora"),policyModel:Ul,referenceModel:Ul,dataset:c({trainSplit:S("train"),validationSplit:b(["validation","frozen_eval"]),maxPairs:u().int().positive().max(1e5),maxPromptTokens:u().int().positive().max(32768),maxCompletionTokens:u().int().positive().max(32768),selectionStrategy:S("stable_hash_top_n"),selectionSeed:u().int()}),lora:c({rank:u().int().positive().max(256),alpha:u().positive().max(1024),dropout:u().min(0).max(1),targetModules:f(Re).min(1).max(100)}),loss:c({variant:S("sigmoid"),beta:u().positive().max(10),labelSmoothing:u().min(0).max(.5).default(0)}),optimizer:c({learningRate:u().positive(),epochs:u().positive().max(100),maxSteps:u().int().positive().max(1e6),batchSize:u().int().positive().max(1e4),gradientAccumulationSteps:u().int().positive().max(1e4),seed:u().int()}),referenceLogprobs:c({cacheSchemaVersion:S("openpond.dpoReferenceLogprobs.v1"),cacheKey:pt,invalidationHash:pt}),resourceLimits:c({cpuThreads:u().int().positive().max(256),memoryBytes:u().int().positive(),wallTimeMs:u().int().positive()})}),SF=c({schemaVersion:S("openpond.ppoRecipe.v1"),method:S("ppo"),parameterization:S("lora"),policyOptimization:gI.extend({optimizer:fI}),lora:c({rank:u().int().positive().max(256),alpha:u().positive().max(1024),dropout:u().min(0).max(1),targetModules:f(Re).min(1).max(100)}),valueHead:c({initialization:S("policy_hidden_state_linear"),optimizerLearningRate:u().positive(),artifactName:S("value_head.safetensors")}),policyLearningRate:u().positive(),resume:c({checkpointId:Re.nullable(),policyHash:pt,referenceHash:pt,valueModelHash:pt,optimizerStateHash:pt.nullable()}),resourceLimits:c({cpuThreads:u().int().positive().max(256),memoryBytes:u().int().positive(),wallTimeMs:u().int().positive()})}),kF=c({schemaVersion:S("openpond.unsupportedRecipe.v1"),method:vr.exclude(["sft","dpo","grpo","ppo"]),parameterization:Eu,unsupportedReason:r().trim().min(1).max(5e3)}),wI=Dt([vF,yF,bF,SF,kF]),xF=c({schemaVersion:S("openpond.trainingDestinationCapabilities.v1"),destinationId:ti,available:A(),methods:f(vr),parameterizations:f(Eu),modelAllowlist:f(Re).default([]),maxDatasetBytes:u().int().nonnegative().nullable(),environmentPlacements:f(b(["none","local","remote","colocated","provider_native"])),nonProduction:A(),unavailableReason:r().trim().min(1).max(5e3).nullable(),checkedAt:Tt}),wF=c({destinationId:ti,available:A(),methods:f(vr),parameterizations:f(Eu),nonProduction:A(),unavailableReason:r().trim().min(1).max(5e3).nullable()}),IF=c({schemaVersion:S("openpond.baseModelCandidate.v1"),selectionKey:Re,label:r().trim().min(1).max(500),sourceLabel:r().trim().min(1).max(500),preference:cc,available:A(),nonProduction:A(),unavailableReason:r().trim().min(1).max(5e3).nullable(),methods:f(vr),executionOptions:f(wF).min(1)}),_F=c({code:Re,severity:b(["warning","error"]),path:r().trim().max(2e3).nullable(),message:r().trim().min(1).max(5e3)}),CF=c({schemaVersion:S("openpond.trainingCompatibility.v1"),compatible:A(),destinationId:ti,tasksetId:Re,recipeMethod:vr,issues:f(_F),checkedAt:Tt}),RF=Dt([p1,b(["destination_unavailable","destination_method_unsupported","destination_model_unsupported","destination_parameterization_unsupported","experimental_destination"])]);c({method:vr,state:b(["recommended","compatible","needs_dataset_work","destination_unavailable","experimental_destination"]),reasonCodes:f(RF).default([]),reasons:f(r().trim().min(1).max(5e3)).default([]),destinationId:ti.nullable().default(null)});b(["small","standard","custom","small_experiment"]);const PF=$1,II=c({schemaVersion:S("openpond.trainingPlan.v1"),id:Re,modelId:Re,tasksetId:Re,tasksetHash:pt,comparisonSeriesEntry:ss.nullable().optional(),evaluationTasksetRef:Kt.nullable().optional(),harnessRelease:ee.nullable().optional(),modelImprovementQualification:ee.nullable().optional(),destinationId:ti,recipe:wI,environmentPlacement:b(["none","local","remote","colocated","provider_native"]),compatibility:CF,dataPolicy:c({exportApproved:A(),approvedSourceIds:f(Re),retentionDays:u().int().nonnegative().nullable(),region:r().trim().min(1).max(200).nullable()}),estimatedCostUsd:u().nonnegative().nullable(),createdAt:Tt,contentHash:pt}),AF=c({path:r().trim().min(1).max(2e3),sha256:pt,sizeBytes:u().int().nonnegative(),role:b(["manifest","task_data","grader","environment","recipe","policy","provenance"])}),Wg=c({schemaVersion:S("openpond.trainingBundle.v1"),id:Re,planId:Re,tasksetId:Re,tasksetHash:pt,recipeHash:pt,files:f(AF).min(1).max(1e6),totalSizeBytes:u().int().nonnegative(),sourceIds:f(Re),excludedSourceIds:f(Re),containsRawChats:S(!1),containsSecrets:S(!1),containsHiddenGraderAssets:S(!1),createdAt:Tt,contentHash:pt});c({schemaVersion:S("openpond.trainingBundleExport.v1"),manifest:Wg,files:f(c({path:r().trim().min(1).max(2e3),sha256:pt,sizeBytes:u().int().nonnegative(),encoding:S("base64"),content:r()})).min(1),contentHash:pt});c({schemaVersion:S("openpond.trainingPreparedStart.v1"),plan:II,bundle:Wg,approvalActor:Re.nullable(),preparedAt:Tt});c({schemaVersion:S("openpond.trainingApproval.v1"),evaluationTasksetRef:Kt.nullable().optional(),id:Re,planId:Re,bundleHash:pt,harnessRelease:ee.nullable().optional(),modelImprovementQualification:ee.nullable().optional(),destinationId:ti,modelId:Re,method:vr,parameterization:Eu,maximumCostUsd:u().nonnegative().nullable(),approvedBy:Re,approvedAt:Tt});c({schemaVersion:S("openpond.trainingJobSourceSnapshot.v1"),evaluationTasksetRef:Kt.nullable().optional(),modelProjectId:Re,sourceProjectRevision:u().int().positive(),profileId:Re,taskset:c({id:Re,revision:u().int().positive(),contentHash:pt}).strict(),tasksetRelease:ee,harnessRelease:ee,baseModel:cc,method:vr}).strict();const TF=b(["queued","starting","running","cancelling","cancelled","succeeded","failed","reconciling"]),_I=c({schemaVersion:S("openpond.trainingJob.v1"),id:Re,planId:Re,bundleHash:pt,approvalId:Re,destinationId:ti,status:TF,nonProduction:A(),workerPid:u().int().positive().nullable(),startedAt:Tt.nullable(),completedAt:Tt.nullable(),error:r().trim().min(1).max(2e4).nullable(),createdAt:Tt,updatedAt:Tt,metadata:dc}),EF=c({schemaVersion:S("openpond.trainingJobEvent.v1"),id:Re,jobId:Re,sequence:u().int().nonnegative(),type:b(["queued","start","progress","metric","checkpoint","cancel","complete","failure","reconcile"]),timestamp:Tt,payload:dc}),MF=c({schemaVersion:S("openpond.sftStepMetric.v1"),step:u().int().nonnegative(),maxSteps:u().int().positive(),timestamp:Tt,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()}),jF=c({schemaVersion:S("openpond.policyOptimizationMetric.v1"),method:b(["grpo","ppo"]),step:u().int().nonnegative(),timestamp:Tt,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()}),OF=c({schemaVersion:S("openpond.managedTrainingRunEvidence.v2"),provider:Re,providerRunId:Re,state:Re,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:Re,gpuType:r().trim().min(1).max(300).nullable(),gpuCount:u().int().nonnegative().nullable(),hourlyCostUsd:u().nonnegative().nullable(),durationSeconds:u().nonnegative().nullable(),gpuSeconds:u().nonnegative().nullable()}),cost:c({totalUsd:u().nonnegative().nullable()}),checkpoint:c({id:Re,policyVersion:u().int().nonnegative(),sha256:pt.nullable(),sizeBytes:u().int().nonnegative().nullable()}).nullable(),movement:c({adapterDeltaNorm:u().nonnegative().nullable()}),evaluations:f(c({reference:c({id:Re,contentHash:pt}).nullable().optional(),kind:b(["baseline","candidate"]),policyVersion:u().int().nonnegative(),taskCount:u().int().nonnegative().nullable().optional(),targetTaskCount:u().int().nonnegative().nullable().optional(),score:u().nullable(),threshold:u().nullable(),passed:A().nullable()})),canonicalPublication:c({state:Re.nullable(),artifactId:Re.nullable()}),syncedAt:Tt}),Ry=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()}),Py=c({status:b(["scored","unavailable"]),score:u().min(0).max(1).nullable(),passed:A(),rewardEligible:A(),failureClass:b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),feedback:f(r().trim().min(1).max(2e4)).max(1e3),components:f(c({graderId:Re,score:u().min(0).max(1).nullable(),passed:A(),feedback:r().trim().max(2e4).nullable()})).max(1e3)}),$F=c({taskId:Re,input:ie(r(),ce()),baseOutput:ie(r(),ce()).nullable(),trainedOutput:ie(r(),ce()).nullable(),baseGrade:Py.nullable(),trainedGrade:Py.nullable()}),NF=c({schemaVersion:S("openpond.trainingEvaluationSummary.v1"),jobId:Re,tasksetId:Re,base:Ry,trained:Ry,meanScoreDelta:u().min(-1).max(1).nullable(),examples:f($F).max(1e6)});c({schemaVersion:S("openpond.trainingRunDetail.v1"),job:_I,events:f(EF),stepMetrics:f(MF),policyMetrics:f(jF).default([]),managedEvidence:OF.nullable().default(null),evaluation:NF.nullable(),generatedAt:Tt});const DF=c({schemaVersion:S("openpond.trainingArtifact.v1"),id:Re,jobId:Re,kind:b(["adapter","checkpoint","metrics","log","manifest","evaluation"]),path:r().trim().min(1).max(4e3),sha256:pt,sizeBytes:u().int().nonnegative(),baseModelId:Re.nullable(),baseModelRevision:r().trim().min(1).max(256).nullable(),tokenizerRevision:r().trim().min(1).max(256).nullable(),chatTemplateHash:pt.nullable(),nonProduction:A(),createdAt:Tt,metadata:dc}),LF=c({schemaVersion:S("openpond.modelArtifactLineage.v1"),id:Re,modelId:Re,artifactId:Re,jobId:Re,tasksetId:Re,tasksetHash:pt,graderHash:pt,planHash:pt,bundleHash:pt,recipeHash:pt,workerVersion:r().trim().min(1).max(256),trainerVersion:r().trim().min(1).max(256),importedAt:Tt,frozenEvaluationArtifactId:Re.nullable(),promotable:A(),pinned:A().default(!1),status:b(["imported","rejected"]).default("imported"),rejectedAt:Tt.nullable().default(null),rejectionReason:r().trim().min(1).max(5e3).nullable().default(null),chatConfiguration:vI.default(JB),managedServing:YB.nullable().default(null)}),UF=b(["chat_manual","agent","extension","authoring_optimizer"]),zF=c({schemaVersion:S("openpond.modelBinding.v1"),id:Re,profileId:Re,role:UF,roleTargetId:Re,modelArtifactLineageId:Re,tasksetId:Re,evaluationArtifactId:Re.nullable(),status:b(["active","rolled_back"]),priorBindingId:Re.nullable(),rollbackTargetBindingId:Re.nullable(),promotedBy:Re,promotedAt:Tt,rolledBackAt:Tt.nullable(),metadata:dc});c({schemaVersion:S("openpond.trainingActivity.v1"),profileId:Re,active:A(),activeCounts:c({jobs:u().int().nonnegative(),creations:u().int().nonnegative(),minerRuns:u().int().nonnegative(),datasetImports:u().int().nonnegative()}),revision:pt,generatedAt:Tt});c({schemaVersion:S("openpond.tasksetOperationalState.v1"),tasksetId:Re,attempts:f(Nq),artifacts:f(Dq),grades:f(Uq),evaluationResults:f(IU).default([]),generatedAt:Tt});const HF=c({schemaVersion:S("openpond.trainingState.v1"),profileId:Re,sources:f(Qw),creations:f(nI),tasksetDrafts:f(fo).default([]),tasksets:f(ly),benchmarkRuns:f(Xm()).default([]),benchmarkComparisons:f(Xm()).default([]),datasetImports:f(Xq).default([]),datasetArtifacts:f(AU).default([]),graderAuditReports:f(zq),evaluationResults:f(Xm()).default([]),candidates:f(eI),minerConfig:Au,minerRuns:f(wq).default([]),modelProjects:f(PF).default([]),modelVersions:f(_B).default([]),modelRuns:f(LB).default([]),comparisonSeries:f(vB).default([]),comparisonSeriesEntries:f(wB).default([]),modelCurrencySnapshots:f(qB).default([]),continualBenchIssueReviews:f(VB).default([]),continualLearningDailyBatches:f(FB).default([]),rewardModelVersions:f(CB).default([]),rewardModelRuns:f(PB).default([]),modelTasksets:f(ly).default([]),plans:f(II),bundles:f(Wg),jobs:f(_I),artifacts:f(DF),models:f(LF),rolloutReceipts:f(gF).default([]),modelBindings:f(zF).default([]),destinations:f(xF),baseModelCandidates:f(IF).default([]),activityRevision:pt.optional(),generatedAt:Tt}),qF=b(["trajectory","reward","demonstration","preference","correction","critique","targeted_feedback","grader_evidence","infrastructure_failure"]),BF=c({datasetRelease:ee,harnessRelease:ee,evidenceSetRelease:ee.nullable(),profileRelease:ee.nullable(),model:c({source:r().trim().min(1).max(200),revision:r().trim().min(1).max(500),artifactHash:Y.nullable()}).strict(),environmentHash:Y,graderHash:Y,toolContractHash:Y,verificationReceiptHash:Y.nullable()}).strict(),Yo=c({schemaVersion:S("openpond.learningSignal.v1"),id:E,taskId:E.nullable(),episodeId:E.nullable(),policyVersion:u().int().nonnegative().nullable(),lineage:BF,approved:A(),verifier:b(["deterministic","model_judge","human","none"]),createdAt:Pe,contentHash:Y,metadata:ie(r(),ce()).default({})}).strict(),FF=Yo.extend({kind:S("trajectory"),payload:c({traceRef:r().trim().min(1).max(2e3),traceHash:Y,terminal:A(),failureClass:b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),optimizerSample:q1.nullable().optional()}).strict()}).strict(),VF=Yo.extend({kind:S("reward"),payload:c({reward:u().finite(),components:ie(r(),u().finite()),eligible:A(),graderEvidenceRefs:f(E).max(1e3)}).strict()}).strict(),KF=Yo.extend({kind:S("demonstration"),payload:c({prompt:r().max(5e5),response:r().max(1e6)}).strict()}).strict(),WF=Yo.extend({kind:S("preference"),payload:c({prompt:r().max(5e5),chosen:r().max(1e6),rejected:r().max(1e6),rationale:r().max(5e5).nullable()}).strict()}).strict(),GF=Yo.extend({kind:S("correction"),payload:c({original:r().max(1e6),corrected:r().max(1e6),rationale:r().max(5e5).nullable()}).strict()}).strict(),ZF=Yo.extend({kind:S("critique"),payload:c({response:r().max(1e6),critique:r().max(5e5),severity:b(["note","warning","error"])}).strict()}).strict(),JF=Yo.extend({kind:S("targeted_feedback"),payload:c({turnIndex:u().int().nonnegative(),target:b(["reasoning","tool","answer","policy"]),feedback:r().max(5e5)}).strict()}).strict(),YF=Yo.extend({kind:S("grader_evidence"),payload:c({graderId:E,score:u().finite().nullable(),passed:A(),privilegedArtifactRefs:f(r().trim().min(1).max(2e3))}).strict()}).strict(),QF=Yo.extend({kind:S("infrastructure_failure"),approved:S(!1),verifier:S("none"),payload:c({code:E,phase:E,retryable:A(),rewardEligible:S(!1)}).strict()}).strict(),CI=Rt("kind",[FF,VF,KF,WF,GF,ZF,JF,YF,QF]);c({schemaVersion:S("openpond.learningSignalBatch.v1"),manifestId:E,manifestHash:Y,sequence:u().int().nonnegative(),signals:f(CI).min(1).max(1e5),contentHash:Y}).strict();const XF=c({id:E,turn:u().int().nonnegative(),kind:b(["message","tool_call","terminal"]),name:E.nullable(),arguments:ie(r(),ce()),content:r().max(1e6).nullable(),contentHash:Y}).strict(),e4=c({actionId:E,turn:u().int().nonnegative(),terminal:A(),output:ie(r(),ce()),artifactRefs:f(r().trim().min(1).max(2e3)),contentHash:Y}).strict(),t4=c({sequence:u().int().nonnegative(),type:b(["created","reset","action","observation","terminal","graded","feedback","failure","collected","destroyed"]),timestamp:Pe,payloadHash:Y,metadata:ie(r(),ce()).default({})}).strict(),Ay=c({graderId:E,graderVersion:r().trim().min(1).max(200),score:u().finite().nullable(),passed:A(),rewardEligible:A(),failureClass:b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),feedback:f(r().max(5e5)),visibleEvidenceRefs:f(r().trim().min(1).max(2e3)),privilegedEvidenceRefs:f(r().trim().min(1).max(2e3)),contentHash:Y}).strict();c({schemaVersion:S("openpond.harnessRunTrace.v1"),manifest:ee,taskId:E,seed:r().trim().min(1).max(500),events:f(t4).max(1e6),actions:f(XF).max(1e5),observations:f(e4).max(1e5),graderEvidence:f(Ay).max(1e4),learningSignals:f(CI).max(1e5),terminal:A(),failureClass:Ay.shape.failureClass,artifactHash:Y,contentHash:Y}).strict();const n4=r().trim().min(1).max(2e3).refine(e=>{const t=e.replaceAll("\\","/");return!t.startsWith("/")&&!t.includes("\0")&&!t.split("/").some(n=>!n||n==="."||n==="..")},"path must be a safe relative path"),a4=b(["instruction","skill","skill_resource","agent","workflow","dependency_lock","program","asset"]),o4=c({id:E,kind:a4,path:n4,parentId:E.nullable(),mediaType:r().trim().min(1).max(200),visibility:b(["policy","verifier","host_private"]),portability:b(["portable","local_only"])}).strict().superRefine((e,t)=>{e.kind==="skill_resource"!=(e.parentId!==null)&&t.addIssue({code:"custom",message:"only Skill resources require parentId",path:["parentId"]})});c({schemaVersion:S("openpond.harnessSourceManifest.v1"),name:r().trim().min(1).max(240),files:f(o4).min(2).max(1e5),toolDeclarations:f(tc).max(200),capabilityRequirements:f(Qh).max(200),lifecycle:gx,graderInterface:vx,runtimeProtocol:r().trim().min(1).max(500),metadata:ie(r(),ce()).default({})}).strict().superRefine((e,t)=>{const n=new Set,a=new Map,o=new Set;for(const[i,s]of e.files.entries())n.has(s.id)&&t.addIssue({code:"custom",message:"file ids must be unique",path:["files",i,"id"]}),o.has(s.path)&&t.addIssue({code:"custom",message:"file paths must be unique",path:["files",i,"path"]}),n.add(s.id),a.set(s.id,s.kind),o.add(s.path);for(const[i,s]of e.files.entries())s.parentId&&!n.has(s.parentId)?t.addIssue({code:"custom",message:"parentId must reference a declared Skill",path:["files",i,"parentId"]}):s.parentId&&a.get(s.parentId)!=="skill"&&t.addIssue({code:"custom",message:"parentId must reference a primary Skill file",path:["files",i,"parentId"]});e.files.filter(i=>i.kind==="dependency_lock").length!==1&&t.addIssue({code:"custom",message:"exactly one dependency lock is required",path:["files"]}),e.files.filter(i=>i.kind==="program").length!==1&&t.addIssue({code:"custom",message:"exactly one Harness program is required",path:["files"]})});c({rootPath:r(),sourcePath:r(),binding:Z2,currentRelease:Gb,releases:f(Gb),transitions:f(J2)}).strict();c({profile:Sx,activate:A().default(!0),reason:r().trim().min(1).max(1e4),actor:r().trim().min(1).max(240).default("local-user"),authoringSkillHash:r().regex(/^[a-f0-9]{64}$/).nullable().default(null)}).strict();c({release:ee,reason:r().trim().min(1).max(1e4),actor:r().trim().min(1).max(240).default("local-user")}).strict();const r4=c({schemaVersion:S("openpond.trainingEngineCapabilities.v1"),adapterId:E,available:A(),methods:f(r().trim().min(1).max(100)),signalKinds:f(qF),modelFamilies:f(r().trim().min(1).max(200)),precisions:f(b(["fp32","fp16","bf16","tf32","int8","int4"])),topologies:f(r().trim().min(1).max(200)),workerProtocolVersion:r().trim().min(1).max(200),upstreamRevision:r().trim().min(1).max(500),workerImageDigest:r().regex(/^sha256:[a-f0-9]{64}$/).nullable().default(null),capabilityReceipt:Y,checkedAt:Pe,unavailableReason:r().trim().min(1).max(5e3).nullable()}).strict(),i4=c({schemaVersion:S("openpond.computeTargetCapabilities.v1"),adapterId:E,kind:b(["local","ssh","managed","custom"]),provider:E.nullable(),available:A(),devices:f(c({id:E,kind:b(["cpu","gpu","accelerator"]),vendor:r().trim().min(1).max(200),name:r().trim().min(1).max(500),memoryBytes:u().int().nonnegative().nullable(),runtime:r().trim().min(1).max(200)}).strict()),supportsWorkerImages:A(),supportsArtifactTransfer:A(),supportsCancellation:A(),capabilityReceipt:Y,checkedAt:Pe,unavailableReason:r().trim().min(1).max(5e3).nullable()}).strict(),s4=c({schemaVersion:S("openpond.harnessRuntimeCapabilities.v1"),adapterId:E,available:A(),placements:f(b(["local","remote","colocated","provider_native"])),lifecycle:f(b(["create","reset","step","grade","collect","destroy"])),deterministicReplay:A(),privilegedIsolation:A(),capabilityReceipt:Y,checkedAt:Pe,unavailableReason:r().trim().min(1).max(5e3).nullable()}).strict();c({schemaVersion:S("openpond.resolvedTrainingPlan.v1"),manifest:Rq,recipe:wI,runtime:Ug,compute:zg,engine:Hg,execution:c({trainingPlanId:E,approvalId:E}).strict().nullable(),maximumSpendUsd:u().nonnegative().nullable(),approvalHash:Y,contentHash:Y}).strict().superRefine((e,t)=>{const n=[["runtime",e.runtime,e.manifest.runtimeTarget],["compute",e.compute,e.manifest.computeTarget],["engine",e.engine,e.manifest.engine]];for(const[a,o,i]of n)JSON.stringify(o)!==JSON.stringify(i)&&t.addIssue({code:"custom",path:[a],message:`${a} must exactly match the Harness Run Manifest`});e.recipe.method!==e.manifest.recipe.method&&t.addIssue({code:"custom",path:["recipe","method"],message:"Recipe method must match the Harness Run Manifest"}),e.approvalHash!==e.manifest.approval.approvalHash&&t.addIssue({code:"custom",path:["approvalHash"],message:"Approval hash must match the Harness Run Manifest"}),e.maximumSpendUsd!==e.manifest.approval.maximumSpendUsd&&t.addIssue({code:"custom",path:["maximumSpendUsd"],message:"Maximum spend must match the Harness Run Manifest"})});c({schemaVersion:S("openpond.adapterValidationReceipt.v1"),adapterId:E,valid:A(),issues:f(c({code:E,path:r().trim().max(2e3).nullable(),message:r().trim().min(1).max(5e3)}).strict()),capabilityReceipt:Y,planHash:Y,createdAt:Pe,contentHash:Y}).strict();c({runId:E,adapterId:E,protocolVersion:b(["openpond.training.v2","adapter.native.v1"]).default("adapter.native.v1"),routeFamily:b(["training_v2","adapter_native"]).default("adapter_native"),routeId:E.optional(),providerJobId:r().trim().min(1).max(1e3).nullable(),tenantId:E.optional(),leaseId:E.nullable(),manifestHash:Y.optional(),inputBundleHash:Y.optional(),createdAt:Pe}).strict();c({runId:E,state:b(["queued","preparing","running","cancelling","cancelled","succeeded","failed"]),phase:r().trim().min(1).max(200),progress:u().min(0).max(1).nullable(),rolloutProgress:c({groupsCompleted:u().int().nonnegative(),groupsTarget:u().int().nonnegative(),optimizerUpdatesApplied:u().int().nonnegative(),optimizerUpdatesSkipped:u().int().nonnegative()}).strict().optional(),updatedAt:Pe,errorCode:E.nullable()}).strict();c({runId:E,manifestHash:Y,artifacts:f(c({kind:b(["checkpoint","adapter","metrics","trace","evaluation","receipt"]),objectRef:r().trim().min(1).max(2e3),sha256:Y,sizeBytes:u().int().nonnegative(),metadata:ie(r(),ce()).optional()}).strict()),contentHash:Y}).strict();const Hf=b(["ready","model_download_required","compute_setup_required","provider_managed","unsupported"]),l4=c({id:E,label:r().trim().min(1).max(500),description:r().trim().min(1).max(2e3),destinationId:E,computeAdapterId:E,runtimeAdapterId:E,engineAdapterId:E,methods:f(r().trim().min(1).max(100)),capabilityPills:f(r().trim().min(1).max(100)),executionMode:b(["local_worker","provider_native"]),approvalPolicy:c({providerId:Jr,providerLabel:r().trim().min(1).max(200),settingsActionLabel:r().trim().min(1).max(500).nullable(),exportApprovalRequired:A(),exportDescription:r().trim().min(1).max(2e3).nullable(),preparationRequired:A(),minimumSpendUsd:u().nonnegative(),maximumSpendUsd:u().positive(),defaultMaximumSpendUsd:u().positive(),minimumRetentionDays:u().int().positive(),maximumRetentionDays:u().int().positive(),defaultRetentionDays:u().int().positive(),methodRequirement:r().trim().min(1).max(2e3).nullable()}).strict().nullable(),limits:c({maximumSequenceLength:u().int().positive(),maximumOutputTokens:u().int().positive(),maximumTrainingExamples:u().int().positive().nullable()}).strict(),defaults:c({loraRank:u().int().positive(),maxSteps:u().int().positive(),rolloutGroupSize:u().int().min(2).max(32),rolloutConcurrency:u().int().positive().max(32),rolloutOutputTokens:u().int().positive()}).strict(),available:A(),unavailableReason:r().trim().min(1).max(5e3).nullable()}).strict(),c4=c({selectionKey:E,label:r().trim().min(1).max(500),source:b(["local","builtin","huggingface","managed","search"]),modelId:r().trim().min(1).max(1e3),revision:r().trim().min(1).max(500).nullable(),tokenizerRevision:r().trim().min(1).max(500).nullable(),chatTemplateHash:Y.nullable(),modelAssetId:E.nullable(),expectedBytes:u().int().nonnegative().nullable(),cached:A(),known:A(),searchResolved:A(),computeAdapterIds:f(E),engineAdapterIds:f(E),preparationState:Hf,reason:r().trim().min(1).max(5e3).nullable(),compatibilities:f(c({targetId:E,methods:f(r().trim().min(1).max(100)),state:Hf,reason:r().trim().min(1).max(5e3).nullable()}).strict())}).strict();c({schemaVersion:S("openpond.trainingCatalog.v1"),models:f(c4).max(1e5),engines:f(r4),compute:f(i4),runtimes:f(s4),targets:f(l4),generatedAt:Pe,contentHash:Y}).strict();c({schemaVersion:S("openpond.trainingPreparationPlan.v1"),modelRunId:E,state:Hf,reason:r().trim().min(1).max(5e3).nullable(),runtime:Ug.nullable(),compute:zg.nullable(),engine:Hg.nullable(),downloads:f(c({kind:S("model"),label:r().trim().min(1).max(500),expectedBytes:u().int().nonnegative(),digest:r().trim().min(8).max(500),cached:A(),state:b(["ready","required","downloading","cancelled","failed"]),progress:u().min(0).max(1).nullable(),cancellable:A(),diskImpactBytes:u().int().nonnegative()}).strict()),dataMovement:f(c({direction:b(["upload","download","none"]),label:r().trim().min(1).max(500),bytes:u().int().nonnegative().nullable()}).strict()),quoteUsd:u().nonnegative().nullable(),maximumSpendUsd:u().nonnegative().nullable(),retentionDays:u().int().nonnegative().nullable(),sideEffectsStarted:S(!1),contentHash:Y}).strict();const Gg=32e3,d4=b(["steer","message","followup","queued","result"]),u4=b(["pending","included","resolved","cancelled","rejected"]),RI=c({id:r().min(1),sequence:u().int().nonnegative(),sessionId:r().min(1),senderSessionId:r().min(1).nullable(),senderKind:b(["user","task","runtime"]),kind:d4,body:r().trim().min(1).max(Gg),payload:ie(r(),ce()).default({}),idempotencyKey:r().min(1).max(200),replyTo:r().min(1).nullable(),expectedTurnId:r().min(1).nullable(),turnId:r().min(1).nullable(),requestIds:f(r()),state:u4,revision:u().int().positive(),createdAt:r(),updatedAt:r(),error:r().nullable()}).strict();c({expectedTurnId:r().trim().min(1),idempotencyKey:r().trim().min(1).max(200),prompt:r().trim().min(1).max(Gg)}).strict();Rt("action",[c({action:S("resume"),expectedRevision:u().int().positive()}).strict(),c({action:S("cancel"),expectedRevision:u().int().positive()}).strict(),c({action:S("edit"),expectedRevision:u().int().positive(),body:r().trim().min(1).max(Gg)}).strict(),c({action:S("steer"),expectedRevision:u().int().positive(),expectedTurnId:r().trim().min(1)}).strict()]);const m4=c({id:r().min(1),sessionId:r().min(1),turnId:r().min(1),targetSessionId:r().min(1).nullable(),targetTurnId:r().min(1).nullable(),targetInputId:r().min(1).nullable().default(null),afterSequence:u().int().nonnegative(),deadline:r(),state:b(["waiting","message","completed","failed","interrupted","unavailable","timeout","cancelled"]),createdAt:r(),updatedAt:r()}).strict();c({sessionId:r(),activeTurnId:r().nullable(),acceptingInput:A(),paused:A(),inputs:f(RI),waits:f(m4)});function p4(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 f4(e){return Math.min(500*2**Math.max(0,e),1e4)}async function h4(e,t,n,a){PI(e);const o=e.body.getReader(),i=new TextDecoder;let s="";for(;!a?.aborted;){const{done:l,value:m}=await o.read();if(l){s+=i.decode();break}s+=i.decode(m,{stream:!0});let d=s.indexOf(`
|
|
179
|
+
|
|
180
|
+
`);for(;d>=0;){const h=s.slice(0,d);s=s.slice(d+2),Ey(h,t,n),d=s.indexOf(`
|
|
181
|
+
|
|
182
|
+
`)}}!a?.aborted&&s.trim()&&Ey(s,t,n)}function PI(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 g4(e,t,n,a,o={}){const i=new AbortController,s=o.fetchImpl??fetch,l=o.reconnectDelayMs??f4;let m=Ty(o.afterSequence),d=!1;return(async()=>{let h=0;for(;!i.signal.aborted;)try{const v=p4(e,i.signal,m),y=await s(v.url,v.init);if(PI(y),d=!0,h=0,await h4(y,w=>{const I=Ty(w.sequence);I>0&&I<=m||(I>0&&(m=I),t(w))},a,i.signal),d=!1,i.signal.aborted)break;throw new Error("event stream ended")}catch(v){if(d=!1,i.signal.aborted)break;n(v),await v4(l(h),i.signal),h+=1}})().catch(()=>{}),{close(){i.abort()},isOpen(){return d}}}function Ty(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0?e:0}function Ey(e,t,n){let a="message";const o=[];for(const i of e.split(`
|
|
183
|
+
`))i.startsWith(":")||(i.startsWith("event: ")&&(a=i.slice(7).trim()),i.startsWith("data: ")&&o.push(i.slice(6)));if(a==="ready"){n?.();return}if(!(a!=="runtime"||o.length===0))try{t(JSON.parse(o.join(`
|
|
184
|
+
`)))}catch{}}async function v4(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 b4 extends Error{constructor(t,n){super(t),this.status=n,this.name="ApiRequestError"}status}function My(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 jy=new WeakMap,Oy=new WeakMap,Vc=new WeakMap;let y4=0;async function q(e,t,n){if(t==="/v1/preferences"&&typeof n?.body=="string"){const o=(Vc.get(e)??Promise.resolve()).catch(()=>{}).then(()=>$y(e,t,n));Vc.set(e,o);try{return await o}finally{Vc.get(e)===o&&Vc.delete(e)}}return $y(e,t,n)}async function $y(e,t,n){const a=++y4;if(t==="/v1/preferences"&&typeof n?.body=="string"){const m=jy.get(e);if(!m)throw new Error("Reload settings before saving so changes can be checked against the current file.");n={...n,body:JSON.stringify({expectedRevision:m,...JSON.parse(n.body)})}}const o=new Headers(n?.headers);o.set("Content-Type","application/json"),o.set("Authorization",`Bearer ${e.token}`);const i=await fetch(`${e.serverUrl}${t}`,{...n,headers:o});if(!i.ok){const m=await i.json().catch(()=>({})),d=m&&typeof m=="object"&&"error"in m?String(m.error):i.statusText;throw new b4(d,i.status)}const s=await i.json(),l=s?.configuration?.rawRevision??(t==="/v1/preferences"?s?.rawRevision:void 0);return typeof l=="string"&&a>=(Oy.get(e)??0)&&(jy.set(e,l),Oy.set(e,a)),s}function TY(e){const t=new URL("/v1/terminal",e.serverUrl);return t.protocol=t.protocol==="https:"?"wss:":"ws:",t.toString()}function EY(e){return["openpond-terminal",`openpond-token.${k4(e.token)}`]}function S4(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 k4(e){return S4(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function x4(e){const t=atob(e),n=new Uint8Array(t.length);for(let a=0;a<t.length;a+=1)n[a]=t.charCodeAt(a);return new TextDecoder().decode(n)}const w4={teamInvitations:e=>q(e,"/v1/team-invitations"),decideTeamInvitation:(e,t,n)=>q(e,`/v1/team-invitations/${t}`,{method:"POST",body:JSON.stringify({token:n})}),organizations:e=>q(e,"/v1/organizations"),createOrganization:(e,t)=>q(e,"/v1/organizations",{method:"POST",body:JSON.stringify(t)}),updateOrganization:(e,t,n)=>q(e,`/v1/organizations/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),organizationMembers:(e,t)=>q(e,`/v1/organizations/${encodeURIComponent(t)}/members`),upsertOrganizationMember:(e,t,n)=>q(e,`/v1/organizations/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify(n)}),organizationMcpServer:(e,t)=>q(e,`/v1/organizations/${encodeURIComponent(t)}/mcp-server`),generateOrganizationMcpServer:(e,t,n)=>q(e,`/v1/organizations/${encodeURIComponent(t)}/mcp-server`,{method:"POST",body:JSON.stringify(n)}),setOrganizationMcpServerStatus:(e,t,n)=>q(e,`/v1/organizations/${encodeURIComponent(t)}/mcp-server/${n}`,{method:"POST"})},I4={taskInbox:(e,t)=>q(e,`/v1/sessions/${encodeURIComponent(t)}/inbox`),steerTurn:(e,t,n)=>q(e,`/v1/sessions/${encodeURIComponent(t)}/turns/steer`,{method:"POST",body:JSON.stringify(n)}),queueTaskInput:(e,t,n,a)=>q(e,`/v1/sessions/${encodeURIComponent(t)}/inbox`,{method:"POST",body:JSON.stringify({input:n,idempotencyKey:a})}),updateTaskInput:(e,t,n,a)=>q(e,`/v1/sessions/${encodeURIComponent(t)}/inbox/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(a)}),sendTurn:(e,t,n)=>q(e,`/v1/sessions/${t}/turns`,{method:"POST",body:JSON.stringify(n)}),runSessionCommand:(e,t,n)=>q(e,`/v1/sessions/${encodeURIComponent(t)}/commands`,{method:"POST",body:JSON.stringify(n)}),recordPreflightTurnFailure:(e,t,n)=>q(e,`/v1/sessions/${t}/preflight-turns/failure`,{method:"POST",body:JSON.stringify(n)}),listCreateImproveRuns:(e,t={})=>q(e,`/v1/create-improve-runs?${_4(t).toString()}`),getCreateImproveRun:(e,t)=>q(e,`/v1/create-improve-runs/${encodeURIComponent(t)}`),getCreateImproveCandidateDiff:(e,t,n)=>q(e,`/v1/create-improve-runs/${encodeURIComponent(t)}/candidates/${encodeURIComponent(n)}/diff`),applyCreateImproveAction:(e,t,n)=>q(e,`/v1/create-improve-runs/${encodeURIComponent(t)}/actions`,{method:"POST",body:JSON.stringify(n)}),interruptTurn:(e,t,n)=>q(e,`/v1/sessions/${t}/turns/interrupt`,{method:"POST",body:JSON.stringify({reason:n})}),compactSession:(e,t,n={reason:"manual"})=>q(e,`/v1/sessions/${t}/compact`,{method:"POST",body:JSON.stringify(n)}),workspaceTool:(e,t,n)=>q(e,`/v1/sessions/${t}/workspace-tools`,{method:"POST",body:JSON.stringify(n)}),ensureCloudWorkspaceReady:(e,t,n)=>q(e,`/v1/sessions/${encodeURIComponent(t)}/workspace/ensure-ready`,{method:"POST",body:JSON.stringify(n)})};function _4(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 C4={sandboxFiles:(e,t,n={})=>{const a=new URLSearchParams({list:"1"});return n.path&&a.set("path",n.path),n.recursive!==void 0&&a.set("recursive",String(n.recursive)),n.maxEntries!==void 0&&a.set("maxEntries",String(n.maxEntries)),q(e,`/v1/sandboxes/${encodeURIComponent(t)}/files?${a.toString()}`)},sandboxUploadFile:(e,t,n)=>q(e,`/v1/sandboxes/${encodeURIComponent(t)}/files`,{method:"POST",body:JSON.stringify(n)}),preserveSandboxSource:(e,t,n={})=>q(e,`/v1/sandboxes/${encodeURIComponent(t)}/preserve-source`,{method:"POST",body:JSON.stringify(n)}),sandboxDownloadFile:async(e,t,n,a={})=>{const o=new URLSearchParams({path:n});a.offsetBytes!==void 0&&o.set("offsetBytes",String(a.offsetBytes)),a.maxBytes!==void 0&&o.set("maxBytes",String(a.maxBytes));const i=await q(e,`/v1/sandboxes/${encodeURIComponent(t)}/files?${o.toString()}`);return{...i,contents:i.file.isBinary?"":x4(i.file.contentsBase64)}}},R4={sandboxGitStatus:(e,t)=>q(e,`/v1/sandboxes/${encodeURIComponent(t)}/git/status`),sandboxGitDiff:(e,t,n)=>q(e,`/v1/sandboxes/${encodeURIComponent(t)}/git/diff`,{method:"POST",body:JSON.stringify(n)})},P4={connectedAppStatus:(e,t={})=>{const n=My(t);return n.set("status",t.status??"all"),q(e,`/v1/connected-apps/status${n.size>0?`?${n.toString()}`:""}`)},integrationConnections:(e,t={})=>{const n=My(t);return t.status&&n.set("status",t.status),q(e,`/v1/integrations/connections${n.size>0?`?${n.toString()}`:""}`)},sandboxIntegrationLeases:(e,t)=>q(e,`/v1/sandboxes/${encodeURIComponent(t)}/integrations`),attachSandboxIntegrationConnection:(e,t,n)=>q(e,`/v1/sandboxes/${encodeURIComponent(t)}/integrations`,{method:"POST",body:JSON.stringify(n)}),removeSandboxIntegrationLease:(e,t,n)=>q(e,`/v1/sandboxes/${encodeURIComponent(t)}/integrations`,{method:"DELETE",body:JSON.stringify({leaseId:n})})},A4={listSandboxProjects:(e,t)=>{const n=new URLSearchParams({teamId:t.teamId});return q(e,`/v1/sandbox-projects?${n.toString()}`)},getSandboxProject:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return q(e,`/v1/sandbox-projects/${encodeURIComponent(t)}?${a.toString()}`)},getSandboxProjectWorkspace:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return q(e,`/v1/sandbox-projects/${encodeURIComponent(t)}/workspace?${a.toString()}`)},upsertSandboxProject:(e,t)=>q(e,"/v1/sandbox-projects",{method:"POST",body:JSON.stringify(t)}),syncSandboxProject:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return q(e,`/v1/sandbox-projects/${encodeURIComponent(t)}/sync?${a.toString()}`,{method:"POST"})},uploadSandboxProjectSource:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId}),{teamId:o,...i}=n;return q(e,`/v1/sandbox-projects/${encodeURIComponent(t)}/source?${a.toString()}`,{method:"POST",body:JSON.stringify(i)})},archiveSandboxProject:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return q(e,`/v1/sandbox-projects/${encodeURIComponent(t)}?${a.toString()}`,{method:"DELETE"})},listSandboxAgents:(e,t)=>{const n=new URLSearchParams({teamId:t.teamId});return q(e,`/v1/sandbox-agents?${n.toString()}`)},upsertSandboxAgent:(e,t)=>q(e,"/v1/sandbox-agents",{method:"POST",body:JSON.stringify(t)}),runSandboxAgent:(e,t,n)=>q(e,`/v1/sandbox-agents/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify(n)}),runProfileAction:(e,t)=>q(e,"/v1/profile/run",{method:"POST",body:JSON.stringify(t)})},T4={sandbox:(e,t)=>q(e,`/v1/sandboxes/${encodeURIComponent(t)}`)},E4={...P4,...A4,...T4,...R4,...C4},M4={communities:(e,t)=>{const n=new URLSearchParams;return t&&n.set("cursor",t),q(e,`/v1/communities${n.size?`?${n}`:""}`)},communityPreview:(e,t)=>q(e,`/v1/communities/${encodeURIComponent(t)}/preview`),communityRules:(e,t)=>q(e,`/v1/communities/${encodeURIComponent(t)}/rules/current`),joinCommunity:(e,t,n)=>q(e,`/v1/communities/${encodeURIComponent(t)}/join`,{method:"POST",body:JSON.stringify({acceptedRulesVersionId:n})}),acceptCommunityRules:(e,t,n)=>q(e,`/v1/communities/${encodeURIComponent(t)}/rules/accept`,{method:"POST",body:JSON.stringify({acceptedRulesVersionId:n})}),leaveCommunity:(e,t)=>q(e,`/v1/communities/${encodeURIComponent(t)}/leave`,{method:"POST",body:"{}"}),communityChannels:(e,t)=>q(e,`/v1/communities/${encodeURIComponent(t)}/channels`),communityMessages:(e,t,n,a={})=>{const o=new URLSearchParams;return a.beforeSequence!=null&&o.set("beforeSequence",String(a.beforeSequence)),a.limit!=null&&o.set("limit",String(a.limit)),q(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages${o.size?`?${o}`:""}`)},sendCommunityMessage:(e,t,n,a)=>q(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages`,{method:"POST",body:JSON.stringify(a)}),editCommunityMessage:(e,t,n,a,o)=>q(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages/${encodeURIComponent(a)}`,{method:"PATCH",body:JSON.stringify({body:o})}),deleteCommunityMessage:(e,t,n,a)=>q(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages/${encodeURIComponent(a)}`,{method:"DELETE",body:"{}"}),markCommunityRead:(e,t,n,a)=>q(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/read`,{method:"POST",body:JSON.stringify({sequence:a})}),setCommunityChannelMuted:(e,t,n,a)=>q(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/mute`,{method:"POST",body:JSON.stringify({muted:a})}),searchCommunityMembers:(e,t,n={})=>{const a=new URLSearchParams;return n.query&&a.set("query",n.query),n.cursor&&a.set("cursor",n.cursor),n.limit!=null&&a.set("limit",String(n.limit)),q(e,`/v1/communities/${encodeURIComponent(t)}/members/search${a.size?`?${a}`:""}`)},updateCommunityNotifications:(e,t,n)=>q(e,`/v1/communities/${encodeURIComponent(t)}/notifications`,{method:"POST",body:JSON.stringify({mode:n})}),communityEvents:(e,t,n={})=>{const a=new URLSearchParams;return n.after!=null&&a.set("after",String(n.after)),n.limit!=null&&a.set("limit",String(n.limit)),q(e,`/v1/communities/${encodeURIComponent(t)}/events${a.size?`?${a}`:""}`)},communityRealtimeSession:(e,t)=>q(e,`/v1/communities/${encodeURIComponent(t)}/realtime-session`),uploadCommunityAttachment:(e,t,n,a)=>q(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/attachments/upload`,{method:"POST",body:JSON.stringify({attachment:a})}),communityAttachmentDownload:(e,t,n,a)=>q(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/attachments/${encodeURIComponent(a)}/download`)},Zg="openpond-app-server-url",zl="openpond-app-token",j4=750;function AI(){return window.location.protocol!=="http:"&&window.location.protocol!=="https:"?null:window.location.origin&&window.location.origin!=="null"?window.location.origin:null}function qf(e){const t=e.getItem(Zg)?.trim(),n=e.getItem(zl)?.trim();return t&&n?{serverUrl:t,token:n}:null}function Dd(e){if(!e)return null;try{const t="__openpond_storage_probe__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return null}}function Ri(e,t){e.setItem(Zg,t.serverUrl),e.setItem(zl,t.token)}function Ny(e,t){const n=qf(e);n?.serverUrl!==t.serverUrl||n.token!==t.token||(e.removeItem(Zg),e.removeItem(zl))}function O4(){const e=window.__OPENPOND_WEB_CONNECTION__,t=e?.serverUrl?.trim(),n=e?.token?.trim();return t&&n?{serverUrl:t,token:n}:null}function $4(){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()||AI();return!a||!n?null:{serverUrl:a,token:n}}function N4(){window.location.hash&&window.history.replaceState(null,"",`${window.location.pathname}${window.location.search}`)}function Kc(e,t){t&&(e.some(n=>n.serverUrl===t.serverUrl&&n.token===t.token)||e.push(t))}function D4(){const e=[],t=Dd(window.sessionStorage),n=Dd(window.localStorage),a=AI(),o=t?.getItem(zl)??n?.getItem(zl);return Kc(e,null),Kc(e,a&&o?{serverUrl:a,token:o.trim()}:null),Kc(e,t?qf(t):null),Kc(e,n?qf(n):null),e}async function jp(e){const t=new AbortController,n=window.setTimeout(()=>t.abort(),j4);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 L4(){if(window.openpond)return window.openpond.getConnection();const e=Dd(window.sessionStorage),t=Dd(window.localStorage),n=$4();if(n&&await jp(n.serverUrl))return t&&Ri(t,n),e&&Ri(e,n),N4(),{...n,platform:navigator.platform};const a=O4();if(a&&await jp(a.serverUrl))return t&&Ri(t,a),e&&Ri(e,a),{...a,platform:navigator.platform};const o=D4();for(const i of o){if(await jp(i.serverUrl))return t&&Ri(t,i),e&&Ri(e,i),{...i,platform:navigator.platform};e&&Ny(e,i),t&&Ny(t,i)}throw new Error("No reachable OpenPond app server. Start `openpond ui` again and open the full printed URL.")}const J={...M4,bootstrap:e=>q(e,"/v1/bootstrap?refreshCodex=1"),localProjectActions:(e,t)=>q(e,`/v1/projects/${encodeURIComponent(t)}/actions`),extensionCatalog:e=>q(e,"/v1/extensions"),extensionPreview:(e,t)=>q(e,"/v1/extensions/preview",{method:"POST",body:JSON.stringify(t)}),extensionAdd:(e,t)=>q(e,"/v1/extensions",{method:"POST",body:JSON.stringify(t)}),extensionUpdate:(e,t,n={})=>q(e,`/v1/extensions/github/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repo)}/update`,{method:"POST",body:JSON.stringify(n)}),extensionUpdateAll:e=>q(e,"/v1/extensions/update-all",{method:"POST"}),extensionRemove:(e,t)=>q(e,`/v1/extensions/github/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repo)}`,{method:"DELETE"}),skillSourceFile:(e,t,n,a)=>q(e,`/v1/skills/${t}/${encodeURIComponent(n)}/source?path=${encodeURIComponent(a)}`),teamChatMembers:(e,t)=>q(e,`/v1/team-chat/members?teamId=${encodeURIComponent(t)}`),teamChatAgents:(e,t)=>q(e,`/v1/team-chat/agents?teamId=${encodeURIComponent(t)}`),teamChatThreads:(e,t)=>q(e,`/v1/team-chat/threads?teamId=${encodeURIComponent(t)}`),teamChatRealtimeSession:(e,t)=>q(e,`/v1/team-chat/realtime-session?teamId=${encodeURIComponent(t)}`),teamChatEvents:(e,t,n={})=>{const a=new URLSearchParams({teamId:t});return n.after!=null&&a.set("after",String(n.after)),n.limit!=null&&a.set("limit",String(n.limit)),q(e,`/v1/team-chat/events?${a.toString()}`)},teamChatGeneral:(e,t)=>q(e,"/v1/team-chat/threads/general",{method:"POST",body:JSON.stringify({teamId:t})}),teamChatDm:(e,t,n)=>q(e,"/v1/team-chat/threads/dm",{method:"POST",body:JSON.stringify({teamId:t,otherUserId:n})}),teamChatThread:(e,t,n,a={})=>{const o=new URLSearchParams({teamId:t});return a.beforeSequence!=null&&o.set("beforeSequence",String(a.beforeSequence)),a.limit!=null&&o.set("limit",String(a.limit)),q(e,`/v1/team-chat/threads/${encodeURIComponent(n)}?${o.toString()}`)},uploadTeamChatAttachment:(e,t,n)=>q(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/attachments/upload`,{method:"POST",body:JSON.stringify(n)}),teamChatAttachmentDownload:(e,t,n)=>q(e,`/v1/team-chat/attachments/${encodeURIComponent(n)}/download?teamId=${encodeURIComponent(t)}`),sendTeamChatMessage:(e,t,n)=>q(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/messages`,{method:"POST",body:JSON.stringify(n)}),createTeamChatAgentRun:(e,t,n)=>q(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/agent-runs`,{method:"POST",body:JSON.stringify(n)}),teamChatAgentConversation:(e,t,n)=>q(e,`/v1/team-chat/agent-runs/${encodeURIComponent(n)}?teamId=${encodeURIComponent(t)}`),editTeamChatMessage:(e,t,n,a)=>q(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/messages/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(a)}),deleteTeamChatMessage:(e,t,n,a)=>q(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/messages/${encodeURIComponent(n)}`,{method:"DELETE",body:JSON.stringify({teamId:a})}),markTeamChatRead:(e,t,n,a)=>q(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/read`,{method:"POST",body:JSON.stringify({teamId:n,sequence:a})}),setTeamChatThreadMuted:(e,t,n,a)=>q(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/mute`,{method:"POST",body:JSON.stringify({teamId:n,muted:a})}),createTeamChatAiThread:(e,t,n)=>q(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/ai-threads`,{method:"POST",body:JSON.stringify(n)}),teamChatAiThread:(e,t,n)=>q(e,`/v1/team-chat/ai-threads/${encodeURIComponent(n)}?teamId=${encodeURIComponent(t)}`),sendTeamChatAiTurn:(e,t,n)=>q(e,`/v1/team-chat/ai-threads/${encodeURIComponent(t)}/turns`,{method:"POST",body:JSON.stringify(n)}),executeTeamChatAiTurn:(e,t,n)=>q(e,`/v1/team-chat/ai-turns/${encodeURIComponent(t)}/execute`,{method:"POST",body:JSON.stringify({teamId:n})}),cancelTeamChatAiTurnExecution:(e,t,n)=>q(e,`/v1/team-chat/ai-turns/${encodeURIComponent(t)}/execute/cancel`,{method:"POST",body:JSON.stringify({teamId:n})}),usage:(e,t={})=>{const n=Dy(t),a=n.size?`?${n.toString()}`:"";return q(e,`/v1/usage${a}`)},usageRecords:(e,t={})=>{const n=Dy(t);t.sessionId&&n.set("sessionId",t.sessionId),t.turnId&&n.set("turnId",t.turnId),t.limit!==void 0&&n.set("limit",String(t.limit));const a=n.size?`?${n.toString()}`:"";return q(e,`/v1/usage/records${a}`)},usageTurnCache:(e,t)=>q(e,`/v1/usage/turn-cache?sessionId=${encodeURIComponent(t)}`),runtimeEventsPage:(e,t={})=>{const n=new URLSearchParams;t.sessionId&&n.set("sessionId",t.sessionId),t.afterSequence!==void 0&&n.set("afterSequence",String(t.afterSequence)),t.beforeSequence!==void 0&&t.beforeSequence!==null&&n.set("beforeSequence",String(t.beforeSequence)),t.limit!==void 0&&n.set("limit",String(t.limit));const a=n.size?`?${n.toString()}`:"";return q(e,`/v1/events/page${a}`)},workOutputs:e=>q(e,"/v1/work/outputs"),harnessHistory:e=>q(e,"/v1/harness"),refinerHistory:e=>q(e,"/v1/refiner"),updateRefinerProfile:(e,t)=>q(e,"/v1/refiner/update",{method:"POST",body:JSON.stringify(t)}),activateRefinerRelease:(e,t)=>q(e,"/v1/refiner/activate",{method:"POST",body:JSON.stringify(t)}),rollbackRefinerRelease:(e,t)=>q(e,"/v1/refiner/rollback",{method:"POST",body:JSON.stringify(t)}),updateHarnessBackgroundReview:(e,t)=>q(e,"/v1/harness/background-review",{method:"POST",body:JSON.stringify(t)}),reviewHarnessEvaluation:(e,t)=>q(e,"/v1/harness/evaluation-review",{method:"POST",body:JSON.stringify(t)}),updateHarnessEvaluationReviewSchedule:(e,t)=>q(e,"/v1/harness/evaluation-review/settings",{method:"POST",body:JSON.stringify(t)}),harnessReleaseDiff:(e,t)=>q(e,"/v1/harness/diff",{method:"POST",body:JSON.stringify(t)}),rollbackHarness:(e,t)=>q(e,"/v1/harness/rollback",{method:"POST",body:JSON.stringify(t)}),reviewHarnessProposal:(e,t)=>q(e,"/v1/harness/review",{method:"POST",body:JSON.stringify(t)}),runSubagentLifecycleAction:(e,t,n)=>q(e,`/v1/subagents/${encodeURIComponent(t)}/lifecycle`,{method:"POST",body:JSON.stringify(n)}),trainingState:(e,t)=>q(e,`/v1/training?profileId=${encodeURIComponent(t)}`),trainingActivity:(e,t)=>q(e,`/v1/training/activity?profileId=${encodeURIComponent(t)}`),portableTrainingCatalog:(e,t="",n)=>{const a=new URLSearchParams;return t.trim()&&a.set("query",t.trim()),n&&a.set("method",n),q(e,`/v1/training/catalog${a.size?`?${a.toString()}`:""}`)},datasetCatalog:(e,t)=>q(e,`/v1/training/datasets?profileId=${encodeURIComponent(t)}`),trainingRunDetail:(e,t,n={})=>q(e,`/v1/training/jobs/${encodeURIComponent(t)}/detail?evaluation=${n.includeEvaluation===!1?"false":"true"}`),candidateReview:(e,t,n=!1,a="models")=>q(e,`/v1/training/${a}/${encodeURIComponent(t)}/candidate-decision?refresh=${n}`),recordCandidateReview:(e,t,n,a="models")=>q(e,`/v1/training/${a}/${encodeURIComponent(t)}/candidate-decision`,{method:"POST",body:JSON.stringify(n)}),candidateReviewHistory:(e,t,n,a="models")=>q(e,`/v1/training/${a}/${encodeURIComponent(t)}/candidate-decision-history?decisionId=${encodeURIComponent(n.id)}&decisionHash=${n.contentHash}`),trainingEvaluationTasks:async(e,t,n,a)=>{const o=new URLSearchParams({limit:"25"});return a&&o.set("cursor",a),q(e,`/v1/training/jobs/${encodeURIComponent(t)}/evaluations/${encodeURIComponent(n.id)}/tasks?${o}`)},trainingRequest:(e,t,n,a="POST")=>q(e,`/v1/training${t}`,{method:a,body:a==="GET"||a==="DELETE"?void 0:JSON.stringify(n)}),datasetStorageState:e=>q(e,"/v1/settings/dataset-storage"),updateDatasetStorage:(e,t)=>q(e,"/v1/settings/dataset-storage",{method:"PATCH",body:JSON.stringify({datasetStorePath:t})}),hostedSavedWork:e=>q(e,"/v1/saved-work"),createHostedSavedWork:(e,t)=>q(e,"/v1/saved-work",{method:"POST",body:JSON.stringify(t)}),updateHostedSavedWork:(e,t,n)=>q(e,`/v1/saved-work/schedules/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),deleteHostedSavedWork:(e,t)=>q(e,`/v1/saved-work/schedules/${encodeURIComponent(t)}`,{method:"DELETE"}),runHostedSavedWork:(e,t,n)=>q(e,`/v1/saved-work/schedules/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify({clientRequestId:n})}),chatWorkflows:(e,t)=>{const n=t?`?sessionId=${encodeURIComponent(t)}`:"";return q(e,`/v1/chat-workflows${n}`)},createChatWorkflow:(e,t)=>q(e,"/v1/chat-workflows",{method:"POST",body:JSON.stringify(t)}),updateChatWorkflow:(e,t,n)=>q(e,`/v1/chat-workflows/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),deleteChatWorkflow:(e,t)=>q(e,`/v1/chat-workflows/${encodeURIComponent(t)}`,{method:"DELETE"}),runChatWorkflow:(e,t)=>q(e,`/v1/chat-workflows/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify({})}),localAgentSchedules:(e,t={})=>{const n=new URLSearchParams;t.localProjectId&&n.set("localProjectId",t.localProjectId);const a=n.size?`?${n.toString()}`:"";return q(e,`/v1/local-agent-schedules${a}`)},syncLocalAgentSchedules:e=>q(e,"/v1/local-agent-schedules/sync",{method:"POST",body:JSON.stringify({})}),patchLocalAgentSchedule:(e,t,n)=>q(e,`/v1/local-agent-schedules/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),runLocalAgentSchedule:(e,t,n={})=>q(e,`/v1/local-agent-schedules/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify(n)}),localAgentScheduleRuns:(e,t,n={})=>{const a=new URLSearchParams;n.limit!==void 0&&a.set("limit",String(n.limit));const o=a.size?`?${a.toString()}`:"";return q(e,`/v1/local-agent-schedules/${encodeURIComponent(t)}/runs${o}`)},refreshOpenPondAccounts:e=>q(e,"/v1/openpond/accounts/refresh",{method:"POST",body:JSON.stringify({})}),refreshOpenPondAccount:e=>q(e,"/v1/openpond/account?refresh=1"),loadMoreOpenPondApps:(e,t)=>q(e,`/v1/openpond/apps/more?offset=${encodeURIComponent(String(t.offset))}&limit=${encodeURIComponent(String(t.limit))}`),switchOpenPondAccount:(e,t)=>q(e,"/v1/openpond/accounts/switch",{method:"POST",body:JSON.stringify(t)}),removeOpenPondAccount:(e,t)=>q(e,"/v1/openpond/accounts",{method:"DELETE",body:JSON.stringify(t)}),signOutOpenPondAccount:e=>q(e,"/v1/openpond/accounts/logout",{method:"POST",body:JSON.stringify({})}),saveOpenPondAccount:(e,t)=>q(e,"/v1/openpond/accounts/login",{method:"POST",body:JSON.stringify(t)}),updateOpenPondAccountConfig:(e,t)=>q(e,"/v1/openpond/accounts/config",{method:"PATCH",body:JSON.stringify(t)}),savePreferences:(e,t)=>q(e,"/v1/preferences",{method:"PATCH",body:JSON.stringify(t)}),saveProviderSettings:(e,t)=>q(e,"/v1/providers",{method:"PATCH",body:JSON.stringify(t)}),providerSettings:e=>q(e,"/v1/providers"),loadProviderModels:(e,t,n={})=>{const a=new URLSearchParams;n.query?.trim()&&a.set("query",n.query.trim()),n.limit&&a.set("limit",String(n.limit));const o=a.size?`?${a.toString()}`:"";return q(e,`/v1/providers/${encodeURIComponent(t)}/models${o}`)},refreshProviderModels:(e,t,n)=>q(e,`/v1/providers/${encodeURIComponent(t)}/models`,{method:"POST",body:JSON.stringify(n)}),saveProviderCredential:(e,t,n)=>q(e,`/v1/providers/${encodeURIComponent(t)}/credential`,{method:"PUT",body:JSON.stringify(n)}),deleteProviderCredential:(e,t,n)=>q(e,`/v1/providers/${encodeURIComponent(t)}/credential`,{method:"DELETE",body:JSON.stringify(n)}),startOpenAiSubscriptionAuth:(e,t)=>q(e,"/v1/providers/openai/subscription-auth",{method:"POST",body:JSON.stringify(t)}),validateProviderCredential:(e,t,n)=>q(e,`/v1/providers/${encodeURIComponent(t)}/validate`,{method:"POST",body:JSON.stringify(n)}),savePersonalization:(e,t)=>q(e,"/v1/personalization",{method:"PATCH",body:JSON.stringify(t)}),recordClientDiagnostic:(e,t)=>q(e,"/v1/diagnostics/client",{method:"POST",body:JSON.stringify(t)}),profileCurrent:e=>q(e,"/v1/profile"),profileCatalog:e=>q(e,"/v1/profile/catalog"),profileWorkflows:e=>q(e,"/v1/profile/workflows"),profileEvaluations:e=>q(e,"/v1/profile/evaluations"),profileEvaluationPrepare:(e,t)=>q(e,"/v1/profile/evaluations/prepare",{method:"POST",body:JSON.stringify(t)}),profileEvaluationRun:(e,t)=>q(e,"/v1/profile/evaluations/run",{method:"POST",body:JSON.stringify(t)}),profileEvaluationRunSuite:(e,t)=>q(e,"/v1/profile/evaluations/run-suite",{method:"POST",body:JSON.stringify(t)}),profileEvaluationCompare:(e,t)=>q(e,"/v1/profile/evaluations/compare",{method:"POST",body:JSON.stringify({id:`comparison-${crypto.randomUUID()}`,runIds:t})}),profileEvaluationSaveReport:(e,t,n)=>q(e,"/v1/profile/evaluations/reports",{method:"POST",body:JSON.stringify({id:`report-${crypto.randomUUID()}`,evidenceKind:t,evidenceId:n})}),profileSelect:(e,t)=>q(e,"/v1/profile/select",{method:"POST",body:JSON.stringify({ref:t})}),profileRemove:(e,t)=>q(e,"/v1/profile/remove",{method:"POST",body:JSON.stringify({ref:t})}),profilePublicationPreview:(e,t)=>q(e,"/v1/profile/publication/preview",{method:"POST",body:JSON.stringify(t)}),profilePublicationPublish:(e,t)=>q(e,"/v1/profile/publication/publish",{method:"POST",body:JSON.stringify(t)}),profileInstall:(e,t)=>q(e,"/v1/profile/install",{method:"POST",body:JSON.stringify(t)}),profileUpdate:(e,t)=>q(e,"/v1/profile/update",{method:"POST",body:JSON.stringify({ref:t})}),profileInit:(e,t)=>q(e,"/v1/profile/init",{method:"POST",body:JSON.stringify(t)}),profileLoad:(e,t)=>q(e,"/v1/profile/load",{method:"POST",body:JSON.stringify(t)}),profileCheck:(e,t)=>q(e,"/v1/profile/check",{method:"POST",body:JSON.stringify(t)}),profileAgentRename:(e,t,n)=>q(e,`/v1/profile/agents/${encodeURIComponent(t)}/name`,{method:"PATCH",body:JSON.stringify(n)}),profileCommit:(e,t)=>q(e,"/v1/profile/commit",{method:"POST",body:JSON.stringify(t)}),profilePush:(e,t)=>q(e,"/v1/profile/push",{method:"POST",body:JSON.stringify(t)}),workspaceLspSettingsStatus:e=>q(e,"/v1/lsp/settings-status"),workspaceLspRuntimeStatus:e=>q(e,"/v1/lsp/status"),restartWorkspaceLsp:e=>q(e,"/v1/lsp/restart",{method:"POST"}),remoteAccess:e=>q(e,"/v1/remote-access"),enableRemoteAccess:e=>q(e,"/v1/remote-access/enable",{method:"POST"}),disableRemoteAccess:e=>q(e,"/v1/remote-access/disable",{method:"POST"}),voiceTranscriptionStatus:(e,t={})=>q(e,"/v1/audio/transcriptions/status",{signal:t.signal}),transcribeVoice:(e,t,n={})=>q(e,"/v1/audio/transcriptions",{method:"POST",body:JSON.stringify(t),signal:n.signal}),createSession:(e,t)=>q(e,"/v1/sessions",{method:"POST",body:JSON.stringify(t)}),patchSession:(e,t,n)=>q(e,`/v1/sessions/${t}`,{method:"PATCH",body:JSON.stringify(n)}),codexHistoryThread:(e,t,n={})=>{const a=new URLSearchParams;n.limit!==void 0&&a.set("limit",String(n.limit)),n.tail&&a.set("tail","1");const o=a.size?`?${a.toString()}`:"";return q(e,`/v1/codex-history/${encodeURIComponent(t)}${o}`)},codexHistoryThreadIncremental:(e,t,n={})=>{const a=new URLSearchParams({incremental:"1"});return n.afterEventId&&a.set("afterEventId",n.afterEventId),n.limit!==void 0&&a.set("limit",String(n.limit)),n.revision&&a.set("revision",n.revision),n.tail&&a.set("tail","1"),q(e,`/v1/codex-history/${encodeURIComponent(t)}?${a.toString()}`)},sendCodexHistoryTurn:(e,t,n)=>q(e,`/v1/codex-history/${encodeURIComponent(t)}/turns`,{method:"POST",body:JSON.stringify(n)}),interruptCodexHistoryTurn:(e,t)=>q(e,`/v1/codex-history/${encodeURIComponent(t)}/turns/interrupt`,{method:"POST"}),patchSidebarAppPreference:(e,t,n)=>q(e,`/v1/sidebar/apps/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),reorderSidebarApps:(e,t)=>q(e,"/v1/sidebar/apps/reorder",{method:"POST",body:JSON.stringify(t)}),sidebarFiles:e=>q(e,"/v1/sidebar/files"),patchSidebarFile:(e,t)=>q(e,"/v1/sidebar/files",{method:"PATCH",body:JSON.stringify(t)}),workspaceStatus:(e,t,n=!1,a={})=>q(e,`/v1/workspaces/${encodeURIComponent(t)}${n?"?ensure=1":""}`,{signal:a.signal}),createWorkspaceBranch:(e,t,n)=>q(e,`/v1/workspaces/${encodeURIComponent(t)}/branches`,{method:"POST",body:JSON.stringify(n)}),checkoutWorkspaceBranch:(e,t,n)=>q(e,`/v1/workspaces/${encodeURIComponent(t)}/branch`,{method:"PATCH",body:JSON.stringify(n)}),workspaceDiff:(e,t,n={})=>q(e,`/v1/workspaces/${encodeURIComponent(t)}/diff`,{signal:n.signal}),workspaceFile:(e,t,n)=>q(e,`/v1/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}`),saveWorkspaceFile:(e,t,n)=>q(e,`/v1/workspaces/${encodeURIComponent(t)}/file`,{method:"PATCH",body:JSON.stringify(n)}),signWorkspaceImageUrl:(e,t)=>q(e,"/v1/assets/workspace-image-url",{method:"POST",body:JSON.stringify(t)}),signLocalImageUrl:(e,t)=>q(e,"/v1/assets/local-image-url",{method:"POST",body:JSON.stringify(t)}),signLocalVideoUrl:(e,t)=>q(e,"/v1/assets/local-video-url",{method:"POST",body:JSON.stringify(t)}),signChatAttachmentImageUrl:(e,t)=>q(e,"/v1/assets/chat-attachment-image-url",{method:"POST",body:JSON.stringify(t)}),chatAttachmentFile:(e,t)=>q(e,"/v1/assets/chat-attachment-file",{method:"POST",body:JSON.stringify(t)}),workspaceLspTouch:(e,t,n,a={})=>q(e,`/v1/workspaces/${encodeURIComponent(t)}/lsp/touch`,{method:"POST",body:JSON.stringify(n),signal:a.signal}),workspaceLspAction:(e,t,n)=>q(e,`/v1/workspaces/${encodeURIComponent(t)}/lsp/action`,{method:"POST",body:JSON.stringify(n)}),workspaceTemplateConfig:(e,t)=>q(e,`/v1/openpond/apps/${encodeURIComponent(t)}/template-config`),...w4,...E4,createLocalProject:(e,t)=>q(e,"/v1/projects",{method:"POST",body:JSON.stringify(t)}),updateLocalProjectAgentSetup:(e,t,n)=>q(e,`/v1/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),uploadLocalProjectCloudSource:(e,t,n)=>q(e,`/v1/projects/${encodeURIComponent(t)}/cloud-source`,{method:"POST",body:JSON.stringify(n)}),previewLocalProjectCloudSource:(e,t,n={})=>{const a=new URLSearchParams;n.branch?.trim()&&a.set("branch",n.branch.trim());const o=a.toString()?`?${a.toString()}`:"";return q(e,`/v1/projects/${encodeURIComponent(t)}/cloud-source/preview${o}`)},deleteLocalProject:(e,t)=>q(e,`/v1/projects/${encodeURIComponent(t)}`,{method:"DELETE"}),gitAvailability:e=>q(e,"/v1/system/git"),installMacOSCommandLineTools:e=>q(e,"/v1/system/git/install-command-line-tools",{method:"POST",body:JSON.stringify({})}),...I4,resolveApproval:(e,t,n)=>q(e,`/v1/approvals/${t}`,{method:"POST",body:JSON.stringify(n)})};function Dy(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 U4=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),z4=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,a)=>a?a.toUpperCase():n.toLowerCase()),Ly=e=>{const t=z4(e);return t.charAt(0).toUpperCase()+t.slice(1)},TI=(...e)=>e.filter((t,n,a)=>!!t&&t.trim()!==""&&a.indexOf(t)===n).join(" ").trim(),H4=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var q4={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 B4=g.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:a,className:o="",children:i,iconNode:s,...l},m)=>g.createElement("svg",{ref:m,...q4,width:t,height:t,stroke:e,strokeWidth:a?Number(n)*24/Number(t):n,className:TI("lucide",o),...!i&&!H4(l)&&{"aria-hidden":"true"},...l},[...s.map(([d,h])=>g.createElement(d,h)),...Array.isArray(i)?i:[i]]));const dt=(e,t)=>{const n=g.forwardRef(({className:a,...o},i)=>g.createElement(B4,{ref:i,iconNode:t,className:TI(`lucide-${U4(Ly(e))}`,`lucide-${e}`,a),...o}));return n.displayName=Ly(e),n};const F4=[["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"}]],V4=dt("activity",F4);const K4=[["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"}]],W4=dt("archive-restore",K4);const G4=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],Z4=dt("arrow-left",G4);const J4=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}]],EI=dt("bookmark",J4);const Y4=[["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"}]],MI=dt("bookmark-x",Y4);const Q4=[["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"}]],Uy=dt("book-open-text",Q4);const X4=[["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"}]],Op=dt("boxes",X4);const e5=[["path",{d:"M16 14v2.2l1.6 1",key:"fo4ql5"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21 7.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3.5",key:"1osxxc"}],["path",{d:"M3 10h5",key:"r794hk"}],["path",{d:"M8 2v4",key:"1cmpym"}],["circle",{cx:"16",cy:"16",r:"6",key:"qoo3c4"}]],t5=dt("calendar-clock",e5);const n5=[["path",{d:"M11 13H7",key:"t0o9gq"}],["path",{d:"M19 9h-4",key:"rera1j"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["rect",{x:"15",y:"5",width:"4",height:"12",rx:"1",key:"q8uenq"}],["rect",{x:"7",y:"8",width:"4",height:"9",rx:"1",key:"sr5ea"}]],jI=dt("chart-column-stacked",n5);const a5=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Eo=dt("check",a5);const o5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],Bf=dt("circle-check",o5);const r5=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Go=dt("chevron-down",r5);const i5=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Wr=dt("chevron-right",i5);const s5=[["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"}]],l5=dt("circle-alert",s5);const c5=[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]],Mu=dt("cloud",c5);const d5=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],u5=dt("credit-card",d5);const m5=[["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"}]],p5=dt("download",m5);const f5=[["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"}]],$p=dt("external-link",f5);const h5=[["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"}]],g5=dt("file-output",h5);const v5=[["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"}]],Jg=dt("file-text",v5);const b5=[["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"}]],OI=dt("folder",b5);const y5=[["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"}]],$I=dt("folder-git-2",y5);const S5=[["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"}]],k5=dt("git-branch",S5);const x5=[["path",{d:"M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4",key:"tonef"}],["path",{d:"M9 18c-4.51 2-5-2-7-2",key:"9comsn"}]],w5=dt("github",x5);const I5=[["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"}]],NI=dt("earth",I5);const _5=[["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"}]],C5=dt("circle-question-mark",_5);const R5=[["path",{d:"M2 5h20",key:"1fs1ex"}],["path",{d:"M6 12h12",key:"8npq4p"}],["path",{d:"M9 19h6",key:"456am0"}]],P5=dt("list-filter",R5);const A5=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],T5=dt("loader-circle",A5);const E5=[["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"}]],M5=dt("maximize-2",E5);const j5=[["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"}]],ju=dt("message-square",j5);const O5=[["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"}]],Ou=dt("ellipsis",O5);const $5=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],DI=dt("panel-left",$5);const N5=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],Ff=dt("panel-right",N5);const D5=[["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"}]],Yg=dt("pin",D5);const L5=[["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"}]],Qg=dt("pin-off",L5);const U5=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],z5=dt("plus",U5);const H5=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],q5=dt("power",H5);const B5=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],F5=dt("search",B5);const V5=[["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"}]],Xg=dt("settings",V5);const K5=[["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"}]],LI=dt("shapes",K5);const W5=[["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"}]],G5=dt("shield",W5);const Z5=[["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"}]],$u=dt("square-pen",Z5);const J5=[["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"}]],UI=dt("square-terminal",J5);const Y5=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],zy=dt("user-round",Y5);const Q5=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Ss=dt("x",Q5);function X5({platform:e}){return!Nu()||ev(e)?null:x.jsxs("div",{className:"window-controls","aria-label":"Window controls",children:[x.jsx("button",{type:"button",className:"window-control minimize",title:"Minimize",onClick:()=>{Np("minimize")},children:x.jsx(Go,{size:14})}),x.jsx("button",{type:"button",className:"window-control maximize",title:"Maximize",onClick:()=>{Np("toggleMaximize")},children:x.jsx(M5,{size:12})}),x.jsx("button",{type:"button",className:"window-control close",title:"Close",onClick:()=>{Np("close")},children:x.jsx(Ss,{size:13})})]})}function ev(e){const t=e?.toLowerCase()??"";return t==="darwin"||t.includes("mac")}function Nu(){if(typeof window>"u")return!1;const e=window.openpond;return!!(e?.minimizeWindow||e?.toggleMaximizeWindow||e?.closeWindow)}async function Np(e){const t=window.openpond;if(!(t&&(e==="minimize"?await t.minimizeWindow?.():e==="toggleMaximize"?await t.toggleMaximizeWindow?.():await t.closeWindow?.())!==!1)){if(e==="toggleMaximize"&&document.fullscreenEnabled){document.fullscreenElement?await document.exitFullscreen():await document.documentElement.requestFullscreen();return}if(e==="close"){window.close();return}console.warn("Window controls require the Electron desktop shell.")}}function e3({value:e,options:t,disabled:n,compact:a,className:o,icon:i,placement:s="bottom",label:l,tooltip:m,searchable:d=!1,floating:h=!1,onChange:v}){const[y,w]=g.useState(!1),[I,R]=g.useState(""),M=g.useRef(null),[P,N]=g.useState();g.useLayoutEffect(()=>{if(!y||!h)return;function C(){const T=M.current?.getBoundingClientRect();if(!T)return;const z=window.innerHeight-T.bottom-12,B=T.top-12,D=z<180&&B>z;N({position:"fixed",left:Math.max(12,T.left),width:Math.min(T.width,window.innerWidth-24),minWidth:0,maxWidth:"calc(100vw - 24px)",right:"auto",top:D?"auto":T.bottom+5,bottom:D?window.innerHeight-T.top+5:"auto",maxHeight:Math.max(80,Math.min(320,D?B-5:z-5)),overflowY:"auto",zIndex:1e3})}return C(),window.addEventListener("resize",C),window.addEventListener("scroll",C,!0),()=>{window.removeEventListener("resize",C),window.removeEventListener("scroll",C,!0)}},[y,h]);const O=t.find(C=>C.value===e)??t[0],j=I.trim().toLowerCase(),k=j?t.filter(C=>[C.label,C.shortLabel,C.description].some(T=>T?.toLowerCase().includes(j))):t;return g.useEffect(()=>{if(!y){R("");return}function C(z){M.current?.contains(z.target)||w(!1)}function T(z){z.key==="Escape"&&w(!1)}return document.addEventListener("pointerdown",C),document.addEventListener("keydown",T),()=>{document.removeEventListener("pointerdown",C),document.removeEventListener("keydown",T)}},[y]),x.jsxs("div",{className:`dropdown-select ${o??""} ${a?"compact":""} ${s==="top"?"open-up":""}`,"data-tooltip":m,ref:M,children:[x.jsxs("button",{type:"button",className:`dropdown-trigger ${y?"active":""}`,disabled:n,"aria-label":l,"aria-haspopup":"menu","aria-expanded":y,onClick:()=>w(C=>!C),children:[i,x.jsx("span",{children:O?.shortLabel??O?.label??e}),x.jsx(Go,{size:14})]}),y&&x.jsxs("div",{className:"dropdown-menu",role:"menu",style:h?P:void 0,children:[d?x.jsxs("label",{className:"dropdown-search",onClick:C=>C.stopPropagation(),children:[x.jsxs("span",{className:"sr-only",children:["Search ",l]}),x.jsx("input",{autoFocus:!0,placeholder:`Search ${l.toLowerCase()}`,value:I,onChange:C=>R(C.target.value)})]}):null,k.map(C=>x.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":C.value===e,disabled:C.disabled,className:[C.value===e?"selected":"",C.separatorBefore?"separator-before":"",C.icon?"with-icon":""].filter(Boolean).join(" "),onClick:()=>{C.disabled||(v(C.value),R(""),w(!1))},children:[x.jsxs("span",{children:[C.icon==="plus"?x.jsx(z5,{size:13}):null,x.jsx("span",{children:C.label})]}),C.description&&x.jsx("small",{children:C.description})]},C.value)),k.length?null:x.jsx("div",{className:"dropdown-empty",children:"No matches"})]})]})}const t3=[{destination:"walkthroughs",icon:Uy,label:"Walkthroughs"},{destination:"external",icon:Uy,label:"Docs",url:"https://openpond.ai/docs"},{destination:"external",icon:Jg,label:"Blog",url:"https://openpond.ai/blog"},{destination:"external",icon:u5,label:"Pricing",url:"https://openpond.ai/pricing"},{destination:"external",icon:NI,label:"Web app",url:"https://openpond.ai/sandboxes"},{destination:"external",icon:w5,label:"GitHub",url:"https://github.com/openpond/openpond"},{destination:"external",icon:ju,label:"Submit issue",url:"https://github.com/openpond/openpond/issues/new/choose"}];function n3({onOpenWalkthroughs:e,walkthroughsActive:t}){const[n,a]=g.useState(!1),o=g.useRef(null);return g.useEffect(()=>{if(!n)return;function i(l){o.current?.contains(l.target)||a(!1)}function s(l){l.key==="Escape"&&a(!1)}return document.addEventListener("pointerdown",i),document.addEventListener("keydown",s),()=>{document.removeEventListener("pointerdown",i),document.removeEventListener("keydown",s)}},[n]),x.jsxs("div",{className:"sidebar-help-menu",ref:o,children:[x.jsx("button",{"aria-expanded":n,"aria-haspopup":"menu","aria-label":"Open docs and help menu",className:`sidebar-icon sidebar-help-trigger ${t?"active":""}`,"data-tooltip":"Help",onClick:()=>a(i=>!i),type:"button",children:x.jsx(C5,{size:17})}),n?x.jsx("div",{className:"sidebar-help-popover",role:"menu","aria-label":"Help",children:t3.map(i=>{const s=i.icon,l=x.jsxs(x.Fragment,{children:[x.jsx(s,{size:15}),x.jsx("span",{children:i.label})]});return i.destination==="walkthroughs"?x.jsx("button",{"aria-current":t?"page":void 0,className:"sidebar-help-item",onClick:()=>{a(!1),e()},role:"menuitem",type:"button",children:l},i.label):x.jsx("a",{className:"sidebar-help-item",href:i.url,onClick:m=>{m.preventDefault(),a(!1),a3(i.url)},rel:"noreferrer",role:"menuitem",target:"_blank",children:l},i.label)})}):null]})}async function a3(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-help",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const MY=[{value:"chat",label:"Chat"},{value:"work",label:"Work"}],Dp=[{value:"chat",label:"Work",description:"Chat and complete tasks"},{value:"models",label:"Models",description:"Evaluate, train, and serve models"}];function zI(e){return e==="chat"?"New chat":"New task"}const Vf=["get-started","models","tasks","tasksets","labeling","rewards","evaluations","runs","versions","serving"],o3={"get-started":"Get started",models:"Models",tasks:"Tasks",tasksets:"Tasksets",labeling:"Labeling",rewards:"Rewards",evaluations:"Runs",runs:"Runs",versions:"Versions",serving:"Serving"},r3={tasks:["drafts"],tasksets:["drafts","formats","batches"],rewards:["scorers","combined"],evaluations:["results","review","comparisons"],runs:["series","new"]},i3={tasksets:["overview","tasks","reward","attempts","releases"],rewards:["definition","usage","evidence"],evaluations:["overview","comparison","activity"],runs:["details","metrics","evaluation","rollouts","activity","artifacts"],versions:["overview","metrics","evaluation","rollouts","activity","artifacts"]};function po(e="models",t=null,n={}){return e==="evaluations"&&n.collection==="review"?po("labeling",t,{...n,collection:"default"}):{page:e,modelId:e==="get-started"?null:t,collection:e==="evaluations"?"results":"default",resourceId:null,detailTab:null,query:"",after:null,...n}}function tv(e){const t=e.pathname.split("/").filter(Boolean);if(t[0]!=="models")return null;let n;try{n=t.slice(1).map(decodeURIComponent)}catch{return null}if(n.some(R=>!R.trim()||R.length>2e3||R.includes("\0")))return null;const a=n[0]&&!Vf.includes(n[0])?n.shift():null;if(a&&(a.length>500||["projects","scorers"].includes(a)))return null;n[0]==="runs"&&n[1]==="evaluations"&&n.splice(0,2,"evaluations","results"),n[0]==="runs"&&n[1]==="comparisons"&&n.splice(0,2,"evaluations","comparisons");const o=n.shift(),i=o??"models";if(!Vf.includes(i)||o==="models"||a&&i==="get-started")return null;let s=i==="evaluations"?"results":"default";if(r3[i]?.includes(n[0]))s=n.shift();else if(i==="evaluations"&&n.length)return null;const l=n.shift()??null,m=n.shift()??null;if(n.length||m&&!l||(i==="models"||i==="get-started")&&l)return null;if(s==="drafts"||s==="new"){if(!l||m)return null}else if(s!=="series"){if(["review","formats","batches","comparisons","scorers","combined"].includes(s)){if(m)return null}else if(m&&!i3[i]?.includes(m))return null}if(i==="serving"&&m)return null;const d=new URLSearchParams(e.search??"");if([...d.keys()].some(R=>!["model","q","after","source"].includes(R))||[...d.keys()].some(R=>d.getAll(R).length!==1))return null;const h=d.get("source");if(h!==null&&(i!=="labeling"&&(i!=="evaluations"||s!=="review")||!h.trim()||h.length>500))return null;const v=d.get("model");if(a&&v&&a!==v)return null;const y=a??v;if(i==="get-started"&&d.size!==0)return null;const w=d.get("q")??"",I=d.get("after");return y!==null&&(!y.trim()||y.length>500)||w.length>1e3||I!==null&&(!I.trim()||I.length>2e3)?null:po(i,y,{collection:s,resourceId:l,detailTab:m,query:w,after:I,...h!==null?{sourceId:h}:{}})}function Du(e){const t=["/models"];if(e.modelId&&t.push(encodeURIComponent(e.modelId)),e.page==="evaluations"&&e.collection==="review")return Du(po("labeling",e.modelId,{collection:"default",resourceId:e.resourceId,sourceId:e.sourceId,query:e.query,after:e.after}));e.page==="evaluations"?t.push("runs",e.collection==="comparisons"?"comparisons":"evaluations"):(e.page!=="models"&&t.push(e.page),e.collection!=="default"&&t.push(e.collection)),e.resourceId&&t.push(encodeURIComponent(e.resourceId)),e.resourceId&&e.detailTab&&t.push(encodeURIComponent(e.detailTab));const n=new URLSearchParams;return e.query&&n.set("q",e.query),e.after&&n.set("after",e.after),(e.page==="labeling"||e.page==="evaluations"&&e.collection==="review")&&e.sourceId&&n.set("source",e.sourceId),`${t.join("/")}${n.size?`?${n}`:""}`}function s3(e,t){return po(e.page,t,{collection:e.collection==="new"||e.collection==="drafts"?"default":e.collection})}function jY(e,t,n=null){return{...e,resourceId:t,detailTab:n,after:null}}const Ld=new Set,Kf=new Set,l3=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"]),Wf={apps:"/apps",outputs:"/outputs",projects:"/projects",scheduled:"/workflows","get-started":"/get-started"};let Gf=!1,Zf="",md=null,HI=null,Hl="",$a=0,sl=null,Il=!1,Lp=null,pd=!1;function nv(e){const t=tv(e);if(t)return{kind:"models",route:t};const n=e.pathname.split("/").filter(Boolean);if(n[0]==="models")return{kind:"models_unavailable",pathname:e.pathname,search:e.search??""};if(n[0]==="settings"&&n.length===2&&l3.has(n[1])){const o=av(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(Wf).find(o=>Wf[o]===e.pathname);return a?{kind:"view",view:a}:null}function qI(e){if(e.kind==="models")return Du(e.route);if(e.kind==="models_unavailable")return`${e.pathname}${e.search}`;if(e.kind==="settings"){const t=av(e.returnTo??null);return`/settings/${e.section}${t?`?${new URLSearchParams({returnTo:t})}`:""}`}return e.kind==="chat"?e.sessionId?`/chat/${encodeURIComponent(e.sessionId)}`:"/chat/new":Wf[e.view]}function c3(e){const t=e?.kind==="settings"?av(e.returnTo??null):null;if(t){const n=new URL(t,"https://local.openpond.invalid"),a=tv(n);if(a)return{kind:"models",route:a}}return{kind:"chat",sessionId:null}}function av(e){if(!e||e.length>6e3||!e.startsWith("/models")||e.startsWith("//"))return null;const t=new URL(e,"https://local.openpond.invalid");if(t.origin!=="https://local.openpond.invalid"||t.hash)return null;const n=tv(t);return n?Du(n):null}function mc(){return`${window.location.pathname}${window.location.search}`}function ov(){if(typeof window>"u")return;const e=Gf?Hl:mc();e!==Zf&&(Zf=e,md=nv(new URL(e,window.location.origin)),HI=md?.kind==="models"?md.route:null)}function BI(){Zf="",ov();for(const e of Kf)e()}async function rv(e){if(pd)return!1;pd=!0;try{for(const t of[...Ld].reverse())if(!await t(e))return!1;return!0}finally{pd=!1}}function iv(e){return{...window.history.state,openpondNavigationIndex:e}}async function d3(){const e=mc(),t=typeof window.history.state?.openpondNavigationIndex=="number"?window.history.state.openpondNavigationIndex:$a-1;if(sl&&t===$a){const a=sl;sl=null,a();return}if(Lp===t||Ld.size===0){Lp=null,Hl=e,$a=t,window.history.replaceState(iv($a),"",e),BI();return}if(t===$a)return;if(Il||pd){sl??=()=>{},window.history.go($a-t);return}Il=!0;const n=t-$a;try{await new Promise(a=>{sl=a,window.history.go(-n)}),await rv(e)&&(Lp=t,window.history.go(n))}finally{Il=!1}}function sv(){if(Gf||typeof window>"u")return;const e=nv(window.location);Hl=e?qI(e):mc(),$a=typeof window.history.state?.openpondNavigationIndex=="number"?window.history.state.openpondNavigationIndex:0,window.history.replaceState(iv($a),"",Hl),window.addEventListener("popstate",d3),Gf=!0}function FI(e){return Kf.add(e),sv(),()=>{Kf.delete(e)}}function OY(e){return Ld.add(e),sv(),()=>{Ld.delete(e)}}async function $Y(e){!Il&&await rv(mc())&&e()}function u3(){return g.useSyncExternalStore(FI,()=>(ov(),HI),()=>null)}function m3(){return g.useSyncExternalStore(FI,()=>(ov(),md),()=>null)}async function cn(e,t="push"){if(typeof window>"u"||(sv(),Il))return!1;if(e.kind==="settings"&&!e.returnTo){const a=nv(window.location),o=a?.kind==="models"?Du(a.route):a?.kind==="settings"?a.returnTo:void 0;o&&(e={...e,returnTo:o})}const n=qI(e);return mc()===n?!0:await rv(n)?(t==="push"&&$a++,window.history[t==="replace"?"replaceState":"pushState"](iv($a),"",n),Hl=n,BI(),!0):!1}function Gi(e,t="push"){return cn({kind:"models",route:e},t)}function p3({experience:e="work",productArea:t="chat",beginNewChat:n,setSectionMenuOpen:a,setSelectedAppId:o,setSelectedProjectId:i,setSelectedSessionId:s,setView:l,view:m,modelProjects:d=[],modelTrainingActivityByProjectId:h={}}){const v=u3(),y=v?.modelId??null,w=v?.page??"models";function I(){o(null),i(null),s(null),a(null)}async function R(O){await Gi(po(O,y))&&(I(),l("labs"))}async function M(O){await Gi(s3(v??po(),O||null))&&(I(),l("labs"))}async function P(O){await cn({kind:"view",view:O})&&(I(),l(O))}const N=y?h[y]??null:null;return x.jsxs("nav",{className:"sidebar-nav","aria-label":"Primary",children:[t==="models"?null:x.jsxs("button",{className:"nav-command nav-command-new-task",type:"button",onClick:()=>{cn({kind:"chat",sessionId:null}),n(null)},children:[x.jsx($u,{size:18}),x.jsx("span",{children:zI(e)})]}),t==="models"?x.jsxs(x.Fragment,{children:[x.jsxs("div",{className:"sidebar-model-project-picker",children:[x.jsx("span",{className:"sidebar-nav-group-label",children:"Model"}),x.jsx(e3,{label:"Model",searchable:d.length>8,value:y??"",options:[{value:"",label:"All models"},...y&&!d.some(O=>O.id===y)?[{value:y,label:"Unavailable model",disabled:!0}]:[],...d.map(O=>({value:O.id,label:O.name}))],onChange:O=>{M(O)}})]}),Vf.filter(O=>O!=="tasksets"&&O!=="evaluations").map(O=>{const j={"get-started":Op,models:V4,tasks:Op,tasksets:Op,labeling:Bf,rewards:G5,evaluations:Bf,runs:jI,versions:k5,serving:Mu}[O];return x.jsxs("button",{className:`nav-command ${m==="labs"&&(w===O||O==="runs"&&w==="evaluations")?"active":""}`,"aria-current":m==="labs"&&(w===O||O==="runs"&&w==="evaluations")?"page":void 0,type:"button",onClick:()=>{R(O)},children:[x.jsx(j,{size:16}),x.jsx("span",{children:o3[O]}),O==="runs"&&N?x.jsx("span",{className:"sidebar-running-dot","aria-label":N.label}):null]},O)})]}):null,t==="chat"?x.jsxs(x.Fragment,{children:[x.jsxs("button",{className:`nav-command nav-command-prominent ${m==="scheduled"?"active":""}`,"aria-label":"Workflows",type:"button",onClick:()=>{P("scheduled")},children:[x.jsx(t5,{size:18}),x.jsx("span",{children:"Workflows"})]}),x.jsxs("button",{className:`nav-command nav-command-prominent ${m==="outputs"?"active":""}`,"aria-label":"Outputs",type:"button",onClick:()=>{P("outputs")},children:[x.jsx(g5,{size:18}),x.jsx("span",{children:"Outputs"})]}),x.jsxs("button",{className:`nav-command nav-command-prominent ${m==="apps"?"active":""}`,"aria-label":"Apps",type:"button",onClick:()=>{P("apps")},children:[x.jsx(LI,{size:18}),x.jsx("span",{children:"Apps"})]}),x.jsxs("button",{className:`nav-command nav-command-prominent ${m==="projects"?"active":""}`,"aria-label":"Projects",type:"button",onClick:()=>{P("projects")},children:[x.jsx($I,{size:18}),x.jsx("span",{children:"Projects"})]})]}):null]})}function f3({setSectionMenuOpen:e,setSelectedAppId:t,setSelectedProjectId:n,setSelectedSessionId:a,setView:o,view:i}){function s(){t(null),n(null),a(null),e(null),o("get-started"),cn({kind:"view",view:"get-started"})}return x.jsx("nav",{className:"sidebar-utility-nav","aria-label":"Resources",children:x.jsx(n3,{onOpenWalkthroughs:s,walkthroughsActive:i==="get-started"})})}const VI=Qm({chatMode:b(["chat","work"]).optional(),notificationMode:b(["all","direct_mentions","none"]).optional(),learningNoticeDismissed:A().optional(),sidebarVisibility:Qm({showCodexChats:A(),onlyRunningTasks:A()}).optional(),scheduledWorkView:b(["calendar","list"]).optional(),editorControlsVisible:A().optional(),voiceNoticeAcknowledged:A().optional(),lessonProgress:ie(r().min(1).max(200),Qm({completed:A(),currentTime:u().finite().nonnegative(),duration:u().finite().positive(),updatedAt:u().finite().nonnegative()})).refine(e=>Object.keys(e).length<=200,"Too many lessons").optional()}),Jf={"openpond:last-chat-task-mode":"chatMode","openpond.team-chat.notification-mode":"notificationMode","openpond.sidebar.continuous-learning.dismissed.v1":"learningNoticeDismissed","openpond.sidebar-task-visibility.v1":"sidebarVisibility","openpond.scheduled-work.view.v1":"scheduledWorkView","openpond.workspace.editorControlsVisible":"editorControlsVisible","openpond.voice.setupNoticeAcknowledged":"voiceNoticeAcknowledged","openpond.post-training-progress.v1":"lessonProgress"},Yf=new Set;let _l=null,Fo=null,Da={},ql={},Up=!1,fd=0,Zi=null,Hy=0;const h3="openpond-client-choices-changed";function lv(){Yf.forEach(e=>e()),typeof window<"u"&&window.dispatchEvent(new Event(h3))}function g3(){return Zi}function v3(e){return Yf.add(e),()=>{Yf.delete(e)}}function pc(e){const t=g.useRef(e);t.current=e,g.useEffect(()=>v3(()=>t.current()),[])}async function qy(e){const t=++Hy,n=await q(e,"/v1/configuration");if(n.clientState?.revision===null){const o=b3();if(Object.keys(o.patch).length){n.clientState=await q(e,"/v1/configuration",{method:"POST",body:JSON.stringify({action:"client-state",owner:n.clientState.owner,patch:o.patch,importOnly:!0})});for(const i of o.keys)try{window.localStorage.removeItem(i)}catch{}}}if(t!==Hy)return;const a=_l?.serverUrl!==e.serverUrl||_l?.token!==e.token||Fo?.owner!==n.clientState?.owner;a&&(fd++,Da={},ql={},Zi=null),_l=e,(a||(n.clientState?.revision??0)>=(Fo?.revision??0))&&(Fo=n.clientState),lv()}async function cv(){if(Up||!_l||!Fo||!Object.keys(Da).length)return;Up=!0;const e=Da,t=_l,n=Fo.owner,a=fd;Da={},ql=e;try{const o=await q(t,"/v1/configuration",{method:"POST",body:JSON.stringify({action:"client-state",owner:n,patch:e})});a===fd&&(Fo=o,Zi=null)}catch(o){a===fd&&(Da={...e,...Da},Zi=`Preference changes have not been saved. ${o instanceof Error?o.message:String(o)}`)}finally{ql={},Up=!1,lv(),!Zi&&Object.keys(Da).length&&cv()}}function NY(){Zi=null,cv()}const fc={getItem(e){const t=Jf[e];if(!t)return null;const n={...Fo?.value,...ql,...Da}[t];return n===void 0?null:typeof n=="string"?n:JSON.stringify(n)},setItem(e,t){if(!Fo)return;const n=Jf[e];if(!n)throw new Error("Unregistered client preference.");let a;try{a=JSON.parse(t)}catch{a=t}const o=VI.parse({[n]:a});JSON.stringify({...Fo.value,...ql,...Da}[n])!==JSON.stringify(o[n])&&(Da={...Da,...o},lv(),cv())}};function b3(){const e={},t=[];if(typeof window>"u")return{patch:e,keys:t};for(const[n,a]of Object.entries(Jf))try{const o=window.localStorage.getItem(n);if(o===null)continue;let i;try{i=JSON.parse(o)}catch{i=o}const s=VI.safeParse({[a]:i});s.success&&(Object.assign(e,s.data),t.push(n))}catch{}return{patch:e,keys:t}}const hd=5,Pn=15,Qf=10,Et={defaultChatProvider:Fr,subagents:QM(),codexPermissionMode:Vh,codexReasoningEffort:Kh,openPondCommandAccessMode:ou,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:""}}}},DY={activeTemplateId:"default",customized:!1,soul:"",soulPath:null,updatedAt:null,templates:[]},KI=[{value:"accounts/fireworks/models/deepseek-v4-pro",label:"DeepSeek V4 Pro",description:"reasoning"},{value:"accounts/fireworks/models/kimi-k3",label:"Kimi K3",description:"reasoning"},{value:"accounts/fireworks/models/glm-5p3",label:"GLM-5.3",description:"reasoning"},{value:"accounts/fireworks/models/deepseek-v4-flash",label:"DeepSeek V4 Flash",description:"reasoning"},{value:"accounts/fireworks/models/nemotron-lightning-3p5-30b-a3b",label:"Nemotron Lightning 3.5 30B A3B",description:"reasoning"},{value:"accounts/fireworks/models/minimax-m3",label:"MiniMax M3",description:"reasoning"}],zp=[{value:"openpond",label:"OpenPond Chat"},{value:"codex",label:"OpenAI Codex",description:"Codex login"}],y3=["openai","xai","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],S3=["openpond","codex",...y3],WI=new Set(S3),GI=[{value:Fh,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"}],LY=[{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."}],UY=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"xhigh",label:"Extra High",shortLabel:"Extra High"}],zY=[{value:"ask",label:"Ask",description:"Ask before running shell commands."},{value:"full-access",label:"Full access",description:"Run shell commands without approval prompts."}],HY=[{value:"auto",label:"Auto",description:"Use installed language servers when available."},{value:"off",label:"Off",description:"Disable editor language servers."}],qY=[{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 dv(e){return e.kind==="local"}function k3(e){return e.kind==="cloud"}function vt(e,t){return`${e}:${t}`}function ZI(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 Ur(e){return`${e.type}:${e.id}`}function Ud(e){const t=e.currentTarget.getBoundingClientRect();return e.clientY<t.top+t.height/2?"before":"after"}function zd(e,t,n,a="before"){if(t===n)return e;const o=e.filter(s=>s!==t),i=o.indexOf(n);return i===-1?e:(o.splice(a==="after"?i+1:i,0,t),o)}function By(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function x3(e,t){if(!t)return e;const n=new Map(e.map(i=>[i.key,i])),a=t.map(i=>n.get(i)).filter(i=>!!i),o=new Set(a.map(i=>i.key));return[...a,...e.filter(i=>!o.has(i.key))]}function uv(e,t){return e?.statuses?.[t]??null}function JI(e,t){return e?.providers?.[t]??null}function YI(e,t){return e?.modelCaches?.[t]??null}function w3(e){const t=[e.contextWindow?`${Math.round(e.contextWindow/1e3)}K context`:"",e.capabilities.reasoning?"reasoning":"",e.source].filter(Boolean);return{value:e.id,label:e.displayName||e.id,description:t.join(" · ")||void 0}}function I3(e){return e==="openpond"?KI:e==="codex"||e==="openai"?GI:[]}function _3(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 BY(e){return WI.has(e)}function Xf(e,t={}){if(!e)return t.localOnly,zp;const n=t.includeUnavailable??!1,a=t.enabledOnly??!1,o=[];for(const i of jh){if(!WI.has(i)||t.localOnly&&i==="openpond")continue;const s=uv(e,i);s&&(!n&&(i==="codex"&&!s.available&&!s.credential.connected||i!=="openpond"&&i!=="codex"&&!s.enabled)||a&&i!=="openpond"&&!s.enabled||a&&i==="codex"&&!s.available&&!s.credential.connected||o.push({value:i,label:i==="openpond"?"OpenPond Chat":s.displayName,description:i==="openpond"?void 0:s.available?"Connected":s.credential.connected?"Configured":s.routing.localByok?"Set up key":s.enabled?"Enabled":void 0}))}return o.length>0?o:zp}function Bl(e,t){const a=(YI(t,e)?.models??[]).filter(s=>e!=="openpond"||s.id!==es).map(w3),o=JI(t,e),i=[...o?.modelOverrides??[],o?.defaultModel].filter(s=>!!s?.trim()&&(e!=="openpond"||s!==es)).map(s=>({value:s,label:s}));return _3([...a,...i,...I3(e)])}function C3(e,t,n){if(e==="codex"||e==="openai")return!0;const a=t.trim();if(!a)return!1;const o=YI(n,e)?.models.find(i=>i.id===a);return o?!!o.capabilities.reasoning:Bl(e,n).some(i=>i.value===a&&/\breasoning\b/i.test(i.description??""))}function Hd(e,t){const n=JI(t,e)?.defaultModel?.trim();if(n)return n;const a=uv(t,e)?.defaultModel?.trim();if(a)return a;const o=Bl(e,t)[0]?.value?.trim();return o||(e==="codex"?Fh:e==="openpond"?es:"")}function br(e,t,n){const a=t?.trim();if(e==="codex"&&(a==="codex-default"||a==="gpt-5.5"))return Fh;const o=Bl(e,n);return a&&o.some(i=>i.value===a)||a&&e!=="codex"&&o.length===0&&!n?a:Hd(e,n)}function QI(e,t){const n=e.modelRef?.providerId??e.provider;return{provider:n,model:br(n,e.modelRef?.modelId,t)}}function mv(e,t,n){return br(e,t,n)||void 0}function ja(e,t,n){const a=mv(e,t,n);return a?{providerId:e,modelId:a}:void 0}function Fy(e){return e==="full-access"?{approvalPolicy:"never",sandbox:"danger-full-access"}:{approvalPolicy:"on-request",sandbox:"workspace-write"}}function ba(e){const t=e?.defaultChatProvider??Et.defaultChatProvider;return{defaultChatProvider:t,defaultChatModel:br(t,e?.defaultChatModel),subagents:Tl.parse(e?.subagents??Et.subagents),codexPermissionMode:e?.codexPermissionMode??Et.codexPermissionMode,codexReasoningEffort:e?.codexReasoningEffort??Et.codexReasoningEffort,openPondCommandAccessMode:e?.openPondCommandAccessMode??Et.openPondCommandAccessMode,defaultBranchPrefix:XI(e?.defaultBranchPrefix),defaultNewProjectDirectory:e?.defaultNewProjectDirectory??Et.defaultNewProjectDirectory,defaultTeamId:e?.defaultTeamId?.trim()||null,advancedWorkspaceControls:e?.advancedWorkspaceControls??Et.advancedWorkspaceControls,steerActiveResponses:e?.steerActiveResponses??Et.steerActiveResponses,contextCompaction:{autoEnabled:e?.contextCompaction?.autoEnabled??Et.contextCompaction.autoEnabled,triggerPercent:e?.contextCompaction?.triggerPercent??Et.contextCompaction.triggerPercent,summaryModel:e?.contextCompaction?.summaryModel??Et.contextCompaction.summaryModel},training:{defaultModelRef:e?.training?.defaultModelRef??Et.training.defaultModelRef,creationMode:e?.training?.creationMode??Et.training.creationMode,autoApproveEvidence:e?.training?.autoApproveEvidence??Et.training.autoApproveEvidence},sidebarWidth:e?.sidebarWidth??Et.sidebarWidth,diffPanelWidth:e?.diffPanelWidth??Et.diffPanelWidth,sidebarSectionsCollapsed:{pinned:e?.sidebarSectionsCollapsed?.pinned??Et.sidebarSectionsCollapsed.pinned,projects:e?.sidebarSectionsCollapsed?.projects??Et.sidebarSectionsCollapsed.projects,cloudProjects:e?.sidebarSectionsCollapsed?.cloudProjects??Et.sidebarSectionsCollapsed.cloudProjects,chats:e?.sidebarSectionsCollapsed?.chats??Et.sidebarSectionsCollapsed.chats,savedForLater:e?.sidebarSectionsCollapsed?.savedForLater??Et.sidebarSectionsCollapsed.savedForLater},editor:{languageServers:e?.editor?.languageServers??Et.editor.languageServers,diagnosticsWhileEditing:e?.editor?.diagnosticsWhileEditing??Et.editor.diagnosticsWhileEditing,checkOnSave:e?.editor?.checkOnSave??Et.editor.checkOnSave,languages:{typescript:{mode:e?.editor?.languages?.typescript?.mode??Et.editor.languages.typescript.mode,customCommand:e?.editor?.languages?.typescript?.customCommand??Et.editor.languages.typescript.customCommand},python:{mode:e?.editor?.languages?.python?.mode??Et.editor.languages.python.mode,customCommand:e?.editor?.languages?.python?.customCommand??Et.editor.languages.python.customCommand},rust:{mode:e?.editor?.languages?.rust?.mode??Et.editor.languages.rust.mode,customCommand:e?.editor?.languages?.rust?.customCommand??Et.editor.languages.rust.customCommand}}}}}function XI(e){const t=e?.trim()??Et.defaultBranchPrefix;if(!t)return"";const a=t.toLowerCase().replace(/[^a-z0-9._/-]+/g,"-").replace(/\/{2,}/g,"/").replace(/^-+/,"").slice(0,48).split("/").map(o=>o.replace(/^-+|-+$/g,"")).filter(Boolean).join("/");return a?`${a}/`:""}function FY(e,t){return e==="openpond"?"OpenPond Chat":uv(t,e)?.displayName??(e==="codex"?"OpenAI Codex":e)}function VY(e,t,n){if(n){const a=Bl(n,t).find(o=>o.value===e);if(a)return a.label}if(t)for(const a of jh){const o=Bl(a,t).find(i=>i.value===e);if(o)return o.label}return[...KI,...GI].find(a=>a.value===e)?.label??e}function R3(e,t){return t==="chat"?e.filter(n=>n.experience==="chat"):e.filter(n=>n.experience==="work"||n.experience==="development")}function P3(e){return e.experience==="chat"?"Chat":"Work"}const pv="taskDraft";function e_(e){if(e?.experience!=="work")return null;const t=e.metadata?.[pv];if(!t||typeof t!="object"||Array.isArray(t))return null;const n=t.prompt;return typeof n=="string"&&n.trim()?n:null}function Fl(e){return e_(e)!==null}function A3(e){return(e.split(/\r?\n/u).map(n=>n.trim()).find(Boolean)||"Task draft").slice(0,64)}function Hp(e,t,n=new Date().toISOString()){const a={version:1,prompt:t,savedAt:n};return{...e??{},[pv]:a}}function T3(e){const t={...e??{}};return delete t[pv],t}function cr(e){const t=Wc(e.metadata?.trainingTasksetId)??Wc(e.metadata?.tasksetId);return t?{id:t,name:Wc(e.metadata?.trainingTasksetName)??Wc(e.metadata?.tasksetName)??E3(t)}:null}function E3(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 Wc(e){return typeof e=="string"&&e.trim()?e.trim():null}const M3="codex_history_";function qt(e){return!!e?.startsWith(M3)}function t_(e){const t=[],n=new Set;for(const a of e)for(const o of[a.workspacePath,a.path]){const i=Lu(o);if(!i)continue;const s=`${a.id}:${i}`;n.has(s)||(n.add(s),t.push({projectId:a.id,path:i}))}return t.sort((a,o)=>o.path.length-a.path.length)}function j3(e,t,n,a=new Set){if(e.localProjectId&&t.has(e.localProjectId))return e.localProjectId;if(e.workspaceKind==="local_project"&&e.workspaceId&&t.has(e.workspaceId))return e.workspaceId;if(e.metadata?.workspaceTarget==="hybrid"&&e.cwd){const i=n_(e.cwd,n);if(i)return i}if(e.cloudProjectId&&a.has(e.cloudProjectId))return e.cloudProjectId;if(!e.cwd||e.workspaceKind==="sandbox"||e.workspaceKind==="sandbox_template"||e.workspaceKind==="sandbox_app"||!a_(e))return null;const o=Lu(e.cwd);if(!o)return null;for(const i of n)if(fv(o,i.path))return i.projectId;return null}function Vy(e,t,n,a=new Set){if(e.localProjectId&&t.has(e.localProjectId))return vt("local",e.localProjectId);if(e.workspaceKind==="local_project"&&e.workspaceId&&t.has(e.workspaceId))return vt("local",e.workspaceId);if(e.metadata?.workspaceTarget==="hybrid"&&e.cwd){const i=n_(e.cwd,n);if(i)return vt("local",i)}if(e.cloudProjectId&&a.has(e.cloudProjectId))return vt("cloud",e.cloudProjectId);if(!e.cwd||e.workspaceKind==="sandbox"||e.workspaceKind==="sandbox_template"||e.workspaceKind==="sandbox_app"||!a_(e))return null;const o=Lu(e.cwd);if(!o)return null;for(const i of n)if(fv(o,i.path))return vt("local",i.projectId);return null}function n_(e,t){const n=Lu(e);if(!n)return null;for(const a of t)if(fv(n,a.path))return a.projectId;return null}function a_(e){return e.workspaceKind==="local_project"||e.provider==="codex"||qt(e.id)}function Lu(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 fv(e,t){const n=Ky(e),a=Ky(t);return n===a||n.startsWith(`${a}/`)}function Ky(e){return/^[A-Z]:\//.test(e)?e.toLowerCase():e}const Wy=[{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"}],O3=[{value:"recent",label:"Recent first"},{value:"manual",label:"Manual order"}];function Gy(e){const t=[];if(e.filter==="done")t.push(...e.doneSessions.filter(o=>!cr(o)));else if(e.filter==="all")t.push(...e.activeSessions.filter(o=>!cr(o)),...e.doneSessions.filter(o=>!cr(o)));else if(e.filter==="tasksets")t.push(...e.activeSessions.filter(o=>Zy(o,e.selectedTasksetId)),...e.doneSessions.filter(o=>Zy(o,e.selectedTasksetId)));else for(const o of e.activeSessions)cr(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=>Ti(o,{inProgressSessionIds:e.inProgressSessionIds,onlyRunningTasks:e.onlyRunningTasks,showCodexChats:e.showCodexChats})),a=e.previewSessionIds?new Map(e.previewSessionIds.map((o,i)=>[o,i])):null;return e.sort==="recent"?n.sort((o,i)=>Yy(o,i,a)):n.sort((o,i)=>{const s=a?.get(o.id),l=a?.get(i.id);if(s!==void 0||l!==void 0){if(s===void 0)return 1;if(l===void 0)return-1;if(s!==l)return s-l}return o.order!==i.order?o.order-i.order:Yy(o,i)})}function Ti(e,t){return t.showCodexChats===!1&&(e.provider==="codex"||qt(e.id))?!1:!t.onlyRunningTasks||t.inProgressSessionIds.has(e.id)}function Zy(e,t){const n=cr(e);return!!(n&&(!t||n.id===t))}function $3(e){return e.filter==="saved_for_later"||e.filter==="tasksets"?{count:Math.max(0,e.activeCount),label:"In Progress",targetFilter:"active",targetLabel:"active"}:{count:Math.max(0,e.savedForLaterCount),label:"Later",targetFilter:"saved_for_later",targetLabel:"saved for later"}}function N3(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 Jy(e,t,n){const a=new Set(t);let o=0;return e.map(i=>{if(!a.has(i))return i;const s=n[o];return o+=1,s??i})}function Yy(e,t,n=null){const a=Cl(e),o=Cl(t);if(a!==o)return a?-1:1;if(a&&o){const s=n?.get(e.id),l=n?.get(t.id);if(s!==void 0||l!==void 0){if(s===void 0)return 1;if(l===void 0)return-1;if(s!==l)return s-l}if(e.order!==t.order)return e.order-t.order}const i=Date.parse(t.updatedAt)-Date.parse(e.updatedAt);return i!==0?i:e.title.localeCompare(t.title)}function Cl(e){return e.pinned&&!e.savedForLater&&!e.archived}const Gc={showCodexChats:!0,onlyRunningTasks:!1},o_="openpond.sidebar-task-visibility.v1";function Qy(e=r_()){try{const t=e?.getItem(o_);if(!t)return Gc;const n=JSON.parse(t);return{showCodexChats:typeof n.showCodexChats=="boolean"?n.showCodexChats:Gc.showCodexChats,onlyRunningTasks:typeof n.onlyRunningTasks=="boolean"?n.onlyRunningTasks:Gc.onlyRunningTasks}}catch{return Gc}}function Xy(e,t=r_()){try{t?.setItem(o_,JSON.stringify(e))}catch{}}function r_(){return typeof window>"u"?null:fc}function i_(e){return`${e.kind}:${e.id}`}function Vl(e,t){return!!(e&&t&&e.kind===t.kind&&e.id===t.id)}function D3(e){return{kind:"session",id:e}}function L3(e){return{kind:"project",id:e}}function U3(e){return{kind:"draft",id:e}}function z3(e){return e.selectedSessionId?D3(e.selectedSessionId):e.selectedProjectId?L3(e.selectedProjectId):U3(e.selectedAppId?`app:${e.selectedAppId}`:"new-chat")}function H3(e){if(!e.previousScope||e.previousScope.kind!=="draft"||e.activeScope.kind!=="session")return[...e.tabs];if(Vl(e.previousScope,e.activeScope))return[...e.tabs];const t=e.now??Date.now();return e.tabs.map(n=>Vl(n.scope,e.previousScope)?{...n,scope:e.activeScope,updatedAt:t}:n)}function KY(e,t){return e.filter(n=>Vl(n.scope,t))}function WY(e,t){return!!(e&&Vl(e.scope,t))}function q3(e){const t={};for(const n of e){const a=i_(n.scope),o=t[a]??{scope:n.scope,tabCount:0,runningCount:0,failedCount:0,lastExitCode:null,status:"none"};o.tabCount+=1,n.commandStatus==="running"&&(o.runningCount+=1),(n.commandStatus==="failed"||n.status==="error")&&(o.failedCount+=1),n.lastExitCode!==null&&(o.lastExitCode=n.lastExitCode),o.status=F3(o.status,n.status,n.commandStatus),t[a]=o}return t}function B3(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 F3(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 s_(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=K3(e),i=t?.linkedCloudSourceKnown===!1&&!!e.headCommit;return o?a.push(o):i?a.push("upload required"):e.diverged?(e.ahead>0&&a.push(dr("ahead",e.ahead)),e.behind>0&&a.push(dr("behind",e.behind)),a.push("diverged")):(e.ahead>0&&a.push(dr("ahead",e.ahead)),e.behind>0&&a.push(dr("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 l_(e,t,n,a={}){const o=e?.linkedSandboxProject??null;if(!o?.projectId&&!t)return"upload required";if(o?.projectId&&a.cloudLinkTrusted===!1)return"uploaded to a different account";const i=o?.defaultBranch??t?.defaultBranch??"main",s=o?.manifestHash??null,l=e?.sandboxTemplate?.manifestHash??null,m=o?.syncedAt??t?.syncedAt??null,d=!!(s&&l&&s!==l),h=!!(o?.projectId&&n?.headCommit&&!o.lastUploadedCommit),v=W3(n);return v?`${i} / ${v}`:h?`${i} / upload required`:`${i} / ${d||!m?"needs sync":"setup ready"}`}function V3(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(c_(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 K3(e){return e.linkedSourceHeadCommit?e.divergedFromLinkedSource?"diverged":e.aheadOfLinkedSource>0?dr("local ahead",e.aheadOfLinkedSource):e.behindLinkedSource>0?dr("cloud ahead",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"sync unknown":null:null}function W3(e){return e?.linkedSourceHeadCommit?e.dirty?"local dirty files not in cloud":e.divergedFromLinkedSource?"diverged from local":e.aheadOfLinkedSource>0?dr("cloud behind local",e.aheadOfLinkedSource):e.behindLinkedSource>0?dr("cloud ahead local",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"source check unavailable":"synced":null}function dr(e,t){return`${e} by ${c_(t)}`}function c_(e){return`${e} commit${e===1?"":"s"}`}function G3({size:e=14,className:t}){return x.jsxs("svg",{className:["lucide lucide-cloud-upload",t??""].filter(Boolean).join(" "),xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[x.jsx("path",{d:"M12 13v8"}),x.jsx("path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242"}),x.jsx("path",{d:"m8 17 4-4 4 4"})]})}function d_({kind:e,linkedCloud:t=!1,open:n=!1,className:a,baseSize:o=15}){const i=e==="cloud"?"cloud":n?"folder-open":"folder";return x.jsx("span",{className:["project-kind-icon",e,t?"linked-cloud":"",a??""].filter(Boolean).join(" "),"aria-hidden":"true",children:x.jsxs("svg",{className:`lucide lucide-${i} project-kind-icon-svg`,xmlns:"http://www.w3.org/2000/svg",width:o,height:o,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e==="cloud"?x.jsx(Y3,{}):n?x.jsx(J3,{}):x.jsx(Z3,{}),t&&e==="local"?x.jsx(Q3,{}):null]})})}function Z3(){return x.jsx("path",{className:"project-kind-icon-base",d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"})}function J3(){return x.jsx("path",{className:"project-kind-icon-base",d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"})}function Y3(){return x.jsx("path",{className:"project-kind-icon-base",d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z"})}function Q3(){return x.jsxs("g",{className:"project-kind-icon-cloud-badge",children:[x.jsx("circle",{cx:"18",cy:"17",r:"5"}),x.jsx("path",{d:"M20.4 18.6h-4.2a2.2 2.2 0 1 1 2.08-2.9h.88a1.45 1.45 0 1 1 1.24 2.9Z"})]})}var eh=GC();function X3({title:e,pinned:t,savedForLater:n,archived:a,onRename:o,onTogglePin:i,onToggleSaveForLater:s,onDockRight:l,onArchive:m}){const d=g.useRef(null),h=g.useRef(null),[v,y]=g.useState(null),w=[...o?[{label:"Rename",Icon:$u,action:o}]:[],{label:t?"Unpin":"Pin",Icon:t?Qg:Yg,action:i},...s?[{label:n?"Return to active":"Save for later",Icon:n?MI:EI,action:s}]:[],...l?[{label:"Open in right panel",Icon:Ff,action:l}]:[],{label:a?"Reopen":"Mark done",Icon:a?W4:Eo,action:m}];function I(R=!1){y(null),R&&d.current?.focus()}return g.useEffect(()=>{if(!v)return;h.current?.querySelector("button")?.focus();const R=P=>{!h.current?.contains(P.target)&&!d.current?.contains(P.target)&&y(null)},M=()=>y(null);return document.addEventListener("pointerdown",R),window.addEventListener("resize",M),()=>{document.removeEventListener("pointerdown",R),window.removeEventListener("resize",M)}},[v]),x.jsxs(x.Fragment,{children:[x.jsx("div",{className:`sidebar-row-actions sidebar-task-menu-trigger${v?" is-open":""}`,children:x.jsx("button",{ref:d,type:"button",className:"sidebar-row-action","aria-label":`More actions for task ${e}`,"aria-haspopup":"menu","aria-expanded":!!v,draggable:!1,onDoubleClick:R=>R.stopPropagation(),onClick:R=>{if(R.stopPropagation(),v){I(!0);return}const M=R.currentTarget.getBoundingClientRect();y({left:Math.max(8,Math.min(M.right-192,window.innerWidth-200)),top:Math.max(8,Math.min(M.bottom+4,window.innerHeight-(w.length*32+17)))})},children:x.jsx(Ou,{size:16})})}),v&&eh.createPortal(x.jsx("div",{ref:h,role:"menu","aria-label":`Actions for ${e}`,className:"sidebar-task-menu",style:v,onClick:R=>R.stopPropagation(),onDoubleClick:R=>R.stopPropagation(),onBlur:R=>{R.currentTarget.contains(R.relatedTarget)||I()},onKeyDown:R=>{R.stopPropagation();const M=Array.from(R.currentTarget.querySelectorAll("button")),P=M.indexOf(document.activeElement);if(R.key==="Escape"&&(R.preventDefault(),I(!0)),["ArrowDown","ArrowUp","Home","End"].includes(R.key)){R.preventDefault();const N=R.key==="Home"?0:R.key==="End"?M.length-1:(P+(R.key==="ArrowDown"?1:-1)+M.length)%M.length;M[N]?.focus()}},children:w.map(({label:R,Icon:M,action:P},N)=>x.jsxs("button",{type:"button",role:"menuitem",className:N===w.length-1?"task-menu-done":void 0,onClick:()=>{I(!0),P()},children:[x.jsx(M,{size:15}),R]},R))}),document.body)]})}function e6({session:e,onSave:t,onClose:n}){const[a,o]=g.useState(e.title),i=g.useRef(null);g.useEffect(()=>{const m=i.current;m&&(m.focus(),m.select())},[]),g.useEffect(()=>{function m(d){d.key==="Escape"&&n()}return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[n]);function s(){const m=a.trim();m&&(t(m),n())}function l(m){m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),s())}return x.jsx("div",{className:"git-dialog-backdrop rename-chat-backdrop",role:"presentation",onMouseDown:n,children:x.jsxs("section",{className:"git-dialog rename-chat-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"rename-chat-title",onMouseDown:m=>m.stopPropagation(),children:[x.jsx("h2",{id:"rename-chat-title",children:"Rename chat"}),x.jsx("textarea",{ref:i,className:"rename-chat-input",value:a,rows:1,maxLength:200,onChange:m=>o(m.target.value),onKeyDown:l,"aria-label":"Chat title"}),x.jsxs("div",{className:"git-dialog-footer",children:[x.jsx("button",{type:"button",className:"git-dialog-secondary",onClick:n,children:"Cancel"}),x.jsx("button",{type:"button",className:"git-dialog-primary",autoFocus:!0,onClick:s,disabled:!a.trim(),children:"Save"})]})]})})}const t6=24;function n6({title:e}){const t=g.useRef(e),[n,a]=g.useState(e);return g.useEffect(()=>{const o=t.current;if(t.current=e,!e){a("");return}if(o||window.matchMedia("(prefers-reduced-motion: reduce)").matches){a(e);return}const i=Array.from(e);let s=0;a("");const l=window.setInterval(()=>{s+=1,a(i.slice(0,s).join("")),s>=i.length&&window.clearInterval(l)},t6);return()=>window.clearInterval(l)},[e]),x.jsx("span",{className:"sidebar-task-title-text","aria-label":e||"New task",children:n||"New task"})}const a6=2650,o6=304,r6=260,i6=new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric"}),s6=new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit"}),l6=new Intl.DateTimeFormat("en-US",{dateStyle:"medium",timeStyle:"short"});function c6(){return{animationDelay:`${-(Date.now()%a6)}ms`}}function d6(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 e0({label:e,actions:t,actionsVisible:n=!1,className:a,titleAccessory:o,children:i,collapsed:s=!1,titleActive:l=!1,onTitleClick:m,onToggleCollapsed:d}){return x.jsxs("section",{className:["sidebar-section",a,n?"actions-visible":""].filter(Boolean).join(" "),children:[x.jsxs("div",{className:"section-header",children:[x.jsxs("div",{className:"section-title-row",children:[m?x.jsxs("div",{className:"section-title-combo",children:[x.jsx("button",{type:"button",className:`section-title-link${l?" active":""}`,onClick:m,children:x.jsx("span",{children:e})}),d&&x.jsx("button",{type:"button",className:"section-chevron-button","aria-label":`${s?"Expand":"Collapse"} ${e}`,"aria-expanded":!s,onClick:d,children:s?x.jsx(Wr,{size:13}):x.jsx(Go,{size:13})})]}):d?x.jsxs("button",{type:"button",className:"section-title-button","aria-label":`${s?"Expand":"Collapse"} ${e}`,"aria-expanded":!s,onClick:d,children:[x.jsx("span",{children:e}),s?x.jsx(Wr,{size:13}):x.jsx(Go,{size:13})]}):x.jsx("span",{children:e}),o]}),t&&x.jsx("div",{className:"section-actions",children:t})]}),!s&&x.jsx("div",{className:"sidebar-section-body",children:i})]})}function t0({children:e,expanded:t=!1,onClick:n}){return x.jsx("button",{type:"button",className:"sidebar-show-more",onClick:n,children:e??(t?"Show less":"Show more")})}function qp({session:e,selected:t,icon:n,archived:a=!1,hideIcon:o=!1,nested:i=!1,dragging:s,placeholder:l,running:m,goalRuntime:d,subagentRuntime:h,terminalIndicator:v,projectLabel:y,ariaDescribedBy:w,childSessionCount:I=0,childSessionsExpanded:R=!1,onSelect:M,onToggleChildSessions:P,onTogglePin:N,onToggleSaveForLater:O,onDockRight:j,onArchive:k,onDragStart:C,onDragEnd:T,onDragOver:z,onDrop:B,onRename:D}){const[V,le]=g.useState(!1),te=d?.status==="queued",Ie=d?.tone==="active"&&!te,ke=(h?.activeCount??0)>0,Z=I>0&&!!P,Ae=o&&!Z,he=ke||Ie||!te&&(m??e.status==="active"),ue=ke&&h?h.label:Ie&&d?m6(d):"Running",be=["sidebar-task-row",Fl(e)?"is-draft":"",he?"has-running-dot":""].filter(Boolean).join(" "),ne=g.useMemo(c6,[]),ge=x.jsx(X3,{title:e.title,pinned:!!e.pinned,savedForLater:!!e.savedForLater,archived:a,onRename:D?()=>le(!0):void 0,onTogglePin:N,onToggleSaveForLater:O,onDockRight:j,onArchive:k}),xe=x.jsxs(hv,{selected:t,dataSessionId:e.id,dragging:s,iconless:Ae,nested:i,placeholder:l,className:be||void 0,ariaExpanded:Z?R:void 0,ariaDescribedBy:w,onSelect:M,onDragStart:C,onDragEnd:T,onDragOver:z,onDrop:B,onDoubleClick:D?()=>le(!0):void 0,children:[Ae?null:Z?x.jsx("button",{type:"button",className:"sidebar-child-toggle","data-tooltip":R?"Hide subagent conversations":"Show subagent conversations","aria-label":`${R?"Hide":"Show"} ${I} subagent ${I===1?"conversation":"conversations"}`,"aria-expanded":R,onClick:Se=>{Se.stopPropagation(),P?.()},children:R?x.jsx(Go,{size:13}):x.jsx(Wr,{size:13})}):n??x.jsx(ju,{size:15}),x.jsx("span",{className:"row-label-shell",title:y||void 0,children:x.jsx("span",{className:"sidebar-session-title-line",children:x.jsx("span",{className:"row-label sidebar-task-title","data-overflowing":"false",onPointerEnter:d6,children:x.jsx(n6,{title:e.title})})})}),x.jsxs("div",{className:"row-meta",children:[x.jsxs("span",{className:"row-meta-status",children:[v?x.jsx(u_,{indicator:v}):null,he?x.jsx("span",{className:`sidebar-running-dot${ke?" subagent":Ie?" goal":""}`,style:ne,"aria-label":ue}):null]}),ge]})]}),qe=V&&D?x.jsx(e6,{session:e,onSave:Se=>D(e,Se),onClose:()=>le(!1)}):null;return x.jsxs(x.Fragment,{children:[xe,qe]})}function u6({file:e,selected:t=!1,placeholder:n,onSelect:a,onTogglePin:o,onToggleSaveForLater:i,onDragStart:s,onDragEnd:l,onDragOver:m,onDrop:d}){const h=e.path.split("/").at(-1)??e.path,v=`${e.workspaceName} · ${e.path}`;return x.jsxs(hv,{selected:t,placeholder:n,className:`sidebar-file-row actions-2${e.available?"":" unavailable"}`,onSelect:a,onDragStart:s,onDragEnd:l,onDragOver:m,onDrop:d,children:[e.available?x.jsx(Jg,{size:15}):x.jsx(l5,{size:15}),x.jsx("span",{className:"row-label-shell",title:v,children:x.jsx("span",{className:"row-label",children:h})}),x.jsx("div",{className:"row-meta",children:x.jsxs("div",{className:"sidebar-row-actions",children:[x.jsx(qd,{label:e.status==="pinned"?"Unpin file":"Pin file",onClick:o,children:e.status==="pinned"?x.jsx(Qg,{size:13}):x.jsx(Yg,{size:13})}),x.jsx(qd,{label:e.status==="saved_for_later"?"Remove from Save for later":"Save file for later",onClick:i,children:e.status==="saved_for_later"?x.jsx(MI,{size:13}):x.jsx(EI,{size:13})})]})})]})}function m6(e){return e.actionLabel}function p6({kind:e="local",project:t,pinned:n=!1,selected:a,expanded:o=!1,disclosure:i=!0,workspaceState:s,cloudLinkTrusted:l=!0,cloudLinkWarning:m=null,placeholder:d,terminalIndicator:h,onSelect:v,onNewChat:y,onMoveToCloud:w,onWorkspaceTargetSelect:I,onTogglePin:R,onRemove:M,onDragStart:P,onDragEnd:N,onDragOver:O,onDrop:j}){const[k,C]=g.useState(!1),T=g.useRef(null),[z,B]=g.useState({}),D=!!w||!!M,V=e==="local"&&l!==!1&&!!t.linkedSandboxProject?.projectId,le=g.useCallback(()=>{if(typeof window>"u")return;const ke=T.current?.getBoundingClientRect();if(!ke)return;const Z=Math.max(12,window.innerWidth-o6-12),Ae=Math.max(12,window.innerHeight-r6),he=Math.max(12,Math.min(ke.right+10,Z)),ue=Math.max(12,Math.min(ke.top-4,Ae)),be={"--sidebar-project-locations-left":`${Math.round(he)}px`,"--sidebar-project-locations-top":`${Math.round(ue)}px`};B(ne=>ne["--sidebar-project-locations-left"]===be["--sidebar-project-locations-left"]&&ne["--sidebar-project-locations-top"]===be["--sidebar-project-locations-top"]?ne:be)},[]),te=g.useCallback(()=>{le(),v()},[v,le]);function Ie(){C(!1)}return x.jsxs("div",{ref:T,className:["sidebar-project-row-shell",k?"project-menu-open":""].filter(Boolean).join(" "),onFocusCapture:le,onPointerEnter:le,children:[x.jsxs(hv,{selected:a,placeholder:d,className:["sidebar-project-row",k?"project-menu-open":""].filter(Boolean).join(" "),ariaExpanded:i?o:void 0,onSelect:te,onDragStart:P,onDragEnd:N,onDragOver:O,onDrop:j,children:[x.jsx(d_,{kind:e,linkedCloud:V,open:e==="local"&&o,className:"sidebar-row-icon",baseSize:15}),x.jsx("span",{className:"row-label-shell",children:x.jsxs("span",{className:"sidebar-project-title-line",children:[x.jsx("span",{className:"row-label",children:t.name}),x.jsx(f6,{value:t.updatedAt}),i?x.jsx("span",{className:"sidebar-project-caret","aria-hidden":"true",children:o?x.jsx(Go,{size:13}):x.jsx(Wr,{size:13})}):null]})}),x.jsxs("div",{className:"row-meta",children:[x.jsx("span",{className:"row-meta-status",children:h?x.jsx(u_,{indicator:h}):null}),x.jsxs("div",{className:"sidebar-row-actions",children:[x.jsx(qd,{label:n?"Unpin project":"Pin project",onClick:R,children:n?x.jsx(Qg,{size:13}):x.jsx(Yg,{size:13})}),D&&x.jsx(P6,{open:k,onToggleOpen:()=>C(ke=>!ke)}),x.jsx(qd,{label:"New task",onClick:y,children:x.jsx($u,{size:13})})]})]})]}),x.jsx(g6,{kind:e,project:t,workspaceState:s,cloudLinkTrusted:l,cloudLinkWarning:m,onWorkspaceTargetSelect:I,style:z}),k&&x.jsx(A6,{onClose:Ie,onMoveToCloud:w?()=>{Ie(),w()}:void 0,onRemove:()=>{Ie(),M()}})]})}function f6({value:e}){const t=h6(e);if(!t||!e)return null;const n=new Date(e);return x.jsx("time",{className:"sidebar-row-updated-at",dateTime:e,title:`Last updated ${l6.format(n)}`,children:t})}function h6(e,t=new Date){if(!e)return null;const n=new Date(e);if(Number.isNaN(n.getTime()))return null;const a=s6.format(n);return n.getFullYear()===t.getFullYear()&&n.getMonth()===t.getMonth()&&n.getDate()===t.getDate()?a:`${i6.format(n)} ${a}`}function u_({indicator:e}){return x.jsx("span",{className:`sidebar-terminal-indicator ${e.status}`,"data-tooltip":e.label,"aria-label":e.label,title:e.label,children:x.jsx(UI,{size:13})})}function g6({kind:e,project:t,workspaceState:n,cloudLinkTrusted:a,cloudLinkWarning:o,onWorkspaceTargetSelect:i,style:s}){const l=y6(e,t,n,a,o);return x.jsxs("aside",{className:"sidebar-project-locations-popover","aria-label":`${t.name} status`,style:s,children:[x.jsx("div",{className:"sidebar-project-locations-title",children:t.name}),x.jsx("div",{className:"sidebar-project-location-list",children:l.map(m=>{const d=["sidebar-project-location-row",m.tone??"",m.actionTarget?"clickable":""].filter(Boolean).join(" "),h=x.jsxs(x.Fragment,{children:[x.jsx("span",{className:["sidebar-project-location-icon",m.key].filter(Boolean).join(" "),"aria-hidden":"true",children:m.icon}),x.jsx("span",{className:"sidebar-project-location-copy",children:x.jsx(v6,{value:m.value})})]});return m.actionTarget?x.jsx("button",{type:"button",className:d,"data-workspace-target":m.actionTarget,disabled:m.disabled||!i,title:m.disabledReason??void 0,onClick:v=>{v.stopPropagation(),!m.disabled&&i?.(m.actionTarget)},children:h},m.key):x.jsx("div",{className:d,children:h},m.key)})})]})}function v6({value:e}){const t=b6(e);return x.jsxs("span",{className:"sidebar-project-location-value","aria-label":e,children:[t.branch?x.jsxs(x.Fragment,{children:[x.jsx("span",{className:"sidebar-project-location-branch",children:t.branch}),x.jsx("span",{className:"sidebar-project-location-separator","aria-hidden":"true",children:"/"})]}):null,x.jsx("span",{className:"sidebar-project-location-status",children:t.status})]})}function b6(e){const n=e.indexOf(" / ");return n===-1?{branch:null,status:e}:{branch:e.slice(0,n),status:e.slice(n+3)}}function y6(e,t,n,a=!0,o=null){return e==="cloud"?k6(t):S6(t,n,a,o)}function S6(e,t,n=!0,a=null){const o=x6(e,t,n),i=w6(t),s=_6(e,n),l=n===!1&&a;return[{key:"local",value:o,tone:i?"attention":"local",icon:e.source==="git"?x.jsx($I,{size:13}):x.jsx(OI,{size:13}),actionTarget:"local"},{key:"cloud",value:l||(s?C6(e,t,n):"not in cloud"),tone:l?"attention":"cloud",icon:x.jsx(Mu,{size:13}),actionTarget:s?"cloud":"upload_cloud"}]}function k6(e){return[{key:"cloud",value:R6(e),tone:e.syncedAt?"cloud":"attention",icon:x.jsx(Mu,{size:13}),actionTarget:"cloud"}]}function x6(e,t,n){const a=I6(e,t);return t?t.error?`${a} / status unavailable`:t.initialized?s_(t,{branch:e.linkedSandboxProject?.defaultBranch??null,linkedCloudSourceKnown:e.linkedSandboxProject?.projectId&&n?!!e.linkedSandboxProject.lastUploadedCommit||!t.headCommit:!0}):`${a} / not checked out`:`${a} / available`}function w6(e){return!!(e?.dirty||(e?.changedFilesCount??0)>0||(e?.untrackedFilesCount??0)>0)}function I6(e,t){return t?.currentBranch??t?.defaultBranch??e.linkedSandboxProject?.defaultBranch??"local"}function _6(e,t=!0){return!!(t&&e.linkedSandboxProject?.projectId||e.linkedOpenPondApp?.appId)}function C6(e,t,n){return l_(e,null,t,{cloudLinkTrusted:n})}function R6(e){const t=e.defaultBranch??"main",n=e.syncedAt?"setup ready":"needs setup";return`${t} / ${n}`}function P6({open:e,onToggleOpen:t}){return x.jsx("button",{type:"button",className:`sidebar-row-action ${e?"active":""}`,"data-tooltip":"More project actions","aria-label":"More project actions","aria-haspopup":"menu","aria-expanded":e,onClick:n=>{n.stopPropagation(),t()},children:x.jsx(Ou,{size:13})})}function A6({onClose:e,onMoveToCloud:t,onRemove:n}){return x.jsxs(x.Fragment,{children:[x.jsx("button",{type:"button",className:"sidebar-project-menu-backdrop","aria-label":"Close project actions",onClick:a=>{a.stopPropagation(),e()}}),x.jsxs("div",{className:"section-menu-popover sidebar-project-row-popover",role:"menu",children:[t&&x.jsxs("button",{type:"button",role:"menuitem",onClick:a=>{a.stopPropagation(),t()},children:[x.jsx(G3,{size:13}),x.jsx("span",{children:"Move to Cloud"})]}),x.jsxs("button",{type:"button",role:"menuitem",onClick:a=>{a.stopPropagation(),n()},children:[x.jsx(Ss,{size:13}),x.jsx("span",{children:"Remove from Projects"})]})]})]})}function hv({children:e,className:t,dataSessionId:n,dragging:a,iconless:o=!1,nested:i=!1,placeholder:s=!1,selected:l,ariaExpanded:m,ariaDescribedBy:d,onSelect:h,onDragStart:v,onDragEnd:y,onDragOver:w,onDrop:I,onDoubleClick:R}){const M=!!v;return x.jsx("div",{className:["sidebar-row",t??"",l?"selected":"",a?"dragging":"",o?"iconless":"",i?"nested":"",s?"placeholder":""].filter(Boolean).join(" "),draggable:M,"data-session-id":n,role:"button",tabIndex:0,"aria-expanded":m,"aria-describedby":d,onClick:h,onDoubleClick:R,onKeyDown:P=>{P.target===P.currentTarget&&(P.key==="Enter"||P.key===" ")&&(P.preventDefault(),h())},onDragStart:v,onDragEnd:y,onDragEnter:P=>{w&&(P.preventDefault(),P.dataTransfer.dropEffect="move",w(P))},onDragOver:P=>{w&&(P.preventDefault(),P.dataTransfer.dropEffect="move",w(P))},onDrop:P=>{I&&(P.preventDefault(),I(P))},children:e})}function qd({children:e,label:t,onClick:n}){return x.jsx("button",{type:"button",className:"sidebar-row-action","data-tooltip":t,"aria-label":t,onClick:a=>{a.stopPropagation(),n()},children:e})}function T6({filter:e,groupByProject:t,noun:n,onFilterChange:a,onGroupByProjectChange:o,onOnlyRunningTasksChange:i,onShowCodexChatsChange:s,onTasksetChange:l,onSortChange:m,onlyRunningTasks:d,openMenu:h,setOpenMenu:v,showCodexChats:y,sort:w,selectedTasksetId:I,tasksets:R}){const M=g.useRef(null),[P,N]=g.useState(!1),j=R.find(T=>T.id===I)?.name??Wy.find(T=>T.value===e)?.label??"Active",k=h==="tasks-filter",C=h==="chats";return g.useEffect(()=>{if(!k&&!C)return;function T(z){M.current?.contains(z.target)||v(null)}return document.addEventListener("pointerdown",T),()=>document.removeEventListener("pointerdown",T)},[k,v,C]),x.jsxs("div",{className:"sidebar-task-list-controls",ref:M,children:[x.jsxs("div",{className:"section-menu",children:[x.jsx("button",{type:"button",className:`section-icon ${C?"active":""}`,"aria-label":`${n==="tasks"?"Task":"Chat"} list options`,"aria-haspopup":"menu","aria-expanded":C,onClick:()=>v(T=>T==="chats"?null:"chats"),children:x.jsx(Ou,{size:14})}),C?x.jsxs("div",{className:"section-menu-popover",role:"menu","aria-label":`${n==="tasks"?"Task":"Chat"} list options`,children:[x.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":y,onClick:()=>s(!y),children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:y?x.jsx(Eo,{size:13}):null}),x.jsx("span",{children:"Show Codex chats"})]}),x.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":d,onClick:()=>i(!d),children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:d?x.jsx(Eo,{size:13}):null}),x.jsx("span",{children:"Only running tasks"})]}),n==="tasks"?x.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":t,onClick:()=>o(!t),children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:t?x.jsx(Eo,{size:13}):null}),x.jsx("span",{children:"Group by project"})]}):null,O3.map(T=>x.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":w===T.value,onClick:()=>{m(T.value),v(null)},children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:w===T.value?x.jsx(Eo,{size:13}):null}),x.jsx("span",{children:T.label})]},T.value))]}):null]}),x.jsxs("div",{className:"section-menu",children:[x.jsx("button",{type:"button",className:`section-icon ${k?"active":""}`,"aria-label":`Filter ${n}: ${j}`,"aria-haspopup":"menu","aria-expanded":k,onClick:()=>v(T=>T==="tasks-filter"?null:"tasks-filter"),children:x.jsx(P5,{size:14})}),k?x.jsx("div",{className:"section-menu-popover",role:"menu","aria-label":`Filter ${n}`,children:Wy.map(T=>x.jsxs(g.Fragment,{children:[T.value==="tasksets"?x.jsxs("button",{type:"button",role:"menuitem","aria-expanded":P,onClick:()=>N(z=>!z),children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:P?x.jsx(Go,{size:13}):x.jsx(Wr,{size:13})}),x.jsx("span",{children:T.label})]}):x.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":e===T.value,onClick:()=>{a(T.value),v(null)},children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e===T.value?x.jsx(Eo,{size:13}):null}),x.jsx("span",{children:T.label})]}),T.value==="tasksets"&&P?x.jsxs(x.Fragment,{children:[x.jsxs("button",{className:"section-menu-taskset-option",type:"button",role:"menuitemradio","aria-checked":e==="tasksets"&&!I,onClick:()=>{l(null),v(null)},children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&!I?x.jsx(Eo,{size:13}):null}),x.jsx("span",{children:"All Tasksets"})]}),R.map(z=>x.jsxs("button",{className:"section-menu-taskset-option",type:"button",role:"menuitemradio","aria-checked":e==="tasksets"&&I===z.id,onClick:()=>{l(z.id),v(null)},children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&I===z.id?x.jsx(Eo,{size:13}):null}),x.jsx("span",{children:z.name}),x.jsx("span",{className:"section-menu-option-count","aria-hidden":"true",children:z.chatCount})]},z.id))]}):null]},T.value))}):null]})]})}const E6=240,M6=36;function j6(e,t,n=!1){const a=Math.max(12,t.width-E6-12),o=Math.max(12,t.height-M6-(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 O6({detail:e,onClose:t}){if(g.useEffect(()=>{if(!e||typeof window>"u")return;const o=l=>{l.key==="Escape"&&t()};let i=!1;const s=window.requestAnimationFrame(()=>{window.addEventListener("scroll",t,!0),i=!0});return window.addEventListener("keydown",o),()=>{window.cancelAnimationFrame(s),window.removeEventListener("keydown",o),i&&window.removeEventListener("scroll",t,!0)}},[e,t]),!e)return null;const n=new Date(e.updatedAt),a=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(n);return x.jsxs("aside",{id:e.descriptionId,className:"sidebar-task-detail-popover",style:e.style,role:"tooltip","aria-label":`Last updated for ${e.title}`,children:[x.jsx("time",{dateTime:e.updatedAt,children:a}),e.folderName?x.jsxs("div",{className:"sidebar-task-detail-folder",children:[x.jsx(OI,{size:13,"aria-hidden":"true"}),x.jsx("span",{children:e.folderName})]}):null]})}function $6({children:e,expanded:t,groupKey:n,kind:a,label:o,onToggle:i,onNewTask:s,onOpenProject:l,onRemoveProject:m,project:d}){const h=`sidebar-task-group-${n.replace(/[^a-zA-Z0-9_-]/g,"-")}`,v=a==="draft"?Jg:ju,[y,w]=g.useState(!1),I=!!(s||l||m);return x.jsxs("section",{className:"sidebar-task-project-group",children:[x.jsxs("div",{className:`sidebar-task-project-group-header-shell${y?" menu-open":""}`,children:[x.jsxs("button",{type:"button",className:"sidebar-task-project-group-header","aria-controls":h,"aria-expanded":t,onClick:()=>{w(!1),i()},children:[d?x.jsx(d_,{kind:d.kind,linkedCloud:!!(d.kind==="local"&&d.project.linkedSandboxProject?.projectId),open:d.kind==="local"&&t,className:"sidebar-task-project-group-icon",baseSize:14}):x.jsx(v,{className:"sidebar-task-project-group-icon",size:14,"aria-hidden":"true"}),x.jsx("span",{className:"sidebar-task-project-group-name",children:o}),x.jsx("span",{className:"sidebar-task-project-group-caret","aria-hidden":"true",children:t?x.jsx(Go,{size:13}):x.jsx(Wr,{size:13})})]}),d&&I?x.jsxs("div",{className:"sidebar-task-project-group-actions",children:[l||m?x.jsx("button",{type:"button",className:`sidebar-row-action${y?" active":""}`,"data-tooltip":"More project actions","aria-label":"More project actions","aria-expanded":y,"aria-haspopup":"menu",onClick:()=>w(R=>!R),children:x.jsx(Ou,{size:13})}):null,s?x.jsx("button",{type:"button",className:"sidebar-row-action","data-tooltip":"New task","aria-label":"New task",onClick:s,children:x.jsx($u,{size:13})}):null]}):null,y?x.jsxs(x.Fragment,{children:[x.jsx("button",{type:"button",className:"sidebar-task-project-group-menu-backdrop","aria-label":"Close project actions",onClick:()=>w(!1)}),x.jsxs("div",{className:"section-menu-popover sidebar-task-project-group-menu",role:"menu",children:[l?x.jsx("button",{type:"button",role:"menuitem",onClick:()=>{w(!1),l()},children:x.jsx("span",{children:"Open project"})}):null,m?x.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{w(!1),m()},children:[x.jsx(Ss,{size:13}),x.jsx("span",{children:"Remove from Projects"})]}):null]})]}):null]}),t?x.jsx("div",{id:h,className:"sidebar-task-project-group-content",children:e}):null]})}const N6={},D6=new Map,L6=new Map;function U6(e,t){return Math.min(Math.max(e,Pn)+Qf,t)}function z6(e,t){const n=Math.max(Pn,Math.min(e,t));if(n<=Pn)return Pn;const a=Math.ceil((n-Pn)/Qf);return Math.max(Pn,Pn+(a-1)*Qf)}function H6(e,t){const n=new Map;for(const a of e){const o=t(a),i=n.get(o.key);i?i.sessions.push(a):n.set(o.key,{...o,sessions:[a]})}return[...n.values()]}function q6({activeSessions:e,archiveSession:t,archivedSessions:n,chatRowsVisibleCount:a,childSessionRowsByParentId:o={},cloudProjectRows:i,beginProjectChat:s,commitTaskDrop:l,commitTaskPreviewDrop:m,dockSessionRight:d,experience:h="work",goalRuntimeBySessionId:v=D6,localProjectRows:y,openSidebarFile:w,pinnedCollapsed:I,pinnedRows:R,previewTaskDrop:M,previewPinnedDrop:P,projectRows:N,renameSession:O,restoreSession:j,runningSessionIds:k,savedForLaterSessions:C,sectionMenuOpen:T,selectedProjectId:z,selectedSessionId:B,setChatRowsVisibleCount:D,setSectionMenuOpen:V,setSelectedAppId:le,setSelectedProjectId:te,setSelectedSessionId:Ie,setView:ke,sidebarProjectIdBySessionId:Z,startTaskDrag:Ae,startPinnedDrag:he,subagentRuntimeBySessionId:ue=L6,taskDragSessionId:be,taskPreviewSessionIds:ne,terminalSummaries:ge=N6,toggleSessionPinned:xe,toggleSessionSavedForLater:qe,view:Se,clearTaskDrag:se,removeProject:we,toggleProjectPinned:Oe,onTogglePinnedCollapsed:Qe,setSidebarFileStatus:Ge,commitPinnedDrop:st,commitPinnedPreviewDrop:Le,clearSidebarDrag:Fe,dragItem:De}){const[L,$]=g.useState("active"),[H,Q]=g.useState("recent"),[me,_e]=g.useState(h!=="chat"),[$e,Xe]=g.useState(Qy);pc(()=>Xe(Qy()));const{onlyRunningTasks:et,showCodexChats:rt}=$e,[it,Me]=g.useState(null),[Be,p]=g.useState(()=>new Set),[U,K]=g.useState(()=>new Map),[de,re]=g.useState(null),F=h==="chat"?"chats":"tasks",_=h==="chat"?"Chats":"Tasks",W=N??[...y,...i],X=g.useMemo(()=>new Map(W.map(ae=>[ae.id,ae.project.name])),[W]),oe=g.useMemo(()=>new Map(W.map(ae=>[ae.id,ae])),[W]),G=g.useMemo(()=>{const ae=new Set(k);for(const Ke of e){const ze=v.get(Ke.id),Ze=ue.get(Ke.id);(ze?.tone==="active"&&ze.status!=="queued"||(Ze?.activeCount??0)>0||yt(Ke.id)?.status==="running")&&ae.add(Ke.id)}return ae},[e,v,k,ue,ge]),pe=g.useMemo(()=>e.filter(ae=>cr(ae)===null&&Ti(ae,{inProgressSessionIds:G,onlyRunningTasks:et,showCodexChats:rt})),[e,G,et,rt]),fe=g.useMemo(()=>C.filter(ae=>cr(ae)===null&&Ti(ae,{inProgressSessionIds:G,onlyRunningTasks:et,showCodexChats:rt})),[G,et,C,rt]),je=Math.max(0,pe.length-fe.length),Ee=$3({activeCount:je,filter:L,savedForLaterCount:fe.length}),Ne=g.useMemo(()=>Gy({activeSessions:e,doneSessions:n,filter:"all",inProgressSessionIds:G,sort:"manual"}),[e,n,G]),Ve=g.useMemo(()=>Gy({activeSessions:e,doneSessions:n,filter:L,inProgressSessionIds:G,onlyRunningTasks:et,selectedTasksetId:it,previewSessionIds:ne,showCodexChats:rt,sort:H}),[e,n,G,et,it,rt,L,ne,H]),Ue=g.useMemo(()=>{const ae=new Map;for(const Ke of[...e,...n]){if(!Ti(Ke,{inProgressSessionIds:G,onlyRunningTasks:et,showCodexChats:rt}))continue;const ze=cr(Ke);if(!ze)continue;const Ze=ae.get(ze.id);Ze?Ze.chatCount+=1:ae.set(ze.id,{...ze,chatCount:1})}return[...ae.values()].sort((Ke,ze)=>Ke.name.localeCompare(ze.name))},[e,n,G,et,rt]),ut=g.useMemo(()=>R.filter(ae=>ae.type!=="session"||Ti(ae.session,{inProgressSessionIds:G,onlyRunningTasks:et,showCodexChats:rt})),[G,et,R,rt]),Qt=g.useMemo(()=>Ve.filter(ae=>!Cl(ae)).slice(0,Math.max(Pn,a)),[a,Ve]),zt=g.useMemo(()=>H6(Qt,ae=>{if(Fl(ae))return{key:"draft",label:"Drafts",projectId:null,project:null,kind:"draft"};const Ke=Z[ae.id],ze=ln(ae)??"No project";return{key:Ke?`project:${Ke}`:`projectless:${ze}`,label:ze,projectId:Ke??null,project:Ke?oe.get(Ke)??null:null,kind:Ke?"project":"projectless"}}),[X,oe,Z,Qt]),Mn=Qt.length<Ve.length,xn=Qt.length>Pn,nn=g.useMemo(()=>new Set(zt.filter(ae=>ae.sessions.some(Ke=>Ke.id===B||G.has(Ke.id))).map(ae=>ae.key)),[zt,G,B]),bt=Ne.filter(ae=>!Cl(ae)).map(ae=>ae.id),sn=Qt.map(ae=>ae.id),Lt=JSON.stringify(Object.entries(o).filter(([ae,Ke])=>Ke.length>0&&(ue.get(ae)?.activeCount??0)>0).flatMap(([ae,Ke])=>Ke.map(ze=>[ae,ze.id])).sort(([ae,Ke],[ze,Ze])=>ae.localeCompare(ze)||Ke.localeCompare(Ze)));g.useEffect(()=>{const ae=JSON.parse(Lt);if(ae.length===0)return;const Ke=new Set(ae.map(([ze])=>ze));p(ze=>[...Ke].every(Ze=>ze.has(Ze))?ze:new Set([...ze,...Ke]))},[Lt]);function yt(ae){return B3(ge[i_({kind:"session",id:ae})])}function ln(ae){if(Fl(ae))return"Draft";const Ke=Z[ae.id];return Ke?X.get(Ke)??ae.workspaceName??"Project":P3(ae)}function Ht(ae){cn({kind:"chat",sessionId:ae.id}),Ie(ae.id);const Ke=Z[ae.id]??null;le(Ke?null:ae.appId),te(Ke),ke("chat")}function pn(ae){return(o[ae.id]??[]).filter(Ke=>Ti(Ke,{inProgressSessionIds:G,onlyRunningTasks:et,showCodexChats:rt}))}function Ln(ae,Ke){return Be.has(ae.id)||Ke.some(ze=>ze.id===B)}function vn(ae){p(Ke=>{const ze=new Set(Ke);return ze.has(ae)?ze.delete(ae):ze.add(ae),ze})}function Ba(ae){const Ke=pn(ae);return Ke.length===0||!Ln(ae,Ke)?null:x.jsx("div",{className:"sidebar-child-session-group",children:Ke.map(ze=>x.jsx(qp,{session:ze,selected:Se==="chat"&&B===ze.id,hideIcon:!0,nested:!0,running:G.has(ze.id),goalRuntime:v.get(ze.id)??null,subagentRuntime:ue.get(ze.id)??null,terminalIndicator:yt(ze.id),projectLabel:ln(ae),onSelect:()=>Ht(ze),onTogglePin:()=>xe(ze),onToggleSaveForLater:()=>qe(ze),onDockRight:()=>d(ze),onArchive:()=>ze.archived?j(ze):t(ze),onRename:O},ze.id))})}function ua(ae,Ke){if(typeof window>"u")return;const ze=Cl(ae)?ln(ae):null;re({descriptionId:`sidebar-task-detail-${ae.id}`,sessionId:ae.id,title:ae.title,updatedAt:ae.updatedAt,folderName:ze,style:j6(Ke.getBoundingClientRect(),{width:window.innerWidth,height:window.innerHeight},!!ze)})}function Bt(ae,Ke={}){const ze=ae.archived,Ze=be===ae.id,kt=pn(ae),gt="sidebar-session-group",lt=H==="manual"?{onDragStart:Ct=>Ae(Ct,{allSessionIds:bt,visibleSessionIds:sn,sessionId:ae.id}),onDragEnd:se,onDragOver:Ct=>{Ze||M(Ct,ae.id)},onDrop:Ct=>{Ze?m():l(Ct,ae.id)}}:{};return x.jsxs("div",{className:gt,onPointerEnter:Ct=>ua(ae,Ct.currentTarget),onPointerLeave:()=>re(null),onFocusCapture:Ct=>ua(ae,Ct.currentTarget),onBlurCapture:Ct=>{Ct.currentTarget.contains(Ct.relatedTarget)||re(null)},children:[x.jsx(qp,{session:ae,selected:!ze&&Se==="chat"&&B===ae.id,archived:ze,hideIcon:!0,placeholder:Ze,running:G.has(ae.id),goalRuntime:v.get(ae.id)??null,subagentRuntime:ue.get(ae.id)??null,terminalIndicator:yt(ae.id),projectLabel:Ke.projectLabel===void 0?ln(ae):Ke.projectLabel,metadataPresentation:Ke.metadataPresentation,ariaDescribedBy:de?.sessionId===ae.id?de.descriptionId:void 0,childSessionCount:kt.length,childSessionsExpanded:Ln(ae,kt),onToggleChildSessions:()=>vn(ae.id),onSelect:()=>{re(null),ze&&j(ae),Ht(ae)},onTogglePin:()=>xe(ae),onToggleSaveForLater:()=>qe(ae),onDockRight:()=>d(ae),onArchive:()=>ze?j(ae):t(ae),onRename:O,...lt}),Ze?null:Ba(ae)]},ae.id)}function Kn(ae){ae!=="tasksets"&&Me(null),$(ae),D(Pn)}function ot(ae){Me(ae),$("tasksets"),D(Pn)}function wn(ae){Q(ae),D(Pn)}function Fa(){D(ae=>U6(ae,Ve.length))}function Va(){D(ae=>z6(ae,Ve.length))}function ma(ae){const Ke={id:ae.id,type:ae.type};return{onDragStart:ze=>he(ze,Ke),onDragEnd:Fe,onDragOver:ze=>P(ze,Ke),onDrop:ze=>{De?.id===ae.id&&De.type===ae.type?Le():st(ze,Ke)}}}function Ka(ae){const Ke=ma(ae),ze=De?.id===ae.id&&De.type===ae.type;if(ae.type==="project"){const kt=ae.item;return x.jsx(p6,{kind:kt.kind,project:kt.project,pinned:!0,selected:Se==="chat"&&z===kt.id,expanded:!1,disclosure:!1,placeholder:ze,onSelect:()=>{le(null),te(kt.id),Ie(null),ke("chat")},onNewChat:()=>s(kt.id),onTogglePin:()=>Oe(kt),onRemove:()=>we(kt),...Ke},ae.key)}if(ae.type==="file")return x.jsx(u6,{file:ae.file,placeholder:ze,onSelect:()=>w(ae.file),onTogglePin:()=>Ge(ae.file,"none"),onToggleSaveForLater:()=>Ge(ae.file,"saved_for_later"),...Ke},ae.key);const Ze=ae.session;return x.jsx("div",{onPointerEnter:kt=>ua(Ze,kt.currentTarget),onPointerLeave:()=>re(null),onFocusCapture:kt=>ua(Ze,kt.currentTarget),onBlurCapture:kt=>{kt.currentTarget.contains(kt.relatedTarget)||re(null)},children:x.jsx(qp,{ariaDescribedBy:de?.sessionId===Ze.id?de.descriptionId:void 0,session:Ze,selected:Se==="chat"&&B===Ze.id,hideIcon:!0,placeholder:ze,running:G.has(Ze.id),goalRuntime:v.get(Ze.id)??null,subagentRuntime:ue.get(Ze.id)??null,terminalIndicator:yt(Ze.id),projectLabel:ln(Ze),metadataPresentation:"flyout",onSelect:()=>{re(null),Ht(Ze)},onTogglePin:()=>xe(Ze),onToggleSaveForLater:()=>qe(Ze),onDockRight:()=>d(Ze),onArchive:()=>t(Ze),onRename:O,...Ke})},ae.key)}return x.jsxs("div",{className:"sidebar-scroll",children:[x.jsxs(e0,{label:_,className:`sidebar-task-section${h!=="chat"?" development":""}`,titleAccessory:h!=="chat"?x.jsx("div",{className:"sidebar-task-mode-buttons",children:x.jsxs("button",{type:"button",className:`section-icon sidebar-task-count-bubble${L==="saved_for_later"?" active":""}`,"aria-label":`Show ${Ee.count} ${Ee.targetLabel} ${Ee.count===1?"task":"tasks"}`,onClick:()=>Kn(Ee.targetFilter),children:[x.jsx("span",{children:Ee.label}),x.jsx("span",{className:"sidebar-task-count-badge","aria-hidden":"true",children:Ee.count>99?"99+":Ee.count})]})}):null,actionsVisible:T==="chats"||T==="tasks-filter",actions:x.jsx(T6,{filter:L,groupByProject:me,noun:F,onFilterChange:Kn,onGroupByProjectChange:_e,onOnlyRunningTasksChange:ae=>{Xe(Ke=>{const ze={...Ke,onlyRunningTasks:ae};return Xy(ze),ze}),D(Pn)},onShowCodexChatsChange:ae=>{Xe(Ke=>{const ze={...Ke,showCodexChats:ae};return Xy(ze),ze}),D(Pn)},onTasksetChange:ot,onSortChange:wn,onlyRunningTasks:et,openMenu:T,setOpenMenu:V,showCodexChats:rt,sort:H,selectedTasksetId:it,tasksets:Ue}),children:[ut.length>0?x.jsx(e0,{label:"Pinned",className:"sidebar-pinned-section",collapsed:I,onToggleCollapsed:Qe,children:ut.map(Ka)}):null,me&&h!=="chat"?zt.map(ae=>{const Ke=nn.has(ae.key)||U.get(ae.key)!==!1;return x.jsx($6,{expanded:Ke,groupKey:ae.key,kind:ae.kind,label:ae.label,onToggle:()=>{K(ze=>{const Ze=new Map(ze);return Ze.set(ae.key,!Ke),Ze})},onNewTask:ae.project?()=>s(ae.project.id):void 0,onOpenProject:ae.project?()=>{le(null),te(ae.project.id),Ie(null),ke("chat")}:void 0,onRemoveProject:ae.project?()=>we(ae.project):void 0,project:ae.project,children:ae.sessions.map(ze=>Bt(ze,{metadataPresentation:"flyout",projectLabel:ae.label}))},ae.key)}):Qt.map(ae=>Bt(ae)),Ve.length===0?x.jsx("div",{className:"empty-row",children:N3(L,F)}):null,Ve.length>Pn&&(Mn||xn)?x.jsxs("div",{className:"sidebar-pagination-controls","aria-label":`Showing ${Qt.length} of ${Ve.length} ${F}`,children:[Mn?x.jsx(t0,{onClick:Fa,children:"Show more"}):null,xn?x.jsx(t0,{onClick:Va,children:"Show less"}):null]}):null]}),x.jsx(O6,{detail:de,onClose:()=>re(null)})]})}const B6="/";function ea(e){return`${B6}${e.replace(/^\.?\//,"")}`}const F6=ea("openpond-icon.png"),V6=ea("openpond-wordlogo-white.png"),GY=ea("tutorials/what-is-an-openpond-agent-poster.png"),ZY=ea("tutorials/what-is-an-openpond-agent.vtt"),JY=ea("tutorials/how-to-make-an-agent-poster.png"),YY=ea("tutorials/how-to-make-an-agent.vtt");function QY(e){return ea(`tutorials/how-to-make-an-agent-${e}-poster.png`)}function XY(e){return ea(`tutorials/how-to-make-an-agent-${e}.vtt`)}const n0={github:ea("connected-apps/github.svg"),google:ea("connected-apps/google.svg"),microsoft_teams:ea("connected-apps/microsoft.svg"),mcp:ea("connected-apps/openpond-mcp.svg"),slack:ea("connected-apps/slack.svg"),x:ea("connected-apps/x.svg")};function eQ(e){return n0[e]??n0.mcp}function K6({value:e,onChange:t}){const[n,a]=g.useState(!1),o=g.useRef(null),i=g.useRef(null),s=g.useRef(null),l=g.useRef(null),m=Dp.find(y=>y.value===e)??Dp[0];g.useEffect(()=>{if(!n)return;const y=I=>{I.target instanceof Node&&!o.current?.contains(I.target)&&a(!1)},w=()=>a(!1);return window.addEventListener("pointerdown",y),window.addEventListener("blur",w),()=>{window.removeEventListener("pointerdown",y),window.removeEventListener("blur",w)}},[n]),g.useLayoutEffect(()=>{n&&l.current&&a0(s.current,l.current),l.current=null},[n]);const d=y=>{if(n){a0(s.current,y);return}l.current=y,a(!0)},h=y=>{y.key==="ArrowDown"?(y.preventDefault(),d("first")):y.key==="ArrowUp"&&(y.preventDefault(),d("last"))},v=y=>{const w=m_(s.current),I=w.findIndex(P=>P===document.activeElement);if(y.key==="Escape"){y.preventDefault(),a(!1),i.current?.focus();return}if(y.key==="Home"||y.key==="End"){y.preventDefault(),w[y.key==="Home"?0:w.length-1]?.focus();return}if(y.key!=="ArrowDown"&&y.key!=="ArrowUp")return;y.preventDefault();const R=y.key==="ArrowDown"?1:-1,M=I<0?0:(I+R+w.length)%w.length;w[M]?.focus()};return x.jsxs("div",{className:"sidebar-experience-menu",ref:o,children:[x.jsxs("button",{ref:i,type:"button",className:"sidebar-wordmark-button sidebar-experience-trigger","aria-label":`OpenPond product: ${m.label}`,"aria-haspopup":"menu","aria-expanded":n,onClick:()=>{l.current=null,a(y=>!y)},onKeyDown:h,children:[x.jsx("img",{className:"sidebar-wordmark",src:V6,alt:""}),x.jsx("span",{className:"sidebar-experience-label",children:m.label}),x.jsx(Go,{size:13,"aria-hidden":"true"})]}),n?x.jsx("div",{ref:s,className:"sidebar-experience-popover",role:"menu","aria-label":"Choose product",onKeyDown:v,children:Dp.map(y=>{const w=y.value===e;return x.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":w,className:w?"active":"","data-product-area":y.value,onClick:()=>{a(!1),w||t(y.value)},children:[x.jsxs("span",{children:[x.jsx("strong",{children:y.label}),x.jsx("small",{children:y.description})]}),w?x.jsx(Eo,{size:14,"aria-hidden":"true"}):null]},y.value)})}):null]})}function m_(e){return e?Array.from(e.querySelectorAll('[role="menuitemradio"]')):[]}function a0(e,t){const n=m_(e);(t==="first"?n[0]:n.at(-1))?.focus()}function W6(...e){for(const t of e){const n=t?.trim();if(n)return n}return null}function G6(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"?W6(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 Z6({account:e,open:t,organizations:n,selectedTeamId:a,onOpenActivity:o,onOpenChange:i,onOpenSettings:s,onSelectTeam:l,onLogOut:m}){const[d,h]=g.useState(null),[v,y]=g.useState(!1),w=g.useRef(null),I=g.useMemo(()=>G6(e),[e]),R=I.label.trim().slice(0,1).toUpperCase(),M=n.find(P=>P.teamId===a)??n[0]??null;return g.useEffect(()=>{if(!t)return;function P(O){w.current?.contains(O.target)||i(!1)}function N(O){O.key==="Escape"&&i(!1)}return document.addEventListener("pointerdown",P),document.addEventListener("keydown",N),()=>{document.removeEventListener("pointerdown",P),document.removeEventListener("keydown",N)}},[i,t]),x.jsxs("div",{className:"user-auth-footer",ref:w,children:[x.jsxs("button",{type:"button",className:`user-auth-trigger ${t?"active":""}`,"aria-haspopup":"menu","aria-expanded":t,"aria-label":`${I.label} account menu`,onClick:()=>i(!t),children:[x.jsx("span",{className:"user-auth-avatar","aria-hidden":"true",children:I.image?x.jsx("img",{src:I.image,alt:""}):R?x.jsx("span",{children:R}):x.jsx(zy,{size:16})}),x.jsx("span",{className:"user-auth-name",children:I.label})]}),t?x.jsxs("div",{className:"user-auth-menu",role:"menu","aria-label":"Account",children:[x.jsxs("div",{className:"user-auth-menu-header",children:[x.jsx("span",{className:"user-auth-menu-avatar","aria-hidden":"true",children:I.image?x.jsx("img",{src:I.image,alt:""}):R?x.jsx("span",{children:R}):x.jsx(zy,{size:17})}),x.jsx("span",{className:"user-auth-menu-identity",children:x.jsx("strong",{children:I.label})})]}),n.length>0&&l?x.jsxs("label",{className:"user-auth-team-picker",children:[x.jsx(LI,{size:15,"aria-hidden":"true"}),x.jsx("span",{className:"user-auth-team-picker-label",children:"Team"}),x.jsx("select",{"aria-label":"Active team",disabled:d!==null,value:M?.teamId??"",onChange:async P=>{const N=P.currentTarget.value;h(N);try{await l(N)}catch{}finally{h(null)}},children:n.map(P=>x.jsx("option",{value:P.teamId,children:P.displayName},P.teamId))})]}):null,x.jsx("div",{className:"user-auth-menu-divider"}),o?x.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",onClick:()=>{i(!1),o()},children:[x.jsx(jI,{size:15}),x.jsx("span",{children:"Activity"})]}):null,x.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",onClick:()=>{i(!1),s()},children:[x.jsx(Xg,{size:15}),x.jsx("span",{children:"Settings"})]}),e?.state==="signed_in"&&m?x.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",disabled:v,onClick:async()=>{y(!0);try{await m(),i(!1)}catch{}finally{y(!1)}},children:[x.jsx(q5,{size:15}),x.jsx("span",{children:v?"Logging out…":"Log out"})]}):null]}):null]})}function o0(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 J6(e,t){const n=o0(e),a=o0(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 p_(e){const t=e?.toLowerCase()??"";return t==="darwin"||t.includes("mac")?"mac":t==="linux"||t.includes("linux")?"linux":null}function Y6(e){const t=e?.toLowerCase()??"";return t==="arm64"||t==="aarch64"?"arm64":t==="x64"||t==="x86_64"||t==="amd64"?"x64":null}function Q6(e,t,n){const a=p_(t),o=Y6(n);if(a==="mac"){const i=e.filter(s=>/-mac-.*\.zip$/i.test(s.name));return o==="arm64"?i.find(s=>/-mac-arm64\.zip$/i.test(s.name))??null:o==="x64"?i.find(s=>/-mac-x64\.zip$/i.test(s.name))??i.find(s=>/-mac-universal\.zip$/i.test(s.name))??null:i.find(s=>/-mac-universal\.zip$/i.test(s.name))??i.find(s=>/-mac-arm64\.zip$/i.test(s.name))??i[0]??null}if(a==="linux"){const i=e.filter(s=>/\.AppImage$/i.test(s.name));return o==="arm64"?i.find(s=>/(?:arm64|aarch64).*\.AppImage$/i.test(s.name))??null:o==="x64"?i.find(s=>/(?:x86_64|x64|amd64).*\.AppImage$/i.test(s.name))??i[0]??null:i[0]??null}return null}function X6(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(!J6(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=Q6(s,e.platform,e.arch);return!l||!o?null:{version:a,releaseUrl:o,assetName:l.name,downloadUrl:l.downloadUrl}}const eV=3600*1e3,tV="https://api.github.com/repos/openpond/openpond/releases/latest";function nV(e){const[t,n]=g.useState({status:"idle",update:null,lastCheckedAt:null}),a=e.currentVersion?.trim()??"",o=e.platform??"",i=e.arch??"",s=e.enabled&&!!a&&!!p_(o);return g.useEffect(()=>{if(!s){n({status:"idle",update:null,lastCheckedAt:null});return}let l=!1;async function m(){n(h=>({...h,status:h.update?"available":"checking"}));try{const h=await fetch(tV,{headers:{Accept:"application/vnd.github+json"}});if(!h.ok)throw new Error(`GitHub release check failed: ${h.status}`);const v=await h.json(),y=X6({payload:v,currentVersion:a,platform:o,arch:i});if(l)return;n({status:y?"available":"current",update:y,lastCheckedAt:Date.now()})}catch{if(l)return;n(h=>({status:h.update?"available":"error",update:h.update,lastCheckedAt:Date.now()}))}}m();const d=window.setInterval(()=>{m()},eV);return()=>{l=!0,window.clearInterval(d)}},[i,a,s,o]),t}const f_="openpond.sidebar.continuous-learning.dismissed.v1";function r0(e=h_()){if(!e)return!1;try{return e.getItem(f_)==="true"}catch{return!1}}function aV(e=h_()){if(e)try{e.setItem(f_,"true")}catch{}}function h_(){return typeof window>"u"?null:fc}function oV({connection:e,onOpenSettings:t}){const[n,a]=g.useState(null),[o,i]=g.useState(r0);pc(()=>i(r0()));const s=g.useCallback(async()=>{if(!e){a(null);return}try{a(await J.harnessHistory(e))}catch{a(null)}},[e]);if(g.useEffect(()=>{s()},[s]),o||!e||!n?.workspace)return null;const l=n.evaluationReviewSchedule,m=l.activityEnabled?`${l.activityBatchSize} outcomes${l.enabled?` + ${l.cadence}`:""}`:l.enabled?l.cadence:"Manual";return x.jsxs("section",{className:"sidebar-learning-notice","aria-label":"Continuous learning",children:[x.jsxs("header",{children:[x.jsx("strong",{children:"Continuous learning"}),x.jsxs("div",{className:"sidebar-learning-notice-actions",children:[x.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Open Continuous learning settings",onClick:t,type:"button",children:x.jsx(Xg,{size:14})}),x.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Close continuous learning",onClick:()=>{i(!0),aV()},type:"button",children:x.jsx(Ss,{size:14})})]})]}),x.jsxs("div",{className:"sidebar-learning-status",children:[x.jsx("strong",{children:"Refiner"}),x.jsx("span",{children:n.backgroundReview.enabled?"On":"Off"})]}),x.jsxs("div",{className:"sidebar-learning-status",children:[x.jsx("strong",{children:"Continuous Review"}),x.jsx("span",{children:m})]})]})}function rV(e){const[t,n]=g.useState(!1),{beginNewChat:a,arch:o,currentVersion:i,experience:s,productArea:l,onProductAreaChange:m,onSidebarResizeStart:d,platform:h,setSectionMenuOpen:v,setSelectedAppId:y,setSelectedProjectId:w,setSelectedSessionId:I,setSidebarOpen:R,setView:M,view:P,modelProjects:N,modelTrainingActivityByProjectId:O}=e,j=g.useCallback(z=>{n(!1),v(z)},[v]),k=g.useCallback(z=>{n(z),z&&v(null)},[v]),C=nV({currentVersion:i,platform:h,arch:o,enabled:Nu()}),T=C.status==="available"?C.update:null;return x.jsxs("aside",{className:"sidebar",children:[x.jsxs("div",{className:"sidebar-toolbar",children:[x.jsx("button",{className:"sidebar-icon","aria-label":"Hide sidebar",onClick:()=>R(!1),children:x.jsx(DI,{size:16})}),x.jsx(K6,{value:l,onChange:m}),T&&x.jsxs("button",{type:"button",className:"sidebar-update-pill",title:`Download OpenPond ${T.version}: ${T.assetName}`,"aria-label":`Download OpenPond ${T.version}`,onClick:()=>{iV(T.downloadUrl)},children:[x.jsx(p5,{size:14}),x.jsx("span",{children:"Update"})]})]}),x.jsx(p3,{productArea:l,experience:s,beginNewChat:a,setSectionMenuOpen:j,setSelectedAppId:y,setSelectedProjectId:w,setSelectedSessionId:I,setView:M,view:P,modelProjects:N,modelTrainingActivityByProjectId:O}),l==="models"?null:x.jsx(q6,{...e,setSectionMenuOpen:j}),x.jsxs("div",{className:"sidebar-bottom-stack",children:[l==="models"?null:x.jsx(oV,{connection:e.connection,onOpenSettings:()=>{v(null),cn({kind:"settings",section:"harness"})}}),x.jsxs("div",{className:"sidebar-footer-row",children:[x.jsx(Z6,{account:e.account,open:t,organizations:e.organizations,selectedTeamId:e.teamChatOrganization?.teamId??null,onOpenChange:k,onOpenActivity:()=>{v(null),cn({kind:"settings",section:"usage"})},onOpenSettings:()=>{v(null),cn({kind:"settings",section:"account"})},onSelectTeam:e.onSelectTeam,onLogOut:e.onLogOut}),x.jsx(f3,{setSectionMenuOpen:j,setSelectedAppId:y,setSelectedProjectId:w,setSelectedSessionId:I,setView:M,view:P})]})]}),x.jsx("div",{className:"sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",onPointerDown:d})]})}async function iV(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-update",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const sV=[/^(?:(?:type)?error:\s*)?failed to fetch\.?$/i,/^networkerror when attempting to fetch resource\.?$/i,/^load failed\.?$/i];function g_(e,t="Something went wrong."){const a=(e instanceof Error?e.message:String(e??"")).trim();return a?v_(a)?"Couldn’t connect to OpenPond.":a:t}function v_(e){const t=e.trim();return sV.some(n=>n.test(t))}const b_=g.createContext(null);function i0({children:e,showToast:t}){return x.jsx(b_.Provider,{value:t,children:e})}function lV(){return g.useContext(b_)}function s0(e,t={}){const n=lV(),a=g.useRef(null),o=t.enabled??!0,i=t.fallback??"Something went wrong.",s=t.prefix?.trim()??"",l=e==null||e===""?null:`${s}${s?": ":""}${g_(e,i)}`;g.useEffect(()=>{if(!o||!l){a.current=null;return}a.current!==l&&(a.current=l,n?.(l,"error",{dismissible:!0}))},[o,l,n])}function cV({state:e,onClose:t,onOpenBrowserUrl:n,onStart:a}){if(s0(e?.previewError,{prefix:"Upload preview"}),s0(e?.error,{prefix:"Cloud setup"}),!e)return null;const o=e.status==="uploading",i=e.status==="ready",s=e.status==="error",l=e.projectKind==="cloud",m=e.preview??null;return x.jsx("div",{className:"git-dialog-backdrop",role:"presentation",children:x.jsxs("section",{className:"git-dialog cloud-setup-dialog",role:"dialog","aria-modal":"true","aria-label":"Set up Cloud coding",children:[x.jsx("button",{className:"git-dialog-close",disabled:o,type:"button",onClick:t,"aria-label":"Close Cloud setup",title:"Close",children:x.jsx(Ss,{size:14})}),x.jsx("div",{className:"git-dialog-icon",children:i?x.jsx(Bf,{size:18}):x.jsx(Mu,{size:18})}),x.jsx("h2",{children:i?"Cloud repo ready":"Set up Cloud coding"}),x.jsx("p",{children:i?"Your source is ready in OpenPond Git. Finish by creating the Cloud sandbox environment.":l?"This Cloud Project is ready for a sandbox environment.":"OpenPond will upload tracked and unignored files into OpenPond Git, then send you to the Cloud sandbox setup page."}),x.jsxs("div",{className:"cloud-setup-summary",children:[x.jsxs("div",{className:"git-dialog-row",children:[x.jsx("span",{children:"Project"}),x.jsx("strong",{children:e.projectName})]}),x.jsxs("div",{className:"git-dialog-row",children:[x.jsx("span",{children:"Source"}),x.jsx("strong",{children:l?"OpenPond Git":"Local project upload"})]}),x.jsxs("div",{className:"git-dialog-row",children:[x.jsx("span",{children:"Branch"}),x.jsx("strong",{children:m?.branch??e.branch??"main"})]}),!l&&x.jsxs("div",{className:"git-dialog-row",children:[x.jsx("span",{children:"Cloud project"}),x.jsx("strong",{children:m?.targetProjectId??e.cloudProjectId??"New on upload"})]})]}),!i&&!l&&x.jsx("div",{className:"cloud-setup-upload-preview",role:"status","aria-live":"polite",children:e.previewLoading?x.jsxs(x.Fragment,{children:[x.jsx("strong",{children:"Calculating upload preview"}),x.jsx("span",{children:"Checking tracked and unignored files before anything is pushed."})]}):e.previewError?x.jsxs(x.Fragment,{children:[x.jsx("strong",{children:"Preview unavailable"}),x.jsx("span",{children:"Close and reopen setup to try the preview again."})]}):m?x.jsxs(x.Fragment,{children:[x.jsx("strong",{children:m.initializedEmptyProject?"Will initialize an empty project":`Will upload ${m.fileCount} files`}),x.jsx("span",{children:l0({byteCount:m.byteCount,skippedCount:m.skippedCount,headCommit:m.headCommit,targetProjectName:m.targetProjectName})})]}):x.jsxs(x.Fragment,{children:[x.jsx("strong",{children:"Upload preview pending"}),x.jsx("span",{children:"File count, byte count, and skipped files will appear here before upload."})]})}),o&&x.jsxs("div",{className:"cloud-setup-progress",role:"status","aria-live":"polite",children:[x.jsx(T5,{className:"cloud-setup-spinner",size:16}),x.jsx("span",{children:"Uploading source to OpenPond Git..."})]}),i&&e.upload&&x.jsxs("div",{className:"cloud-setup-upload-result",children:[x.jsx("strong",{children:e.upload.initializedEmptyProject?"Initialized empty project":`Uploaded ${e.upload.fileCount} files`}),x.jsx("span",{children:l0({byteCount:e.upload.byteCount,skippedCount:e.upload.skippedCount,headCommit:e.upload.headCommit,targetProjectName:e.upload.branch})})]}),i&&e.setupUrl&&x.jsxs("div",{className:"cloud-setup-next",children:[e.projectUrl?x.jsxs("span",{children:["Your repo is ready here:"," ",x.jsxs("a",{href:e.projectUrl,target:"_blank",rel:"noreferrer",onClick:d=>Bp(d,e.projectUrl,n,{newTab:!0}),children:["Project page",x.jsx($p,{size:13})]})]}):x.jsx("span",{children:"Your repo is ready. Next step:"}),x.jsxs("a",{href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:d=>Bp(d,e.setupUrl,n),children:["Setup the Cloud sandbox",x.jsx($p,{size:13})]})]}),x.jsxs("div",{className:"git-dialog-footer",children:[x.jsx("button",{className:"git-dialog-secondary",disabled:o,type:"button",onClick:t,children:i?"Done":"Cancel"}),i?e.setupUrl?x.jsxs("a",{className:"git-dialog-primary cloud-setup-primary-link",href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:d=>Bp(d,e.setupUrl,n),children:["Open setup",x.jsx($p,{size:13})]}):null:x.jsx("button",{className:"git-dialog-primary",disabled:o,type:"button",onClick:a,children:o?"Uploading":s?"Try again":l?"Show setup link":"Upload source"})]})]})})}function Bp(e,t,n,a={}){!t||!n||(e.preventDefault(),n(t,a))}function dV(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 l0({byteCount:e,skippedCount:t,headCommit:n,targetProjectName:a}){const o=[dV(e),`${t} skipped`],i=uV(n);return i&&o.push(`local ${i}`),o.push(a),o.join(" · ")}function uV(e){const t=e?.trim();return t?t.slice(0,7):null}const mV=g.lazy(()=>Gr(()=>import("./CommandMenu-Coahy7-K.js"),__vite__mapDeps([0,1,2,3]),import.meta.url).then(e=>({default:e.CommandMenu}))),pV=g.lazy(()=>Gr(()=>import("./SettingsView-B-O30p4h.js"),__vite__mapDeps([4,1,2,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]),import.meta.url).then(e=>({default:e.SettingsView}))),fV=g.lazy(()=>Gr(()=>import("./NewProjectDialog-CtJJ6u5l.js"),__vite__mapDeps([26,1,2,8,15]),import.meta.url).then(e=>({default:e.NewProjectDialog}))),hV=g.lazy(()=>Gr(()=>import("./WorkspaceGitDialogs-CE6uwWBo.js"),__vite__mapDeps([27,1,2,13,14,28,25]),import.meta.url).then(e=>({default:e.CommitDialog}))),gV=g.lazy(()=>Gr(()=>import("./WorkspaceGitDialogs-CE6uwWBo.js"),__vite__mapDeps([27,1,2,13,14,28,25]),import.meta.url).then(e=>({default:e.BranchDialog})));function vV({payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:o,onError:i,onToast:s,onBack:l,onOpenSourceSession:m,onStartRefinerAuthoring:d,onAcceptEvaluationReview:h,onOpenSkill:v,onOpenExtension:y,teamChatCurrentUserId:w,teamChatEnabled:I,teamChatNotificationMode:R,teamChatThreads:M,onTeamChatNotificationModeChange:P,onTeamChatThreadMuteChange:N,diffPanelWidth:O,diffPanelResizing:j,diffPanelExpanded:k,onDiffPanelResizeStart:C,onDiffPanelExpandedChange:T}){return x.jsx(g.Suspense,{fallback:null,children:x.jsx(pV,{payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:o,onError:i,onToast:s,onBack:l,onOpenSourceSession:m,onStartRefinerAuthoring:d,onAcceptEvaluationReview:h,onOpenSkill:v,onOpenExtension:y,teamChatCurrentUserId:w,teamChatEnabled:I,teamChatNotificationMode:R,teamChatThreads:M,onTeamChatNotificationModeChange:P,onTeamChatThreadMuteChange:N,diffPanelWidth:O,diffPanelResizing:j,diffPanelExpanded:k,onDiffPanelResizeStart:C,onDiffPanelExpandedChange:T})})}function bV({activeSessions:e,branchDialogName:t,branchDialogOpen:n,commitDialogOpen:a,commitDraft:o,commitIncludeUnstaged:i,commitMessage:s,commitNextStep:l,canPublishOpenPondProject:m,expandProject:d,newProjectBusy:h,newProjectDialogOpen:v,newProjectDirectory:y,newProjectMode:w,newProjectName:I,newProjectPath:R,projectRows:M,query:P,searchOpen:N,visibleWorkspaceDiff:O,visibleWorkspaceState:j,workspaceBusy:k,appDispatch:C,beginNewChat:T,openDefaultsSettingsFromBranchDialog:z,setBranchDialogName:B,setBranchDialogOpen:D,setCommitDialogOpen:V,setCommitDraft:le,setCommitIncludeUnstaged:te,setCommitMessage:Ie,setCommitNextStep:ke,setNewProjectDialogOpen:Z,setNewProjectName:Ae,setNewProjectPath:he,setQuery:ue,setSearchOpen:be,submitCommitDialog:ne,submitCreateWorkspaceBranch:ge,submitNewProjectDialog:xe}){return x.jsxs(x.Fragment,{children:[N&&x.jsx(g.Suspense,{fallback:null,children:x.jsx(mV,{open:N,query:P,projects:M,sessions:e,onQueryChange:ue,onClose:()=>{be(!1),ue("")},onNewChat:()=>{be(!1),ue(""),T()},onOpenProject:qe=>{C({type:"selectProject",projectId:qe.id}),C({type:"patch",patch:{searchOpen:!1,query:""}}),d(qe.id)},onOpenSession:qe=>{C({type:"selectSession",sessionId:qe.id,appId:qe.appId,projectId:qe.workspaceKind==="local_project"&&qe.workspaceId?vt("local",qe.workspaceId):null}),C({type:"patch",patch:{searchOpen:!1,query:""}})}})}),v&&x.jsx(g.Suspense,{fallback:null,children:x.jsx(fV,{open:v,mode:w,name:I,path:R,directory:y,busy:h,onNameChange:Ae,onPathChange:he,onClose:()=>{h||Z(!1)},onSubmit:xe})}),a&&x.jsx(g.Suspense,{fallback:null,children:x.jsx(hV,{open:a,branch:j?.currentBranch??null,filesChanged:O?.filesChanged??j?.changedFilesCount??0,additions:O?.additions??0,deletions:O?.deletions??0,message:s,includeUnstaged:i,nextStep:l,draft:o,busy:k,canPush:!!j?.remoteUrl,canPublish:m,onMessageChange:Ie,onIncludeUnstagedChange:te,onNextStepChange:ke,onDraftChange:le,onClose:()=>{k||V(!1)},onSubmit:ne})}),n&&x.jsx(g.Suspense,{fallback:null,children:x.jsx(gV,{open:n,branchName:t,busy:k,onBranchNameChange:B,onSetPrefix:z,onClose:()=>{k||D(!1)},onSubmit:ge})})]})}function y_({toast:e,onDismiss:t}){if(!e)return null;const n=!!(e.actionLabel&&e.onAction),a=!!(e.persistent||e.dismissible);return x.jsxs("div",{className:`app-toast ${e.tone} ${e.placement??"bottom-right"}`,role:e.tone==="error"?"alert":"status","aria-live":"polite",children:[x.jsx("span",{className:"app-toast-message",children:e.message}),(n||a)&&x.jsxs("div",{className:"app-toast-actions",children:[n&&x.jsx("button",{type:"button",className:e.actionIcon?"app-toast-icon-action":void 0,"aria-label":e.actionLabel,title:e.actionIcon?e.actionLabel:void 0,onClick:()=>{t(),e.onAction?.()},children:e.actionIcon==="settings"?x.jsx(Xg,{size:15}):e.actionLabel}),a&&x.jsx("button",{type:"button",className:"app-toast-close","aria-label":"Dismiss notification",onClick:t,children:x.jsx(Ss,{size:14})})]})]})}const hc=g.createContext(null);function yV({children:e}){const[t,n]=g.useState(null),[a,o]=g.useState(null),i=g.useMemo(()=>({title:t,actions:a,setTitle:n,setActions:o}),[t,a]);return x.jsx(hc.Provider,{value:i,children:e})}function tQ({children:e}){return x.jsx(hc.Provider,{value:null,children:e})}function SV({children:e,className:t=""}){const n=g.useContext(hc);return x.jsx("div",{ref:n?.setTitle,className:`page-chrome-title-target ${t}`,children:e?x.jsx("div",{className:"page-chrome-fallback",children:e}):null})}function kV({className:e=""}){const t=g.useContext(hc);return x.jsx("div",{ref:t?.setActions,className:e})}function nQ({title:e,actions:t,fallback:n,children:a}){const o=g.useContext(hc);return o?x.jsxs(x.Fragment,{children:[o.title?eh.createPortal(x.jsx("div",{className:"page-chrome-title",children:e}),o.title):null,o.actions&&t?eh.createPortal(t,o.actions):null,a]}):n??x.jsxs("header",{children:[e,t]})}async function xV(e){if(!e)return!1;try{if(navigator.clipboard?.writeText)return await navigator.clipboard.writeText(e),!0}catch(t){console.warn("Clipboard write failed",t)}try{const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly",""),t.style.position="fixed",t.style.left="-1000px",t.style.top="-1000px",document.body.appendChild(t),t.select();const n=document.execCommand("copy");return t.remove(),n}catch(t){return console.warn("Clipboard fallback failed",t),!1}}function wV({activeView:e,onDiscoverCommunities:t,onOpenTeamChat:n}){return x.jsxs("div",{className:"titlebar-collaboration-actions",children:[x.jsx("button",{type:"button",className:`titlebar-icon${e==="team"?" active":""}`,"aria-label":"Team chat",title:"Team chat",onClick:n,children:x.jsx(ju,{size:16})}),x.jsx("button",{type:"button",className:`titlebar-icon${e==="community"?" active":""}`,"aria-label":"Discover communities",title:"Discover communities",onClick:t,children:x.jsx(NI,{size:16})})]})}const IV=g.lazy(()=>Gr(()=>import("./WorkspaceEnvironmentMenu-DcFKeae1.js"),__vite__mapDeps([29,1,2,21,10,14,5,30,28,31]),import.meta.url).then(e=>({default:e.WorkspaceEnvironmentMenu})));function _V({sidebarOpen:e,title:t,conversationId:n,breadcrumbs:a,backAction:o,workspaceName:i,workspaceId:s,busy:l,workspaceState:m,workspaceKind:d,selectedApp:h,selectedProject:v,workspaceDiff:y,managedWorkspace:w,workspaceBusy:I,defaultTeamId:R,showDiffControls:M,diffPanelOpen:P,terminalOpen:N,rightSidebarAvailable:O=!1,rightSidebarOpen:j=!1,onToggleDiffPanel:k,onToggleRightSidebar:C,onOpenSearch:T,onToggleTerminal:z,onRunTerminalCommand:B,onWorkspaceToolAction:D,onOpenCommitDialog:V,onWorkspaceBranchChange:le,onWorkspaceBranchCreate:te,connection:Ie,onBootstrap:ke,onOpenSandboxWorkspace:Z,onShowSidebar:Ae,onOpenTeamChat:he,onDiscoverCommunities:ue,collaborationView:be=null,platform:ne,showWorkspaceControls:ge=!0}){const xe=y?.filesChanged??0,qe=Nu()&&!ev(ne),Se=!!(he||ue)||ge||O||qe,[se,we]=g.useState(null);g.useEffect(()=>{if(!se)return;const Ge=()=>we(null);return window.addEventListener("pointerdown",Ge),window.addEventListener("blur",Ge),window.addEventListener("resize",Ge),()=>{window.removeEventListener("pointerdown",Ge),window.removeEventListener("blur",Ge),window.removeEventListener("resize",Ge)}},[se]);const Oe=Ge=>{Ge.preventDefault(),Ge.stopPropagation();const st=190,Le=n?76:42;we({x:Math.min(Ge.clientX,window.innerWidth-st-8),y:Math.min(Ge.clientY,window.innerHeight-Le-8)})},Qe=Ge=>{xV(Ge),we(null)};return x.jsxs("header",{className:"app-titlebar",children:[x.jsxs("div",{className:"titlebar-left",children:[!e&&x.jsx("button",{className:"titlebar-icon",title:"Show sidebar",onClick:Ae,children:x.jsx(DI,{size:16})}),o?x.jsx("button",{className:"titlebar-icon",type:"button","aria-label":o.label,title:o.label,onClick:o.onSelect,children:x.jsx(Z4,{size:16})}):null,x.jsx(SV,{children:a?.length?x.jsx("nav",{className:"titlebar-breadcrumbs","aria-label":"Breadcrumb",children:a.map((Ge,st)=>{const Le=st===a.length-1;return x.jsxs("div",{className:"titlebar-breadcrumb-item",children:[Ge.onSelect&&!Le?x.jsx("button",{type:"button",onClick:Ge.onSelect,children:Ge.label}):x.jsx("strong",{children:Ge.label}),!Le&&x.jsx(Wr,{size:14})]},`${Ge.label}-${st}`)})}):x.jsxs("div",{className:"titlebar-title",children:[x.jsx("strong",{className:"titlebar-copy-target",title:"Double-click to select; right-click for copy options",onContextMenu:Oe,children:t}),i&&x.jsx("span",{children:i})]})})]}),Se&&x.jsxs("div",{className:"titlebar-right",children:[x.jsx(kV,{className:"page-chrome-actions"}),x.jsx(wV,{activeView:be,onDiscoverCommunities:ue,onOpenTeamChat:he}),ge&&x.jsxs("div",{className:"titlebar-actions",children:[x.jsx(g.Suspense,{fallback:null,children:x.jsx(IV,{mode:"topbar",busy:l,workspaceState:m,workspaceId:s,workspaceKind:d,selectedApp:h,selectedProject:v,workspaceBusy:I,defaultTeamId:R,workspaceDiff:y,managedWorkspace:w,showDiffControls:M,diffPanelOpen:P,onToggleDiffPanel:k,onRunTerminalCommand:B,onWorkspaceToolAction:D,onOpenCommitDialog:V,onWorkspaceBranchChange:le,onWorkspaceBranchCreate:te,connection:Ie,onBootstrap:ke,onOpenSandboxWorkspace:Z})}),x.jsx("button",{type:"button",className:"titlebar-icon",title:"Search chats and projects","aria-label":"Search chats and projects",onClick:T,children:x.jsx(F5,{size:16})}),x.jsx("button",{type:"button",className:`titlebar-icon ${N?"active":""}`,title:`${N?"Hide":"Show"} terminal`,"aria-label":`${N?"Hide":"Show"} terminal`,"aria-pressed":N,onClick:z,children:x.jsx(UI,{size:16})}),M&&x.jsx("button",{type:"button",className:`topbar-diff-button ${j?"active":""}`,title:`${j?"Hide":"Show"} sidebar${xe?`, ${xe} changed files`:""}`,"aria-label":`${j?"Hide":"Show"} sidebar`,"aria-pressed":j,onClick:k,children:x.jsx(Ff,{size:16})})]}),O&&C&&!M?x.jsx("div",{className:"titlebar-actions",children:x.jsx("button",{type:"button",className:`topbar-diff-button ${j?"active":""}`,title:`${j?"Hide":"Show"} sidebar`,"aria-label":`${j?"Hide":"Show"} sidebar`,"aria-pressed":j,onClick:C,children:x.jsx(Ff,{size:16})})}):null,x.jsx(X5,{platform:ne})]}),se&&x.jsxs("div",{className:"titlebar-copy-menu",role:"menu","aria-label":"Conversation title actions",style:{left:se.x,top:se.y},onPointerDown:Ge=>Ge.stopPropagation(),children:[x.jsx("button",{type:"button",role:"menuitem",onClick:()=>Qe(t),children:"Copy title"}),n&&x.jsx("button",{type:"button",role:"menuitem",onClick:()=>Qe(n),children:"Copy conversation ID"})]})]})}function CV(){const[e,t]=g.useState(null),n=g.useRef(null),a=g.useCallback(i=>new Promise(s=>{n.current?.resolve(!1);const l={...i,cancelLabel:i.cancelLabel??"Cancel",tone:i.tone??"default",resolve:s};n.current=l,t(l)}),[]),o=g.useCallback(i=>{const s=n.current;n.current=null,t(null),s?.resolve(i)},[]);return{confirmAction:a,confirmDialog:e,resolveConfirmDialog:o}}function RV({state:e,onResolve:t}){const n=g.useId(),a=g.useId();if(g.useEffect(()=>{if(!e)return;function i(s){s.key==="Escape"&&t(!1)}return document.addEventListener("keydown",i),()=>document.removeEventListener("keydown",i)},[t,e]),!e)return null;const o=e.tone==="danger"?"git-dialog-primary danger":"git-dialog-primary";return x.jsx("div",{className:"git-dialog-backdrop",role:"presentation",onMouseDown:()=>t(!1),children:x.jsxs("section",{className:"git-dialog project-confirm-dialog",role:"alertdialog","aria-modal":"true","aria-labelledby":n,"aria-describedby":a,onMouseDown:i=>i.stopPropagation(),children:[x.jsx("h2",{id:n,children:e.title}),x.jsx("p",{id:a,children:e.body}),x.jsxs("div",{className:"git-dialog-footer",children:[x.jsx("button",{type:"button",className:"git-dialog-secondary",onClick:()=>t(!1),children:e.cancelLabel}),x.jsx("button",{type:"button",className:o,autoFocus:!0,onClick:()=>t(!0),children:e.confirmLabel})]})]})})}function PV(){const{confirmAction:e,confirmDialog:t,resolveConfirmDialog:n}=CV();return{confirmProjectAction:g.useCallback(o=>e({tone:"danger",...o}),[e]),projectConfirmDialog:t,resolveProjectConfirmDialog:n}}function AV({state:e,onResolve:t}){return x.jsx(RV,{state:e,onResolve:t})}const Bd=new Map,TV=(e,t,n)=>{const a=Bd.get(e)??{commits:0,maxActualDurationMs:0,totalActualDurationMs:0};a.commits+=1,a.maxActualDurationMs=Math.max(a.maxActualDurationMs,n),a.totalActualDurationMs+=n,Bd.set(e,a)};function EV({children:e,id:t}){return x.jsx(g.Profiler,{id:t,onRender:TV,children:e})}typeof window<"u"&&(window.__OPENPOND_RENDER_COMMITS__={get:()=>Object.fromEntries([...Bd.entries()].map(([e,t])=>[e,{...t}])),reset:()=>Bd.clear()});const MV=g.lazy(()=>Gr(()=>import("./MainPane-Bl91XbhC.js").then(e=>e.M),__vite__mapDeps([32,1,2,13,33,6,30]),import.meta.url).then(e=>({default:e.MainPane})));function jV({className:e,style:t,sidebar:n,topBar:a,mainPane:o,cloudSetup:i,projectConfirm:s,lazyPanels:l,toast:m}){return x.jsx(yV,{children:x.jsxs("div",{className:e,style:t,children:[x.jsx(EV,{id:"sidebar",children:x.jsx(rV,{...n})}),x.jsxs("div",{className:"content-shell",children:[x.jsx(_V,{...a}),x.jsx(g.Suspense,{fallback:x.jsx("main",{className:"main-pane","aria-busy":"true","aria-label":"Loading workspace"}),children:x.jsx(MV,{...o})})]}),x.jsx(cV,{...i}),x.jsx(AV,{...s}),x.jsx(bV,{...l}),x.jsx(y_,{...m})]})})}function OV({settings:e,toast:t}){return x.jsxs(x.Fragment,{children:[x.jsx(vV,{...e}),x.jsx(y_,{...t})]})}const gd="OpenPond".split("");function $V({visibleLetterCount:e=gd.length}){const t=gd.slice(0,Math.max(0,Math.min(e,gd.length)));return x.jsxs("div",{className:"app-splash-lockup",children:[x.jsx("div",{className:"app-splash-mark",children:x.jsx("img",{alt:"OpenPond",className:"app-splash-logo",decoding:"async",src:F6})}),x.jsx("span",{"aria-hidden":"true",className:`app-splash-wordmark${t.length>0?" is-visible":""}`,children:t.map((n,a)=>x.jsx("span",{className:"app-splash-letter",children:n},`${n}-${a}`))})]})}const Fp=gd.length,NV=520,DV=240;function c0(){return typeof window>"u"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function LV({startup:e}){const[t,n]=g.useState(()=>c0()?Fp:0);return g.useEffect(()=>{if(c0()){n(Fp);return}const a=Array.from({length:Fp},(o,i)=>window.setTimeout(()=>n(i+1),NV+DV*i));return()=>{a.forEach(o=>window.clearTimeout(o))}},[]),x.jsxs("main",{className:"app-splash","aria-busy":"true","aria-label":e.label,role:"status",children:[x.jsx($V,{visibleLetterCount:t}),x.jsx("span",{className:"app-splash-status",children:e.label})]})}const gv=5e3;function Oo(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 Mo(e,t,n=gv){return vd(Oo(e,t),n)}function vd(e,t=gv){return e.length<=t?e:e.slice(e.length-t)}function UV(e,t,n){return n.length===0?e:{...e,[t]:Oo(e[t]??[],n)}}function zV(e,t){if(t.length===0)return vd(e);if(e.length===0)return vd(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 vd([...n.values()].sort((o,i)=>qV(o,i)).map(({event:o})=>o))}function Fd(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 HV(e){let t=null;for(const n of e)n.sequence!==void 0&&(t===null||n.sequence<t)&&(t=n.sequence);return t}function qV(e,t){const n=e.event.sequence,a=t.event.sequence;if(typeof n=="number"&&typeof a=="number"){const s=n-a;if(s!==0)return s}const o=Date.parse(e.event.timestamp),i=Date.parse(t.event.timestamp);if(Number.isFinite(o)&&Number.isFinite(i)){const s=o-i;if(s!==0)return s}return e.index-t.index}function d0(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 BV(e){return e===null?"unknown":e>=85?"high":e>=65?"medium":"low"}function u0(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 FV(e){return e==="codex"}function VV(e){return e==="openpond"}function S_(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="session.context.updated")continue;const a=EO.safeParse(n.data);if(a.success)return a.data}return null}function k_(e){if(e.snapshot&&e.snapshot.provider===e.provider){const n=e.snapshot.usedTokens,a=e.snapshot.maxContextTokens,o=Math.min(100,Math.round(e.snapshot.percentFull)),i=`${o}% full`,s=`${d0(n)} / ${d0(a)} tokens used`;return{usedTokens:n,maxTokens:a,percent:o,summary:i,tokensLabel:s,detail:u0(e.preferences,o),tooltip:`Context window: ${i} ${s}. ${u0(e.preferences,o)}`,tone:BV(o)}}if(FV(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(!VV(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 vv(e){let t=!1;const n=x_(e);for(let a=e.length-1;a>=0;a-=1){const o=e[a];if(KV(o)){t=!0;continue}const i=ls(o?.data);if(!(o?.name!=="diagnostic"||!i)){if(i.kind==="thread_goal_cleared")return null;if(i.kind==="thread_goal"){const s=bv(ls(i.goal),Yn(i.provider),n);if(s){const l=Kl(s);return t&&l.tone==="active"?null:l}}if(i.kind==="goal_context"){const s=I_(o.output??"",Yn(i.provider)??"codex",n);if(s){const l=Kl(s);return t&&l.tone==="active"?null:l}}}}return null}function Vd(e){const t=x_(e);for(let n=e.length-1;n>=0;n-=1){const a=e[n],o=ls(a?.data);if(!(a?.name!=="diagnostic"||!o)){if(o.kind==="thread_goal_cleared"&&o.synthetic!==!0)return null;if(o.kind==="thread_goal"){const i=bv(ls(o.goal),Yn(o.provider),t);if(!i)continue;const s=Kl(i);return s.tone==="active"?s:null}if(o.kind==="goal_context"){const i=I_(a.output??"",Yn(o.provider)??"codex",t);if(!i)continue;const s=Kl(i);return s.tone==="active"?s:null}}}return null}function Vp(e){const t=ls(ls(e)?.codexGoalRuntime),n=bv(t,Yn(t?.provider)??"codex");if(!n)return null;const a=Kl(n);return a.tone==="active"?a:null}function KV(e){return e?.name==="turn.completed"||e?.name==="turn.interrupted"||e?.name==="turn.failed"}function Kl(e){const t=__(e.status),n=P_(e.timeUsedSeconds),a=`Goal ${n}`,o=e.tokensUsed===null?null:e.tokenBudget===null?`${Kp(e.tokensUsed)} tokens`:`${Kp(e.tokensUsed)} / ${Kp(e.tokenBudget)} tokens`,i=o?`${e.statusLabel} · ${o}`:e.statusLabel;return{objective:e.objective,status:e.status,timeUsedSeconds:e.timeUsedSeconds,tokensUsed:e.tokensUsed,tokenBudget:e.tokenBudget,actionLabel:t.actionLabel,timeLabel:n,label:a,detail:i,tooltip:`Goal runtime: ${A_(e.timeUsedSeconds)}. ${i}. ${e.objective}`,tone:t.tone,observedAt:e.observedAt}}function WV(e,t){if(!e||e.tone!=="active"||!e.observedAt)return e;const n=w_(e.observedAt,t);if(n<=0)return e;const a=e.timeUsedSeconds+n,o=P_(a);return{...e,timeUsedSeconds:a,timeLabel:o,label:`Goal ${o}`,tooltip:`Goal runtime: ${A_(a)}. ${e.detail}. ${e.objective}`,observedAt:t}}function bv(e,t=null,n=null){if(!e)return null;const a=Yn(e.objective)??"Active goal",o=Yn(e.status)??"active";if((th(t)??th(Yn(e.provider)))!=="codex")return null;const s=n??Yn(e.updatedAt)??Yn(e.updated_at)??null,l=Pi(e.timeUsedSeconds)??Pi(e.time_used_seconds)??0,m=Yn(e.activeSinceAt)??Yn(e.active_since_at),d=__(o).tone==="active"?w_(m??Yn(e.createdAt)??Yn(e.created_at),s):0,h=m?l+d:Math.max(l,d),v=Pi(e.tokensUsed)??Pi(e.tokens_used),y=Pi(e.tokenBudget)??Pi(e.token_budget);return{objective:a,status:o,statusLabel:R_(o),timeUsedSeconds:Math.max(0,Math.floor(h)),tokensUsed:v===null?null:Math.max(0,Math.floor(v)),tokenBudget:y===null?null:Math.max(0,Math.floor(y)),observedAt:s}}function x_(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 w_(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 I_(e,t=null,n=null){if(!e.trim()||th(t)!=="codex")return null;const a=C_(e,"Status")??"active",o=ll(e,"Tokens used"),i=ll(e,"Token budget"),s=ll(e,"Time used seconds")??ll(e,"Time spent pursuing goal")??ll(e,"Elapsed seconds")??0;return{objective:m0(e,"objective")??m0(e,"untrusted_objective")??"Active goal",status:a,statusLabel:R_(a),timeUsedSeconds:Math.max(0,Math.floor(s)),tokensUsed:o,tokenBudget:i,observedAt:n}}function __(e){switch(GV(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 GV(e){return e.trim().toLowerCase().replace(/[-\s]+/g,"_")}function C_(e,t){const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^\\s*-?\\s*${n}:\\s*(.+?)\\s*$`,"im").exec(e)?.[1]?.trim()||null}function ll(e,t){const n=C_(e,t);if(!n)return null;const a=n.replace(/,/g,""),o=/-?\d+(?:\.\d+)?/.exec(a);if(!o)return null;const i=Number(o[0]);return Number.isFinite(i)?i:null}function m0(e,t){return new RegExp(`<${t}>\\s*([\\s\\S]*?)\\s*<\\/${t}>`,"i").exec(e)?.[1]?.trim()||null}function R_(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function P_(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 A_(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 Kp(e){if(e<1e3)return String(e);if(e>=1e6){const n=e/1e6;return n<10?`${p0(n,2)}M`:n<100?`${p0(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 p0(e,t){return e.toFixed(t).replace(/\.?0+$/,"")}function ls(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Yn(e){return typeof e=="string"&&e.trim()?e.trim():null}function th(e){return e?.trim().toLowerCase()||null}function Pi(e){return typeof e=="number"&&Number.isFinite(e)?e:null}const ZV=new Set(["planning","applying_source","running_checks","evaluating","pushing_hosted","running_hosted_checks"]),JV=new Set(["awaiting_questions","awaiting_plan_approval","paused"]);function nh(e){const t=T_(e);return t?eK(t):null}function T_(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="create_improve.updated")continue;const a=XV(rK(n.data));if(a)return a}return null}function YV(e){if(e.events)return T_(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 QV(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 XV(e){const t=ec.safeParse(e?.createImproveRun);return t.success?t.data:null}function eK(e){const t=tK(e);if(!t)return null;const n=nK(e.createdAt,e.updatedAt),a=e.blockedReason??aK(e.state);return{objective:e.objective,status:e.state,timeUsedSeconds:n,tokensUsed:null,tokenBudget:null,actionLabel:t.actionLabel,timeLabel:oK(n),label:t.actionLabel,detail:a,tooltip:`${t.actionLabel}: ${a}. ${e.objective}`,tone:t.tone}}function tK(e){const t=e.state,n=e.target.kind==="agent"?"Agent":"Work";return ZV.has(t)?{tone:"active",actionLabel:`${n} running`}:JV.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 nK(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 aK(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function oK(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 rK(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function E_(e,t){if(!t)return null;const n=new Map,a=[];for(const j of e){if(!j.name.startsWith("subagent."))continue;const k=lK(j);k&&a.push(k);const C=sK(j);C?.parentSessionId===t&&n.set(C.id,C)}if(n.size===0)return null;const o=[...n.values()].sort((j,k)=>Ei(k).localeCompare(Ei(j))),i=o.filter(j=>j.status==="queued"||j.status==="running"),s=o.filter(j=>j.status==="completed"),l=o.filter(j=>j.status==="failed"),m=o.filter(j=>j.status==="cancelled"),d=o.filter(j=>j.status==="needs_resume"),h=[...s,...l,...m].sort((j,k)=>Ei(k).localeCompare(Ei(j))),v=o.reduce((j,k)=>{const C=cs(k.metadata?.usage);return j.totalTokens+=Jc(C?.totalTokens),j.promptTokens+=Jc(C?.promptTokens),j.completionTokens+=Jc(C?.completionTokens),j.requestCount+=Jc(C?.requestCount),j},{totalTokens:0,promptTokens:0,completionTokens:0,requestCount:0}),y=o.flatMap(j=>M_([...j.report?.blockers??[],j.error,j.progress.currentBlocker]).map(k=>({runId:j.id,roleId:j.roleId,status:j.status,message:k}))),w=o.flatMap(j=>j_([...j.report?.artifacts??[],j.report?.patchRef,j.report?.diffRef,...j.progress.patchRefs]).map(k=>({...k,runId:j.id,roleId:j.roleId}))),I=h.map(j=>iK(j,a)),R=o[0]??null,M=R?{runId:R.id,roleId:R.roleId,status:R.status,message:R.progress.latestMeaningfulActivity||R.report?.summary||R.objective,updatedAt:Ei(R)}:null,P=i.length>0?`${i.length} ${i.length===1?"child":"children"} running`:`${h.length} ${h.length===1?"child":"children"} finished`,N=[i.length?`${i.length} active`:null,s.length?`${s.length} completed`:null,l.length?`${l.length} failed`:null,m.length?`${m.length} cancelled`:null,d.length?`${d.length} paused`:null].filter(Boolean).join(" · "),O=M?`${uK(M.roleId)}: ${M.message}`:"";return{sessionId:t,runs:o,activeRuns:i,completedRuns:s,failedRuns:l,cancelledRuns:m,needsResumeRuns:d,terminalRuns:h,latestRun:R,latestMeaningfulUpdate:M,activeCount:i.length,completedCount:s.length,failedCount:l.length,cancelledCount:m.length,needsResumeCount:d.length,terminalCount:h.length,usage:v,blockers:y,evidenceRefs:w,finalResults:I,testsRunCount:o.reduce((j,k)=>j+k.progress.validationAttempts.length,0),label:P,tooltip:[N,O].filter(Boolean).join(". ")}}function iK(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:j_([...e.report?.artifacts??[],e.report?.patchRef,e.report?.diffRef]),testsRun:e.report?.testsRun??[],validationAttempts:e.progress.validationAttempts.map(n=>n.command),blockers:M_([...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:cK(e),updatedAt:Ei(e)}}function sK(e){const t=cs(e.data),n=[t?.run,cs(t?.message)?.run];for(const a of n){const o=_k.safeParse(a);if(o.success)return o.data}return null}function lK(e){const t=YM.safeParse(cs(e.data)?.message);return t.success?t.data:null}function cK(e){const t=cs(cs(e.metadata?.workspaceHandoff)?.workspaceRetention);return t?.status!=="retained"?null:{status:"retained",reason:Zc(t.reason),retainedAt:Zc(t.retainedAt),expiresAt:Zc(t.expiresAt),retentionDays:dK(t.retentionDays),trigger:Zc(t.trigger),cleanupAfterExpiry:t.cleanupAfterExpiry===!0}}function Ei(e){return e.updatedAt??e.completedAt??e.startedAt??e.createdAt}function M_(e){return[...new Set(e.map(t=>t?.trim()).filter(t=>!!t))]}function j_(e){const t=new Map;for(const n of e)n&&t.set(`${n.kind}:${n.id}`,n);return[...t.values()]}function cs(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Zc(e){return typeof e=="string"&&e.trim()?e.trim():null}function Jc(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function dK(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function uK(e){return e.slice(0,1).toUpperCase()+e.slice(1).replace(/[-_]+/g," ")}const ah=[];function oh(e,t){return O_(e,t,null)}function O_(e,t,n){const a=n&&gK(n.events,e)?pK(n.indexes,n.events.length,e):mK(e),o=hK(t);return{...a,...o}}function mK(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 fK(t)}function pK(e,t,n){const a=new Map(e.eventsBySessionId),o=new Map(e.latestContextUsageBySessionId),i=new Map(e.latestGoalRuntimeBySessionId),s=new Map(e.latestSubagentRuntimeBySessionId),l=new Set(e.activeGoalSessionIds),m=new Set(e.activeSubagentSessionIds),d=new Set;for(let h=t;h<n.length;h+=1){const v=n[h];if(!v.sessionId)continue;if(d.has(v.sessionId)){a.get(v.sessionId).push(v);continue}const y=a.get(v.sessionId);a.set(v.sessionId,y?[...y,v]:[v]),d.add(v.sessionId)}for(const h of d){const v=a.get(h)??ah,y=S_(v);y?o.set(h,y):o.delete(h);const w=N_(v);w?(i.set(h,w),w.tone==="active"?l.add(h):l.delete(h)):(i.delete(h),l.delete(h));const I=E_(v,h);I?(s.set(h,I),$_({sessionEvents:v,sessionId:h,latestGoalRuntimeBySessionId:i,activeGoalSessionIds:l}),I.activeCount>0?m.add(h):m.delete(h)):(s.delete(h),m.delete(h))}return{eventsBySessionId:a,latestContextUsageBySessionId:o,latestGoalRuntimeBySessionId:i,latestSubagentRuntimeBySessionId:s,activeGoalSessionIds:l,activeSubagentSessionIds:m}}function fK(e){const t=new Map,n=new Map,a=new Map,o=new Set,i=new Set;for(const[s,l]of e){const m=S_(l);m&&t.set(s,m);const d=N_(l);d&&(n.set(s,d),d.tone==="active"&&o.add(s))}for(const[s,l]of e){const m=E_(l,s);m&&(a.set(s,m),$_({sessionEvents:l,sessionId:s,latestGoalRuntimeBySessionId:n,activeGoalSessionIds:o}),m.activeCount>0&&i.add(s))}return{eventsBySessionId:e,latestContextUsageBySessionId:t,latestGoalRuntimeBySessionId:n,latestSubagentRuntimeBySessionId:a,activeGoalSessionIds:o,activeSubagentSessionIds:i}}function $_(e){if(e.latestGoalRuntimeBySessionId.has(e.sessionId))return;const t=Vd(e.sessionEvents);t&&(e.latestGoalRuntimeBySessionId.set(e.sessionId,t),t.tone==="active"&&e.activeGoalSessionIds.add(e.sessionId))}function N_(e){return nh(e)??vv(e)??Vd(e)}function hK(e){const t=new Map,n=new Map,a=new Map,o=new Map;for(const i of e){t.set(i.id,i);const s=n.get(i.status);if(s?s.push(i):n.set(i.status,[i]),i.status!=="pending")continue;const l=a.get(i.sessionId);l?l.push(i):a.set(i.sessionId,[i]);const m=o.get(i.sessionId);(!m||f0(i.createdAt)>f0(m.createdAt))&&o.set(i.sessionId,i)}return{approvalsById:t,approvalsByStatus:n,pendingApprovalsBySessionId:a,latestPendingApprovalBySessionId:o}}function gK(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 gc(e,t){return t?e.eventsBySessionId.get(t)??ah:ah}function D_(e,t){return t?e.latestContextUsageBySessionId.get(t)??null:null}function L_(e,t){return t?e.latestGoalRuntimeBySessionId.get(t)??null:null}function vK(e,t){return t?e.latestSubagentRuntimeBySessionId.get(t)??null:null}function bK(e,t){return t?e.latestPendingApprovalBySessionId.get(t)??null:null}function f0(e){const t=Date.parse(e);return Number.isFinite(t)?t:Number.NEGATIVE_INFINITY}function yK(e,t){return e?.conversationId===t}function SK(e,t){return e?.id===t?null:e}function kK(e){const t=new Set;if(e.readmePath){const n=e.readmePath.replaceAll("\\","/").split("/").at(-1);n&&t.add(n)}for(const n of e.skills){t.add(n.relativePath);const a=n.relativePath.lastIndexOf("/"),o=a>=0?n.relativePath.slice(0,a):"";for(const i of n.resourceFiles)t.add(o?`${o}/${i}`:i)}return{name:`${e.owner}/${e.repo}`,description:`${e.skills.length} installed skill${e.skills.length===1?"":"s"} from GitHub.`,scope:"extension",packagePath:e.sourcePath,files:[...t]}}function xK(e){return JSON.stringify([e.source,e.repositoryId,e.profileId])}function aQ(e,t){return e.profiles.find(n=>xK(n.ref)===t)?.ref??null}function wK(e,t){return!!(e&&t&&e.source===t.source&&e.repositoryId===t.repositoryId&&e.profileId===t.profileId)}function oQ(e,t){return e.profiles.find(n=>wK(n.ref,t))?.state??null}function IK(e,t){const n=new Map(xN.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 _K(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 rQ(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 U_="openpond:last-chat-task-mode";function CK(e,t){return e==="labs"?"models":"chat"}function RK(e){try{return e.getItem(U_)==="work"?"work":"chat"}catch{return"chat"}}function yv(){if(typeof window>"u")return"chat";try{return RK(fc)}catch{return"chat"}}function PK(e,t){try{e.setItem(U_,t==="chat"?"chat":"work")}catch{}}function AK(e){if(!(typeof window>"u"))try{PK(fc,e)}catch{}}const TK="uploaded to a different account";function z_(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 _a(e,t){const n=z_(e,t);return n.state==="confirmed"?n.cloudProject:null}function EK(e,t){return z_(e,t).state==="different_account"?TK:null}function go(e){return e==="sandbox"||e==="sandbox_template"||e==="sandbox_app"}function H_(e={}){return{...e,workspaceTarget:"hybrid"}}function MK(e={}){return{...e,workspaceTarget:"local"}}function vo(e){return e?.metadata?.workspaceTarget==="hybrid"}function jK(e){return!!(e&&e.provider==="openpond"&&e.workspaceKind==="local_project"&&e.cloudProjectId&&e.title.trim().endsWith(" Cloud"))}function q_({cloudProjects:e,selectedCloudProject:t,selectedProject:n}){const a=n?.linkedSandboxProject??null,o=e?_a(n,e):null,i=t?.id??o?.id??(e?null:a?.projectId??null),s=t?.teamId??o?.teamId??(e?null:a?.teamId??null);return!i||!s?{kind:"missing_cloud_project",message:"Upload/sync this Project to Cloud before using Hybrid."}:{kind:"ready",cloudProjectId:i,cloudTeamId:s,cwd:n?.workspacePath??null,localProjectId:n?.id??null,workspaceName:t?.name??o?.name??a?.projectName??n?.name??"Hybrid workspace"}}function B_({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:H_(),cwd:n.cwd,title:a}}function OK(e){return g.useEffect(()=>{const t=e_(e.selectedSession);!t||e.composerDraftStore.getSnapshot()||e.composerDraftStore.set(t)},[e.composerDraftStore,e.selectedSession?.id]),g.useCallback(async t=>{const n=t.trim();if(!e.connection||!n||e.activeExperience==="chat")return!1;const a=A3(n);try{let o;const i=e.selectedSession;if(i&&Fl(i))o=await J.patchSession(e.connection,i.id,{title:a,metadata:Hp(i.metadata,n)}),e.setSessions(s=>s.map(l=>l.id===o.id?o:l));else{const s=i?.metadata?.workspaceTarget==="hybrid"?"hybrid":i?.metadata?.workspaceTarget==="local"?"local":null,l=i?.provider??(e.selectedCloudProject?"openpond":e.activeProvider),m=i?.modelRef??(l==="openpond"?{providerId:"openpond",modelId:es}:{providerId:l,modelId:e.activeModel}),d=s?{workspaceTarget:s}:!i&&e.workspaceTarget==="local"?{workspaceTarget:"local"}:{};let h;if(!i&&e.workspaceTarget==="hybrid"){const v=q_({cloudProjects:e.cloudProjects,selectedCloudProject:e.selectedCloudProject,selectedProject:e.selectedProject});if(v.kind!=="ready")throw new Error(v.message);const y=B_({modelRef:m,provider:l,target:v,title:a});h={...y,experience:"work",metadata:Hp(y.metadata,n)}}else h={experience:"work",provider:l,modelRef:m,openPondCommandAccessMode:i?.openPondCommandAccessMode??e.activeOpenPondCommandAccessMode,appId:i?.appId??null,appName:i?.appName??null,workspaceKind:i?.workspaceKind??(e.selectedCloudProject?"sandbox":e.selectedProject?"local_project":void 0),workspaceId:i?.workspaceId??e.selectedCloudProject?.id??e.selectedProject?.id??null,workspaceName:i?.workspaceName??e.selectedCloudProject?.name??e.selectedProject?.name??null,localProjectId:i?.localProjectId??e.selectedProject?.id??null,cloudProjectId:i?.cloudProjectId??e.selectedCloudProject?.id??null,cloudTeamId:i?.cloudTeamId??e.selectedCloudProject?.teamId??null,cwd:i?.cwd??e.selectedProject?.workspacePath??null,metadata:Hp(d,n),title:a};o=await J.createSession(e.connection,h),e.setSessions(v=>[o,...v])}return e.composerDraftStore.set(""),e.setMentionedAppId(null),e.setSelectedSessionId(null),e.setView("chat"),e.requestComposerFocus(),e.showToast("Task draft saved.","success"),!0}catch(o){return e.showToast(o instanceof Error?o.message:"Could not save task draft.","error"),!1}},[e.activeExperience,e.activeModel,e.activeOpenPondCommandAccessMode,e.activeProvider,e.cloudProjects,e.composerDraftStore,e.connection,e.requestComposerFocus,e.selectedCloudProject,e.selectedProject,e.selectedSession,e.setMentionedAppId,e.setSelectedSessionId,e.setSessions,e.setView,e.showToast,e.workspaceTarget])}const $K=[];function NK({primary:e,secondary:t}){const[n,a]=g.useState(!1),o=m3(),{composerDraftStore:i,appDispatch:s,pendingTerminalCommand:l,setPendingTerminalCommand:m,terminalTabs:d,setTerminalTabs:h,trainingDetailTasksetId:v,setTrainingDetailTasksetId:y,mentionedAppId:w,setMentionedAppId:I,cloudSetupDialog:R,setCloudSetupDialog:M,rightPanelTabRequest:P,workspaceDiffPanelViewState:N,mainComposerFocusRequestId:O,requestMainComposerFocus:j,projectConfirmDialog:k,resolveProjectConfirmDialog:C,query:T,searchOpen:z,archivedChatsOpen:B,sectionMenuOpen:D,cloudProjectsExpanded:V,sidebarOpen:le,view:te,selectedAppId:Ie,selectedProjectId:ke,selectedSessionId:Z,codexPermissionMode:Ae,codexReasoningEffort:he,busy:ue,diffPanelOpen:be,diffPanelExpanded:ne,rightPanelMode:ge,activeExperience:xe,changeNewExperience:qe,terminalOpen:Se,settingsSection:se,newProjectDialogOpen:we,newProjectMode:Oe,newProjectName:Qe,newProjectPath:Ge,newProjectBusy:st,commitDialogOpen:Le,commitMessage:Fe,commitIncludeUnstaged:De,commitNextStep:L,commitDraft:$,branchDialogOpen:H,branchDialogName:Q,toast:me,labDetailNavigation:_e,setQuery:$e,setSearchOpen:Xe,setArchivedChatsOpen:et,setSectionMenuOpen:rt,setCloudProjectsExpanded:it,setChatRowsVisibleCount:Me,setSidebarOpen:Be,setView:p,setSelectedAppId:U,setSelectedProjectId:K,setSelectedSessionId:de,setPrompt:re,setDraftProvider:F,setDraftModel:_,setDraftExperience:W,setDiffPanelOpen:X,setDiffPanelExpanded:oe,setRightPanelMode:G,setTerminalOpen:pe,setSettingsSection:fe,setNewProjectDialogOpen:je,setNewProjectName:Ee,setNewProjectPath:Ne,setCommitDialogOpen:Ve,setCommitMessage:Ue,setCommitIncludeUnstaged:ut,setCommitNextStep:Qt,setCommitDraft:zt,setBranchDialogOpen:Mn,setBranchDialogName:xn,setError:nn,showToast:bt,applyBootstrapPayload:sn,bootstrap:Lt,connection:yt,startup:ln,training:Ht,pinnedCollapsed:pn,cloudProjectsCollapsed:Ln,chatsCollapsed:vn,savedForLaterCollapsed:Ba,sidebarWidth:ua,sidebarResizing:Bt,diffPanelWidth:Kn,diffPanelResizing:ot,togglePinnedCollapsed:wn,toggleCloudProjectsCollapsed:Fa,toggleChatsCollapsed:Va,toggleSavedForLaterCollapsed:ma,startSidebarResize:Ka,startDiffPanelResize:ae,selectedApp:Ke,selectedCloudProject:ze,selectedProject:Ze,selectedProjectLinkedApp:kt,selectedSession:gt,sidebarSessions:lt,runtimeIndexes:Ct,runtimeEventStore:pa,chatMentionApps:Wn,connectedAppMentions:tt,pendingApproval:Rn,pendingChatUserMessages:St,account:In,activeModel:Un,activeProvider:jn,appDefaults:Wa,startMessage:Pa,organizations:yo,teamChatOrganization:Ga,teamChatTeamId:oa,teamChat:xt,publishTeamProfileAgent:Za,communitySidebar:fa,communityView:ni,teamAiThreadId:Sr,toggleTeamAiSidebar:kr,activeOpenPondCommandAccessMode:So,viewWorkspaceAppId:ai,viewWorkspaceId:oi,viewWorkspaceKind:ri,viewWorkspaceName:ii,selectedActionCatalog:ks,expandedProjectIds:xs,expandProject:Ja,toggleProjectExpanded:ws,changeCodexPermissionMode:si,changeCodexReasoningEffort:li,changeOpenPondCommandAccessMode:ci,resolveApproval:Is,beginNewChat:ra,beginNewChatWithTrainingModel:_s,dismissTrainingChatHandoff:Cs,trainingChatHandoff:Rs,selectTrainingChatTaskForComposer:di,chatHistoryLoadStates:ui,loadMoreSelectedChatHistory:mi,selectedPagedSessionEvents:Ps,activeSessions:Ya,archivedSessions:ko,pinnedSessions:Gn,savedForLaterSessions:As,savedForLaterFiles:Ts,sidebarFileBookmarks:bn,setSidebarFileStatus:pi,setSessions:Zn,projectRows:Aa,localProjectRows:xo,cloudProjectRows:Qa,projectSessionRowsByProjectId:Es,childSessionRowsByParentId:Ms,sidebarProjectIdBySessionId:wo,chatRows:xr,visibleChatRows:fi,chatRowsVisibleCount:wr,sessionEvents:hi,goalRuntime:Ir,subagentRuntime:gi,visibleChatMessages:ha,activeTerminalScope:Qo,terminalSummaries:_r,runningSessionIds:Io,selectedSessionRunning:vi,sidebarGoalRuntimeBySessionId:Xa,sidebarSubagentRuntimeBySessionId:bi,taskDragSessionId:js,taskPreviewSessionIds:Cr,startTaskDrag:yi,clearTaskDrag:Si,previewTaskDrop:ki,commitTaskDrop:Os,commitTaskPreviewDrop:Rr,dragItem:xi,startPinnedDrag:Xo,clearSidebarDrag:eo,previewPinnedDrop:$s,commitPinnedDrop:Ns,commitPinnedPreviewDrop:Ds,commandProjectRows:Ls,contextWindowStatus:Ta,pinnedRows:wi,workspaceBusy:Pr,diffBusy:Us,visibleWorkspaceState:_o,visibleWorkspaceDiff:zn,refreshVisibleWorkspaceDiff:zs,managedWorkspace:Hs,canSyncActiveWorkspace:qs,canPublishOpenPondProject:Bs,projectTarget:mt,workspaceTarget:Ft}=e,{title:Jn,browserConversationId:fn,handleWorkspaceDiffPanelViewStateChange:ia,openSessionInChat:On,changeProjectTarget:Ku,submitNewProjectDialog:Wu,changeWorkspaceBranch:Gu,openCommitDialog:Fs,openCreateWorkspaceBranchDialog:bc,openDefaultsSettingsFromBranchDialog:Zu,runWorkspaceTool:Ju,submitCommitDialog:Yu,submitCreateWorkspaceBranch:Qu,syncWorkspaceLocally:Xu,answerCreateImproveQuestion:em,applyCreateImproveCandidate:tm,approveCreateImproveRun:nm,cancelCreateImproveRun:am,changeDraftProvider:yc,openCreateImprovePullRequest:om,reconcileCreateImprovePullRequest:Sc,rejectCreateImproveCandidate:rm,pauseCreateImproveRun:im,resumeCreateImproveRun:sm,reviseCreateImproveRun:kc,stopTurn:Vs,archiveSession:lm,restoreSession:cm,renameSession:xc,toggleSessionPinned:wc,toggleProjectPinned:Ic,toggleSessionSavedForLater:Ks,moveProjectToCloud:dm,startCloudSetupUpload:_c,changeWorkspaceTarget:um,sendPromptFromMainComposer:Ws,openSandboxWorkspace:mm,openCloudProjectDialog:Cc,openUrlInBrowserPanel:pm,showBrowserPanel:Rc,showChangesPanel:fm,showGoalSidebarTab:hm,rightChatTrainingLaunchRequest:Pc,setRightChatTrainingLaunchRequest:gm,closeRightChatPanel:vm,openRightChatPanel:Gs,rightChatPanelViews:bm,showRightChatPanel:ym,showRightPanelDiffTab:er,submitRightChatPrompt:Ac,activateRightChatPanel:Sm,updateRightChatModel:km,updateRightChatPrompt:xm,updateRightChatProvider:wm,updateRightChatScrollState:Im,openProfileSettings:_m,diagnosticEvents:Cm,toggleRightSidebar:Tc,removeProject:Rm}=t,Ii=g.useCallback(Te=>{U(null),K(Te),de(null),p("chat"),Ja(Te),j()},[Ja,j,U,K,de,p]),Pm=g.useCallback((Te=null)=>{const ct=Z?wo[Z]??null:null;if(!Te&&ct){Ii(ct);return}ra(Te)},[ra,Ii,Z,wo]),Am=g.useCallback(async Te=>{if(!(!yt||!Lt))try{const ct=await J.savePreferences(yt,{defaultTeamId:Te});sn({...Lt,preferences:ct.preferences})}catch(ct){const jt=ct instanceof Error?ct.message:String(ct);throw nn(jt),bt("Could not switch teams","error"),ct}},[sn,Lt,yt,nn,bt]),Tm=g.useCallback(async()=>{if(yt)try{const Te=await J.signOutOpenPondAccount(yt);sn(Te);const ct=await J.savePreferences(yt,{defaultTeamId:null});sn({...Te,preferences:ct.preferences}),bt("Logged out","success")}catch(Te){const ct=Te instanceof Error?Te.message:String(Te);throw nn(ct),bt("Could not log out","error"),Te}},[sn,yt,nn,bt]),Zs=oa??Wa.defaultTeamId??null,Em=g.useMemo(()=>Aa.filter(Te=>Te.kind==="local"||Zs!==null&&Te.project.teamId===Zs),[Aa,Zs]),Mm=g.useMemo(()=>{const Te={};for(const ct of Ya){const jt=wo[ct.id];jt&&(Te[jt]=(Te[jt]??0)+1)}for(const ct of xo){if(ct.kind!=="local")continue;const jt=ct.project.linkedSandboxProject?.projectId;if(!jt||!ct.cloudLinkTrusted)continue;const ga=vt("cloud",jt);Te[ct.id]=(Te[ct.id]??0)+(Te[ga]??0)}return Te},[Ya,xo,wo]),[Js,Ys]=g.useState(null),[Qs,Xs]=g.useState(null),jm=IK(Lt?.profile,Lt?.extensionCatalog),[el,tl]=g.useState(null),[nl,Ec]=g.useState(null),[to,al]=g.useState(null),Mc=g.useCallback(()=>{U(null),K(null),de(null),rt(null),p("team")},[rt,U,K,de,p]),Om=g.useCallback(()=>{U(null),K(null),de(null),rt(null),fa.discoverCommunities()},[fa.discoverCommunities,rt,U,K,de]),ol=OK({activeExperience:xe,activeModel:Un,activeOpenPondCommandAccessMode:So,activeProvider:jn,cloudProjects:Lt?.cloudProjects??$K,composerDraftStore:i,connection:yt,requestComposerFocus:j,selectedCloudProject:ze,selectedProject:Ze,selectedSession:gt,setMentionedAppId:I,setSelectedSessionId:de,setSessions:Zn,setView:p,showToast:bt,workspaceTarget:Ft.value}),$m=g.useCallback(async Te=>{if(!yt)throw new Error("OpenPond is not connected.");let ct=jn,jt=Un;ct==="codex"&&(ct=Xf(Lt?.providers,{enabledOnly:!0}).find(yn=>yn.value!=="codex")?.value??Fr,jt=Hd(ct,Lt?.providers)??Ml);const ga=lt.find(yn=>yn.id===Te.sourceSessionId),Co=await J.createSession(yt,{experience:Te.target,provider:ct,modelRef:{providerId:ct,modelId:jt},openPondCommandAccessMode:So,appId:null,appName:null,workspaceId:null,workspaceName:null,localProjectId:null,cloudProjectId:null,cloudTeamId:null,cwd:null,title:`Continue ${ga?.title??"task"}`.slice(0,120),metadata:{experienceHandoff:_K({sourceTaskId:Te.sourceSessionId,sourceExperience:ga?.experience??null,targetExperience:Te.target,sourceMessageIds:Te.sourceMessageIds??[],sourceContext:Te.sourceContext,output:Te.output})}});return Zn(yn=>[Co,...yn]),W(Te.target),F(ct),_(jt),i.set(Te.prompt),cn({kind:"chat",sessionId:Co.id}),s({type:"selectSession",sessionId:Co.id,appId:null,projectId:null}),U(null),K(null),pe(!1),p("chat"),G("home"),X(Te.target==="work"),oe(!1),Co},[Un,So,jn,s,Lt?.providers,i,yt,oe,X,W,_,F,G,U,K,Zn,pe,p,lt]),jc=g.useCallback(Te=>{tl(Te),Ec(null),ra(null),Be(!0)},[ra,Be]),Nm=g.useCallback(Te=>{ra(null),W("work"),i.set(`$openpond-refiner-authoring ${Te}`),p("chat"),Be(!0)},[ra,i,W,Be,p]),Ar=g.useCallback(Te=>{Ec(kK(Te)),tl(null),ra(null),Be(!0)},[ra,Be]);g.useEffect(()=>{!el&&!nl||te!=="chat"||Z||ke||Ie||(Ys(el),Xs(nl),tl(null),Ec(null),G("home"),oe(!1),X(!0))},[el,nl,Ie,ke,Z,oe,X,G,te]),g.useEffect(()=>{!Js&&!Qs||te==="chat"&&be&&ge==="home"||(Ys(null),Xs(null))},[be,Qs,Js,ge,te]);const Dm=g.useCallback(()=>{Ys(null),Xs(null),oe(!1),X(!1)},[oe,X]),Lm=g.useCallback(Te=>{let ct;if(Te.workspaceKind==="local"){const jt=vt("local",Te.workspaceId);ct=`draft:${jt}`,U(null),K(jt),de(null),Ja(jt),p("chat")}else{const jt=lt.find(ga=>ga.id===Te.sourceSessionId||ga.workspaceId===Te.workspaceId);if(!jt){bt("This saved file's cloud chat is no longer available.","error");return}ct=jt.id,On(jt.id)}G("changes"),X(!0),al({id:Date.now(),conversationId:ct,file:Te}),Te.available||bt(`File unavailable: ${Te.path}`,"error")},[Ja,On,X,G,U,K,de,p,bt,lt]);g.useEffect(()=>{if(!yK(to,fn))return;const Te=window.setTimeout(()=>{G("changes"),X(!0),al(ct=>SK(ct,to.id))},0);return()=>window.clearTimeout(Te)},[fn,X,G,to]);const Um=CK(te);g.useEffect(()=>{if(o){if(o.kind==="models"||o.kind==="models_unavailable"){te!=="labs"&&p("labs");return}if(o.kind==="settings"){U(null),K(null),de(null),fe(o.section),te!=="settings"&&p("settings");return}if(o.kind==="view"){U(null),K(null),de(null),te!==o.view&&p(o.view);return}o.sessionId!==null&&(U(null),K(null)),de(o.sessionId),te!=="chat"&&p("chat")}},[o,U,K,de,fe,p,te]);const zm=g.useCallback(Te=>{if(rt(null),U(null),K(null),de(null),Te==="models"){Gi(po()),p("labs");return}Te==="chat"&&cn({kind:"chat",sessionId:null}),qe(yv())},[qe,cn,rt,U,K,de,p]),Hm=g.useCallback(async(Te,ct)=>{const jt=await Ht.actions.acceptHarnessReview(Te,ct,{providerId:jn,modelId:Un},he);return jt?(y(jt.materializedTasksetId??null),Gi(po()),p("labs"),!0):(bt("Taskset review could not be opened.","error"),!1)},[Un,jn,he,Gi,po,y,p,bt,Ht.actions]);if(!ln.ready)return x.jsx(LV,{startup:ln});if(te==="settings")return x.jsx(i0,{showToast:bt,children:x.jsx(OV,{settings:{payload:Lt,connection:yt,diagnostics:Cm,initialSection:se,onPayload:sn,onError:nn,onToast:bt,onOpenSourceSession:On,onStartRefinerAuthoring:Nm,onAcceptEvaluationReview:Hm,onOpenSkill:jc,onOpenExtension:Ar,teamChatCurrentUserId:xt.currentUserId,teamChatEnabled:oa!==null,teamChatNotificationMode:xt.notificationMode,teamChatThreads:xt.threads,onTeamChatNotificationModeChange:xt.setNotificationMode,onTeamChatThreadMuteChange:xt.setThreadMuted,diffPanelWidth:Kn,diffPanelResizing:ot,diffPanelExpanded:ne,onDiffPanelResizeStart:ae,onDiffPanelExpandedChange:oe,onBack:()=>{const Te=c3(o);cn(Te),p(Te.kind==="models"?"labs":"chat"),Be(!0)}},toast:{toast:me,onDismiss:()=>s({type:"field",key:"toast",value:null})}})});const qm=Nu(),rl=yt?.platform??navigator.platform,Oc=qm&&ev(rl),il=Qo,Bm=_o?.initialized?_o.repoPath:gt?.cwd??null,Fm={"--sidebar-width":`${ua}px`,"--diff-panel-width":`${Kn}px`},Vm=te==="chat"&&xe!=="chat"||te==="labs"||te==="scheduled"&&n||te==="team"&&!!Sr,Km=["app-shell",Oc?"platform-macos":"",le?"sidebar-open":"sidebar-closed",Bt?"sidebar-resizing":"",ot?"diff-panel-resizing":""].filter(Boolean).join(" "),at=Z?ui[Z]:null,Xt=Z?at?.cursorSequence??HV(Mo(Ps,gc(Ct,Z))):null,Gt=!!Z&&!!yt&&(qt(Z)?!0:!!Lt?.eventWindow?.hasMoreBefore&&!!Xt)&&(at?.hasMore??!0),Ea=!!at?.loading,Wm=(()=>{const Te=Ht.payload;if(!Te)return{};const ct=new Map(Te.plans.map(yn=>[yn.id,yn])),jt=new Set(["queued","starting","running","cancelling","reconciling"]),ga={queued:"Queued",starting:"Starting",running:"Running",cancelling:"Cancelling",reconciling:"Reconciling"},Co={};for(const yn of[...Te.modelRuns].sort((Ma,_i)=>_i.updatedAt.localeCompare(Ma.updatedAt))){if(yn.kind==="evaluation"||!["prepared","running"].includes(yn.status))continue;const Ma=Te.jobs.filter(Gm=>Gm.metadata.modelRunId===yn.id).sort((Gm,WC)=>WC.updatedAt.localeCompare(Gm.updatedAt))[0];if(Ma&&!jt.has(Ma.status))continue;const _i=Ma?.status??(yn.status==="prepared"?"starting":"running");Co[yn.modelId]={label:ga[_i]??"Running",status:_i}}for(const yn of[...Te.jobs].sort((Ma,_i)=>_i.updatedAt.localeCompare(Ma.updatedAt))){if(!jt.has(yn.status))continue;const Ma=ct.get(yn.planId)?.modelId;!Ma||Co[Ma]||(Co[Ma]={label:ga[yn.status]??"Active",status:yn.status})}return Co})();return x.jsx(i0,{showToast:bt,children:x.jsx(jV,{className:Km,style:Fm,sidebar:{productArea:Um,modelProjects:(Ht.payload?.modelProjects??[]).filter(Te=>Te.hosted===null||Te.hosted.teamId===(Wa.defaultTeamId?.trim()??null)),modelTrainingActivityByProjectId:Wm,onProductAreaChange:zm,experience:xe,view:te,selectedAppId:Ie,selectedProjectId:ke,selectedSessionId:Z,selectedTeamThreadId:xt.selectedThreadId,teamChatEnabled:oa!==null,organizations:yo,teamChatOrganization:Ga,teamChatLoading:xt.loading,currentUserId:xt.currentUserId,teamMembers:xt.members,teamThreads:xt.threads,...fa,account:In,connection:yt,profile:Lt?.profile,pinnedCollapsed:pn,cloudProjectsCollapsed:Ln,chatsCollapsed:vn,savedForLaterCollapsed:Ba,archivedChatsOpen:B,cloudProjectsExpanded:V,sectionMenuOpen:D,dragItem:xi,taskDragSessionId:js,taskPreviewSessionIds:Cr,activeSessions:Ya,archivedSessions:ko,pinnedRows:wi,pinnedSessions:Gn,savedForLaterSessions:As,savedForLaterFiles:Ts,projectRows:Aa,localProjectRows:xo,cloudProjectRows:Qa,projectSessionRowsByProjectId:Es,childSessionRowsByParentId:Ms,sidebarProjectIdBySessionId:wo,terminalSummaries:_r,runningSessionIds:Io,goalRuntimeBySessionId:Xa,subagentRuntimeBySessionId:bi,visibleChatRows:fi,chatRows:xr,chatRowsVisibleCount:wr,expandedProjectIds:xs,currentVersion:Lt?.server.version??null,platform:rl,arch:yt?.arch??null,onSidebarResizeStart:Ka,setSidebarOpen:Be,setView:p,setSelectedAppId:U,setSelectedProjectId:K,setSelectedSessionId:de,setSearchOpen:Xe,setSectionMenuOpen:rt,setSettingsSection:fe,onSelectTeam:Am,onLogOut:Tm,onTogglePinnedCollapsed:wn,onToggleCloudProjectsCollapsed:Fa,onToggleChatsCollapsed:Va,onToggleSavedForLaterCollapsed:ma,setArchivedChatsOpen:et,setCloudProjectsExpanded:it,setChatRowsVisibleCount:Me,beginNewChat:Pm,beginProjectChat:Ii,dockSessionRight:Gs,selectTeamThread:Te=>{p("team"),xt.selectThread(Te)},openTeamDm:Te=>{p("team"),xt.openDm(Te)},toggleSessionPinned:wc,toggleProjectPinned:Ic,toggleSessionSavedForLater:Ks,openSidebarFile:Lm,setSidebarFileStatus:(Te,ct)=>{pi(Te,ct)},archiveSession:lm,restoreSession:cm,renameSession:xc,removeProject:Rm,expandProject:Ja,toggleProjectExpanded:ws,startPinnedDrag:Xo,clearSidebarDrag:eo,previewPinnedDrop:$s,commitPinnedDrop:Ns,commitPinnedPreviewDrop:Ds,startTaskDrag:yi,clearTaskDrag:Si,previewTaskDrop:ki,commitTaskDrop:Os,commitTaskPreviewDrop:Rr},topBar:{sidebarOpen:le,title:Jn,backAction:_e.backAction,breadcrumbs:_e.breadcrumbs,conversationId:te==="chat"?Z:null,workspaceName:ii,workspaceId:oi,busy:ue,workspaceState:_o,workspaceKind:ri,selectedApp:kt??Ke,selectedProject:Ze,workspaceDiff:zn,managedWorkspace:Hs,workspaceBusy:Pr,defaultTeamId:Wa.defaultTeamId,showDiffControls:te==="chat"&&xe==="development",diffPanelOpen:be,terminalOpen:Se,rightSidebarAvailable:Vm,rightSidebarOpen:te==="scheduled"?n:be,onToggleDiffPanel:Tc,onToggleRightSidebar:te==="scheduled"?()=>a(Te=>!Te):te==="team"&&Sr?kr:Tc,onOpenSearch:()=>{rt(null),Xe(!0)},onToggleTerminal:()=>pe(Te=>!Te),onRunTerminalCommand:Te=>{m({id:Date.now(),scope:il,command:Te}),pe(!0)},onWorkspaceToolAction:Ju,onOpenCommitDialog:Fs,onWorkspaceBranchChange:Gu,onWorkspaceBranchCreate:bc,connection:yt,onBootstrap:sn,onOpenSandboxWorkspace:mm,onShowSidebar:()=>Be(!0),onOpenTeamChat:Mc,onDiscoverCommunities:Om,collaborationView:te==="team"||te==="community"?te:null,platform:rl,showWorkspaceControls:te!=="team"&&te!=="community"&&te!=="labs"&&te!=="scheduled"&&te!=="outputs"&&te!=="projects"&&(xe==="development"||xe==="work"&&!!(Ze||gt?.localProjectId||gt?.cloudProjectId||gt?.workspaceKind==="local_project"))},mainPane:{experience:xe,onNewExperienceChange:qe,view:te,teamChat:{currentUserId:xt.currentUserId,members:xt.members,agents:xt.agents,profile:Lt?.profile??null,teamId:oa,teamName:Ga?.displayName??null,detail:xt.detail,aiThread:xt.aiThread,agentConversation:xt.agentConversation,loading:xt.loading,busy:xt.busy,error:xt.error,connection:yt,providerSettings:Lt?.providers??null,provider:jn,model:Un,codexPermissionMode:Ae,codexReasoningEffort:he,openPondCommandAccessMode:So,contextWindowStatus:Ta,showToast:bt,onProviderChange:yc,onModelChange:_,onCodexPermissionModeChange:si,onCodexReasoningEffortChange:li,onOpenPondCommandAccessModeChange:ci,onOpenProviderSettings:()=>{fe("providers"),p("settings"),cn({kind:"settings",section:"providers"})},onSendMessage:xt.sendMessage,onPublishProfileAgent:Za,onOpenAiThread:async Te=>{await xt.openAiThread(Te),G("chat"),X(!0)},onOpenAgentConversation:async Te=>{await xt.openAgentConversation(Te),G("chat"),X(!0)},onCloseAiThread:()=>X(!1),onCloseAgentConversation:()=>{xt.closeAgentConversation(),X(!1)},onSendAgentTurn:xt.sendAgentTurn,onSendAiTurn:xt.sendAiTurn,onStopAiTurn:xt.stopAiTurn,onEditMessage:xt.editMessage,onDeleteMessage:xt.deleteMessage,onRetryMessage:xt.retryMessage,onDismissFailedMessage:xt.dismissFailedMessage,onLoadMoreMessages:xt.loadMoreMessages,onRetryLoad:xt.refresh},community:ni,bootstrap:Lt,runtimeEvents:hi,chatMessages:ha,pendingUserMessage:Z?St[Z]??null:null,contextWindowStatus:Ta,goalRuntime:Ir,subagentRuntime:gi,selectedSessionId:Z,composerDraftStore:i,mainComposerFocusRequestId:O,labCloseDetailRequestId:_e.closeDetailRequestId,labCloseDetailKind:_e.closeDetailKind,sideChatTrainingLaunchRequest:Pc,onSideChatTrainingLaunchHandled:Te=>gm(ct=>ct?.id===Te?null:ct),mentionApps:Wn,connectedAppMentions:tt,profileSkills:jm,selectedMentionAppId:w,busy:ue,turnRunning:vi,activeProvider:jn,activeModel:Un,codexPermissionMode:Ae,codexReasoningEffort:he,openPondCommandAccessMode:So,pendingApproval:Rn,activeWorkspaceAppId:ai,activeWorkspaceId:oi,activeWorkspaceKind:ri,projectTarget:mt,actionCatalog:ks,workspaceTarget:Ft,connection:yt,workspaceName:ii,workspaceState:_o,workspaceDiff:zn,workspaceBusy:Pr,diffBusy:Us,forceChatThread:!!Z,diffPanelOpen:be,diffPanelExpanded:ne,rightPanelMode:ge,rightPanelTabRequest:P,rightChatPanels:bm,runtimeEventStore:pa,nativeSkillSidebar:Js,extensionSkillSidebar:Qs,workspaceDiffPanelViewState:N,sidebarFileOpenRequest:to,sidebarFileBookmarks:bn,onSetSidebarFileStatus:(Te,ct)=>{pi(Te,ct)},browserConversationId:fn,terminalScope:il,terminalTabs:d,terminalCwd:Bm,pendingTerminalCommand:l,terminalOpen:Se,onToggleTerminal:()=>pe(Te=>!Te),onWorkspaceDiffPanelViewStateChange:ia,training:Ht,trainingSessions:lt,trainingChatHandoff:Rs,trainingDetailTasksetId:v,onTrainingDetailTasksetIdChange:y,onTrainingChatTaskSelect:di,onTrainingChatHandoffDismiss:Cs,onOpenSession:On,onExperienceHandoff:$m,cloudProjects:Lt?.cloudProjects??[],projects:Em,projectsAccountBaseUrl:In?.baseUrl??In?.activeProfile?.baseUrl??null,projectsTeamName:Ga?.displayName??null,projectTaskCounts:Mm,onNewCloudProject:Cc,onNewProjectTask:Te=>Ii(Te.id),onToggleProjectPinned:Ic,onUploadLocalProject:dm,chatHistoryHasMore:Gt,chatHistoryLoading:Ea,onDiffPanelResizeStart:ae,onToggleDiffPanelExpanded:()=>oe(Te=>!Te),onShowDiffPanel:fm,onShowBrowserPanel:Rc,onShowFilesPanel:()=>er("files"),onShowGoalSidebarTab:hm,onShowTrainingDraftPanel:()=>{G("training"),X(!0)},onShowRightChatPanel:ym,onAddRightChat:()=>Gs(null),onOpenRightChatForSession:(Te,ct)=>{const jt=ct??lt.find(ga=>ga.id===Te)??null;jt&&Gs(jt,{preserveView:!0})},onLabDetailOpenChange:_e.onDetailOpenChange,scheduledDetailOpen:n,onScheduledDetailOpenChange:a,onTerminalTabsChange:h,onCloseRightChatPanel:vm,onCloseNativeSkillSidebar:Dm,onActivateRightChatPanel:Sm,onRightChatModelChange:km,onRightChatPromptChange:xm,onRightChatScrollStateChange:Im,onRightChatProviderChange:wm,onSubmitRightChat:Ac,onStopRightChat:Te=>Vs(Te),onCloseTerminal:()=>pe(!1),onLoadMoreChatHistory:mi,canSyncWorkspace:qs,startMessage:Pa,onPayload:sn,onError:nn,setView:p,onOpenProfileSettings:_m,onOpenProviderSettings:()=>{cn({kind:"settings",section:"providers"})},onOpenTrainingSettings:()=>{cn({kind:"settings",section:"training"})},onOpenDatasetStorageSettings:()=>{cn({kind:"settings",section:"dataset-storage"})},changeDraftProvider:yc,changeProjectTarget:Ku,changeWorkspaceTarget:um,setDraftProvider:F,setDraftModel:_,onBeginNewChatWithModel:_s,changeCodexPermissionMode:si,changeCodexReasoningEffort:li,changeOpenPondCommandAccessMode:ci,resolveApproval:Is,answerCreateImproveQuestion:em,applyCreateImproveCandidate:tm,approveCreateImproveRun:nm,cancelCreateImproveRun:am,openCreateImprovePullRequest:om,reconcileCreateImprovePullRequest:Sc,rejectCreateImproveCandidate:rm,pauseCreateImproveRun:im,resumeCreateImproveRun:sm,reviseCreateImproveRun:kc,setMentionedAppId:I,showToast:bt,onSaveTaskDraft:ol,sendPrompt:Ws,stopTurn:Te=>Vs(void 0,Te),syncWorkspaceLocally:Xu,refreshWorkspaceDiff:zs},cloudSetup:{state:R,onClose:()=>M(null),onOpenBrowserUrl:pm,onStart:()=>{_c()}},projectConfirm:{state:k,onResolve:C},lazyPanels:{activeSessions:Ya,branchDialogName:Q,branchDialogOpen:H,commitDialogOpen:Le,commitDraft:$,commitIncludeUnstaged:De,commitMessage:Fe,commitNextStep:L,canPublishOpenPondProject:Bs,connection:yt,expandProject:Ja,newProjectBusy:st,newProjectDialogOpen:we,newProjectDirectory:Wa.defaultNewProjectDirectory,newProjectMode:Oe,newProjectName:Qe,newProjectPath:Ge,projectRows:Ls,query:T,searchOpen:z,visibleWorkspaceDiff:zn,visibleWorkspaceState:_o,workspaceBusy:Pr,appDispatch:s,beginNewChat:()=>ra(null),openDefaultsSettingsFromBranchDialog:Zu,setBranchDialogName:xn,setBranchDialogOpen:Mn,setCommitDialogOpen:Ve,setCommitDraft:zt,setCommitIncludeUnstaged:ut,setCommitMessage:Ue,setCommitNextStep:Qt,setNewProjectDialogOpen:je,setNewProjectName:Ee,setNewProjectPath:Ne,setPrompt:re,setQuery:$e,setSearchOpen:Xe,submitCommitDialog:Yu,submitCreateWorkspaceBranch:Qu,submitNewProjectDialog:Wu},toast:{toast:me,onDismiss:()=>s({type:"field",key:"toast",value:null})}})})}const Hi=new Map,bd=new Map;function rh(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 DK(e){const t=e?.trim();if(!t)return null;const n=Hi.get(t);return n?.updatedAt?n.organizations:null}function LK(e,t){const n=e?.trim();if(n){Hi.set(n,{organizations:t,promise:null,updatedAt:Date.now()});for(const a of bd.get(n)??[])a()}}function UK(e,t){const n=e?.trim();if(!n)return()=>{};const a=bd.get(n)??new Set;return a.add(t),bd.set(n,a),()=>{a.delete(t),a.size===0&&bd.delete(n)}}function h0(e){const t=e.accountKey?.trim();if(!t)return Promise.resolve([]);const n=Hi.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=>(LK(t,o),o)).catch(o=>{const i=Hi.get(t);throw i?.promise===a&&Hi.set(t,{organizations:i.organizations,promise:null,updatedAt:i.updatedAt}),o});return Hi.set(t,{organizations:n?.organizations??[],promise:a,updatedAt:n?.updatedAt??0}),a}const iQ="openpond.config.json";function sQ(e,t,n){return t<=0?-1:n==="Home"?0:n==="End"?t-1:n==="ArrowRight"?(e+1)%t:(e-1+t)%t}function F_(){return{activeTab:"files",openFilePaths:[],selectedPath:null}}function Wp(e){return{activeTab:e.activeTab,openFilePaths:[...e.openFilePaths],selectedPath:e.selectedPath}}function lQ(e,t=null){const n=HK(e.openFilePaths.map(o=>v0(o,t)).filter(Boolean)),a=e.selectedPath&&v0(e.selectedPath,t)||null;return{activeTab:e.activeTab==="file"&&!a?"files":e.activeTab,openFilePaths:n,selectedPath:a}}function g0(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 v0(e,t=null){let n=zK(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 cQ(e){return e.startsWith("/")||/^[A-Za-z]:\//.test(e)}function dQ(e){return{path:e,status:"unchanged",additions:0,deletions:0,patch:"",content:null}}function uQ(e,t){const n=b0(e.path);return!n||e.path.endsWith("/")||e.content==null&&/Could not access .+\/null['"]?/.test(e.patch)?!0:t.some(a=>{const o=b0(a);return!!(o&&o.startsWith(`${n}/`))})}function mQ(e){return/\.(?:md|markdown|mdx)$/i.test(e)||/(?:^|\/)readme$/i.test(e)}function pQ(e){return/\.(?:doc|docx|pdf)$/i.test(e)}function zK(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 HK(e){return Array.from(new Set(e))}function b0(e){const n=e.replace(/\\/g,"/").replace(/^\.\/+/,"").split("/").filter(Boolean);return n.length===0?null:n.join("/")}function qK(e){if(!e||e.state!=="signed_in")return null;const t=e.accounts.find(l=>l.isActive)??null,n=e.profile?.id?.trim()??"",a=e.activeProfile?.handle?.trim()||t?.handle?.trim()||e.label.trim()||"signed_in",o=e.activeProfile?.baseUrl??t?.baseUrl??e.baseUrl??"",i=e.apiBaseUrl??t?.apiBaseUrl??"",s=e.chatApiBaseUrl??t?.chatApiBaseUrl??"";return[n?`profile:${n}`:"profile:unknown",a,o,i,s].join("|")}function V_(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"cloud-project"}function BK(e){const t=new TextEncoder().encode(e);let n="";for(const a of t)n+=String.fromCharCode(a);return btoa(n)}function Uu(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||V_(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 FK(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 VK(e,t){const n=e.filter(o=>o.status==="active"&&o.workspaceKind==="shared"),a=t?.trim()??"";if(a){const o=n.find(i=>i.teamId===a);if(o)return o}return n.find(o=>o.role==="owner")??n.find(o=>o.role==="admin")??n[0]??null}function KK(...e){for(const t of e){const n=t?.trim();if(n)return n}return""}function WK({draftProvider:e,hasSelectedCloudProject:t,selectedSessionHybridWorkspace:n}){return t&&!n?"openpond":e}const GK=[{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 ZK(...e){return KK(...e.map(t=>{const n=t?.trim();return n&&!n.includes("@")?n:null}))}function JK(e){if(e?.state!=="signed_in")return"";const t=e.accounts.find(n=>n.isActive)??null;return ZK(e.profile?.name,e.label,t?.displayLabel,e.profile?.handle,t?.handle,e.activeProfile?.handle)}function YK({bootstrap:e,draftModel:t,draftProvider:n,selectedApp:a,selectedAppId:o,selectedCloudProject:i,selectedProject:s,selectedSession:l,selectedSessionId:m,selectedSessionLinkedProject:d}){const h=l?.workspaceKind==="local_project"?l.workspaceId??null:d?.id??null,v=qt(m)&&!l,y=l?go(l.workspaceKind):!1,w=vo(l),I=l?jK(l):!1,R=l?.cwd&&(!y||w)?Qk(l.cwd):null,M=e?.providers??null,P=_a(s,e?.cloudProjects??[]),N=WK({draftProvider:n,hasSelectedCloudProject:!!i,selectedSessionHybridWorkspace:w}),O=br(N,t,M),j=ba(e?.preferences),k=v?null:l?y?l.workspaceKind??"sandbox":I?"sandbox":h?"local_project":l.workspaceKind??(l.appId?"sandbox_app":R?"local_project":null):i?"sandbox":s?"local_project":o?"sandbox_app":null,C=v?null:l?y&&!w||I?null:h||(l.workspaceId??l.appId??R):i?null:s?.id??o,T=v?null:l?y?l.workspaceId??null:I?null:h??l.workspaceId??l.appId??R:i?null:s?.id??o,z=e?.account??null,B=!e||z?.state==="loading"||z?.state==="switching",D=!B&&z?.state==="signed_out",V=B?null:D?"Sign in":z?.label??z?.activeProfile?.handle??"Account",le=JK(z),te=le?`Welcome, ${le}`:"Welcome",Ie=l?.workspaceName??l?.appName??i?.name??s?.name??a?.name??null,ke=go(k)?"cloud":"local",Z=s?.name??d?.name??(l?.workspaceKind==="local_project"?l.workspaceName:null)??"Local workspace",Ae=(ke==="cloud"?Ie:null)??i?.name??P?.name??s?.name??"Cloud workspace",he=!!(i?.id||P?.id||l?.cloudProjectId||ke==="cloud");return{account:z,accountLabel:V,accountPending:B,accountSignedOut:D,activeModel:O,activeProvider:N,activeWorkspaceAppId:C,activeWorkspaceId:T,activeWorkspaceKind:k,activeWorkspaceLocation:ke,appDefaults:j,cloudLinked:he,cloudTargetName:Ae,localTargetName:Z,selectedCodexHistoryPending:v,selectedSessionCloudWorkspace:y,selectedSessionLocalPathWorkspaceId:R,selectedSessionPendingCloudStart:I,selectedSessionProjectId:h,startMessage:te,workspaceName:Ie}}function QK({accountPending:e,accountSignedOut:t,activeWorkspaceLocation:n,bootstrap:a,busy:o,cloudLinked:i,selectedCloudProject:s,selectedProject:l,selectedSession:m,pendingWorkspaceTarget:d,workspaceStates:h,workspaceBusy:v}){const y=_a(l,a?.cloudProjects??[]),I=!!!l?.linkedSandboxProject?.projectId||!!y,R=g.useMemo(()=>{const T=(a?.localProjects??[]).map(V=>({value:`local:${V.id}`,label:V.name,detail:V.workspacePath,kind:"local"})),z=(a?.cloudProjects??[]).map(V=>({value:`cloud:${V.id}`,label:V.name,detail:V.organizationName??V.sourceLabel??"OpenPond Cloud",kind:"cloud"})),B=l?`local:${l.id}`:s?`cloud:${s.id}`:"none",D=[...T,...z].find(V=>V.value===B)??null;return{value:B,label:D?.label??"Select Project",detail:D?.detail??"Choose a project for local or cloud work",busy:v||o,options:[...T,...z,...GK,{value:"none",label:"Don't work in a project",detail:"General chat without project files",kind:"none"}]}},[a?.cloudProjects,a?.localProjects,o,s,l,v]),M=!!(i||l),P=!!(s?.id||y?.id||m?.cloudProjectId||vo(m)),N=l?h[l.id]??null:null,O=s_(N,{branch:l?.linkedSandboxProject?.defaultBranch??null,path:l?.workspacePath??m?.cwd??null,linkedCloudSourceKnown:l?.linkedSandboxProject?.projectId&&I?!!l.linkedSandboxProject.lastUploadedCommit||!N?.headCommit:!0}),j=l_(l,s??y,N,{cloudLinkTrusted:I}),k=V3(l,N,{cloudLinkTrusted:I}),C=g.useMemo(()=>{const T={value:"local",label:l?"Local checkout":"Local",detail:l?"Use the selected checkout on this machine.":"Use an app-managed task workspace on this machine.",stateNote:l?O:"App-managed local task workspace",disabled:!1,disabledReason:null},z={value:"hybrid",label:"Hybrid",detail:"Use your selected model with hosted sandbox edits.",stateNote:P?j:"upload required",disabled:e||t||!P,disabledReason:t?"Add an OpenPond account before using Hybrid.":"Upload/sync this Project to Cloud before using Hybrid."},B={value:"cloud",label:"Hosted",detail:"Run with hosted compute, with or without a Project.",stateNote:l||s?j:"Projectless hosted task",disabled:e||t,disabledReason:t?"Add an OpenPond account before using Cloud.":e?"Checking OpenPond account.":null},D={value:"upload_cloud",label:"Upload/sync to cloud",detail:"Push local source to OpenPond Git before cloud work.",stateNote:k,disabled:e||t||!l,disabledReason:t?"Add an OpenPond account before uploading source.":"Select a local Project before uploading source."},V=n==="cloud"?"local":"cloud",le=V==="local"?T:B;let te=n==="cloud"?B:T;return d==="cloud"?te=B:d==="local"?te=T:(vo(m)||d==="hybrid")&&(te=z),{value:te.value,label:te.label,detail:te.stateNote||te.detail,busy:v,action:{...le,label:V==="cloud"?"Hosted":l?"Local checkout":"Check out locally"},uploadAction:l?D:null,options:[T,z,B]}},[n,e,t,i,M,j,P,O,d,l,m,k,v]);return{projectTarget:R,workspaceTarget:C}}function Dn(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")}function K_(e){return Dn(e.name||e.gitRepo||e.id)}function fQ(e){return`@${K_(e)}`}function W_(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>Dn(t[1]??"")).filter(Boolean)}function XK(e,t){const n=W_(e);if(n.length===0)return!1;const a=new Set([Dn(t.id),K_(t),t.gitRepo?Dn(t.gitRepo):""].filter(Boolean));return n.some(o=>a.has(o))}function G_(e){return e.filter(t=>t.sandbox)}function e9(e,t){const n=W_(e);if(n.length===0)return null;const a=new Map;for(const o of n){const i=t.find(s=>{const l=Dn(s.id),m=Dn(s.name),d=s.gitRepo?Dn(s.gitRepo):"";return o===l||o===m||o===d});i&&a.set(i.id,i)}return a.size===1?Array.from(a.values())[0]??null:null}function hQ(e,t){const n=e.slice(0,t),a=n.match(/(?:^|\s)@([A-Za-z0-9_-]*)$/);if(!a||typeof a.index!="number")return null;const o=n.slice(a.index).indexOf("@");return o<0?null:{query:Dn(a[1]??""),start:a.index+o}}function t9(e){return new Set(e.map(t=>t.id))}function y0(e,t){const n=e?.linkedOpenPondApp??null;return n?.appId&&t.has(n.appId)?n:null}function n9({bootstrap:e,codexHistorySessions:t,selectedProjectId:n,selectedSessionId:a,selectedAppId:o,sessions:i}){const s=g.useMemo(()=>e?.apps.find(D=>D.id===o)??null,[e?.apps,o]),l=g.useMemo(()=>new Map((e?.localProjects??[]).map(D=>[D.id,D])),[e?.localProjects]),m=g.useMemo(()=>new Map((e?.cloudProjects??[]).map(D=>[D.id,D])),[e?.cloudProjects]),d=g.useMemo(()=>ZI(n),[n]),h=g.useMemo(()=>d?.kind==="local"?l.get(d.id)??null:null,[l,d]),v=g.useMemo(()=>d?.kind==="cloud"?m.get(d.id)??null:null,[m,d]),y=g.useMemo(()=>t9(e?.apps??[]),[e?.apps]),w=g.useMemo(()=>G_(e?.apps??[]),[e?.apps]),I=g.useMemo(()=>{const D=[];for(const V of e?.localProjects??[]){const le=y0(V,y);le&&D.push([le.appId,V.id])}return new Map(D)},[e?.localProjects,y]),R=g.useMemo(()=>new Set((e?.localProjects??[]).map(D=>D.id)),[e?.localProjects]),M=g.useMemo(()=>t_(e?.localProjects??[]),[e?.localProjects]),P=g.useRef([]),N=g.useMemo(()=>a9(i,t,P.current),[t,i]),O=g.useMemo(()=>N.find(D=>D.id===a)??null,[N,a]),j=g.useMemo(()=>{if(!O)return null;if(O.localProjectId)return l.get(O.localProjectId)??null;if(O.workspaceKind==="local_project")return O.workspaceId?l.get(O.workspaceId)??null:null;const D=j3(O,R,M);if(D)return l.get(D)??null;if(!O.appId)return null;const V=I.get(O.appId);return V?l.get(V)??null:null},[I,l,R,M,O]),k=g.useMemo(()=>O?.cloudProjectId?m.get(O.cloudProjectId)??null:null,[m,O]),C=h??j,T=v??k,z=g.useMemo(()=>y0(C,y),[y,C]),B=g.useMemo(()=>z?e?.apps.find(D=>D.id===z.appId)??null:null,[e?.apps,z]);return{cloudProjectById:m,currentAppIds:y,linkedProjectByAppId:I,localProjectById:l,mentionableSandboxApps:w,selectedApp:s,selectedCloudProject:T,selectedProject:C,selectedProjectLinkedApp:B,selectedProjectLinkedOpenPondApp:z,selectedSession:O,selectedSessionLinkedProject:j,sidebarSessions:N}}function a9(e,t,n){const a=new Map;for(const d of e){const h=S0(d);a.set(h,d)}for(const d of t){const h=S0(d),v=a.get(h);a.set(h,v?o9(v,d):d)}const o=Array.from(a.entries());if(!n)return o.sort((d,h)=>k0(d[1],h[1])).map(d=>d[1]);const i=[],s=new Set;for(const d of n){const h=a.get(d);h&&(i.push([d,h]),s.add(d))}const m=[...o.filter(([d])=>!s.has(d)).sort((d,h)=>k0(d[1],h[1])),...i];return n.splice(0,n.length,...m.map(([d])=>d)),m.map(d=>d[1])}function o9(e,t){return{...e,metadata:r9(e.metadata,t.metadata),status:e.status==="active"||t.status==="active"?"active":e.status,updatedAt:i9(e.updatedAt,t.updatedAt)}}function S0(e){return e.codexThreadId?`codex:${e.codexThreadId}`:`session:${e.id}`}function k0(e,t){const n=x0(t)-x0(e);return n!==0?n:e.title.localeCompare(t.title)}function r9(e,t){const n={...e??{},...t??{}};return Object.keys(n).length>0?n:void 0}function i9(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 x0(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 s9(e){return!!(e&&go(e.workspaceKind)&&!vo(e)&&e.provider!=="openpond")}function l9(e,t){const n=QI(e,t);return`${e.id}\0${n.provider}\0${n.model}`}function c9({activeWorkspaceId:e,activeWorkspaceKind:t,appDispatch:n,connection:a,expandProject:o,linkedProjectByAppId:i,providerSettings:s,selectedAppId:l,selectedSession:m,selectedSessionId:d,selectedSessionProjectId:h,setDiffPanelExpanded:v,setDraftModel:y,setDraftProvider:w,setError:I,setSelectedAppId:R,setSelectedProjectId:M,setSessions:P,setTerminalOpen:N,toast:O}){const j=g.useRef(null);g.useEffect(()=>{if(!l)return;const k=h??(d?null:i.get(l)??null);if(!k)return;const C=vt("local",k);R(null),M(C),o(C)},[o,i,l,d,h,R,M]),g.useEffect(()=>{if(!O||O.persistent)return;const k=window.setTimeout(()=>{n({type:"clearToast",toastId:O.id})},O.durationMs??(O.tone==="error"?7e3:3500));return()=>window.clearTimeout(k)},[n,O]),g.useEffect(()=>{function k(C){(C.metaKey||C.ctrlKey)&&C.key==="`"&&(C.preventDefault(),N(T=>!T))}return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[N]),g.useEffect(()=>{v(!1)},[e,t,v]),g.useEffect(()=>{if(!d){j.current=null;return}if(!m||m.id!==d)return;const k=l9(m,s);if(j.current===k)return;j.current=k;const C=QI(m,s);w(C.provider),y(C.model)},[s,m,d,y,w]),g.useEffect(()=>{!a||!m||!s9(m)||J.patchSession(a,m.id,{provider:"openpond"}).then(k=>{P(C=>C.map(T=>T.id===k.id?k:T)),w("openpond"),y(C=>br("openpond",C))}).catch(k=>{I(k instanceof Error?k.message:String(k))})},[a,m,y,w,I,P])}function d9({connection:e,setError:t}){return g.useCallback(async(n,a)=>{if(!e){const o=new Error("OpenPond App server is not connected.");throw t(o.message),o}t(null);try{await J.resolveApproval(e,n,{decision:a})}catch(o){const i=o instanceof Error?o.message:String(o);throw t(i),o}},[e,t])}function u9({activeProvider:e,contextCompaction:t,contextUsage:n,pinnedItems:a,pinnedPreviewKeys:o,pinnedProjects:i,projectRows:s,visibleProjectRows:l}){const m=g.useMemo(()=>x3(a,o),[a,o]),d=g.useMemo(()=>k_({provider:e,snapshot:n,preferences:t}),[e,t,n]),h=g.useMemo(()=>Array.from(new Set([...i,...l].filter(dv).map(y=>y.project.id))),[i,l]);return{commandProjectRows:g.useMemo(()=>s,[s]),contextWindowStatus:d,pinnedRows:m,sidebarWorkspaceAppIds:h}}function m9({appDispatch:e,expandProject:t,linkedProjectByAppId:n,requestComposerFocus:a,onBeginNewChat:o,setMentionedAppId:i}){return g.useCallback((s=null)=>{o?.();const l=s?.id?n.get(s.id)??null:null;if(l){const m=vt("local",l);i(null),e({type:"selectProject",projectId:m}),t(m),a();return}i(null),e({type:"beginNewChat",appId:s?.id??null}),a()},[e,t,n,o,a,i])}const Z_={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 gQ(e){return`@${e.token}`}function p9(e){return`@${b9(e)}`}function f9(e){const t=new Map;for(const n of e){if(!n.connected||n.statusSource!=="integration_connection")continue;const a=t.get(n.providerFamily)??[];a.push(n),t.set(n.providerFamily,a)}return Array.from(t.entries()).map(([n,a])=>{const o=a[0],i=Mi(a.flatMap(v=>v.capabilities.map(y=>y.id))),s=Mi(a.flatMap(v=>v.capabilityLabels)),l=Mi(a.flatMap(v=>v.connections.map(y=>y.id).filter(S9))),m=Mi(a.map(v=>v.id)),d=Mi(a.map(v=>v.setupSurface)),h=v9(n);return{provider:n,label:o.providerLabel,detail:s.length>0?s.slice(0,4).join(", "):o.description,token:h,tokens:g9(a),ref:{kind:"integration",provider:n,appIds:m,setupSurfaces:d,...l.length>0?{connectionIds:l}:{},...i.length>0?{capabilities:i}:{}}}})}function vQ(e,t){const n=Dn(t);return e.filter(a=>n?a.tokens.some(o=>o.includes(n)):!0).slice(0,8)}function h9(e,t){const n=y9(e);if(n.length===0)return[];const a=new Map;for(const o of n){const i=t.find(s=>s.tokens.includes(o));i&&a.set(i.provider,i)}return Array.from(a.values())}function bQ(e,t){if(t.length===0)return[];const n=[];for(const a of e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)){const o=a[1]??"",i=Dn(o);if(!i)continue;const s=t.find(v=>v.tokens.includes(i));if(!s)continue;const m=(a[0]??"").indexOf("@");if(m<0||typeof a.index!="number")continue;const d=a.index+m,h=`@${o}`;n.push({detail:s.detail,displayText:p9(s),end:d+h.length,label:s.label,provider:s.provider,start:d,text:h})}return n}function g9(e){return Mi(e.flatMap(t=>[...Z_[t.providerFamily],t.providerFamily,t.id,t.label,t.shortLabel]).map(Dn).filter(Boolean))}function v9(e){return Dn(Z_[e][0]??e)}function b9(e){return e.provider==="github"?"GitHub":e.provider==="x"?"X":e.provider==="mcp"?"MCP":e.label}function y9(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>Dn(t[1]??"")).filter(Boolean)}function Mi(e){return Array.from(new Set(e))}function S9(e){return typeof e=="string"&&e.length>0}function k9({bootstrap:e,connectedAppRows:t,mentionableSandboxApps:n,runtimeIndexes:a,selectedApp:o,selectedCloudProject:i,selectedProject:s,selectedSession:l,selectedSessionId:m}){const d=g.useMemo(()=>{const I=new Map;for(const R of e?.cloudProjects??[]){const M=I.get(R.teamId)??[];M.push(R.id),I.set(R.teamId,M)}return I},[e?.cloudProjects]),v=!!(l||o||s||i)?[]:n,y=g.useMemo(()=>f9(t),[t]),w=g.useMemo(()=>bK(a,m),[a,m]);return{chatMentionApps:v,cloudProjectIdsByTeam:d,connectedAppMentions:y,pendingApproval:w}}function x9({connection:e,setBootstrap:t,setCodexPermissionMode:n,setCodexReasoningEffort:a,setError:o}){const i=g.useCallback(l=>{if(!e){o("Connect to OpenPond before saving preferences.");return}J.savePreferences(e,{codexPermissionMode:l}).then(m=>{n(m.preferences.codexPermissionMode),a(m.preferences.codexReasoningEffort),t(d=>d&&{...d,preferences:m.preferences})}).catch(m=>{o(m instanceof Error?m.message:String(m))})},[e,t,n,a,o]),s=g.useCallback(l=>{if(!e){o("Connect to OpenPond before saving preferences.");return}J.savePreferences(e,{codexReasoningEffort:l}).then(m=>{n(m.preferences.codexPermissionMode),a(m.preferences.codexReasoningEffort),t(d=>d&&{...d,preferences:m.preferences})}).catch(m=>{o(m instanceof Error?m.message:String(m))})},[e,t,n,a,o]);return{changeCodexPermissionMode:i,changeCodexReasoningEffort:s}}const w9=6e4;function Sv(e,t){if(!e)return t;const n=_9(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 Y_(e,n)?e:n}function I9(e,t){const n=Sv(e,t),a=e?{...n,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order,updatedAt:e.updatedAt}:n;return e&&Y_(e,a)?e:a}function bl(e,t){let n=!1,a=!1;const o=e.map(i=>{if(i.id!==t.id)return i;n=!0;const s=Sv(i,t);return s!==i&&(a=!0),s});return n?a?o:e:[t,...e]}function zu(e,t){let n=!1,a=!1;const o=e.map(i=>{if(i.id!==t.id)return i;n=!0;const s=I9(i,t);return s!==i&&(a=!0),s});return n?a?o:e:[t,...e]}function ih(e,t,n,a=Date.now()){const o=new Map(e.map(i=>[i.id,i]));return t.map(i=>{const s=o.get(i.id);if(s&&n){const l=R9(s,i,n,a);if(l)return l}return Sv(s,i)})}function w0(e,t,n,a=Date.now()){const o=new Map(e.map(d=>[d.id,d])),i=new Map(ih(e,t,n,a).map(d=>[d.id,d])),s=new Set(o.keys()),l=t.filter(d=>!s.has(d.id)).map(d=>i.get(d.id)??d),m=e.map(d=>{const h=i.get(d.id);return h||(J_(d,t)?d:null)}).filter(d=>!!d);return[...l,...m]}function J_(e,t){const n=Date.parse(e.updatedAt);if(!Number.isFinite(n))return!1;const a=C9(t);return a===null||n>=a}function I0(e,t,n,a=Date.now()){const o=new Map(t.map(i=>[i.id,i]));for(const i of n){const s=o.get(i.id);s&&(Q_(s,i)||(e[i.id]=a))}}function _9(e,t){const n=Date.parse(e),a=Date.parse(t);return Number.isFinite(n)&&Number.isFinite(a)&&n>a}function Y_(e,t){return JSON.stringify(e)===JSON.stringify(t)}function C9(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 R9(e,t,n,a){const o=n[t.id];return o===void 0?null:a-o>w9||Q_(e,t)?(delete n[t.id],null):{...t,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order}}function Q_(e,t){return e.pinned===t.pinned&&e.savedForLater===t.savedForLater&&e.archived===t.archived&&e.order===t.order}const X_=800,P9=5e3,_0=5e4,A9=16,T9=3e4,Xn=new Map;function E9(e,t){return Xn.get(tC(e,t))?.payload??null}async function eC(e,t,n={}){const a=tC(e,t),o=Xn.get(a),i=n.limit??X_,s=n.tail??!0;if(o?.promise)return o.promise;if(!n.force&&s&&o?.payload&&Date.now()-o.fetchedAt<=T9)return C0(a,o),o.payload;const l=!!(n.force&&s&&o?.payload),m=l?o?.payload?.events.at(-1)?.id:void 0,d=J.codexHistoryThreadIncremental(e,t,{afterEventId:m,limit:i,revision:l?o?.revision:void 0,tail:s}).then(h=>{const v=Xn.get(a)?.payload??o?.payload;if(h.unchanged){if(!v)throw new Error("Codex history revision matched without a cached thread.");return Xn.set(a,{fetchedAt:Date.now(),payload:v,revision:h.revision}),C0(a,Xn.get(a)),v}const y={session:h.session,events:h.events},w=s&&v&&!h.reset?{...y,events:M9(v.events,y.events)}:y;return Xn.set(a,{fetchedAt:Date.now(),payload:w,revision:h.revision}),R0(),w}).catch(h=>{throw Xn.get(a)?.promise===d&&Xn.delete(a),h});return Xn.set(a,{fetchedAt:o?.fetchedAt??0,payload:o?.payload,promise:d,revision:o?.revision}),R0(),d}function tC(e,t){return`${e.serverUrl}
|
|
185
|
+
${e.token}
|
|
186
|
+
${t}`}function C0(e,t){Xn.delete(e),Xn.set(e,t)}function R0(){for(;Xn.size>A9;){const e=Xn.keys().next().value;if(!e)return;Xn.delete(e)}}function M9(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 j9=500,O9=2500,$9=15e3;function N9(e){return e.active?j9:e.surface==="thread"?O9:$9}function kv(e,t){return!t||e.session.status==="active"?e:{...e,session:{...e.session,status:"active"}}}function D9(e={}){const t={cachedPayload:e.cachedPayload??E9,clearTimer:e.clearTimer??(d=>globalThis.clearTimeout(d)),loadPayload:e.loadPayload??eC,now:e.now??Date.now,setTimer:e.setTimer??((d,h)=>globalThis.setTimeout(d,h))},n=new Map;let a=1;function o(d){const h=U9(d.connection,d.sessionId);let v=n.get(h);v||(v={connection:d.connection,disposed:!1,inFlight:null,latestPayload:t.cachedPayload(d.connection,d.sessionId),nextRefreshAt:null,sessionId:d.sessionId,subscribers:new Map,timer:null},n.set(h,v));const y=a++;return v.subscribers.set(y,d),v.latestPayload&&d.onPayload(v.latestPayload),i(v,0),()=>{const w=n.get(h);if(w){if(w.subscribers.delete(y),w.subscribers.size>0){i(w,l(w));return}w.disposed=!0,m(w),n.delete(h)}}}function i(d,h){if(d.disposed||d.subscribers.size===0||d.inFlight)return;const v=t.now()+Math.max(0,h);d.timer&&d.nextRefreshAt!==null&&d.nextRefreshAt<=v||(m(d),d.nextRefreshAt=v,d.timer=t.setTimer(()=>{d.timer=null,d.nextRefreshAt=null,s(d)},Math.max(0,h)))}async function s(d){if(d.disposed||d.subscribers.size===0||d.inFlight)return;const h=t.loadPayload(d.connection,d.sessionId,{force:!!d.latestPayload});d.inFlight=h;try{const v=await h;if(d.disposed||v===d.latestPayload)return;d.latestPayload=v;for(const y of d.subscribers.values())y.onPayload(v)}catch(v){if(d.disposed)return;for(const y of d.subscribers.values())y.onError?.(v)}finally{d.inFlight===h&&(d.inFlight=null),d.disposed||i(d,l(d))}}function l(d){const h=[...d.subscribers.values()],v=h.some(w=>w.locallyActive||w.reportedActive)||d.latestPayload?.session.status==="active"||vv(d.latestPayload?.events??[])?.tone==="active",y=h.some(w=>w.surface==="thread")?"thread":"sidebar";return N9({active:v,surface:y})}function m(d){d.timer&&t.clearTimer(d.timer),d.timer=null,d.nextRefreshAt=null}return{subscribe:o}}const L9=D9();function xv(e){return L9.subscribe(e)}function U9(e,t){return`${e.serverUrl}
|
|
187
|
+
${e.token}
|
|
188
|
+
${t}`}function z9({connection:e,selectedSessionId:t,selectedSessionLocallyActive:n,selectedSessionStatus:a,setCodexHistorySessions:o,setError:i}){const[s,l]=g.useState({events:[],sessionId:null}),m=qt(t)?t:null,d=m&&s.sessionId===m?s.events:[],h=g.useCallback(v=>{l(y=>{if(!m)return{events:[],sessionId:null};const w=y.sessionId===m?y.events:[];return{events:typeof v=="function"?v(w):v,sessionId:m}})},[m]);return g.useEffect(()=>{if(!e||!m){l(w=>w.sessionId===null&&w.events.length===0?w:{events:[],sessionId:null});return}i(w=>w==="Session not found"?null:w);const v=n;return xv({connection:e,locallyActive:v,onError:w=>i(w instanceof Error?w.message:String(w)),onPayload:w=>{const I=kv(w,v);l(R=>R.sessionId!==m?{events:I.events,sessionId:m}:{events:Mo(R.events,I.events),sessionId:m}),i(R=>R==="Session not found"?null:R),o(R=>zu(R,I.session))},reportedActive:a==="active",sessionId:m,surface:"thread"})},[e,m,n,a,o,i]),{codexHistoryEvents:d,setCodexHistoryEvents:h}}function nC(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 H9({connection:e,appPreferences:t,sessions:n,pinnedItems:a,setAppPreferences:o,setCodexHistorySessions:i,setSessions:s,sidebarFileBookmarks:l,setSidebarFileBookmarks:m,setError:d}){const[h,v]=g.useState(null),[y,w]=g.useState(null),I=g.useRef(null),R=g.useRef(null);function M(C,T){C.dataTransfer.effectAllowed="move",C.dataTransfer.setData("text/plain",`${T.type}:${T.id}`),nC(C);const z=a.map(B=>B.key);I.current=T,R.current=z,v(T),w(z)}function P(){I.current=null,R.current=null,v(null),w(null)}function N(C,T){const z=I.current;if(!z)return;const B=Ud(C),D=R.current??a.map(le=>le.key),V=zd(D,Ur(z),Ur(T),B);By(D,V)||(R.current=V,w(V))}function O(C){if(!e)return;const T=a.map(ke=>ke.key),z=new Set(T),B=[...C.filter(ke=>z.has(ke)),...T.filter(ke=>!C.includes(ke))];if(By(T,B))return;const D=t,V=new Map(n.map(ke=>[ke.id,ke])),le=l,te=new Map(a.map(ke=>[ke.key,ke]));o(ke=>{const Z={...ke};return B.forEach((Ae,he)=>{const ue=te.get(Ae);ue?.type==="project"&&(Z[ue.id]={...Z[ue.id]??{},pinned:!0,archived:!1,order:he})}),Z});const Ie=ke=>{const Z=new Map(ke.map(ue=>[ue.id,ue])),Ae=B.map((ue,be)=>{const ne=te.get(ue),ge=ne?.type==="session"?Z.get(ne.id):null;return ge?{...ge,order:be}:null}).filter(ue=>!!ue),he=new Map(Ae.map(ue=>[ue.id,ue]));return ke.map(ue=>he.get(ue.id)??ue)};s(Ie),i(Ie),m(ke=>{const Z=new Map;return B.forEach((Ae,he)=>{const ue=te.get(Ae);ue?.type==="file"&&Z.set(ue.id,he)}),ke.map(Ae=>{const he=Z.get(Ae.id);return he===void 0?Ae:{...Ae,order:he}})}),Promise.all(B.map((ke,Z)=>{const Ae=te.get(ke);return Ae?Ae.type==="project"?J.patchSidebarAppPreference(e,Ae.id,{pinned:!0,archived:!1,order:Z}):Ae.type==="session"?J.patchSession(e,Ae.id,{order:Z}):J.patchSidebarFile(e,{workspaceKind:Ae.file.workspaceKind,workspaceId:Ae.file.workspaceId,workspaceName:Ae.file.workspaceName,path:Ae.file.path,status:"pinned",order:Z,sourceSessionId:Ae.file.sourceSessionId}):Promise.resolve(null)})).catch(ke=>{d(ke instanceof Error?ke.message:String(ke)),o(D);const Z=Ae=>Ae.map(he=>V.get(he.id)??he);s(Z),i(Z),m(le)})}function j(C,T){const z=I.current;if(z){const B=R.current??a.map(V=>V.key),D=zd(B,Ur(z),Ur(T),Ud(C));O(D)}P()}function k(){I.current&&O(R.current??a.map(T=>T.key)),P()}return{dragItem:h,pinnedPreviewKeys:y,startPinnedDrag:M,clearSidebarDrag:P,previewPinnedDrop:N,commitPinnedDrop:j,commitPinnedPreviewDrop:k}}function q9({connection:e,sessions:t,setCodexHistorySessions:n,setError:a,setSessions:o}){const[i,s]=g.useState(null),[l,m]=g.useState(null),d=g.useRef(null),h=g.useRef(null);function v(P,N){P.dataTransfer.effectAllowed="move",P.dataTransfer.setData("text/plain",`session:${N.sessionId}`),nC(P),d.current=N,h.current=N.visibleSessionIds,s(N.sessionId),m(N.visibleSessionIds)}function y(P,N){const O=d.current;if(!O)return;const j=h.current??O.visibleSessionIds,k=zd(j,O.sessionId,N,Ud(P));B9(j,k)||(h.current=k,m(k))}function w(){d.current=null,h.current=null,s(null),m(null)}function I(P,N){const O=d.current;if(!O){w();return}const j=h.current??O.visibleSessionIds,k=zd(j,O.sessionId,N,Ud(P));M(Jy(O.allSessionIds,O.visibleSessionIds,k)),w()}function R(){const P=d.current;P&&M(Jy(P.allSessionIds,P.visibleSessionIds,h.current??P.visibleSessionIds)),w()}function M(P){const N=new Map(P.map((C,T)=>[C,T])),O=new Map(t.map(C=>[C.id,C.order])),j=P.filter((C,T)=>O.get(C)!==T);if(j.length===0)return;const k=C=>C.map(T=>{const z=N.get(T.id);return z===void 0||z===T.order?T:{...T,order:z}});o(k),n(k),e&&Promise.all(j.map(C=>J.patchSession(e,C,{order:N.get(C)}))).catch(C=>{const T=z=>z.map(B=>{const D=O.get(B.id);return D===void 0||D===B.order?B:{...B,order:D}});o(T),n(T),a(C instanceof Error?C.message:String(C))})}return{clearTaskDrag:w,commitTaskDrop:I,commitTaskPreviewDrop:R,previewTaskDrop:y,startTaskDrag:v,taskDragSessionId:i,taskPreviewSessionIds:l}}function B9(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function P0({afterMessageId:e=null,attachments:t,content:n,sessionId:a}){const o=new Date().toISOString(),i=`pending_user_${a}_${o}_${Math.random().toString(36).slice(2,8)}`,s=F9(t);return{id:i,role:"user",content:n,sessionId:a,afterMessageId:e,timestamp:o,turnId:i,...s.length>0?{attachments:s}:{}}}function aC(e,t){return!t||oC(e,t)?e:[...e,t]}function oC(e,t){const n=t.afterMessageId?e.findIndex(i=>i.id===t.afterMessageId):-1,a=n>=0?n+1:0,o=Date.parse(t.timestamp);for(let i=a;i<e.length;i+=1){const s=e[i];if(s.role!=="user"||s.content!==t.content)continue;if(n>=0||!t.afterMessageId)return!0;const l=Date.parse(s.timestamp);if(!Number.isFinite(o)||!Number.isFinite(l)||l>=o)return!0}return!1}function F9(e){return e.map(({contentsBase64:t,text:n,...a})=>a)}function ye(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 yr(e){const t=e.trim();if(!t||!t.startsWith("{")&&!t.startsWith("["))return null;try{return JSON.parse(t)}catch{return null}}function Ce(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Vo(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];if(t(a))return a}return null}function V9(e,t,n){if(t.name==="workspace_action_result"){const a=Vo(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:sh([...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 K9(e){if(e.name!=="workspace_action"&&e.name!=="workspace_action_result")return null;const t=Ce(e.data),n=Ce(e.args),a=ye(n,["actionName"])??ye(Ce(n?.input),["actionName"])??Gp(t)??Gp(Ce(t?.run))??Gp(Ce(t?.agentRun));if(!(e.action==="sandbox_run_action"||e.action==="profile_run_action"||!!a||t?.openPondActionRun===!0||t?.openPondProfileActionRun===!0)||!a)return null;const i=Ce(t?.run)??Ce(t?.agentRun),s=Ce(i?.metadata),l=Ce(t?.actionSummary)??Ce(i?.actionSummary)??Ce(s?.actionSummary),m=Ce(t?.action)??l??Ce(s?.selectedAction)??null,d=Ce(t?.responseSummary)??Ce(i?.responseSummary)??Ce(s?.responseSummary),h=Ce(t?.sourceSummary)??Ce(i?.sourceSummary)??Ce(s?.sourceSummary),v=Ce(t?.traceSummary)??Ce(i?.traceSummary)??Ce(s?.traceSummary),y=Ce(t?.evalSummary)??Ce(i?.evalSummary)??Ce(s?.evalSummary),w=sh([...Ao("artifact",t?.artifactRefs,"Artifact"),...Ao("artifact",m?.artifactRefs,"Artifact"),...Ao("artifact",l?.artifactRefs,"Artifact"),...Ao("artifact",d?.artifactRefs,"Artifact"),...Ao("trace",t?.traceArtifactRefs,"Trace"),...Ao("trace",v?.artifactRefs,"Trace"),...Ao("eval",t?.evalResultArtifactRefs,"Eval"),...Ao("eval",y?.artifactRefs,"Eval"),...Ao("output",t?.outputRefs,"Output")]),I=ye(h,["sourceRef","ref"]);return I&&w.push({id:lh("source",I),kind:"source",label:"Source",target:I}),{actionName:a,title:ye(m,["label","title","name"])??ye(s,["selectedActionLabel"])??Q9(a),status:W9(e,d,i),responseText:ye(d,["text","summary","message"])??(e.name==="workspace_action_result"&&e.output?.trim()||null),runId:ye(i,["id","runId"])??ye(t,["runId","agentRunId"])??null,projectId:ye(i,["projectId"])??ye(t,["projectId"])??ye(n,["projectId"])??null,agentId:ye(i,["agentId"])??ye(t,["agentId"])??ye(n,["agentId"])??null,agentName:ye(Ce(m?.implementation),["agentName"])??ye(m,["agentName"])??ye(s,["selectedAgentName"])??null,sandboxId:ye(i,["sandboxId"])??ye(t,["sandboxId"])??ye(Ce(t?.sandbox),["id"])??ye(Ce(t?.createdSandbox),["id"])??ye(n,["sandboxId"])??null,runtimeId:ye(i,["runtimeId"])??ye(t,["runtimeId"])??null,implementationType:ye(t,["implementationType"])??ye(m,["implementationType","type","kind"])??ye(Ce(m?.implementation),["type","kind"])??ye(s,["implementationType"])??(e.action==="profile_run_action"||t?.openPondProfileActionRun===!0?"openpond-profile-action":null),sourceRef:I,manifestHash:ye(h,["manifestHash"])??ye(t,["manifestHash"])??ye(s,["manifestHash"])??null,refs:sh(w),childCalls:Z9(t,i,s)}}function Gp(e){return e?ye(e,["actionName","name"])??ye(Ce(e.action),["actionName","name"])??ye(Ce(e.actionSummary),["actionName","name"])??ye(Ce(e.selectedEntrypoint),["name"]):null}function W9(e,t,n){if(e.status==="failed")return"failed";const a=ye(t,["status"]);if(a==="failed")return"failed";if(a==="running"||a==="pending")return a;if(a==="available"||e.status==="completed")return"completed";const o=ye(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 Ao(e,t,n){return(Array.isArray(t)?t:t?[t]:[]).flatMap(o=>{const i=G9(e,o,n);return i?[i]:[]})}function G9(e,t,n){if(typeof t=="string"&&t.trim()){const s=t.trim();return{id:lh(e,s),kind:e,label:n,target:s}}const a=Ce(t);if(!a)return null;const o=ye(a,["url","webUrl","artifactPath","path","ref"])??ye(Ce(a.artifact),["url","webUrl","path","ref"]);if(!o)return null;const i=ye(a,["label","title","name","type","kind"])??n;return{id:lh(e,o),kind:e,label:i,target:o}}function sh(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 lh(e,t){return`${e}:${t}`}function Z9(e,t,n){return[e?.childCalls,e?.childRuns,e?.implementationCalls,t?.childCalls,t?.childRuns,n?.childCalls,n?.childRuns].flatMap(o=>J9(o)).slice(0,6)}function J9(e){return(Array.isArray(e)?e:e?[e]:[]).flatMap((n,a)=>{const o=Ce(n);if(!o)return[];const i=ye(o,["id","runId","callId"])??`child_${a+1}`,s=ye(o,["label","title","actionName","name","tool"])??ye(Ce(o.action),["label","name"])??"Implementation call",l=ye(o,["detail","summary","runId","sandboxId","runtimeId"])??null;return[{id:i,label:s,status:Y9(o),detail:l}]})}function Y9(e){const t=ye(e,["status","state"]);return t==="running"||t==="completed"||t==="failed"||t==="pending"?t:t==="succeeded"?"completed":"unknown"}function Q9(e){const t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e}const X9=new Set([".avif",".gif",".jpeg",".jpg",".png",".webp"]);function rC(e){if(!e)return!1;const t=e.split("?")[0]?.split("#")[0]??e,n=t.lastIndexOf(".");return n<0?!1:X9.has(t.slice(n).toLowerCase())}function iC(e){return e.split("/").filter(Boolean).pop()??e}function eW(e){if(!dh(e))return;const t=Ce(e.data),a=(typeof t?.openpondImagePreviewPath=="string"?t.openpondImagePreviewPath:null)??zr(e.data)??zr(e.args)??zr(e.output);if(!(!a||!rC(a)))return{path:a,appId:e.appId??null,title:iC(a)}}function tW(e){if(e.name!=="tool.completed"&&e.name!=="workspace_action_result")return[];const t=[],n=new Set;return ch(e.data,t,n),t.slice(0,12)}function ch(e,t,n,a=0){if(a>7||e==null)return;if(Array.isArray(e)){for(const l of e)ch(l,t,n,a+1);return}const o=Ce(e);if(!o)return;const i=ye(o,["path","artifactRef"]),s=ye(o,["contentType","mimeType"]);i&&s&&!n.has(i)&&(n.add(i),t.push({path:i,title:ye(o,["title","name"])??iC(i),contentType:s,sizeBytes:typeof o.sizeBytes=="number"?o.sizeBytes:null}));for(const l of Object.values(o))ch(l,t,n,a+1)}function dh(e){if(e.name!=="tool.started"&&e.name!=="tool.completed")return!1;const t=Ce(e.data);return typeof t?.openpondImagePreviewPath=="string"&&t.openpondImagePreviewPath.trim()?!0:[e.output,e.action,ye(t,["tool","toolName","tool_name","name","functionName","function_name","command"]),ye(Ce(t?.input),["tool","toolName","tool_name","name"]),ye(Ce(t?.arguments),["tool","toolName","tool_name","name"]),ye(Ce(t?.args),["tool","toolName","tool_name","name"])].filter(a=>!!a).some(a=>a.toLowerCase().includes("view_image"))}function zr(e,t=0,n=""){if(t>5||e==null)return null;if(typeof e=="string"){if(Zp(n)&&rC(e.trim()))return e.trim();const o=yr(e);if(o!==null){const i=zr(o,t+1,n);if(i)return i}return nW(e)}if(Array.isArray(e)){for(const o of e){const i=zr(o,t+1,n);if(i)return i}return null}const a=Ce(e);if(!a)return null;for(const[o,i]of Object.entries(a)){if(!Zp(o))continue;const s=zr(i,t+1,o);if(s)return s}for(const[o,i]of Object.entries(a)){if(Zp(o))continue;const s=zr(i,t+1,o);if(s)return s}return null}function Zp(e){return/^(path|filePath|filepath|imagePath|image|localPath|uri|url)$/i.test(e)}function nW(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 aW(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=rW(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 oW(e){if(e.action!=="connected_app_search"&&e.action!=="connected_app_read"&&e.action!=="connected_app_write")return null;const t=sC(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 rW(e){return sC(e).providerLabel}function sC(e){const t=Ce(e.args),n=Ce(e.data),a=Ce(n?.result),o=au(ye(t,["provider"])??ye(a,["provider"])??ye(n,["provider"])??void 0),i=ye(a,["providerLabel"])??ye(n,["providerLabel"])??(o?Bh(o)?.label:null)??"connected app",s=ye(t,["operation"]),l=ye(a,["operation"])??ye(n,["operation"]),m=Jp(t?.capabilityIds)||Jp(a?.capabilityIds)||Jp(n?.capabilityIds);return{providerLabel:i,providerOperation:s,operation:l,capabilityCount:m}}function Jp(e){return Array.isArray(e)?e.length:0}function lC(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()||Yp(a)}}return t==="<turn_aborted>"?{kind:"turn_aborted",text:Yp("turn_aborted")}:t==="<goal_context>"?{kind:"goal_context",text:Yp("goal_context")}:null}function Yp(e){return e==="turn_aborted"?"The previous turn was interrupted.":"Goal context updated."}function Hu(e){return e.name==="diagnostic"&&Ce(e.data)?.kind==="goal_context"}const iW="Steered by user";function sW(e){return e?.trim().toLowerCase()===iW.toLowerCase()}function lW(e,t){if(!t.turnId)return;pW(e,t.turnId);const n=cW(t);if(!n)return;const a=mW(e,t.turnId);if(a){a.refinerActivity=n;return}const o={id:`${t.id}:work-refiner`,role:"activity_group",activities:[],timestamp:t.timestamp,turnId:t.turnId,traceState:"completed",traceStartedAt:t.timestamp,traceCompletedAt:t.timestamp,refinerActivity:n},i=e.findIndex(s=>s.role==="assistant"&&s.turnId===t.turnId);i>=0?e.splice(i,0,o):e.push(o)}function cW(e){const t=Ce(e.data),n=Ce(t?.activity);return n?dW(n,e):uW(e,t)}function yQ(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 · ${vW(e.route??"external")} issue routed`;const t=e.result==="applied"?"Applied":"Needs review";return`Refiner · ${e.summary} — ${t}`}function dW(e,t){const n=so(e.state,["running","completed","failed"]);if(!n)return null;const a=n==="failed"?"failed":so(e.result,["no_action","routed","applied","retained"]),o=Bn(e.reason)??t.output??t.error??null;return{state:n,visibility:so(e.visibility,["always","material_only"])??"material_only",result:n==="running"?null:a,workspaceId:Bn(e.workspaceId),decision:so(e.decision,["no_action","route","propose"]),route:Bn(e.route),operation:so(e.operation,["create","update","delete"]),target:Bn(e.target),summary:Bn(e.summary)??cC(n,a),expectedOutcome:Bn(e.expectedOutcome),reason:o,evidenceBasis:fW(e.evidenceBasis),critiqueStatus:so(e.critiqueStatus,["not_applicable","pending","passed","rejected","failed"])??(n==="running"?"pending":"not_applicable"),validationStatus:so(e.validationStatus,["not_applicable","pending","passed","failed"])??(n==="running"?"pending":"not_applicable"),validations:hW(e.validationReceipts),edits:gW(e.edits),refs:{trigger:io(e.trigger),outcome:io(e.outcome),proposal:io(e.proposal),applyReceipt:io(e.applyReceipt),advanceReceipt:io(e.advanceReceipt),inputHarness:io(e.inputHarness),outputHarness:io(e.outputHarness)}}}function uW(e,t){if(!e.name.startsWith("harness.refiner."))return null;const n=e.name==="harness.refiner.failed"||e.status==="failed",a=e.name==="harness.refiner.completed",o=Ce(t?.outcome),i=Ce(t?.proposal),s=o?.routed===!0,l=Bn(t?.workspaceAdvance),m=n?"failed":a?i?l==="advanced"||/\bapplied\b/i.test(e.output??"")?"applied":"retained":s?"routed":"no_action":null;return{state:n?"failed":a?"completed":"running",visibility:"material_only",result:m,workspaceId:null,decision:i?"propose":s?"route":a?"no_action":null,route:Bn(o?.route),operation:null,target:null,summary:cC(n?"failed":a?"completed":"running",m),expectedOutcome:null,reason:e.output??e.error??null,evidenceBasis:null,critiqueStatus:i?"passed":"not_applicable",validationStatus:i?"pending":"not_applicable",validations:[],edits:[],refs:{trigger:io(t?.trigger),outcome:io(o),proposal:io(i),applyReceipt:null,advanceReceipt:null,inputHarness:null,outputHarness:null}}}function mW(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 pW(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 fW(e){const t=Ce(e),n=so(t?.kind,["single_deterministic","recurrent_independent"]);return!t||!n?null:{kind:n,supportingEvidenceIds:A0(t.supportingEvidenceIds),counterevidence:A0(t.counterevidence)}}function hW(e){return Array.isArray(e)?e.flatMap(t=>{const n=Ce(t),a=Bn(n?.id),o=so(n?.status,["passed","failed","blocked","skipped"]),i=Bn(n?.summary);return a&&o&&i?[{id:a,status:o,summary:i}]:[]}):[]}function gW(e){return Array.isArray(e)?e.flatMap(t=>{const n=Ce(t),a=Bn(n?.id),o=so(n?.operation,["create","update","delete"]),i=Bn(n?.target),s=Bn(n?.summary);return!a||!o||!i||!s?[]:[{id:a,operation:o,target:i,summary:s,content:typeof n?.content=="string"?n.content:null}]}):[]}function io(e){const t=Ce(e),n=Bn(t?.id),a=Bn(t?.contentHash);return n&&a?`${n} · ${a.slice(0,12)}`:null}function A0(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()):[]}function Bn(e){return typeof e=="string"&&e.trim()?e.trim():null}function so(e,t){return typeof e=="string"&&t.includes(e)?e:null}function cC(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 vW(e){return e.length>0?`${e[0].toUpperCase()}${e.slice(1)}`:e}const T0=64*1024,E0=8*1024;function M0(e,t){const n=dC(t);if(n.subagentMessage){e.push({id:t.id,role:"activity_group",activities:[n],timestamp:t.timestamp,turnId:t.turnId});return}const a=bW(e,t.turnId);if(a){a.activities=kW(a.activities??[],t,n),a.timestamp=t.timestamp;return}yd(e,t),e.push({id:t.id,role:"activity_group",activities:[n],timestamp:t.timestamp,turnId:t.turnId,traceState:"running",traceStartedAt:t.timestamp})}function yd(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 bW(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 uh(e,t,n){if(!t.turnId)return;const a=e.filter(l=>l.role==="activity_group"&&l.turnId===t.turnId&&!l.activities?.some(m=>m.subagentMessage)),o=a.filter(l=>l.traceState==="running"),i=o.length>0?o:a.length>0?[a[a.length-1]]:[];for(const l of i)l.traceState=n;const s=i.at(-1);s&&(s.traceCompletedAt=t.timestamp,s.timestamp=t.timestamp)}function yW(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];if(a?.turnId!==t.turnId||a.role!=="activity_group")continue;const o=a.activities?.filter(i=>i.controlKind!=="turn_aborted")??[];o.length!==a.activities?.length&&(o.length===0?e.splice(n,1):a.activities=o)}uh(e,t,"interrupted"),!sW(t.output)&&e.push({id:t.id,role:"status_divider",content:SW(t),timestamp:t.timestamp,turnId:t.turnId,statusKind:"interruption",statusState:"failed",statusTone:"danger"})}function SW(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 kW(e,t,n=dC(t)){const a=[...e];return EW(a,t,n)||PW(a,t,n)||AW(a,t,n)||TW(a,t,n)?a:[...a,n]}function xW(e){return e.name==="session.compaction.started"||e.name==="session.compaction.completed"||e.name==="session.compaction.failed"}function wW(e,t){const n={id:t.id,role:"status_divider",content:IW(t),timestamp:t.timestamp,turnId:t.turnId,statusKind:"compaction",statusState:_W(t),statusTone:CW(t)};if(t.name!=="session.compaction.started"){const a=Vo(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 IW(e){const t=RW(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 _W(e){return e.name==="session.compaction.started"?"running":e.name==="session.compaction.completed"?"completed":"failed"}function CW(e){return e.name==="session.compaction.failed"?"danger":e.name==="session.compaction.completed"?"success":"info"}function RW(e){return Ce(e.data)?.reason==="auto"?"auto":"manual"}function dC(e){const t=eW(e),n=e.name==="assistant.reasoning.delta"?"reasoning":HW(e),a=qW(e),o=VW(e),i=FW(e),s=KW(e),l=WW(e),m=tW(e);return{id:e.id,label:l?l.direction==="received"?"Child message received":"Child message sent":OW(e),content:l?.summary??NW(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:wv(e)??void 0}:{},...n&&e.name==="command.output"?{detail:mh(e)}:{},...n==="command"?{terminal:XW(e)}:{},...i?{meta:i}:{},...o?{receipt:o}:{},...s?{openSession:s}:{},...l?{subagentMessage:l}:{},state:jW(e),...t?{imagePreview:t}:{},...m.length>0?{artifacts:m}:{}}}function PW(e,t,n){if(t.name==="tool.completed"){const a=j0(e,t);if(!a)return!1;const o=e8(a.timestamp,t.timestamp);a.label=t.status==="failed"?"Failed":"Ran",a.state=n.state,a.timestamp=t.timestamp,a.artifacts=n.artifacts,a.terminal={...a.terminal,...n.terminal,...o!==null?{durationMs:o}:{}};const i=mh(t);return i&&i!==a.content&&(a.detail=Kd(a.detail,i)),!0}if(t.name==="command.output"){const a=j0(e,t);if(!a)return!1;const o=mh(t);return o&&(a.detail=Kd(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 AW(e,t,n){if(t.name!=="tool.completed"||n.kind==="command")return!1;const a=wv(t),o=Vo(e,s=>s.state==="running"&&s.kind!=="command"&&(a?s.callId===a:!!t.action&&s.action===t.action));if(!o)return!1;const i=n.content.trim();return o.id=n.id,o.label=n.label,o.timestamp=n.timestamp,o.state=n.state,i&&i!==o.content.trim()&&(o.content.trim()===o.action?o.content=i:o.detail=Kd(o.detail,i)),n.detail&&(o.detail=Kd(o.detail,n.detail)),o.meta=n.meta,o.receipt=n.receipt,o.imagePreview=n.imagePreview??o.imagePreview,o.artifacts=n.artifacts,!0}function TW(e,t,n){if(t.name!=="workspace_action_result")return!1;const a=MW(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 EW(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 j0(e,t){const n=wv(t);if(n){const a=Vo(e,o=>o.kind==="command"&&o.callId===n);if(a)return a}return Vo(e,a=>a.kind==="command")}function MW(e,t){const n=t.action??"",a=uC[n]??{started:"Running workspace action"};return Vo(e,o=>o.state==="running"&&o.label===a.started&&o.kind!=="command"&&!o.controlKind)}function jW(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 OW(e){if(e.name==="assistant.reasoning.delta")return ye(Ce(e.data),["kind"])==="commentary"?"Update":"Reasoning";if(Hu(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(dh(e)&&e.name==="tool.started")return"Reading image";if(dh(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=aW(e);if(t)return t;const n=LW(e);if(n)return n;const a=DW(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"?$W(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 uC={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 $W(e){const t=e.action??"",n=uC[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 NW(e,t){if(e.name==="assistant.reasoning.delta")return e.output??"";if(t)return t.path;const n=lC(e.output??"");if(n)return n.text;if(Hu(e)||e.name==="turn.interrupted")return e.output??e.error??"";const a=UW(e);if(a)return a;const o=zW(e);if(o)return o;const i=oW(e);if(i)return i;const s=mC(e);if(s)return s;if(e.name==="command.output")return fC(e.output??"");if(e.name==="tool.started"||e.name==="tool.completed"){const l=e.data;if(l&&typeof l=="object"){const m=l.command;if(typeof m=="string"&&m.trim())return m;const d=l.tool;if(typeof d=="string"&&d.trim())return d;const h=l.type;if(typeof h=="string"&&h.trim())return h}}return e.name==="session.compaction.started"||e.name==="session.compaction.completed"||e.name==="session.compaction.failed"?e.error??e.output??"":e.output??e.action??""}function DW(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 LW(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 UW(e){if(!e.action?.startsWith("openpond_browser_"))return null;const t=Ce(Ce(e.data)?.result),n=ye(t,["output"]);if(n)return n;const a=Ce(yr(e.output??"")),o=ye(a,["output"]);if(o)return o;const i=Ce(e.args),s=ye(i,["url"]);return s||(e.action==="openpond_browser_type"?"Text redacted":e.error??e.output??e.action)}function zW(e){if(e.action!=="openpond_create_improve")return null;const t=Ce(Ce(e.data)?.result),n=ye(t,["nextStep"]);if(n)return n;const a=Ce(yr(e.output??"")),o=ye(a,["output"]);if(o)return o;const i=Ce(e.args),s=ye(i,["reason"]);if(s)return s;const l=ye(i,["objective"]);return l||(e.error??null)}function HW(e){if(e.name==="command.output")return"command";if(e.name!=="tool.started"&&e.name!=="tool.completed")return;const t=Ce(e.data),n=ye(t,["type"]),a=ye(t,["tool","toolName","tool_name","name","functionName","function_name"]);if(e.action==="commandExecution"||n==="commandExecution"||mC(e)||a&&/(^|[._-])exec_command$/i.test(a))return"command"}function qW(e){if(e.name==="turn.interrupted")return"turn_aborted";if(Hu(e))return"goal_context"}function mC(e){const t=Ce(e.data),n=ye(t,["type"]),a=ye(t,["tool","toolName","tool_name","name","functionName","function_name"]),o=Ce(t?.result),i=Ce(yr(e.output??"")),s=Ce(i?.data),l=ye(t,["command","cmd"])??ye(Ce(t?.input),["command","cmd"])??ye(Ce(t?.arguments),["command","cmd"])??ye(Ce(t?.args),["command","cmd"])??BW(ye(t,["arguments","args","input"]))??ye(Ce(e.args),["command","cmd"])??ye(o,["command","cmd"])??ye(s,["command","cmd"]);return l||e.name==="tool.started"&&(e.action==="commandExecution"||n==="commandExecution"||/(^|[._-])exec_command$/i.test(a??""))&&e.output?.trim()||null}function BW(e){if(!e)return null;const t=yr(e),n=Ce(t);return ye(n,["command","cmd"])}function wv(e){const t=Ce(e.data);return ye(t,["callId","call_id","toolCallId","tool_call_id","id","itemId","item_id"])}function FW(e){const t=Ce(e.data);if(!t)return null;const n=[],a=Ce(t.workspaceToolTiming),o=typeof a?.durationMs=="number"?a.durationMs:null;o!==null&&n.push(JW(o));const i=Ce(t.workspaceExecutionTarget),s=ye(i,["target"]);if(s==="sandbox"){const d=i?.hybrid===!0,h=ye(i,["sandboxId","workspaceId"]);n.push(`${d?"Hybrid ":""}sandbox${h?` ${O0(h)}`:""}`)}else s==="local"&&n.push("local workspace");const l=Ce(t.sourcePreservation);if(l?.attempted===!0)if(l.ok!==!0)n.push("checkpoint failed");else if(l.preserved===!0){const d=ye(l,["preservedSha"]);n.push(d?`checkpoint ${QW(d)}`:"checkpoint saved")}else n.push("checkpoint clean");const m=pC(t);return m&&(n.push(`receipt ${O0(m.id)}`),n.push(`${YW(m.totalUsd)} ${m.status}`)),n.length>0?n.join(" · "):null}function VW(e){const t=pC(Ce(e.data));return t?{id:t.id,status:t.status,totalUsd:t.totalUsd}:void 0}function KW(e){if(!e.name.startsWith("subagent."))return;const t=Ce(e.data),n=Ce(t?.run),a=ye(t,["childSessionId"])??ye(n,["childSessionId"]);if(!a)return;const o=ye(n,["roleId"])??ye(t,["roleId"]),i=ye(n,["status"])??ye(t,["status"]);return{sessionId:a,label:"Open conversation",...o?{roleId:o}:{},...i?{status:i}:{}}}function WW(e){if(e.name!=="subagent.message")return;const t=Ce(e.data),n=Ce(t?.message);if(!n)return;const a=ye(n,["id"]),o=ye(n,["kind"]),i=ye(n,["fromRunId"]),s=ye(n,["body"]);if(!a||!o||!i||!s)return;const l=Ce(t?.delivery??n.delivery),m=Ce(t?.modelRef),d=ye(m,["providerId"]),h=ye(m,["modelId"]),y=ye(l,["deliveredParentSessionId"])===e.sessionId&&!i.startsWith("parent:")?"received":"sent",w=Array.isArray(n.refs)?n.refs.flatMap(I=>{const R=Ce(I),M=ye(R,["kind"]),P=ye(R,["id"]),N=ye(R,["label"]);return M&&P&&N?[{kind:M,id:P,label:N}]:[]}):[];return{direction:y,summary:GW(s),body:s,messageId:a,kind:o,fromRunId:i,toRunId:ye(n,["toRunId"]),toRole:ye(n,["toRole"]),childSessionId:ye(t,["childSessionId"]),roleId:ye(t,["roleId"]),modelRef:d&&h?{providerId:d,modelId:h}:null,deliveryStatus:ye(l,["status"]),wakeReason:ye(l,["wakeParentReason"]),createdAt:ye(n,["createdAt"]),refs:w}}function GW(e){const t=e.replace(/\s+/g," ").trim();if(!t)return"No message body";const n=/^(.*?[.!?])(?:\s|$)/.exec(t)?.[1]??t;return ZW(n,96)}function ZW(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 pC(e){const t=Ce(e?.sandbox),n=Array.isArray(t?.receipts)?t.receipts:[];for(let a=n.length-1;a>=0;a-=1){const o=Ce(n[a]),i=ye(o,["id"]),s=ye(o,["status"]),l=ye(o,["totalUsd","retailTotalUsd"]);if(i&&s&&l)return{id:i,status:s,totalUsd:l}}return null}function JW(e){return e<1e3?`${Math.max(0,Math.round(e))} ms`:e<1e4?`${(e/1e3).toFixed(1)} s`:`${Math.round(e/1e3)} s`}function YW(e){const t=e.trim();return t.startsWith("$")?t:`$${t}`}function QW(e){return e.length>12?e.slice(0,12):e}function O0(e){const t=e.trim();return t.length<=14?t:`${t.slice(0,6)}...${t.slice(-4)}`}function fC(e){let t=e.replace(/\r\n/g,`
|
|
189
|
+
`).trim();if(!t)return"";const n=t8(t);if(n!==null)return Ji(n);const a=`
|
|
190
|
+
Output:
|
|
191
|
+
`,o=t.indexOf(a);return o>=0&&n8(t.slice(0,o))&&(t=t.slice(o+a.length).trim()),t=t.replace(/^Total output lines: \d+\n\n/,""),Ji(t.trim())}function mh(e){const t=fC(e.output??"");if(t)return t;const n=Ce(Ce(e.data)?.result);return n?Ji(hC(n)):""}function XW(e){const t=Ce(e.data),n=Ce(t?.result),a=Ce(yr(e.output??"")),o=Ce(a?.data),i=Ce(t?.workspaceToolTiming),s=[n?.exitCode,o?.exitCode,t?.exitCode].find(m=>typeof m=="number"),l=i?.durationMs;return{...typeof s=="number"?{exitCode:s}:{},...typeof l=="number"?{durationMs:l}:{}}}function e8(e,t){const n=Date.parse(t)-Date.parse(e);return Number.isFinite(n)&&n>0?n:null}function t8(e){const t=Ce(yr(e)),n=typeof t?.action=="string"?t.action:"";if(!t||typeof t.ok!="boolean"||!n||typeof t.output!="string")return null;const a=Ce(t.data);return a?hC(a,ye(t,["output"])):typeof t.output=="string"?t.output.trim():""}function hC(e,t=null){const n=ye(e,["stdout"])?.replace(/\r\n/g,`
|
|
192
|
+
`).trimEnd()??"",a=ye(e,["stderr"])?.replace(/\r\n/g,`
|
|
193
|
+
`).trimEnd()??"",o=[n,a].filter(Boolean);return o.length>0?o.join(`
|
|
194
|
+
`):t?.replace(/\r\n/g,`
|
|
195
|
+
`).trim()??""}function n8(e){return/^(Chunk ID|Exit code):/m.test(e)&&/Wall time:/m.test(e)}function Kd(e,t){const n=e??"";if(!n)return Ji(t);if(n===t||n.includes(t))return n;if(t.includes(n))return Ji(t);const a=n.endsWith(`
|
|
196
|
+
`)||t.startsWith(`
|
|
197
|
+
`)?"":`
|
|
198
|
+
`;return Ji(`${n}${a}${t}`)}function Ji(e){if(e.length<=T0)return e;const t=`
|
|
199
|
+
|
|
200
|
+
… output omitted from live view; full output remains in task history …
|
|
201
|
+
|
|
202
|
+
`,n=Math.max(0,T0-E0-t.length);return`${e.slice(0,E0)}${t}${e.slice(-n)}`}const a8=/\bopenpond\s+opchat\b/i,o8=/\b(?:50[0-9]|52[0-9]|53[0-9])\b|bad\s+gateway|gateway\s+timeout|service\s+unavailable/i;function gC(e){const t=e?.trim()||"Turn failed";return a8.test(t)&&o8.test(t)?"Server connection lost. Retry your message.":t}function r8(e,t){if((Yc(t,"code")??Yc(t,"errorCode"))==="opchat_quota_exceeded")return"opchat_quota_exceeded";const a=t&&typeof t=="object"?t.error:null;if(a&&typeof a=="object"&&(Yc(a,"code")??Yc(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 Yc(e,t){if(!e||typeof e!="object")return null;const a=e[t];return typeof a=="string"&&a.trim()?a.trim():null}function i8(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=s8(a.activities??[]);if(o.length===0){a.deliverables=void 0;continue}const i=t.get(a.turnId)??"",s=i?l8(o,i):[];if(s.length>0){a.deliverables=s;continue}a.deliverables=n.has(a.turnId)?[o[o.length-1]]:void 0}}function s8(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 l8(e,t){const n=vC(t);return e.filter(a=>c8(a).some(o=>t.includes(o)||n.includes(o)))}function c8(e){const t=new Set;for(const n of[e.path,e.title,d8(e.path)]){const a=n.trim();a&&(t.add(a),t.add(vC(a)))}return[...t]}function d8(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).at(-1)??e}function vC(e){try{return decodeURIComponent(e)}catch{return e}}const bC=8;function u8(e){if(e.name!=="tool.completed"||e.status==="failed")return[];if(e.action!=="web_search"&&e.action!=="web_fetch")return[];const t=fh(e.data),n=e.output?fh(yr(e.output)):null;return m8(t??n)}function ph(e,t){if(t.length===0)return e;const n=[],a=new Set;for(const o of[...e??[],...t]){const i=yC(o.url);if(!(!i||a.has(i))&&(a.add(i),n.push(o),n.length>=bC))break}return n.length>0?n:void 0}function fh(e,t=0){if(t>5)return null;const n=Ce(e);if(!n)return null;const a=Array.isArray(n.results)?n.results:Array.isArray(n.items)?n.items:ye(n,["url"])?[n]:null;if(a)return{provider:ye(n,["provider"]),results:a};for(const o of["result","data","output"]){const i=fh(n[o],t+1);if(i)return i}return null}function m8(e){if(!e)return[];const t=[],n=new Set;for(let a=0;a<e.results.length;a+=1){const o=p8(e.results[a],a,e.provider);if(!o)continue;const i=yC(o.url);if(!(!i||n.has(i))&&(n.add(i),t.push(o),t.length>=bC))break}return t}function p8(e,t,n){const a=Ce(e);if(!a)return null;const o=ye(a,["url","href"]);if(!o||!f8(o))return null;const i=ye(a,["title"])??$0(o)??`Source ${t+1}`;return{id:ye(a,["id"])??`source_${t+1}`,title:i,url:o,sourceName:ye(a,["sourceName","source_name","source"])??$0(o),snippet:ye(a,["snippet","description"]),provider:n,faviconUrl:h8(ye(a,["faviconUrl","favicon_url","iconUrl","icon_url"]))??g8(o),publishedAt:ye(a,["publishedAt","published_at"]),updatedAt:ye(a,["updatedAt","updated_at"])}}function f8(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function yC(e){try{const t=new URL(e);return t.hash="",t.toString()}catch{return null}}function h8(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 g8(e){try{return new URL("/favicon.ico",e).toString()}catch{return null}}function $0(e){try{return new URL(e).hostname.replace(/^www\./i,"")}catch{return null}}const N0=new WeakMap;function qu(e){const t=N0.get(e);if(t)return t;const n=v8(e);return N0.set(e,n),n}function v8(e){const t=[],n=new Set,a=new Map;for(const o of e){if(o.name==="task.input"){const i=RI.safeParse(Ce(o.data)?.input);i.success&&i.data.senderKind==="user"&&i.data.kind==="steer"&&!n.has(i.data.id)&&(n.add(i.data.id),t.push({id:`task-input:${i.data.id}`,role:"user",content:i.data.body,timestamp:o.timestamp,turnId:i.data.turnId??void 0}));continue}if(o.name==="turn.started"){yd(t,o),b8(t,o);const i=x8(o.args);if(i){const s=lC(i);if(s){M0(t,{...o,name:s.kind==="turn_aborted"?"turn.interrupted":"diagnostic",output:s.text,data:{...Ce(o.data)??{},kind:s.kind}});continue}t.push({id:o.id,role:"user",content:i,attachments:w8(o.args),timestamp:o.timestamp,turnId:o.turnId});const l=L0(o.args);l&&t.push({id:`${o.id}:create-improve`,role:"assistant",timestamp:o.timestamp,turnId:o.turnId,createImproveRun:l})}continue}if(o.name==="create_improve.updated"){const i=L0(o.data);if(!i)continue;const s=Vo(t,l=>l.turnId===o.turnId&&!!l.createImproveRun);s?(s.createImproveRun=i,s.timestamp=o.timestamp):t.push({id:`${o.id}:create-improve`,role:"assistant",timestamp:o.timestamp,turnId:o.turnId,createImproveRun:i});continue}if(o.name==="assistant.delta"){const i=o.output??"";if(!i)continue;yd(t,o);const s=t[t.length-1];if(s?.role==="assistant"&&s.turnId===o.turnId&&!s.createImproveRun)s.content=`${s.content??""}${i}`,s.timestamp=o.timestamp,s.sources=ph(s.sources,D0(a,o.turnId)??[]);else{const l=D0(a,o.turnId);t.push({id:o.id,role:"assistant",content:i,timestamp:o.timestamp,turnId:o.turnId,...l?.length?{sources:l}:{}})}continue}if(o.name==="assistant.reasoning.delta"){const i=o.output??"";if(!i)continue;yd(t,o);const s=t[t.length-1];s?.role==="assistant"&&s.turnId===o.turnId&&s.reasoningContent!==void 0&&!s.createImproveRun?(s.reasoningContent=`${s.reasoningContent}${i}`,s.timestamp=o.timestamp):s?.role==="assistant"&&s.turnId===o.turnId&&!s.reasoningContent&&!s.createImproveRun?(s.reasoningContent=i,s.timestamp=o.timestamp):t.push({id:o.id,role:"assistant",reasoningContent:i,timestamp:o.timestamp,turnId:o.turnId});continue}if(o.name==="user_question.asked"){const i=Ce(o.data),s=nj.safeParse(i?.question);if(!s.success)continue;t.push({id:o.id,role:"assistant",timestamp:o.timestamp,turnId:o.turnId,userQuestion:s.data});continue}if(o.name==="user_question.answered"||o.name==="user_question.dismissed"){const i=Ce(o.data),s=aj.safeParse(i?.resolution);if(!s.success)continue;const l=Vo(t,m=>m.userQuestion?.id===s.data.questionId);if(!l?.userQuestion||l.userQuestion.status!=="pending")continue;l.userQuestion={...l.userQuestion,status:s.data.action==="answer"?"answered":"dismissed",answer:s.data.action==="answer"?{optionId:s.data.optionId,text:s.data.text}:null,answeredAt:o.timestamp},l.timestamp=o.timestamp;continue}if(o.name==="turn.completed"){uh(t,o,"completed");continue}if(o.name==="turn.failed"){uh(t,o,"failed");const i=o.error??"Turn failed",s=r8(i,o.data);t.push({id:o.id,role:"error",content:gC(i),...s?{errorKind:s}:{},timestamp:o.timestamp,turnId:o.turnId});continue}if(o.name==="turn.interrupted"){yW(t,o);continue}if(xW(o)){wW(t,o);continue}if(o.name.startsWith("harness.refiner.")){lW(t,o);continue}if(o.name==="tool.started"||o.name==="tool.completed"||o.name==="skill.selected"||o.name==="skill.loaded"||o.name==="skill.load_failed"||o.name==="command.output"||o.name==="workspace_action"||o.name==="workspace_action_result"||o.name==="approval.requested"||o.name.startsWith("subagent.")||Hu(o)){if(S8(o))continue;const i=K9(o);if(i){V9(t,o,i);continue}const s=u8(o);s.length>0&&y8(t,a,o.turnId,s),M0(t,o)}if(o.name==="workspace.diff"){const i=k8(o.data);if(!i||i.filesChanged===0)continue;const s=Vo(t,l=>l.role==="assistant"&&l.turnId===o.turnId);s&&(s.changeSummary=i,s.timestamp=o.timestamp)}}return i8(t),t}function b8(e,t){if(Ce(t.args)?.interactionKind!=="steer")return;const n=e.at(-1);n?.role==="status_divider"&&n.statusKind==="interruption"&&n.content==="Stopped by user"&&e.pop()}function y8(e,t,n,a){if(!n)return;const o=e[e.length-1];if(o?.role!=="assistant"||o.turnId!==n){t.set(n,ph(t.get(n),a));return}o.sources=ph(o.sources,a)}function D0(e,t){if(!t)return;const n=e.get(t);return n&&e.delete(t),n}function S8(e){if(e.name!=="approval.requested")return!1;if(e.action==="create_plan")return!0;const t=Ce(e.data),n=Ce(t?.approval);return t?.kind==="create_plan"||n?.kind==="create_plan"}function k8(e){const t=gO.safeParse(e);return t.success?t.data:null}function x8(e){if(!e||typeof e!="object"||!("prompt"in e))return"";const t=e.prompt;return typeof t=="string"?t:""}function w8(e){if(!e||typeof e!="object"||!("attachments"in e))return;const t=YN.array().safeParse(e.attachments);return t.success&&t.data.length>0?t.data:void 0}function L0(e){const t=Ce(e);if(!t)return null;const n=ec.safeParse(t.createImproveRun);return n.success?n.data:null}function SQ(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 kQ(e){const t=SC(e);return t?t.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):""}function xQ(e){const t=SC(e);return t?t.toLocaleString():""}function SC(e){if(!e)return null;const t=new Date(e);return Number.isNaN(t.getTime())?null:t}function I8(e){const{chatMessages:t,runtimeIndexes:n,selectedSessionId:a}=e,[o,i]=g.useState({}),s=g.useCallback(m=>{i(d=>({...d,[m.sessionId]:m}))},[]);g.useEffect(()=>{i(m=>{let d=m;for(const[h,v]of Object.entries(m)){const y=qu(gc(n,h));oC(y,v)&&(d===m&&(d={...m}),delete d[h])}return d})},[n]);const l=g.useMemo(()=>aC(t,a?o[a]:null),[t,o,a]);return{pendingChatUserMessages:o,recordPendingChatUserMessage:s,visibleChatMessages:l}}function _8({connection:e,selectedSession:t,setBootstrap:n,setError:a,setOpenPondCommandAccessMode:o,setSessions:i}){return{changeOpenPondCommandAccessMode:g.useCallback((l,m=t)=>{if(!e){a("Connect to OpenPond before saving preferences.");return}const d=m?.provider==="codex"?null:m;J.savePreferences(e,{openPondCommandAccessMode:l}).then(h=>{o(h.preferences.openPondCommandAccessMode),n(v=>v&&{...v,preferences:h.preferences})}).catch(h=>{a(h instanceof Error?h.message:String(h))}),d&&J.patchSession(e,d.id,{openPondCommandAccessMode:l}).then(h=>{i(v=>v.map(y=>y.id===h.id?h:y))}).catch(h=>{a(h instanceof Error?h.message:String(h))})},[e,t,n,a,o,i])}}function C8({localProjects:e,cloudProjects:t,sessions:n,runtimeIndexes:a,appPreferences:o,selectedSessionId:i,selectedProjectId:s,archivedChatsOpen:l,projectsExpanded:m,chatRowsVisibleCount:d,sidebarFileBookmarks:h=[]}){const v=g.useMemo(()=>e.filter(se=>!se.hiddenFromDefaultSidebar),[e]),y=g.useMemo(()=>n.filter(se=>!se.archived&&U0(se)),[n]),w=g.useMemo(()=>y.filter(se=>se.pinned),[y]),I=g.useMemo(()=>y.filter(se=>!!se.savedForLater),[y]),R=g.useMemo(()=>n.filter(se=>se.archived&&U0(se)),[n]),M=g.useMemo(()=>new Set(e.map(se=>se.id)),[e]),P=g.useMemo(()=>new Set(t.map(se=>se.id)),[t]),N=g.useMemo(()=>t_(e),[e]),O=g.useMemo(()=>{const se={};for(const we of[...y,...R]){const Oe=Vy(we,M,N,P);Oe&&(se[we.id]=Oe)}return se},[y,R,P,M,N]),j=g.useMemo(()=>y.filter(se=>!se.pinned&&!se.savedForLater&&!se.appId&&!O[se.id]),[y,O]),k=g.useMemo(()=>R.filter(se=>!se.appId&&!Vy(se,M,N,P)),[R,P,M,N]),C=g.useMemo(()=>{const se={};for(const we of y){if(we.pinned||we.savedForLater)continue;const Oe=O[we.id];if(!Oe)continue;const Qe=se[Oe];Qe?Qe.push(we):se[Oe]=[we]}return se},[y,O]),T=g.useMemo(()=>{const se={};for(const we of n){if(we.archived||!kC(we))continue;const Oe=se[we.parentSessionId];Oe?Oe.push(we):se[we.parentSessionId]=[we]}for(const we of Object.values(se))we.sort((Oe,Qe)=>Date.parse(Qe.updatedAt)-Date.parse(Oe.updatedAt));return se},[n]),z=g.useMemo(()=>v.map((se,we)=>{const Oe=vt("local",se.id),Qe=EK(se,t);return{id:Oe,kind:"local",project:se,pinned:!!o[Oe]?.pinned,order:o[Oe]?.order??we,cloudLinkTrusted:!Qe,cloudLinkWarning:Qe}}).sort(Qp),[o,t,v]),B=g.useMemo(()=>t.map((se,we)=>{const Oe=vt("cloud",se.id);return{id:Oe,kind:"cloud",project:se,pinned:!!o[Oe]?.pinned,order:o[Oe]?.order??we,cloudLinkTrusted:!0,cloudLinkWarning:null}}).sort(Qp),[o,t]),D=g.useMemo(()=>new Set(v.map(se=>_a(se,t)?.id??null).filter(se=>!!se)),[t,v]),V=g.useMemo(()=>B.filter(se=>!D.has(se.project.id)),[B,D]),le=g.useMemo(()=>[...z,...V].sort(Qp),[V,z]),te=g.useMemo(()=>le.filter(se=>se.pinned),[le]),Ie=g.useMemo(()=>h.filter(se=>se.status==="pinned"),[h]),ke=g.useMemo(()=>h.filter(se=>se.status==="saved_for_later"),[h]),Z=le,Ae=g.useMemo(()=>R8(Z,m,s),[Z,m,s]),he=g.useMemo(()=>[...te.map(se=>({type:"project",key:Ur({type:"project",id:se.id}),id:se.id,item:se,order:se.order})),...w.map(se=>({type:"session",key:Ur({type:"session",id:se.id}),id:se.id,session:se,order:se.order})),...Ie.map((se,we)=>({type:"file",key:Ur({type:"file",id:se.id}),id:se.id,file:se,order:se.order??te.length+w.length+we}))].sort((se,we)=>{if(se.order!==we.order)return se.order-we.order;if(se.type!==we.type){const Ge={project:0,session:1,file:2};return Ge[se.type]-Ge[we.type]}const Oe=se.type==="project"?se.item.project.name:se.type==="session"?se.session.title:se.file.path,Qe=we.type==="project"?we.item.project.name:we.type==="session"?we.session.title:we.file.path;return Oe.localeCompare(Qe)}),[Ie,te,w]),ue=g.useMemo(()=>l?[...j,...k]:j,[l,k,j]),be=g.useMemo(()=>ue.slice(0,Math.max(Pn,d)),[ue,d]),ne=g.useMemo(()=>gc(a,i),[a,i]),ge=g.useMemo(()=>qu(ne),[ne]),xe=D_(a,i),qe=L_(a,i),Se=vK(a,i);return{activeSessions:y,pinnedSessions:w,savedForLaterSessions:I,pinnedFiles:Ie,savedForLaterFiles:ke,chatSessions:j,archivedSessions:R,pinnedProjects:te,pinnedItems:he,projectRows:Z,localProjectRows:z,visibleProjectRows:Ae,cloudProjectRows:V,projectSessionRowsByProjectId:C,childSessionRowsByParentId:T,sidebarProjectIdBySessionId:O,chatRows:ue,visibleChatRows:be,sessionEvents:ne,chatMessages:ge,contextUsage:xe,goalRuntime:qe,subagentRuntime:Se}}function U0(e){return kC(e)?!1:e.hiddenFromDefaultSidebar?e.metadata?.benchmarkRuntime==="desktop_local_work":!0}function kC(e){return!!(e.parentSessionId&&e.subagentRunId)}function Qp(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 R8(e,t,n){if(t||e.length<=hd)return e;const a=e.slice(0,hd);if(!n||a.some(i=>i.id===n))return a;const o=e.find(i=>i.id===n);return o?[...a.slice(0,hd-1),o]:a}function P8(e){return e.name==="turn.completed"||e.name==="turn.failed"||e.name==="turn.interrupted"}function xC(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||!P8(o))&&!(n&&o.turnId&&o.turnId!==n))return o.name==="turn.completed"?"completed":"blocked"}return"pending"}function z0(e,t){if(e.systemKind)return!1;const n=gc(t,e.id);if(n.length===0)return!1;const a=xC(n);return a==="pending"||a==="none"&&wC(n)==="pending"}function H0(e,t){if(e.systemKind||e.status!=="active")return!1;const n=gc(t,e.id);if(n.length===0)return!0;const a=xC(n);return a==="pending"||a==="none"&&wC(n)!=="terminal"}function wC(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 A8({goalRuntime:e,goalRuntimeBySessionId:t,runtimeIndexes:n,selectedSession:a,selectedSessionId:o,sidebarSessions:i,subagentRuntimeBySessionId:s}){const l=g.useMemo(()=>new Map(i.map(y=>[y.id,y])),[i]),m=g.useMemo(()=>{const y=new Set;for(const[w,I]of t??[]){const R=l.get(w);I.tone==="active"&&!R?.systemKind&&y.add(w)}for(const w of n.activeGoalSessionIds)l.get(w)?.systemKind||y.add(w);return o&&!a?.systemKind&&e?.tone==="active"&&y.add(o),y},[e,t,n,a,o,l]),d=g.useMemo(()=>{const y=new Set(m);for(const[w,I]of s??[]){const R=l.get(w);I.activeCount>0&&!R?.systemKind&&y.add(w)}for(const w of n.activeSubagentSessionIds)l.get(w)?.systemKind||y.add(w);for(const w of i)w.systemKind||z0(w,n)&&y.add(w.id);return a&&z0(a,n)&&y.add(a.id),y},[m,n,a,i,l,s]),h=g.useMemo(()=>{const y=new Set(d);for(const w of i)H0(w,n)&&y.add(w.id);return a&&H0(a,n)&&y.add(a.id),y},[d,n,a,i]),v=!!(a&&!a.systemKind&&d.has(a.id));return{runningSessionIds:h,selectedSessionRunning:v}}const T8=1e3;function E8(e){const[t,n]=g.useState(()=>new Date().toISOString());return g.useEffect(()=>{if(!e)return;const a=()=>n(new Date().toISOString());a();const o=window.setInterval(a,T8);return()=>window.clearInterval(o)},[e]),t}function M8(e){const{codexHistoryEvents:t,codexHistorySessions:n,connection:a,expandedProjectIds:o,goalRuntime:i,locallyActiveCodexHistorySessionIds:s,pinnedSessions:l,savedForLaterSessions:m,projectSessionRowsByProjectId:d,rightChatHistoryEvents:h,runtimeIndexes:v,selectedSession:y,selectedSessionId:w,serverId:I,setCodexHistorySessions:R,sidebarSessions:M,subagentRuntime:P,visibleChatRows:N,visibleProjectRows:O}=e,[j,k]=g.useState({});g.useEffect(()=>{k({})},[I]);const C=g.useMemo(()=>{const ue=[],be=new Set,ne=xe=>{!xe||xe.id===w||!qt(xe.id)||be.has(xe.id)||(be.add(xe.id),ue.push(xe.id))};for(const xe of n)(xe.status==="active"||s.has(xe.id))&&ne(xe);const ge=ue.length;for(const xe of O)for(const qe of(d[xe.id]??[]).slice(0,2))ne(qe);for(const xe of o)for(const qe of(d[xe]??[]).slice(0,hd))ne(qe);for(const xe of l)ne(xe);for(const xe of m)ne(xe);for(const xe of N)ne(xe);return[...ue.slice(0,ge),...ue.slice(ge,ge+8)].join(`
|
|
203
|
+
`)},[n,o,s,l,m,d,w,N,O]),T=g.useCallback(ue=>{k(be=>be[ue.session.id]===ue.events?be:{...be,[ue.session.id]:ue.events}),R(be=>zu(be,ue.session))},[R]),z=g.useMemo(()=>{if(!C)return"";const ue=new Set(C.split(`
|
|
204
|
+
`).filter(Boolean));return M.filter(be=>ue.has(be.id)&&be.status==="active").map(be=>be.id).join(`
|
|
205
|
+
`)},[C,M]),B=g.useMemo(()=>C?C.split(`
|
|
206
|
+
`).filter(ue=>s.has(ue)).join(`
|
|
207
|
+
`):"",[C,s]);g.useEffect(()=>{!y||!w||!qt(w)||t.length===0||T({session:y,events:t})},[T,t,y,w]),g.useEffect(()=>{if(!a||!C)return;const ue=a,be=C.split(`
|
|
208
|
+
`).filter(Boolean),ne=new Set(z.split(`
|
|
209
|
+
`).filter(Boolean)),ge=new Set(B.split(`
|
|
210
|
+
`).filter(Boolean)),xe=be.map(qe=>xv({connection:ue,locallyActive:ge.has(qe),onPayload:Se=>T(kv(Se,ge.has(qe))),reportedActive:ne.has(qe),sessionId:qe,surface:"sidebar"}));return()=>xe.forEach(qe=>qe())},[T,z,B,C,a]);const D=g.useMemo(()=>new Map(M.map(ue=>[ue.id,ue])),[M]),V=g.useMemo(()=>{const ue=new Map(v.latestGoalRuntimeBySessionId);for(const be of M){const ne=be.status==="active"?Vp(be.metadata):null;ne&&ue.set(be.id,ne)}for(const be of[j,h])for(const[ne,ge]of Object.entries(be)){const xe=D.get(ne),qe=xe?.status==="active"?Vp(xe.metadata):null,Se=nh(ge)??vv(ge)??(xe?.status==="active"?Vd(ge)??qe:null);Se?ue.set(ne,Se):ue.delete(ne)}if(w)if(i)ue.set(w,i);else if(y?.status==="active"&&t.length>0){const be=nh(t)??Vd(t)??Vp(y.metadata);be?ue.set(w,be):ue.delete(w)}else(!qt(w)||t.length>0)&&ue.delete(w);return ue},[t.length,j,i,h,v.latestGoalRuntimeBySessionId,y?.status,y?.metadata,w,D,M]),le=g.useMemo(()=>[...V.values()].some(ue=>ue.tone==="active"&&!!ue.observedAt),[V]),te=E8(le),Ie=g.useMemo(()=>le?new Map([...V].map(([ue,be])=>[ue,WV(be,te)??be])):V,[V,te,le]),ke=w?Ie.get(w)??i:i,Z=g.useMemo(()=>{const ue=new Map(v.latestSubagentRuntimeBySessionId);return w&&(P?ue.set(w,P):ue.delete(w)),ue},[v.latestSubagentRuntimeBySessionId,w,P]),{runningSessionIds:Ae,selectedSessionRunning:he}=A8({goalRuntime:ke,goalRuntimeBySessionId:Ie,runtimeIndexes:v,selectedSession:y,selectedSessionId:w,sidebarSessions:M,subagentRuntimeBySessionId:Z});return{goalRuntime:ke,runningSessionIds:Ae,selectedSessionRunning:he,sidebarGoalRuntimeBySessionId:Ie,sidebarSubagentRuntimeBySessionId:Z}}function j8({searchOpen:e,sectionMenuOpen:t,setSectionMenuOpen:n,setSearchOpen:a,setQuery:o}){g.useEffect(()=>{const i=s=>{if((s.metaKey||s.ctrlKey)&&s.key.toLowerCase()==="k"){s.preventDefault(),n(null),a(l=>!l);return}if(s.key==="Escape"&&e){s.preventDefault(),a(!1),o(""),n(null);return}s.key==="Escape"&&t&&(s.preventDefault(),n(null))};return document.addEventListener("keydown",i),()=>document.removeEventListener("keydown",i)},[e,t,o,a,n])}function O8({afterSequence:e,appendEvents:t,connection:n,setApprovals:a,setSessions:o,setError:i,onDisconnected:s}){g.useEffect(()=>{if(!n?.token||e===null)return;const l=n;let m=null,d=[],h=null,v=null,y=!1;const w=new Map;let I=0;const R=16;function M(){m!==null&&(window.clearTimeout(m),m=null)}function P(){i(D=>D==="Event stream disconnected"?null:D)}function N(){h=null;const D=d;if(d=[],D.length===0)return;I=Date.now(),t(D);const V=$8(D);V.length>0&&o(le=>V.reduce(bl,le)),a(le=>{let te=le;for(const Ie of D)if(Ie.name==="approval.requested"&&Ie.data&&(te=[Ie.data,...te]),Ie.name==="approval.resolved"&&Ie.data&&typeof Ie.data=="object"){const ke=Ie.data;ke.approvalId&&(te=te.filter(Z=>Z.id!==ke.approvalId))}return te})}function O(){const D=Date.now()-I;if(D>=R){h!==null&&(window.clearTimeout(h),h=null),N();return}h===null&&(h=window.setTimeout(N,R-D))}function j(D){k(D),d.push(D),O()}function k(D){if(!(!D.sessionId||!D.name.startsWith("harness.refiner."))){if(D.name==="harness.refiner.completed"||D.name==="harness.refiner.failed"){w.delete(D.sessionId);return}(D.name==="harness.refiner.queued"||D.name==="harness.refiner.started")&&(w.set(D.sessionId,typeof D.sequence=="number"?D.sequence:0),C())}}function C(){v!==null||w.size===0||(v=window.setTimeout(()=>{v=null,T()},1e3))}async function T(){if(!(y||w.size===0)){y=!0;try{await Promise.all([...w].map(async([D,V])=>{const le=await J.runtimeEventsPage(l,{sessionId:D,afterSequence:V,limit:100});for(const te of le.events){const Ie=te.event;w.set(D,Math.max(w.get(D)??0,te.sequence)),j(Ie)}}))}catch{}finally{y=!1,C()}}}function z(){h!==null&&(window.clearTimeout(h),h=null),N()}document.addEventListener("visibilitychange",z);const B=g4(n,D=>{M(),P(),j(D)},()=>{M(),m=window.setTimeout(()=>{B.isOpen()||(i("Event stream disconnected"),s?.())},2e3)},()=>{M(),P(),window.dispatchEvent(new Event("openpond-runtime-connected"))},{afterSequence:e});return()=>{M(),h!==null&&window.clearTimeout(h),v!==null&&window.clearTimeout(v),h=null,v=null,d=[],document.removeEventListener("visibilitychange",z),B.close()}},[e,t,n,s,a,i,o])}function $8(e){const t=new Map;for(const n of e){const a=n.data;if(!a||typeof a!="object"||Array.isArray(a))continue;const o=n.name==="session.started"||n.name==="session.title.updated"?"session":n.name==="subagent.started"||n.name==="subagent.failed"?"childSession":null;if(!o)continue;const i=$l.safeParse(a[o]);i.success&&t.set(i.data.id,i.data)}return[...t.values()]}function Xp(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function N8(e){return typeof e=="string"&&e.trim()?e.trim():null}function D8(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n.name!=="create_improve.updated")continue;const a=Xp(n.data),o=Xp(a?.createImproveRun);if(o?.state!=="ready_local"&&o?.state!=="released"||Xp(o.adapter)?.kind!=="local")continue;const s=N8(o.id)??n.id;return[n.sessionId??"global",n.turnId??"turn",s].join(":")}return null}const L8=332,q0=244,B0=560,U8=560,F0=320,V0=2400,z8=440;function ef(e){const t=typeof window>"u"?B0:Math.min(B0,Math.max(q0,window.innerWidth-420));return Math.min(t,Math.max(q0,Math.round(e)))}function tf(e){const t=typeof window>"u"?V0:Math.min(V0,Math.max(F0,window.innerWidth-z8));return Math.min(t,Math.max(F0,Math.round(e)))}function H8(e,t){return!!(e&&e.serverUrl===t.serverUrl&&e.token===t.token&&e.platform===t.platform)}const qi=new Map;function Iv(e,t){const n=e?.trim();return n?`${t?.trim()||"global"}|${n}`:null}function IC(e,t){const n=Iv(e,t);if(!n)return null;const a=qi.get(n);return a?.updatedAt?a.agents:null}function q8(e,t,n){const a=Iv(e,n);a&&qi.set(a,{agents:t,promise:null,updatedAt:Date.now()})}function _v(e){const t=e.teamId?.trim();if(!t)return Promise.resolve([]);const n=Iv(t,e.accountKey);if(!n)return Promise.resolve([]);const a=qi.get(n);if(!e.force){if(a?.updatedAt)return Promise.resolve(a.agents);if(a?.promise)return a.promise}const o=e.fetchAgents(t).then(i=>(q8(t,i,e.accountKey),i)).catch(i=>{const s=qi.get(n);throw s?.promise===o&&qi.set(n,{agents:s.agents,promise:null,updatedAt:s.updatedAt}),i});return qi.set(n,{agents:a?.agents??[],promise:o,updatedAt:a?.updatedAt??0}),o}const B8=6e4,F8=6e4,V8=6e4,Cv=["pinned","projects","cloudProjects","chats","savedForLater"];function K8(e,t,n,a=Date.now()){for(const o of J8(t,n))_C(t[o],n[o])||(e[o]=a)}function W8(e,t,n,a=Date.now()){const o={...t};for(const[i,s]of Object.entries(n)){if(a-s>B8){delete n[i];continue}const l=Q8(e,i),m=e[i];!l||_C(m,t[i])||(o[i]=m)}return o}function G8(e,t,n,a=Date.now()){for(const o of Cv)t[o]!==n[o]&&(e[o]=a)}function Z8(e,t,n,a=Date.now()){const o={...t};for(const i of Cv){const s=n[i];if(s!==void 0){if(a-s>F8){delete n[i];continue}if(e[i]===t[i]){delete n[i];continue}o[i]=e[i]}}return Y8(e,o)?e:o}function K0(e,t,n=Date.now()){return e===t?null:{value:t,changedAt:n}}function W0(e,t,n=Date.now()){return t?n-t.changedAt>V8?{value:e,localChange:null}:e===t.value?{value:e,localChange:t}:{value:t.value,localChange:t}:{value:e,localChange:null}}function J8(e,t){return new Set([...Object.keys(e),...Object.keys(t)])}function _C(e,t){return e?.pinned===t?.pinned&&e?.archived===t?.archived&&e?.order===t?.order}function Y8(e,t){return Cv.every(n=>e[n]===t[n])}function Q8(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const X8=5e4,ir="\0openpond-unscoped-runtime-events",ro=[];class eG{perSessionLimit;totalLimit;entries=new Map;eventKeyById=new Map;listenersByKey=new Map;allListeners=new Set;summaryListeners=new Set;retainedKeys=new Set;allEventsSnapshot=ro;summaryEventsSnapshot=ro;clock=0;eventCount=0;constructor(t={}){if(this.perSessionLimit=J0(t.perSessionLimit??gv,"perSessionLimit"),this.totalLimit=J0(t.totalLimit??X8,"totalLimit"),this.totalLimit<this.perSessionLimit)throw new Error("totalLimit must be greater than or equal to perSessionLimit")}append(t){if(t.length===0)return Z0();const n=new Map;let a=0;for(const d of t){if(this.eventKeyById.has(d.id)){a+=1;continue}const h=d.sessionId||ir,v=n.get(h);v?v.push(d):n.set(h,[d]),this.eventKeyById.set(d.id,h)}if(n.size===0)return{...Z0(),duplicateEventCount:a};const o=new Set;let i=0,s=0,l=!1;for(const[d,h]of n){h.some(Y0)&&(l=!0);const v=this.entries.get(d),y=v?.snapshot.events??ro,w=Math.max(0,Math.min(y.length,this.perSessionLimit-h.length)),I=h.length>this.perSessionLimit?h.slice(h.length-this.perSessionLimit):h,R=w===y.length?y:y.slice(y.length-w),M=R.length===0?I:[...R,...I],P=y.slice(0,y.length-R.length);P.some(Y0)&&(l=!0);for(const j of P)this.eventKeyById.delete(j.id);for(const j of h.slice(0,h.length-I.length))this.eventKeyById.delete(j.id);const O={eventIds:new Set(M.map(j=>j.id)),lastTouched:++this.clock,retained:v?.retained??this.retainedKeys.has(d),snapshot:{events:M,latestSequence:Fd(M),revision:(v?.snapshot.revision??0)+1}};this.entries.set(d,O),this.eventCount+=M.length-y.length,i+=I.length,s+=P.length+h.length-I.length,o.add(d)}const m=this.enforceTotalLimit(o);return s+=m,this.publish(o,l||m>0),nG({acceptedEventCount:i,duplicateEventCount:a,evictedEventCount:s,changedKeys:o})}mergeBootstrap(t){const n=tG(t),a=new Set([...this.entries.keys(),...n.keys()]),o=[];for(const i of a){const s=n.get(i)??ro,l=this.entries.get(i)?.snapshot.events??ro;o.push(...zV(s,l))}return this.replace(o)}replace(t){const n=new Set(this.eventKeyById.keys()),a=new Set(this.entries.keys());this.entries.clear(),this.eventKeyById.clear(),this.eventCount=0,this.allEventsSnapshot=ro,this.summaryEventsSnapshot=ro;const o=this.append(t);for(const m of this.retainedKeys){const d=this.entries.get(m);d&&(d.retained=!0)}const i=this.eventKeyById;let s=0;for(const m of n)i.has(m)||(s+=1);const l=new Set([...a].filter(m=>!this.entries.has(m)));return l.size>0&&this.publish(l,!0),{...o,evictedEventCount:o.evictedEventCount+s,changedSessionIds:new Set([...o.changedSessionIds,...[...l].filter(m=>m!==ir)]),unscopedEventsChanged:o.unscopedEventsChanged||l.has(ir)}}clear(){if(this.entries.size===0)return;const t=new Set(this.entries.keys());this.entries.clear(),this.eventKeyById.clear(),this.eventCount=0,this.allEventsSnapshot=ro,this.summaryEventsSnapshot=ro,this.publish(t,!0)}retainSession(t,n=!0){n?this.retainedKeys.add(t):this.retainedKeys.delete(t);const a=this.entries.get(t);a&&(a.retained=n)}getSessionSnapshot=t=>t?this.entries.get(t)?.snapshot??G0:G0;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(aG),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!==ir&&a.retained&&(t+=1);return{eventCount:this.eventCount,retainedSessionCount:t,sessionCount:this.entries.size-(this.entries.has(ir)?1:0),perSessionLimit:this.perSessionLimit,totalLimit:this.totalLimit}}subscribeAll=t=>(this.allListeners.add(t),()=>this.allListeners.delete(t));subscribeSummary=t=>(this.summaryListeners.add(t),()=>this.summaryListeners.delete(t));subscribeSession(t,n){let a=this.listenersByKey.get(t);return a||(a=new Set,this.listenersByKey.set(t,a)),a.add(n),()=>{a?.delete(n),a?.size===0&&this.listenersByKey.delete(t)}}enforceTotalLimit(t){let n=0;for(;this.eventCount>this.totalLimit&&this.entries.size>0;){const a=this.oldestEvictionCandidate(!1)??this.oldestEvictionCandidate(!0);if(!a)break;const[o,i]=a,s=this.eventCount-this.totalLimit;if(!i.retained||i.snapshot.events.length<=s){n+=i.snapshot.events.length,this.removeEntry(o),t.add(o);continue}const l=i.snapshot.events.slice(0,s),m=i.snapshot.events.slice(s);for(const d of l)this.eventKeyById.delete(d.id);i.eventIds=new Set(m.map(d=>d.id)),i.snapshot={events:m,latestSequence:Fd(m),revision:i.snapshot.revision+1},this.eventCount-=l.length,n+=l.length,t.add(o)}return n}oldestEvictionCandidate(t){let n=null;for(const a of this.entries)!t&&a[1].retained||(!n||a[1].lastTouched<n[1].lastTouched)&&(n=a);return n}removeEntry(t){const n=this.entries.get(t);if(n){for(const a of n.snapshot.events)this.eventKeyById.delete(a.id);this.eventCount-=n.snapshot.events.length,this.entries.delete(t)}}publish(t,n=!1){if(t.size!==0){this.allEventsSnapshot=null,n&&(this.summaryEventsSnapshot=null);for(const a of t)for(const o of this.listenersByKey.get(a)??[])o();for(const a of this.allListeners)a();if(n)for(const a of this.summaryListeners)a()}}}const G0=Object.freeze({events:ro,latestSequence:null,revision:0});function tG(e){const t=new Map;for(const n of e){const a=n.sessionId||ir,o=t.get(a);o?o.push(n):t.set(a,[n])}return t}function nG(e){return{acceptedEventCount:e.acceptedEventCount,duplicateEventCount:e.duplicateEventCount,evictedEventCount:e.evictedEventCount,changedSessionIds:new Set([...e.changedKeys].filter(t=>t!==ir)),unscopedEventsChanged:e.changedKeys.has(ir)}}function Z0(){return{acceptedEventCount:0,duplicateEventCount:0,evictedEventCount:0,changedSessionIds:new Set,unscopedEventsChanged:!1}}function aG(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 J0(e,t){if(!Number.isInteger(e)||e<=0)throw new Error(`${t} must be a positive integer`);return e}function Y0(e){return e.name!=="assistant.delta"&&e.name!=="assistant.reasoning.delta"&&e.name!=="command.output"}const oG=256,rG=15e3,iG=5e3,sG=3e4;class lG{constructor(t={}){this.options=t}options;entries=new Map;connection=null;accountScope=null;generation=0;activateConnection(t){cG(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,dG(this.entries,t,a),a.state==="ready"?a.url:null):null}load(t,n){const a=this.get(t);if(a)return Promise.resolve(a);const o=this.now(),i=this.entries.get(t);if(i?.state==="loading"&&!this.expired(i,o))return i.promise;if(i?.state==="failed"&&!this.expired(i,o))return Promise.resolve(null);const s=this.generation,l=n().then(m=>this.generation!==s?null:(this.entries.set(t,{state:"ready",url:m.url,expiresAt:m.expiresAt,lastAccessedAt:this.now()}),this.prune(),m.url)).catch(()=>{if(this.generation!==s)return null;const m=this.now();return this.entries.set(t,{state:"failed",expiresAt:m+(this.options.failureTtlMs??iG),lastAccessedAt:m}),this.prune(),null});return this.entries.set(t,{state:"loading",promise:l,expiresAt:o+(this.options.loadingTtlMs??sG),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??oG;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??rG:0;return t.expiresAt<=n+a}now(){return(this.options.now??Date.now)()}}const Q0=new lG;function wQ(e,t,...n){return[t,e.serverUrl,...n].join("\0")}function cG(e,t){return e?.serverUrl===t?.serverUrl&&e?.token===t?.token&&e?.platform===t?.platform}function dG(e,t,n){e.delete(t),e.set(t,n)}const uG={connecting:"Connecting to OpenPond",account:"Loading account",team:"Loading default team",ready:"Ready"};function mG(e){return{label:uG[e],ready:e==="ready",stage:e}}const pG=650,fG=1200,hG=6e4;function gG(e){const{setDraftModel:t,setDraftProvider:n,setCodexPermissionMode:a,setCodexReasoningEffort:o,setOpenPondCommandAccessMode:i,setError:s,setSelectedAppId:l,setSelectedProjectId:m,setSelectedSessionId:d}=e,[h,v]=g.useState(null),[y,w]=g.useState(null),[I]=g.useState(()=>new eG),R=g.useSyncExternalStore(I.subscribeSummary,I.getSummaryEvents,I.getSummaryEvents),M=g.useCallback($=>{const H=I.getAllEvents(),Q=typeof $=="function"?$(H):$;Q!==H&&I.replace(Q)},[I]),P=g.useCallback($=>{I.append($)},[I]),[N,O]=g.useState(null),[j,k]=g.useState([]),[C,T]=g.useState([]),[z,B]=g.useState([]),[D,V]=g.useState({}),[le,te]=g.useState("connecting"),Ie=rh(y?.account),ke=g.useRef({}),Z=g.useRef({}),Ae=g.useRef({}),he=g.useRef([]),ue=g.useRef([]),be=g.useRef(null),ne=g.useRef(null),ge=g.useRef(!1),xe=g.useRef(Date.now()),qe=g.useRef(null),Se=g.useRef(null);g.useEffect(()=>{Q0.activateConnection(h),Q0.activateAccountScope(Ie)},[h,Ie]);const se=g.useCallback($=>{ge.current||te($)},[]),we=g.useCallback($=>{V(H=>{const Q=typeof $=="function"?$(H):$;return K8(ke.current,H,Q),Q})},[]),Oe=g.useCallback($=>{k(H=>{const Q=typeof $=="function"?$(H):$;return I0(Z.current,H,Q),he.current=Q,Q})},[]),Qe=g.useCallback($=>{T(H=>{const Q=typeof $=="function"?$(H):$;return I0(Ae.current,H,Q),ue.current=Q,Q})},[]),Ge=g.useCallback(()=>{if(ge.current||qe.current!==null)return;const $=()=>{qe.current=null,!ge.current&&(ge.current=!0,te("ready"))},H=Date.now()-xe.current,Q=vG(H);if(Q===0){$();return}qe.current=window.setTimeout($,Q)},[]);g.useEffect(()=>()=>{qe.current!==null&&window.clearTimeout(qe.current)},[]);const st=g.useCallback($=>{const H=be.current,Q=!H||H===$.server.id;be.current=$.server.id,O(me=>me?.serverId===$.server.id?me:{afterSequence:$.eventWindow?.latestSequence??Fd($.events)??0,serverId:$.server.id}),w($),Q?I.mergeBootstrap($.events):I.replace($.events),k(me=>{const _e=Q?w0(me,$.sessions,Z.current):ih(me,$.sessions,Z.current);return he.current=_e,_e}),T(me=>{const _e=Q?w0(me,$.codexHistorySessions??[],Ae.current):ih(me,$.codexHistorySessions??[],Ae.current);return ue.current=_e,_e}),B($.approvals),V(me=>W8(me,$.sidebarAppPreferences,ke.current)),l(me=>me&&$.apps.some(_e=>_e.id===me)?me:null),m(me=>{if(!me)return null;const _e=ZI(me);return _e?.kind==="local"&&$.localProjects.some($e=>$e.id===_e.id)?vt("local",_e.id):_e?.kind==="cloud"&&($.cloudProjects??[]).some($e=>$e.id===_e.id)?vt("cloud",_e.id):$.localProjects.some($e=>$e.id===me)?vt("local",me):($.cloudProjects??[]).some($e=>$e.id===me)?vt("cloud",me):null}),d(me=>{if(!me)return null;const _e=[...$.sessions,...$.codexHistorySessions??[]];if(_e.some(Xe=>Xe.id===me&&!Xe.archived))return me;if(!Q)return null;const $e=he.current.find(Xe=>Xe.id===me)??ue.current.find(Xe=>Xe.id===me)??null;return $e&&!$e.archived&&J_($e,_e)?me:null})},[I,l,m,d]),Le=g.useCallback($=>{w(H=>H&&{...H,preferences:$.preferences})},[]);g.useEffect(()=>{const $=ba(y?.preferences);n($.defaultChatProvider),t($.defaultChatModel)},[y?.preferences.defaultChatProvider,y?.preferences.defaultChatModel,t,n]),g.useEffect(()=>{a(ba(y?.preferences).codexPermissionMode)},[y?.preferences.codexPermissionMode,a]),g.useEffect(()=>{o(ba(y?.preferences).codexReasoningEffort)},[y?.preferences.codexReasoningEffort,o]),g.useEffect(()=>{i(ba(y?.preferences).openPondCommandAccessMode)},[y?.preferences.openPondCommandAccessMode,i]),g.useEffect(()=>{if(!h||!y){ne.current=null;return}if(y.account.state!=="signed_in"){ne.current=null,Ge();return}const $=rh(y.account);if(!$){ne.current=null,Ge();return}Ge(),se("team");const H=y.preferences.defaultTeamId?.trim()??"",Q=bG($,H,y.accountMeta.asOf??"initial");if(ne.current===Q)return;ne.current=Q;let me=!1;const _e=$e=>_v({teamId:$e,accountKey:$,fetchAgents:async Xe=>(await J.listSandboxAgents(h,{teamId:Xe})).agents}).catch(()=>{!me&&ne.current===Q&&(ne.current=null)});return h0({accountKey:$,force:!0,fetchOrganizations:()=>X0(h)}).then(async $e=>{if(me)return;if($e.length===0){Ge();return}if(!!H&&$e.some(rt=>rt.teamId===H)){await _e(H),Ge();return}const et=FK($e)?.teamId;if(!et){Ge();return}if(H){s("The configured default team is unavailable for this account. Select an available team in account settings."),Ge();return}await _e(et),me||Ge()}).catch($e=>{me||(ne.current=null,s($e instanceof Error?$e.message:String($e)),Ge())}),()=>{me=!0}},[st,Le,y?.account,y?.accountMeta.asOf,y?.preferences.defaultTeamId,Ge,h,se,s]),g.useEffect(()=>{if(!h||!Ie)return;let $=!1;const H=()=>{$||($=!0,h0({accountKey:Ie,force:!0,fetchOrganizations:()=>X0(h)}).catch(()=>{}).finally(()=>{$=!1}))},Q=()=>{document.visibilityState==="visible"&&H()},me=window.setInterval(H,hG);return window.addEventListener("focus",H),document.addEventListener("visibilitychange",Q),()=>{window.clearInterval(me),window.removeEventListener("focus",H),document.removeEventListener("visibilitychange",Q)}},[h,Ie]),pc(()=>{const $=g3();s($||(H=>H?.startsWith("Preference changes have not been saved.")?null:H))}),g.useEffect(()=>{h&&qy(h).catch($=>s(String($)))},[h,Ie,s]);const Fe=g.useCallback(async()=>{se("connecting"),O(null);const $=await L4();v(Q=>H8(Q,$)?Q:$),se("account");const H=await J.bootstrap($);await qy($),st(H),Ge(),s(Q=>Q&&(v_(Q)||Q==="Event stream disconnected")?null:Q)},[st,Ge,se,s]);g.useEffect(()=>{let $=!1,H=null;const Q=async me=>{try{await Fe()}catch(_e){if($)return;s(_e instanceof Error?_e.message:String(_e));const $e=Math.min(5e3,750+me*750);H=window.setTimeout(()=>{Q(me+1)},$e)}};return Q(0),()=>{$=!0,H!==null&&window.clearTimeout(H)}},[Fe,s]);const De=g.useCallback(()=>{Fe().catch(()=>{})},[Fe]);O8({afterSequence:N?.afterSequence??null,appendEvents:P,connection:h,setApprovals:B,setSessions:Oe,setError:s,onDisconnected:De}),g.useEffect(()=>{if(!h||!y){Se.current=null;return}const $=D8(R);!$||Se.current===$||(Se.current=$,J.profileCurrent(h).then(H=>{w(Q=>Q&&{...Q,profile:H})}).catch(H=>{Se.current=null,s(H instanceof Error?H.message:String(H))}))},[y,h,R,s]);const L=g.useCallback(()=>{h&&J.refreshOpenPondAccount(h).then(({account:$,accountMeta:H})=>{w(Q=>Q&&{...Q,account:$,accountMeta:H})}).catch($=>s($ instanceof Error?$.message:String($)))},[h,s]);return{appPreferences:D,applyBootstrapPayload:st,approvals:z,bootstrap:y,codexHistorySessions:C,connection:h,events:R,runtimeEventStore:I,refreshOpenPondAccount:L,sessions:j,startup:mG(le),setAppPreferences:we,setBootstrap:w,setCodexHistorySessions:Qe,setEvents:M,setSessions:Oe}}async function X0(e){return(await J.organizations(e)).organizations.map(Uu).filter(n=>!!n).filter(n=>n.status==="active")}function vG(e){return e>=fG?0:Math.max(0,pG-e)}function bG(e,t,n){return`${e}::${t||"none"}::${n}`}function yG({appDispatch:e,error:t,setErrorState:n}){const a=g.useRef(null),o=g.useRef(null),i=g.useRef(null),s=g.useRef(0),l=g.useCallback((h,v="info",y={})=>{const w=Date.now()+ ++s.current;return e({type:"showToast",toast:{id:w,message:h,tone:v,...y}}),w},[e]),m=g.useCallback(()=>{e({type:"patch",patch:{settingsSection:"diagnostics",sidebarOpen:!0,view:"settings"}})},[e]),d=g.useCallback(h=>{const v=o.current,y=typeof h=="function"?h(v):h;if(Object.is(v,y))return;if(o.current=y,n(y),!y){i.current!==null&&(e({type:"clearToast",toastId:i.current}),i.current=null);return}i.current=l(SG(y),"error",{actionLabel:"Open diagnostics settings",actionIcon:"settings",onAction:m,dismissible:!0});const w=a.current;w&&J.recordClientDiagnostic(w,{message:y,surface:"app",context:{href:window.location.href}}).catch(I=>{console.warn("Unable to record client diagnostic.",I)})},[e,m,n,l]);return g.useEffect(()=>{o.current=t,!(t||i.current===null)&&(e({type:"clearToast",toastId:i.current}),i.current=null)},[e,t]),{connectionRef:a,setError:d,showToast:l}}function SG(e){return g_(e)}const kG={query:"",searchOpen:!1,archivedChatsOpen:!1,sectionMenuOpen:null,projectsExpanded:!1,cloudProjectsExpanded:!1,chatRowsVisibleCount:Pn,sidebarOpen:!0,view:"chat",selectedAppId:null,selectedProjectId:null,selectedSessionId:null,prompt:"",promptDrafts:{},draftProvider:Fr,draftModel:Ml,draftExperience:"chat",codexPermissionMode:Vh,codexReasoningEffort:Kh,openPondCommandAccessMode:ou,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 Rv(e){return e.selectedSessionId?`session:${e.selectedSessionId}`:e.selectedProjectId?`project:${e.selectedProjectId}`:e.selectedAppId?`app:${e.selectedAppId}`:`new-${e.draftExperience}`}function Wd(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 xG(e){return Wd(e.promptDrafts,Rv(e),e.prompt)}function cl(e,t,n={}){const a={...e,...t},o=Rv(a),i=xG(e),s=n.clearSelectedDraft?Wd(i,o,""):n.preserveCurrentPrompt?Wd(i,o,e.prompt):i;return{...e,...t,promptDrafts:s,prompt:n.clearSelectedDraft?"":n.preserveCurrentPrompt?e.prompt:s[o]??""}}function wG(e){return e==="draftExperience"||e==="selectedAppId"||e==="selectedProjectId"||e==="selectedSessionId"}function IG(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:Wd(e.promptDrafts,Rv(e),o)}}return wG(t.key)?cl(e,{[t.key]:a}):{...e,[t.key]:a}}case"patch":return{...e,...t.patch};case"selectApp":return cl(e,{selectedAppId:t.appId,selectedProjectId:null,selectedSessionId:null,view:"chat"});case"selectProject":return cl(e,{selectedAppId:null,selectedProjectId:t.projectId,selectedSessionId:null,view:"chat"},{preserveCurrentPrompt:!0});case"selectSession":{const n=t.projectId??null;return cl(e,{selectedSessionId:t.sessionId,selectedAppId:n?null:t.appId??null,selectedProjectId:n,view:"chat"})}case"beginNewChat":return cl(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 ht(e,t){return n=>e({type:"field",key:t,value:n})}function _G(e){return{setQuery:ht(e,"query"),setSearchOpen:ht(e,"searchOpen"),setArchivedChatsOpen:ht(e,"archivedChatsOpen"),setSectionMenuOpen:ht(e,"sectionMenuOpen"),setProjectsExpanded:ht(e,"projectsExpanded"),setCloudProjectsExpanded:ht(e,"cloudProjectsExpanded"),setChatRowsVisibleCount:ht(e,"chatRowsVisibleCount"),setSidebarOpen:ht(e,"sidebarOpen"),setView:ht(e,"view"),setSelectedAppId:ht(e,"selectedAppId"),setSelectedProjectId:ht(e,"selectedProjectId"),setSelectedSessionId:ht(e,"selectedSessionId"),setPrompt:ht(e,"prompt"),setDraftProvider:ht(e,"draftProvider"),setDraftModel:ht(e,"draftModel"),setDraftExperience:ht(e,"draftExperience"),setCodexPermissionMode:ht(e,"codexPermissionMode"),setCodexReasoningEffort:ht(e,"codexReasoningEffort"),setOpenPondCommandAccessMode:ht(e,"openPondCommandAccessMode"),setBusy:ht(e,"busy"),setDiffPanelOpen:ht(e,"diffPanelOpen"),setDiffPanelExpanded:ht(e,"diffPanelExpanded"),setRightPanelMode:ht(e,"rightPanelMode"),setRightChatPanels:ht(e,"rightChatPanels"),setTerminalOpen:ht(e,"terminalOpen"),setSyncingWorkspaceAppId:ht(e,"syncingWorkspaceAppId"),setSettingsSection:ht(e,"settingsSection"),setNewProjectDialogOpen:ht(e,"newProjectDialogOpen"),setNewProjectMode:ht(e,"newProjectMode"),setNewProjectName:ht(e,"newProjectName"),setNewProjectPath:ht(e,"newProjectPath"),setNewProjectBusy:ht(e,"newProjectBusy"),setCommitDialogOpen:ht(e,"commitDialogOpen"),setCommitMessage:ht(e,"commitMessage"),setCommitIncludeUnstaged:ht(e,"commitIncludeUnstaged"),setCommitNextStep:ht(e,"commitNextStep"),setCommitDraft:ht(e,"commitDraft"),setBranchDialogOpen:ht(e,"branchDialogOpen"),setBranchDialogName:ht(e,"branchDialogName"),setToast:ht(e,"toast"),setError:ht(e,"error")}}function dl(e){return e.selectedSessionId?`session:${e.selectedSessionId}`:e.selectedProjectId?`project:${e.selectedProjectId}`:e.selectedAppId?`app:${e.selectedAppId}`:"new-chat"}function CG(e={selectedAppId:null,selectedProjectId:null,selectedSessionId:null}){let t=e,n="";const a=new Map,o=new Set,i=d=>{if(!Object.is(n,d)){n=d;for(const h of o)h()}},s=()=>{const d=dl(t);n?a.set(d,n):a.delete(d)},l=(d,h={})=>{const v=n;s(),t={...t,...d};const y=dl(t);if(h.clear&&a.delete(y),h.preserveCurrentDraft){v?a.set(y,v):a.delete(y),i(v);return}i(h.clear?"":a.get(y)??"")},m={getScopeKey:()=>dl(t),getSnapshot:()=>n,subscribe(d){return o.add(d),()=>o.delete(d)},set:d=>m.setForScope(dl(t),d),setForScope(d,h){const v=dl(t),y=d===v?n:a.get(d)??"",w=typeof h=="function"?h(y):h;Object.is(y,w)||(w?a.set(d,w):a.delete(d),d===v&&i(w))},applyAppAction(d){if(d.type==="field"){if(d.key==="prompt"){m.set(d.value);return}if(d.key==="selectedAppId"||d.key==="selectedProjectId"||d.key==="selectedSessionId"){const h=t[d.key],v=typeof d.value=="function"?d.value(h):d.value;Object.is(h,v)||l({[d.key]:v})}return}if(d.type==="patch"){const h={};"selectedAppId"in d.patch&&(h.selectedAppId=d.patch.selectedAppId),"selectedProjectId"in d.patch&&(h.selectedProjectId=d.patch.selectedProjectId),"selectedSessionId"in d.patch&&(h.selectedSessionId=d.patch.selectedSessionId),Object.keys(h).length>0&&l(h),"prompt"in d.patch&&typeof d.patch.prompt=="string"&&m.set(d.patch.prompt);return}if(d.type==="selectApp"){l({selectedAppId:d.appId,selectedProjectId:null,selectedSessionId:null});return}if(d.type==="selectProject"){l({selectedAppId:null,selectedProjectId:d.projectId,selectedSessionId:null},{preserveCurrentDraft:!0});return}if(d.type==="selectSession"){const h=d.projectId??null;l({selectedSessionId:d.sessionId,selectedAppId:h?null:d.appId??null,selectedProjectId:h});return}d.type==="beginNewChat"&&l({selectedSessionId:null,selectedAppId:d.appId,selectedProjectId:null})}};return m}function IQ(e){return g.useSyncExternalStore(e.subscribe,e.getSnapshot,e.getSnapshot)}function RG(e){return{...e,draftExperience:yv()}}function PG(){const[e,t]=g.useReducer(IG,kG,RG),[n]=g.useState(()=>CG()),a=g.useCallback(i=>{n.applyAppAction(i),t(i)},[n]),o=g.useMemo(()=>({..._G(a),setPrompt:n.set}),[n,a]);return pc(()=>o.setDraftExperience(yv())),{composerDraftStore:n,dispatch:a,setters:o,state:e}}function AG(e){return!!(e&&e.includes("Git is required for OpenPond app workspaces")&&e.includes("Command Line Tools"))}function TG(e){const{connection:t,events:n,showToast:a}=e,o=g.useRef(new Set),i=g.useCallback(async()=>{if(t)try{const l=await J.installMacOSCommandLineTools(t);a(l.message,"info")}catch(l){a(l instanceof Error?l.message:String(l),"error")}},[t,a]),s=g.useCallback((l="OpenPond needs Git to create and sync local projects.")=>{a(l,"error",{actionLabel:"Install Tools",onAction:()=>{i()},persistent:!0})},[a,i]);g.useEffect(()=>{if(!t)return;let l=!1;return J.gitAvailability(t).then(m=>{l||m.ok||m.installAction!=="macos_command_line_tools"||s("OpenPond needs Git before it can create local projects.")}).catch(()=>{}),()=>{l=!0}},[t,s]),g.useEffect(()=>{for(const l of n){if(o.current.has(l.id))continue;const m=l.error??l.output??null;l.name==="workspace_action_result"&&l.status==="failed"&&AG(m)&&(o.current.add(l.id),s("OpenPond needs Git before it can update this project."))}},[n,s])}function EG({connection:e,preferences:t,sidebarOpen:n,diffPanelExpanded:a,setBootstrap:o,setError:i}){const[s,l]=g.useState(()=>ba().sidebarSectionsCollapsed),m=g.useRef(s),d=g.useRef({}),h=g.useRef(null),v=g.useRef(null),[y,w]=g.useState(L8),[I,R]=g.useState(!1),[M,P]=g.useState(U8),[N,O]=g.useState(!1),{pinned:j,projects:k,cloudProjects:C,chats:T,savedForLater:z}=s;g.useEffect(()=>{if(I)return;const ne=ef(ba(t).sidebarWidth),ge=W0(ne,h.current);h.current=ge.localChange,w(ge.value)},[t,I]),g.useEffect(()=>{if(N)return;const ne=tf(ba(t).diffPanelWidth),ge=W0(ne,v.current);v.current=ge.localChange,P(ge.value)},[N,t]),g.useEffect(()=>{const ne=ba(t).sidebarSectionsCollapsed;l(ge=>{const xe=Z8(ge,ne,d.current);return m.current=xe,xe})},[t]);const B=g.useCallback(ne=>{o(ge=>ge&&{...ge,preferences:ne.preferences})},[o]),D=g.useCallback(async ne=>{if(e&&ef(ba(t).sidebarWidth)!==ne)try{B(await J.savePreferences(e,{sidebarWidth:ne}))}catch(ge){i(ge instanceof Error?ge.message:String(ge))}},[e,t,i,B]),V=g.useCallback(async ne=>{if(e&&tf(ba(t).diffPanelWidth)!==ne)try{B(await J.savePreferences(e,{diffPanelWidth:ne}))}catch(ge){i(ge instanceof Error?ge.message:String(ge))}},[e,t,i,B]),le=g.useCallback(async ne=>{if(!e)return;const ge=ba(t).sidebarSectionsCollapsed;if(!MG(ge,ne))try{B(await J.savePreferences(e,{sidebarSectionsCollapsed:ne}))}catch(xe){i(xe instanceof Error?xe.message:String(xe))}},[e,t,i,B]),te=g.useCallback(ne=>{const ge=m.current;G8(d.current,ge,ne),m.current=ne,l(ne),le(ne)},[le]),Ie=g.useCallback(()=>{const ne=m.current;te({...ne,pinned:!ne.pinned})},[te]),ke=g.useCallback(()=>{const ne=m.current;te({...ne,projects:!ne.projects})},[te]),Z=g.useCallback(()=>{const ne=m.current;te({...ne,cloudProjects:!ne.cloudProjects})},[te]),Ae=g.useCallback(()=>{const ne=m.current;te({...ne,chats:!ne.chats})},[te]),he=g.useCallback(()=>{const ne=m.current;te({...ne,savedForLater:!ne.savedForLater})},[te]),ue=g.useCallback(ne=>{if(!n)return;ne.preventDefault();const ge=ne.clientX,xe=y;let qe=xe;R(!0);function Se(we){qe=ef(xe+we.clientX-ge),w(qe)}function se(){window.removeEventListener("pointermove",Se),window.removeEventListener("pointerup",se);const we=K0(xe,qe);we&&(h.current=we),R(!1),D(qe)}window.addEventListener("pointermove",Se),window.addEventListener("pointerup",se,{once:!0})},[D,n,y]),be=g.useCallback(ne=>{if(a)return;ne.preventDefault();const ge=ne.clientX,xe=M;let qe=xe;O(!0);function Se(we){qe=tf(xe-(we.clientX-ge)),P(qe)}function se(){window.removeEventListener("pointermove",Se),window.removeEventListener("pointerup",se);const we=K0(xe,qe);we&&(v.current=we),O(!1),V(qe)}window.addEventListener("pointermove",Se),window.addEventListener("pointerup",se,{once:!0})},[a,M,V]);return{pinnedCollapsed:j,projectsCollapsed:k,cloudProjectsCollapsed:C,chatsCollapsed:T,savedForLaterCollapsed:z,sidebarWidth:y,sidebarResizing:I,diffPanelWidth:M,diffPanelResizing:N,togglePinnedCollapsed:Ie,toggleProjectsCollapsed:ke,toggleCloudProjectsCollapsed:Z,toggleChatsCollapsed:Ae,toggleSavedForLaterCollapsed:he,startSidebarResize:ue,startDiffPanelResize:be}}function MG(e,t){return e.pinned===t.pinned&&e.projects===t.projects&&e.cloudProjects===t.cloudProjects&&e.chats===t.chats&&e.savedForLater===t.savedForLater}function jG(e){const[t,n]=g.useState({id:0,kind:null}),[a,o]=g.useState(null),i=g.useCallback((d=null)=>{n(h=>({id:h.id+1,kind:d}))},[]),s=g.useCallback(d=>{o(d)},[]),l=null,m=g.useMemo(()=>{if(e)return OG(a,i)},[e,a,i]);return{backAction:l,breadcrumbs:m,closeDetailKind:t.kind,closeDetailRequestId:t.id,onDetailOpenChange:s}}function OG(e,t){return e?[{label:"Models",onSelect:()=>t(null)},{label:e.kindLabel,onSelect:e.kindOnSelect??(()=>t(e.kind))},...e.workproductLabel?[{label:e.workproductLabel,onSelect:e.workproductOnSelect}]:[],...e.segments]:[{label:"Models"}]}const eS=new WeakMap,hh=new WeakMap;function $G(e){if(!e)return"disconnected";let t=eS.get(e);return(!t||t.serverUrl!==e.serverUrl||t.token!==e.token)&&(t={serverUrl:e.serverUrl,token:e.token,id:crypto.randomUUID()},eS.set(e,t)),t.id}function _Q(e,t){return hh.set(e,t),e}function CQ(e){if(!e)return["learning","disconnected"];let t=hh.get(e);return t||(t=["learning",crypto.randomUUID()],hh.set(e,t)),t}var Gd=wt.shape.id,NG=c({schemaVersion:S("openpond.modelBatchReviewInspection.v1"),packageHash:r().regex(/^[a-f0-9]{64}$/),definition:Iu,binding:wu,evidence:f(_u).min(1).max(1e4),decisions:f(jg).min(1).max(1e4)}).strict(),RQ=c({schemaVersion:S("openpond.modelBatchReviewRequest.v1"),operationId:Gd,modelId:Gd,expectedModelRevision:u().int().positive(),tasksetRef:wt,rewardBindingRef:wt.nullable(),definition:c({name:r().trim().min(1).max(500).optional(),instructions:r().trim().min(1).max(2e4).optional(),inputSchema:Vt.optional(),outputSchema:Vt.optional(),requiredOutputs:Iu.shape.requiredOutputs}).strict(),examples:f(c({evidence:wt,input:Vt.optional(),expected:Vt.nullable().optional(),evaluatorContext:Vt.nullable().optional(),proposedTarget:Vt.nullable().optional()}).strict()).max(1e4)}).strict(),DG=c({schemaVersion:S("openpond.modelBatchReviewReceipt.v1"),operationId:Gd,modelId:Gd,source:Mg,evidence:f(_u).min(1).max(1e4),proposals:f(S1).max(1e4)}).strict();function LG(e,t,n){return{inspectModelBatch:async a=>{if(!e)throw new Error("Connect to OpenPond to inspect this batch.");return NG.parse(await J.trainingRequest(e,"/models/batch-review/inspect",{profileId:t,modelId:a},"POST"))},beginModelBatchReview:async a=>{const o=await n(a);return o?DG.parse(o):null}}}function UG(e,t,n,a){async function o(i,s){if(!e)throw new Error("Connect to OpenPond to load tasks.");const l=vq.parse(s),m=new URLSearchParams({profileId:t});for(const[d,h]of Object.entries(l))h!==void 0&&m.set(d,String(h));return J.trainingRequest(e,`${i}?${m}`,{},"GET")}return{taskInventory:async(i={})=>yq.parse(await o("/tasks",i)),taskInventoryDetail:async i=>{const s=await o("/tasks/detail",i);return{item:J1.parse(s.item),task:Pg.parse(s.task)}},tasksetDraftFiles:async i=>{if(!e)return null;try{return await J.trainingRequest(e,`/taskset-drafts/${encodeURIComponent(i)}/files?${new URLSearchParams({profileId:t})}`,{},"GET")}catch(s){return a(s),null}},tasksetDraftFile:async(i,s)=>{if(!e)return null;try{return await J.trainingRequest(e,`/taskset-drafts/${encodeURIComponent(i)}/file?${new URLSearchParams({profileId:t,path:s})}`,{},"GET")}catch(l){return a(l),null}},saveTasksetDraftFile:i=>n("save-taskset-draft-file",`/taskset-drafts/${encodeURIComponent(i.draftId)}/file`,{profileId:t,...i},"PATCH"),inspectTasksetDraftSource:(i,s)=>n("inspect-taskset-draft-source","/taskset-drafts/source",{profileId:t,modelId:i,expectedModelRevision:s}),createTasksetDraftFromSource:i=>n("create-taskset-draft","/taskset-drafts",{profileId:t,sourceRequest:i}),createTasksetDraft:(i="",s)=>n("create-taskset-draft","/taskset-drafts",{profileId:t,name:i,modelId:s??null}),importTasksetDraftPackage:i=>n("import-taskset-draft-package","/taskset-drafts/import",{packagePath:i,profileId:t}),saveTasksetDraft:i=>n("save-taskset-draft",`/taskset-drafts/${encodeURIComponent(i.id)}`,i,"PUT"),tasksetDraftWorkspace:async i=>{if(!e)return null;try{return await J.trainingRequest(e,`/taskset-drafts/${encodeURIComponent(i)}/workspace`,{},"GET")}catch(s){return a(s),null}},publishTasksetDraft:(i,s)=>n("publish-taskset-draft",`/taskset-drafts/${encodeURIComponent(i)}/publish`,{modelId:s??null}),refreshTasksetDraftModel:(i,s)=>n("refresh-taskset-draft-model",`/taskset-drafts/${encodeURIComponent(i.id)}/model-revision`,{expectedDraftRevision:i.revision,expectedModelRevision:s}),deleteTasksetDraft:i=>n("delete-taskset-draft",`/taskset-drafts/${encodeURIComponent(i)}`,{},"DELETE")}}function CC(e,t){return vH({id:e.id,profileId:e.profileId,name:e.name,objective:e.objective,defaultBaseModel:e.defaultBaseModel,defaultDestinationId:e.defaultDestinationId,trainingSetup:e.trainingSetup},t)}async function zG(e,t,n){if(!e)throw new Error("Connect to the execution owner to check this configuration.");const a=await CC(t,n);return D1.parse(await J.trainingRequest(e,"/models/check",a,"POST"))}function HG(e,t){return{listModelStarters:async(n,a=!1)=>{if(!e)throw new Error("Connect to OpenPond to browse model starters.");return J.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 J.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 D1.parse(await J.trainingRequest(e,"/model-starters/check",n))},createModelFromStarter:n=>t("create-model-from-starter","/model-starters/create",n)}}const tS=1e4,nS=3e4;function qG(e){const{connection:t,profileId:n}=e,a=IS(),o=$G(t),i=g.useMemo(()=>["training",o,n],[o,n]),s=g.useCallback(async()=>HF.parse(await J.trainingState(t,n)),[t,n]),l=jR({queryKey:i,queryFn:s,enabled:!!t}),m=l.data??null,d=!!t&&l.isPending,[h,v]=g.useState(null),[y,w]=g.useState(null),I=g.useRef(null);I.current=m?.activityRevision??null;const R=g.useCallback(async()=>{if(!t)return null;try{const k=await a.fetchQuery({queryKey:i,queryFn:s,staleTime:0});return w(null),k}catch(k){return w(To(k)),null}},[t,a,i,s]),M=g.useCallback(async()=>(await a.cancelQueries({queryKey:i,exact:!0}),await a.invalidateQueries({queryKey:i,exact:!0,refetchType:"none"}),await a.invalidateQueries({queryKey:["task-inventory",o,n]}),R()),[a,i,o,n,R]),P=g.useCallback(async(k,C,T,z="POST",B={})=>{if(!t)return null;B.silent||v(k);try{const D=await J.trainingRequest(t,C,T,z);return await M(),B.silent||w(null),D}catch(D){return B.silent||w(To(D)),null}finally{B.silent||v(null)}},[t,M]),N=m?[m.jobs.some(k=>["queued","starting","running","cancelling","reconciling"].includes(k.status)),m.creations.some(k=>["planning","materializing","validating"].includes(k.state)),m.minerRuns.some(k=>["queued","running","cancelling"].includes(k.status)),m.datasetImports.some(k=>["inspecting","materializing","validating","cancelling"].includes(k.status))].some(Boolean):!1;g.useEffect(()=>{if(!t)return;let k=!0,C=null;const T=N?tS:nS,z=async()=>{let B=T;try{const D=await J.trainingActivity(t,n);B=D.active?tS:nS,(I.current===null||I.current!==D.revision)&&await R()}catch(D){w(To(D))}k&&(C=window.setTimeout(()=>{z()},B))};return C=window.setTimeout(()=>{z()},T),()=>{k=!1,C!==null&&window.clearTimeout(C)}},[t,N,n,R]);const O=g.useMemo(()=>({...HG(t,P),saveComparisonSeries:k=>P("save-comparison-series","/comparison-series",{series:k}),saveContinualBenchIssueReview:k=>P("save-continual-support-issue-review","/continual-support/issue-reviews",{review:k},"PUT"),importContinualLearningDailyBatch:(k,C="json_upload")=>P("import-continual-learning-daily-batch","/continual-learning/daily-batches/import",{manifest:k,source:C}),saveContinualLearningDailyBatch:k=>P("save-continual-learning-daily-batch","/continual-learning/daily-batches",{batch:k},"PUT"),generateContinualLearningResponses:k=>P("generate-continual-learning-responses","/continual-learning/responses",k),sealComparisonSeries:(k,C)=>P("seal-comparison-series",`/comparison-series/${encodeURIComponent(k)}/seal`,{expectedRevision:C}),archiveComparisonSeries:(k,C)=>P("archive-comparison-series",`/comparison-series/${encodeURIComponent(k)}/archive`,{expectedRevision:C}),queueComparisonRelease:k=>P("queue-comparison-release",`/comparison-series/${encodeURIComponent(k.seriesId)}/releases`,k),startComparisonEvaluation:k=>P("start-comparison-evaluation",`/comparison-series-entries/${encodeURIComponent(k.entryId)}/evaluations`,k),loadComparisonAttemptEvidence:k=>t?J.trainingRequest(t,`/model-runs/${encodeURIComponent(k.runId)}/attempts/${encodeURIComponent(k.attemptId)}/evidence?kind=${k.kind}`,{},"GET"):Promise.resolve(null),linkComparisonRun:k=>P("link-comparison-run",`/comparison-series-entries/${encodeURIComponent(k.entryId)}/run`,k,"PATCH"),decideComparisonEntry:k=>P("decide-comparison-entry",`/comparison-series-entries/${encodeURIComponent(k.entryId)}/decision`,k),recordComparisonPromotion:k=>P("record-comparison-promotion",`/comparison-series-entries/${encodeURIComponent(k.entryId)}/promotion`,k),checkModelProject:(k,C=k.revision)=>zG(t,k,C),...LG(t,n,k=>P("begin-model-batch-review","/models/batch-review",{profileId:n,request:k})),saveModelProject:async(k,C=k.revision)=>P("save-model-project","/models",await CC(k,C),"PUT"),listHostedModelProjects:async(k={})=>{if(!t)return null;k.silent||v("list-hosted-model-projects");try{const C=await J.trainingRequest(t,`/hosted-model-projects?profileId=${encodeURIComponent(n)}&refresh=${k.refresh===!0}`,{},"GET");return k.silent||w(null),C}catch(C){return k.silent||w(To(C)),null}finally{k.silent||v(C=>C==="list-hosted-model-projects"?null:C)}},openHostedModelProject:(k,C,T,z={})=>P(`open-hosted-model-project:${k}`,`/hosted-model-projects/${encodeURIComponent(k)}/open`,{profileId:n,teamId:C,apiOrigin:T},"POST",z),pullHostedModelProject:k=>P(`pull-hosted-model-project:${k}`,`/hosted-model-projects/${encodeURIComponent(k)}/pull`,{profileId:n}),syncModelProject:k=>P("sync-model-project",`/models/${encodeURIComponent(k)}/sync`,{}),publishModelProjectTaskset:(k,C)=>P("publish-model-project-taskset",`/models/${encodeURIComponent(k)}/tasksets/${encodeURIComponent(C)}/publish`,{}),createScorer:(k,C,T)=>P("create-scorer","/scorers",{grader:k,tasksetId:C,modelProjectId:T??null}),prepareLearningBatch:k=>P("prepare-learning-batch","/learning-batches/prepare",{profileId:n,batchId:k}),...UG(t,n,P,k=>w(To(k))),tasksetGraderDetails:async k=>{if(!t)return null;try{return await J.trainingRequest(t,`/tasksets/${encodeURIComponent(k)}/graders`,{},"GET")}catch(C){return w(To(C)),null}},inspectHuggingFaceDataset:k=>P("inspect-huggingface-dataset","/dataset-imports/huggingface/inspect",{profileId:n,url:k}),materializeDatasetImport:(k,C)=>P("materialize-dataset-import",`/dataset-imports/${encodeURIComponent(k)}/materialize`,C),cancelDatasetImport:k=>P("cancel-dataset-import",`/dataset-imports/${encodeURIComponent(k)}/cancel`,{}),datasetRows:(k,C={})=>{if(!t)return Promise.resolve(null);const T=new URLSearchParams;C.split&&T.set("split",C.split),C.cursor&&T.set("cursor",C.cursor),T.set("limit",String(C.limit??25));for(const z of C.columns??[])T.append("column",z);return J.trainingRequest(t,`/tasksets/${encodeURIComponent(k)}/rows?${T}`,{},"GET")},addSource:(k,C)=>P("add-source","/sources",{profileId:n,sessionId:k,turnIds:C}),addSources:k=>P("add-sources","/sources/batch",{profileId:n,sessionIds:k}),estimateSources:k=>t?J.trainingRequest(t,"/sources/estimate",{sessionIds:k}):Promise.resolve([]),searchChats:(k,C,T=0,z=20)=>t?J.trainingRequest(t,"/sources/search",{query:k,candidates:C,offset:T,limit:z}):Promise.resolve({schemaVersion:"openpond.trainingChatSearchResult.v1",query:k,offset:T,limit:z,total:0,hasMore:!1,indexedChats:0,totalChats:0,indexing:!1,entries:[]}),removeSource:k=>P("remove-source",`/sources/${encodeURIComponent(k)}`,{},"DELETE"),deleteTaskset:k=>P("delete-model",`/tasksets/${encodeURIComponent(k)}`,{},"DELETE"),runBenchmark:(k,C,T,z)=>P(`run-benchmark-${C}`,`/tasksets/${encodeURIComponent(k)}/benchmark-runs`,{phase:C,model:T,reasoningEffort:z,seeds:[17],repetitions:1}),startHarnessRefinerBenchmark:(k,C,T)=>P("run-harness-refiner-benchmark",`/models/${encodeURIComponent(k)}/harness-refiner-benchmark`,{profileId:n,model:C,reasoningEffort:T,maximumSpendUsd:10}),acceptHarnessReview:(k,C,T=null,z=null)=>P("accept-harness-review","/harness-reviews/accept",{profileId:n,workspaceId:k,reviewRef:C,analysisModel:T,analysisReasoningEffort:z}),startCreation:(k,C={})=>P("create-taskset","/task-creations",{profileId:n,sourceIds:k,surface:C.surface??"training_page",mode:C.mode??"defaults",entryMode:C.entryMode??"manual",resourceIntent:C.resourceIntent??"workproduct",buildIntent:C.buildIntent??"demonstrations",buildSpecification:C.buildSpecification??null,objective:C.objective??null,methodHint:C.methodHint??null,preferredBaseModelId:C.preferredBaseModel?.modelId??null,preferredBaseModel:C.preferredBaseModel??null,candidateId:C.candidateId??null,analysisModel:C.analysisModel??null,analysisReasoningEffort:C.analysisReasoningEffort??null,createImproveRunId:C.createImproveRunId??null,targetIntent:C.targetIntent??{kind:"model",id:null,displayName:null,operation:"create"}}),createModelFromTaskset:(k,C)=>P("create-model","/models/from-taskset",{profileId:n,tasksetId:k,preferredBaseModelId:C.modelId,preferredBaseModel:C}),scanBaseModels:async()=>{if(!t)return null;v("scan-base-models");try{const k=await R();return w(null),k}catch(k){return w(To(k)),null}finally{v(null)}},approveDisclosure:(k,C)=>P("approve-disclosure",`/task-creations/${encodeURIComponent(k)}/disclosure`,{approved:C}),retryCreation:k=>P("retry-creation",`/task-creations/${encodeURIComponent(k)}/retry`,{}),answerQuestions:(k,C)=>P("answer-questions",`/task-creations/${encodeURIComponent(k)}/questions`,{answers:C}),materialize:(k,C)=>P("materialize",`/task-creations/${encodeURIComponent(k)}/materialize`,{approved:C}),chatCreation:(k,C)=>P("task-creator-chat",`/task-creations/${encodeURIComponent(k)}/chat`,{message:C}),renameCreation:(k,C)=>P("rename-creation",`/task-creations/${encodeURIComponent(k)}/name`,{name:C},"PATCH"),cancelCreation:k=>P("cancel-creation",`/task-creations/${encodeURIComponent(k)}/cancel`,{}),runMiner:(k=[],C=[],T)=>P("run-miner","/miner/run",{profileId:n,sourceIds:k,sessionIds:C,config:T}),cancelMinerRun:k=>P("cancel-miner-run",`/miner/runs/${encodeURIComponent(k)}/cancel`,{}),configureMiner:k=>P("configure-miner","/miner/config",{profileId:n,config:k},"PUT"),patchCandidate:(k,C)=>P("candidate",`/candidates/${encodeURIComponent(k)}`,C,"PATCH"),createCandidate:(k,C,T,z)=>P("create-candidate",`/candidates/${encodeURIComponent(k)}/create`,{mode:C,analysisModel:T??null,analysisReasoningEffort:z??null}),auditGraders:k=>P("audit-graders","/audit-graders",{tasksetId:k}),executeTasksetAttempt:(k,C,T)=>P("execute-taskset-attempt",`/tasksets/${encodeURIComponent(k)}/attempts`,{taskId:C,model:T,seed:17,attempt:0,sampling:{maxOutputTokens:4096,temperature:0,topP:1}}),materializeSyntheticPreferenceCollection:k=>P("materialize-synthetic-preference-collection",`/tasksets/${encodeURIComponent(k.tasksetId)}/synthetic-preference-collection`,k),tasksetOperationalState:k=>t?J.trainingRequest(t,`/tasksets/${encodeURIComponent(k)}/operations`,{},"GET"):Promise.resolve(null),calibrateJudges:k=>P("calibrate-judges","/calibrate-judges",{tasksetId:k}),nextPreferenceComparison:(k,C)=>P("next-preference-comparison",`/tasksets/${encodeURIComponent(k)}/preference-comparisons/next`,{reviewerKey:C}),submitPreferenceComparison:k=>P("submit-preference-comparison",`/tasksets/${encodeURIComponent(k.tasksetId)}/preference-comparisons/${encodeURIComponent(k.assignmentId)}/submit`,k),submitSyntheticFixturePreference:k=>P("submit-synthetic-fixture-preference",`/tasksets/${encodeURIComponent(k.tasksetId)}/preference-comparisons/${encodeURIComponent(k.assignmentId)}/fixture-submit`,{...k,id:crypto.randomUUID()}),listPreferenceDatasets:k=>t?J.trainingRequest(t,`/tasksets/${encodeURIComponent(k)}/preference-datasets`,{},"GET"):Promise.resolve(null),materializePreferenceDataset:k=>P("materialize-preference-dataset",`/tasksets/${encodeURIComponent(k.tasksetId)}/preference-datasets`,{...k,id:`preference-dataset-${crypto.randomUUID()}`,revision:1}),launchRewardModelRun:k=>P("launch-reward-model-run",`/tasksets/${encodeURIComponent(k.tasksetId)}/reward-model-runs`,{...k,id:`reward-model-run-${crypto.randomUUID()}`}),learnedPreferenceRewardBinding:k=>P("learned-preference-reward-binding",`/tasksets/${encodeURIComponent(k.tasksetId)}/learned-preference-reward-binding`,k),retryRewardModelQualification:k=>P("retry-reward-model-qualification",`/reward-model-runs/${encodeURIComponent(k.runId)}/retry-qualification`,k),cancelRewardModelRun:k=>P("cancel-reward-model-run",`/reward-model-runs/${encodeURIComponent(k)}/cancel`,{}),markPreferenceComparisonUnreviewable:k=>P("mark-preference-comparison-unreviewable",`/tasksets/${encodeURIComponent(k.tasksetId)}/preference-comparisons/${encodeURIComponent(k.assignmentId)}/unreviewable`,k),preferenceCalibrationStatus:(k,C,T)=>{if(!t)return Promise.resolve(null);const z=new URLSearchParams({reviewerKey:C});return T&&z.set("comparisonReleaseId",T),J.trainingRequest(t,`/tasksets/${encodeURIComponent(k)}/preference-comparisons/calibration/status?${z}`,{},"GET")},startPreferenceCalibrationBatch:k=>P("start-preference-calibration-batch",`/tasksets/${encodeURIComponent(k.tasksetId)}/preference-comparisons/calibration/batches`,{...k,id:crypto.randomUUID()}),syncPreferenceCalibrationBatch:k=>P("sync-preference-calibration-batch",`/tasksets/${encodeURIComponent(k.tasksetId)}/preference-comparisons/calibration/batches/${encodeURIComponent(k.jobId)}/sync`,k),reviewPreferenceComparisonWithModel:k=>P("review-preference-comparison-with-model",`/tasksets/${encodeURIComponent(k.tasksetId)}/preference-comparisons/${encodeURIComponent(k.assignmentId)}/model-review`,{...k,id:crypto.randomUUID()}),runNextPreferenceCalibrationReview:k=>P("run-next-preference-calibration-review",`/tasksets/${encodeURIComponent(k.tasksetId)}/preference-comparisons/calibration/model-reviews/next`,{...k,id:crypto.randomUUID()}),savePreferenceCalibration:k=>P("save-preference-calibration",`/tasksets/${encodeURIComponent(k.tasksetId)}/preference-comparisons/calibration/report`,{...k,id:crypto.randomUUID()}),preferenceArtifactUrl:async k=>{if(!t)return null;const C=await fetch(`${t.serverUrl}/v1/training/artifacts/${encodeURIComponent(k)}/download`,{headers:{Authorization:`Bearer ${t.token}`}});if(!C.ok)throw new Error(await C.text());return URL.createObjectURL(await C.blob())},readiness:k=>P("readiness","/readiness",{tasksetId:k}),previewExpertBootstrap:k=>P("preview-expert-bootstrap",`/tasksets/${encodeURIComponent(k)}/expert-bootstrap/preview`,{}),approveExpertBootstrap:(k,C)=>P("approve-expert-bootstrap",`/tasksets/${encodeURIComponent(k)}/expert-bootstrap/approve`,{previewHash:C}),createPlan:k=>P("create-plan","/plans",{...k,tasksetId:k.tasksetId}),buildBundle:k=>P("build-bundle","/bundles",{planId:k}),approveTraining:(k,C)=>P("approve-training","/approvals",{planId:k,bundleId:C}),launch:(k,C)=>P("launch","/launch",{planId:k,approvalId:C}),prepareTraining:k=>P("prepare-training","/prepare",k),prepareModelRun:(k,C)=>P("prepare-model-run",`/model-projects/${encodeURIComponent(k)}/training/prepare`,C),startModelRun:(k,C)=>P("start-model-run",`/model-projects/${encodeURIComponent(k)}/training/start`,C),startPreparedTraining:k=>P("start-prepared-training","/start/prepared",k),startTraining:k=>P("start-training","/start",k),cancelJob:k=>P("cancel-job",`/jobs/${encodeURIComponent(k)}/cancel`,{}),retryModelRunCollection:k=>P("retry-model-run-collection",`/model-runs/${encodeURIComponent(k)}/retry-collection`,{}),cancelModelRun:k=>P("cancel-model-run",`/model-runs/${encodeURIComponent(k)}/cancel`,{}),rejectModel:(k,C)=>P("reject-model",`/models/${encodeURIComponent(k)}/reject`,{reason:C}),bindModel:(k,C,T)=>P("bind-model",`/models/${encodeURIComponent(k)}/bind`,{profileId:n,role:C,roleTargetId:T,promotedBy:n}),rollbackModelBinding:k=>P("rollback-model-binding",`/bindings/${encodeURIComponent(k)}/rollback`,{rolledBackBy:n}),updateModelConfiguration:(k,C)=>P("update-model-configuration",`/models/${encodeURIComponent(k)}/configuration`,C,"PATCH",{silent:!0}),setModelPinned:(k,C)=>P("pin-model-version",`/models/${encodeURIComponent(k)}/pin`,{pinned:C},"PATCH"),downloadArtifact:async k=>{if(!t)return!1;v("download-artifact");try{const C=await fetch(`${t.serverUrl}/v1/training/artifacts/${encodeURIComponent(k)}/download`,{headers:{Authorization:`Bearer ${t.token}`}});if(!C.ok)throw new Error(await C.text());const T=C.headers.get("content-disposition")??"",z=/filename="([^"]+)"/.exec(T)?.[1]??"openpond-model-artifact",B=URL.createObjectURL(await C.blob()),D=document.createElement("a");return D.href=B,D.download=z,D.click(),URL.revokeObjectURL(B),!0}catch(C){return w(To(C)),!1}finally{v(null)}},downloadModelPackage:async k=>j(`/models/${encodeURIComponent(k)}/download`,`${k}.openpond-lora.tar`),downloadBundle:async k=>j(`/bundles/${encodeURIComponent(k)}/download`,"openpond-model-improvement-bundle.json")}),[t,P,n,R]);async function j(k,C){if(!t)return!1;v("download-bundle");try{const T=await fetch(`${t.serverUrl}/v1/training${k}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!T.ok)throw new Error(await T.text());const z=T.headers.get("content-disposition")??"",B=/filename="([^"]+)"/.exec(z)?.[1]??C,D=URL.createObjectURL(await T.blob()),V=document.createElement("a");return V.href=D,V.download=B,V.click(),URL.revokeObjectURL(D),!0}catch(T){return w(To(T)),!1}finally{v(null)}}return{connection:t,payload:m,loading:d,busyAction:h,error:y??l.error?.message??null,refresh:R,actions:O}}function To(e){return e instanceof Error?e.message:String(e)}function PQ({modelId:e,taskset:t}){const n=t.metadata.toolContractHash===uc?"cross_system":t.environment.kind==="stateful_harness"&&t.environment.actionBindings?.length?"harness":null,a=n?KG(t,n):[];return{model:{providerId:"openpond",modelId:e},tasksetId:t.id,tasksetName:t.name,taskRuntime:n,sourceProjectId:WG(t),tasks:a,selectedTaskIndex:0,sessionId:null}}function AQ(e){return{model:{providerId:"openpond",modelId:e.modelId},tasksetId:e.tasksetId,tasksetName:e.modelName,taskRuntime:null,sourceProjectId:null,tasks:[],selectedTaskIndex:0,sessionId:null}}function ji(e){return e?.tasks.length?e.tasks[AC(e,e.selectedTaskIndex)]??null:null}function RC(e,t){return{...e,selectedTaskIndex:AC(e,t)}}function BG(e){return RC(e,e.selectedTaskIndex+1)}function FG(e,t,n){if(!e||PC(e,n))return null;const a=ji(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 PC(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 VG({model:e,connection:t,loadBootstrap:n,applyBootstrap:a}){e.providerId!=="openpond"||!t||a(await n(t))}function KG(e,t){const n=new Set;return e.tasks.flatMap(a=>{const o=t==="cross_system"?a.metadata.taskId:a.metadata.caseId,i=typeof o=="string"?o.trim():"",s=typeof a.input.prompt=="string"?a.input.prompt.trim():"";return!i||!s||n.has(i)?[]:(n.add(i),[{authoredTaskId:a.id,generatedTaskId:i,prompt:s,split:a.split}])})}function WG(e){const t=new Set(e.sourceRefs.filter(rz).flatMap(n=>{const a=n.workspaceId?.trim();return a?[a]:[]}));return t.size===1?t.values().next().value??null:null}function AC(e,t){return e.tasks.length?Math.max(0,Math.min(Math.trunc(t),e.tasks.length-1)):0}function GG({activeModel:e,activeProvider:t,applyBootstrapPayload:n,beginNewChat:a,composerDraftStore:o,connection:i,requestComposerFocus:s,selectedLocalProjectId:l,selectedSessionId:m,selectLocalProject:d,setDraftModel:h,setDraftProvider:v,setError:y,view:w}){const[I,R]=g.useState(null),M=g.useCallback(T=>{T.sourceProjectId?d(T.sourceProjectId):a(null)},[a,d]),P=g.useCallback(T=>{if(!I)return;const z={...RC(I,T),sessionId:I.sessionId?null:I.sessionId},B=ji(z);R(z),B&&(I.sessionId&&M(z),o.set(B.prompt),s())},[M,o,I,s]),N=g.useCallback(()=>{const T=ji(I);T&&o.getSnapshot().trim()===T.prompt.trim()&&o.set(""),R(null)},[o,I]),O=g.useCallback(T=>{const z=T.model;VG({model:z,connection:i,loadBootstrap:J.bootstrap,applyBootstrap:n}).then(()=>{const B={...T,selectedTaskIndex:0,sessionId:null};v(z.providerId),h(z.modelId),R(B.tasks.length?B:null),M(B);const D=ji(B);D&&o.set(D.prompt)}).catch(y)},[n,M,o,i,h,v,y]),j=g.useCallback(T=>{const z=!!(I&&I.model.providerId===t&&I.model.modelId===e);return{active:z,error:z?PC(I,l):null,metadata:z?FG(I,T,l):null}},[e,t,I,l]),k=g.useCallback(T=>{R(z=>z&&{...z,sessionId:T})},[]),C=g.useCallback(()=>{if(!I)return;const T={...BG(I),sessionId:null},z=ji(T);R(T),z&&(M(T),o.set(z.prompt),s())},[M,o,I,s]);return g.useEffect(()=>{const T=ji(I);!T||w!=="chat"||m||o.set(z=>z.trim()?z:T.prompt)},[o,I,l,m,w]),g.useEffect(()=>{I&&m&&I.sessionId!==m&&R(null)},[I?.sessionId,m]),{advanceAfterTurn:C,begin:O,bindSession:k,dismiss:N,handoff:I,prepareTurn:j,selectTask:P}}const ul=[],nf=500;function ZG(e){const{approvals:t,codexHistoryEvents:n,connection:a,latestServerSequence:o,runtimeIndexes:i,runtimeEventStore:s,selectedSessionId:l,serverId:m,setCodexHistoryEvents:d,setCodexHistorySessions:h,setError:v}=e,[y,w]=g.useState({}),[I,R]=g.useState({}),M=g.useRef(new Set);g.useEffect(()=>{w({}),R({}),M.current.clear()},[m]);const P=g.useCallback(async()=>{if(!a||!l||M.current.has(l))return!1;const C=I[l];if(C?.hasMore===!1)return!1;if(qt(l)){const B=Math.max(C?.totalMatchingEvents??0,n.length,X_),D=Math.min(_0,Math.max(P9,B*2));M.current.add(l),R(V=>({...V,[l]:{cursorSequence:null,hasMore:!0,loading:!0,totalMatchingEvents:V[l]?.totalMatchingEvents??n.length}}));try{const V=await eC(a,l,{force:!0,limit:D,tail:!1});return d(V.events),h(le=>zu(le,V.session)),R(le=>({...le,[l]:{cursorSequence:null,hasMore:V.events.length>=D&&D<_0,loading:!1,totalMatchingEvents:D}})),V.events.length>n.length}catch(V){return v(V instanceof Error?V.message:String(V)),R(le=>({...le,[l]:{cursorSequence:null,hasMore:le[l]?.hasMore??!0,loading:!1,totalMatchingEvents:le[l]?.totalMatchingEvents??n.length}})),!1}finally{M.current.delete(l)}}const T=Oo(y[l]??ul,s.getSessionEvents(l)),z=C?.cursorSequence??JG(T);if(!z)return!1;M.current.add(l),R(B=>({...B,[l]:{cursorSequence:B[l]?.cursorSequence??z,hasMore:B[l]?.hasMore??!0,loading:!0,totalMatchingEvents:B[l]?.totalMatchingEvents??null}}));try{const B=await J.runtimeEventsPage(a,{sessionId:l,beforeSequence:z,limit:nf}),D=B.events.map(V=>V.event);return w(V=>({...V,[l]:Oo(D,V[l]??ul)})),R(V=>({...V,[l]:{cursorSequence:B.previousSequence,hasMore:B.hasMore,loading:!1,totalMatchingEvents:B.totalMatchingEvents}})),D.length>0}catch(B){return v(B instanceof Error?B.message:String(B)),R(D=>({...D,[l]:{cursorSequence:D[l]?.cursorSequence??z,hasMore:D[l]?.hasMore??!0,loading:!1,totalMatchingEvents:D[l]?.totalMatchingEvents??null}})),!1}finally{M.current.delete(l)}},[I,n.length,a,y,s,l,d,h,v]),N=l?y[l]??ul:ul,O=g.useMemo(()=>s.getSessionEvents(l).length,[s,l]),j=g.useRef(null);g.useEffect(()=>{if(!a||!l||qt(l)||M.current.has(l)||N.length>0||O>0)return;const C=o;if(!C)return;const T=l,z=C+1;M.current.add(T),R(B=>({...B,[T]:{cursorSequence:B[T]?.cursorSequence??z,hasMore:B[T]?.hasMore??!0,loading:!0,totalMatchingEvents:B[T]?.totalMatchingEvents??null}})),J.runtimeEventsPage(a,{sessionId:T,beforeSequence:z,limit:nf}).then(B=>{const D=B.events.map(V=>V.event);w(V=>({...V,[T]:Oo(D,V[T]??ul)})),R(V=>({...V,[T]:{cursorSequence:B.previousSequence,hasMore:B.hasMore,loading:!1,totalMatchingEvents:B.totalMatchingEvents}}))}).catch(B=>{v(B instanceof Error?B.message:String(B)),R(D=>({...D,[T]:{cursorSequence:D[T]?.cursorSequence??z,hasMore:D[T]?.hasMore??!0,loading:!1,totalMatchingEvents:D[T]?.totalMatchingEvents??null}}))}).finally(()=>{M.current.delete(T)})},[o,a,N.length,O,l,v]),g.useEffect(()=>{if(!a||!l||qt(l)||M.current.has(l)||!o)return;const C=Oo(N,s.getSessionEvents(l)),T=Fd(C);if(!T||T>=o)return;const z=`${l}:${T}:${o}`;if(j.current===z)return;j.current=z;let B=!1;return J.runtimeEventsPage(a,{sessionId:l,afterSequence:T,limit:nf}).then(D=>{if(B)return;const V=D.events.map(le=>le.event);V.length!==0&&w(le=>UV(le,l,V))}).catch(D=>{B||(j.current=null,v(D instanceof Error?D.message:String(D)))}),()=>{B=!0}},[o,a,s,N,l,v]);const k=g.useMemo(()=>qt(l)?oh(n,[]):!l||N.length===0?i:oh(Oo(N,s.getSessionEvents(l)),t),[t,n,i,N,l]);return{chatHistoryLoadStates:I,loadMoreSelectedChatHistory:P,selectedPagedSessionEvents:N,selectedRuntimeIndexes:k}}function JG(e){let t=null;for(const n of e)n.sequence!==void 0&&(t===null||n.sequence<t)&&(t=n.sequence);return t}function YG(e,t){const n=g.useRef(null);return g.useMemo(()=>{const a=O_(e,t,n.current);return n.current={events:e,indexes:a},a},[t,e])}function Bi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function af(e){return Array.isArray(e)?e.filter(t=>!!Bi(t)):[]}function Mr(e){return typeof e=="string"&&e.trim()?e.trim():null}function aS(e){return Mr(e)??Bi(e)}function QG(e){if(!e)return[];const t=Bi(e.sandboxActionRegistry),n=Bi(e.sandboxManifest),a=new Map;for(const o of[...af(n?.actionCatalog),...af(t?.actions),...af(n?.actions)]){const i=Mr(o.id)??Mr(o.name);if(!i)continue;const s=a.get(i);a.set(i,{id:i,name:Mr(o.name)??s?.name??i,label:Mr(o.label)??s?.label??XG(i),description:Mr(o.description)??s?.description??null,visibility:Mr(o.visibility)??s?.visibility??"default",inputSchema:aS(o.inputSchema)??s?.inputSchema??null,outputSchema:aS(o.outputSchema)??s?.outputSchema??null,implementation:Bi(o.implementation)??s?.implementation??null,mcp:Bi(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 XG(e){const t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e}function TC(e){if(e.selectedCloudProject)return{id:e.selectedCloudProject.id,teamId:e.selectedCloudProject.teamId,name:e.selectedCloudProject.name,selectionKey:vt("cloud",e.selectedCloudProject.id),localProjectId:null};const t=e.selectedProject?.linkedSandboxProject??null;if(!t?.projectId||!t.teamId)return null;const n=e.cloudProjects?_a(e.selectedProject,e.cloudProjects):null;return e.cloudProjects&&!n?null:{id:n?.id??t.projectId,teamId:n?.teamId??t.teamId,name:n?.name??t.projectName??e.selectedProject?.name??"Cloud Project",selectionKey:vt("cloud",n?.id??t.projectId),localProjectId:e.selectedProject?.id??null}}const EC="openpond-agent",MC="openpond-profile-action";function Bu(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function $o(e){return typeof e=="string"&&e.trim()?e.trim():null}function Pv(e){return e.displayPrompt&&/(?:^|\s)@[A-Za-z0-9_-]+/.test(e.displayPrompt)?"mention":"slash"}function e7(e){const t=Bu(e),n=$o(t?.scope);return n!=="entire_manifest"&&n!=="start"&&n!=="action"&&n!=="service"&&n!=="schedule"?null:{scope:n,name:$o(t?.name)}}function t7(e){const t=$o(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 n7(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:EC,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 a7(e){const t=Bu(e.implementation);if(t?.type!==EC)return null;const n=$o(t.agentId),a=$o(t.teamId),o=$o(t.projectId),i=e7(t.selectedEntrypoint),s=t7(t.workflowMode);return!n||!a||!o||!i||!s?null:{agentId:n,agentName:$o(t.agentName)??e.label??e.name??e.id,teamId:a,projectId:o,projectName:$o(t.projectName),selectedEntrypoint:i,workflowMode:s}}function o7(e,t={}){const n=t.agentName?.trim()||null;return{...e,implementation:{...Bu(e.implementation)??{},type:MC,actionId:e.id,...n?{agentName:n}:{}},invokesModel:e.invokesModel??!0}}function r7(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=>o7(n,{agentName:n.agentId?t.get(n.agentId):null}))}function TQ(e){return!!(e&&Av(e))}function EQ(e){return!!(e&&Av(e)&&e.sourceActionId==="chat")}function Av(e){const t=Bu(e.implementation);if(t?.type!==MC)return null;const n=$o(t.actionId)??e.id;return n?{actionId:n,actionLabel:e.label??e.name??n}:null}function i7({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:Pv({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{},...o?{sessionId:o}:{}}}}function s7({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:Pv({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{}}}}function l7({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:Pv({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{}},workflowMode:e.workflowMode}}const Fi=new Map;function Tv(e,t){const n=e?.trim();return n?`${t?.trim()||"global"}|${n}`:null}function c7(e,t){const n=Tv(e,t);if(!n)return null;const a=Fi.get(n);return a?.updatedAt?a.projects:null}function d7(e,t,n){const a=Tv(e,n);a&&Fi.set(a,{projects:t,promise:null,updatedAt:Date.now()})}function u7(e){const t=e.teamId?.trim();if(!t)return Promise.resolve([]);const n=Tv(t,e.accountKey);if(!n)return Promise.resolve([]);const a=Fi.get(n);if(!e.force){if(a?.updatedAt)return Promise.resolve(a.projects);if(a?.promise)return a.promise}const o=e.fetchProjects(t).then(i=>(d7(t,i,e.accountKey),i)).catch(i=>{const s=Fi.get(n);throw s?.promise===o&&Fi.set(n,{projects:s.projects,promise:null,updatedAt:s.updatedAt}),i});return Fi.set(n,{projects:a?.projects??[],promise:o,updatedAt:a?.updatedAt??0}),o}function of(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 m7({cloudProjectById:e,cloudProjects:t,connection:n,defaultTeamId:a,accountScopeKey:o,localProjects:i,profile:s,selectedCloudProject:l,selectedProject:m,reportError:d}){const[h,v]=g.useState(null),[y,w]=g.useState([]),[I,R]=g.useState([]),M=g.useMemo(()=>{const T=new Set;a&&T.add(a);for(const z of t)T.add(z.teamId);for(const z of i){const B=t.find(D=>D.id===z.linkedSandboxProject?.projectId&&D.teamId===z.linkedSandboxProject?.teamId);B?.teamId&&T.add(B.teamId)}return[...T].sort()},[t,a,i]),P=M.join("\0"),N=g.useMemo(()=>TC({cloudProjects:t,selectedCloudProject:l,selectedProject:m}),[t,l,m]);g.useEffect(()=>{if(!n||M.length===0){R([]);return}let T=!1;const z=M.flatMap(B=>IC(B,o)??[]);return R(of(z)),Promise.all(M.map(B=>_v({teamId:B,accountKey:o,fetchAgents:async D=>(await J.listSandboxAgents(n,{teamId:D})).agents}))).then(B=>{T||R(of(B.flat()))}).catch(()=>{T||R(of(z))}),()=>{T=!0}},[o,n,P]),g.useEffect(()=>{if(!n||!N){v(null);return}const T=c7(N.teamId,o);T&&v(T.find(B=>B.id===N.id)??null);let z=!1;return u7({teamId:N.teamId,accountKey:o,fetchProjects:async B=>(await J.listSandboxProjects(n,{teamId:B})).projects}).then(B=>{z||v(B.find(D=>D.id===N.id)??null)}).catch(()=>{z||v(null)}),()=>{z=!0}},[o,n,N?.id,N?.teamId]),g.useEffect(()=>{if(!n||!m){w([]);return}let T=!1;return J.localProjectActions(n,m.id).then(z=>{T||w(z.actions)}).catch(z=>{T||(w([]),d?.(`Could not load Project Actions for ${m.name}: ${z instanceof Error?z.message:String(z)}`))}),()=>{T=!0}},[n,d,m?.id,m?.name,m?.updatedAt]);const O=g.useMemo(()=>{const T=new Map;for(const z of QG(h))T.set(z.id,z);for(const z of y)T.set(z.id,z);return[...T.values()]},[y,h]),j=g.useMemo(()=>r7(s),[s]),k=g.useMemo(()=>[...I.map(T=>n7(T,e.get(T.projectId)?.name??null)),...j,...O],[e,j,O,I]);return{openPondActionCatalog:g.useMemo(()=>[...j,...O],[j,O]),selectedActionCatalog:k,selectedProjectActionCatalog:O}}function p7({selectedProjectId:e}){const[t,n]=g.useState(()=>new Set),a=g.useCallback(i=>{n(s=>{if(s.has(i))return s;const l=new Set(s);return l.add(i),l})},[]),o=g.useCallback(i=>{n(s=>{const l=new Set(s);return l.has(i)?l.delete(i):l.add(i),l})},[]);return g.useEffect(()=>{e&&a(e)},[a,e]),{expandedProjectIds:t,expandProject:a,toggleProjectExpanded:o,setExpandedProjectIds:n}}function f7(){const e=new Map;function t(o,i){const s=e.get(o);if(s)return s.consumers+=1,n(o,s,!0);const l=new AbortController,m={controller:l,consumers:1,settled:!1,promise:Promise.resolve().then(()=>i(l.signal)).finally(()=>{m.settled=!0,e.get(o)===m&&e.delete(o)})};return e.set(o,m),n(o,m,!1)}function n(o,i,s){let l=!1;return{key:o,promise:i.promise,shared:s,release:()=>{l||(l=!0,i.consumers=Math.max(0,i.consumers-1),i.consumers===0&&!i.settled&&i.controller.abort())}}}function a(){for(const o of e.values())o.consumers=0,o.settled||o.controller.abort()}return{request:t,cancelAll:a,inFlightCount:()=>e.size}}function rf(e,t,n){return`workspace-status:${e.serverUrl}:${t}:${n?"ensure":"read"}`}function h7(e,t){return`workspace-diff:${e.serverUrl}:${t}`}function sf(e){return e instanceof Error&&e.name==="AbortError"}function g7({connection:e,activeWorkspaceAppId:t,view:n,shouldLoadWorkspaceDiff:a,sidebarWorkspaceAppIds:o,setError:i}){const[s,l]=g.useState(null),[m,d]=g.useState({}),[h,v]=g.useState(null),[y,w]=g.useState(!1),[I,R]=g.useState(!1),M=g.useRef(new Set),P=g.useRef(new Set),N=g.useRef(f7()),O=t?m[t]??(s?.appId===t?s:null):null,j=h?.appId===t?h:null,k=n==="chat"||n==="labs",C=g.useCallback(B=>{M.current.add(B.appId),l(B),d(D=>({...D,[B.appId]:B}))},[]),T=g.useCallback(async(B,D=!1)=>{if(!e||!B)return l(null),null;w(!0);const V=N.current.request(rf(e,B,D),le=>J.workspaceStatus(e,B,D,{signal:le}));try{const le=await V.promise;return C(le),D&&le.error?i(`Workspace sync failed: ${le.error}`):D&&i(null),le}catch(le){return sf(le)||(l(null),i(le instanceof Error?le.message:String(le))),null}finally{V.release(),w(!1)}},[e,C,i]),z=g.useCallback(async(B=t,D={})=>{if(!e||!B)return v(null),null;D.silent||R(!0);const V=N.current.request(h7(e,B),le=>J.workspaceDiff(e,B,{signal:le}));try{const le=await V.promise;return v(le),le}catch(le){return sf(le)||(v(null),i(le instanceof Error?le.message:String(le))),null}finally{V.release(),D.silent||R(!1)}},[t,e,i]);return g.useEffect(()=>{if(!e||!t||!k){l(null),v(null),w(!1);return}let B=!1;const D=N.current.request(rf(e,t,!1),V=>J.workspaceStatus(e,t,!1,{signal:V}));return w(!0),D.promise.then(V=>{B||(C(V),V.initialized||v(le=>le?.appId===V.appId?null:le))}).catch(V=>{sf(V)||B||(l(null),i(V instanceof Error?V.message:String(V)))}).finally(()=>{D.release(),B||w(!1)}),()=>{B=!0,D.release()}},[t,e,C,i,k]),g.useEffect(()=>{if(!e||!t||!k){v(null);return}if(!O?.initialized){O&&!O.initialized&&v(B=>B?.appId===t?null:B);return}a&&z(t)},[t,e,z,a,k,O?.dirty,O?.initialized]),g.useEffect(()=>{if(!e||o.length===0)return;const B=o.filter(le=>!M.current.has(le)&&!P.current.has(le));if(B.length===0)return;B.forEach(le=>P.current.add(le));let D=!1;const V=B.map(le=>({appId:le,request:N.current.request(rf(e,le,!1),te=>J.workspaceStatus(e,le,!1,{signal:te}))}));return Promise.all(V.map(({appId:le,request:te})=>te.promise.then(Ie=>({appId:le,state:Ie})).catch(()=>({appId:le,state:null})).finally(()=>{te.release(),P.current.delete(le)}))).then(le=>{if(!D)for(const te of le)te.state&&C(te.state)}),()=>{D=!0,V.forEach(({appId:le,request:te})=>{te.release(),P.current.delete(le)})}},[e,C,o]),g.useEffect(()=>()=>N.current.cancelAll(),[]),{workspaceState:s,workspaceStates:m,workspaceDiff:h,workspaceBusy:y,diffBusy:I,visibleWorkspaceState:O,visibleWorkspaceDiff:j,rememberWorkspaceState:C,refreshWorkspace:T,refreshWorkspaceDiff:z,setWorkspaceBusy:w}}const v7=1,b7=15e3,y7=15e3,jC=5*6e4,S7=5e3,k7=1e4;function OC(e,t=(a,o)=>new WebSocket(a,o),n={}){const a=new x7(e,t,n.reconnectDelayMs??w7);return a.open(),{close:()=>a.close()}}class x7{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=jC;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===v7)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-${I7(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."))},b7))},n.onmessage=a=>{this.isCurrent(n,t)&&this.handleMessage(n,a)},n.onerror=()=>{this.isCurrent(n,t)&&this.failConnection(new Error("Team chat realtime socket failed."),!1)},n.onclose=a=>{this.isCurrent(n,t)&&(this.socket=null,this.clearConnectionTimers(),this.closed||((a.code===4401||a.code===4403)&&this.reportError(new Error("Team chat realtime authorization expired.")),this.scheduleReconnect()))}}handleMessage(t,n){if(typeof n.data!="string")return;let a;try{const i=JSON.parse(n.data);if(!i||typeof i!="object"||Array.isArray(i))return;a=i}catch{this.reportError(new Error("Team chat realtime returned an invalid frame."));return}const o=typeof a.type=="string"?a.type:"";if(o==="connection_ack"){this.connectionAckTimer&&clearTimeout(this.connectionAckTimer),this.connectionAckTimer=null,this.keepAliveTimeoutMs=C7(a.connectionTimeoutMs),this.lastKeepAliveAt=Date.now(),this.startKeepAliveMonitor(),this.subscribe(t);return}if(o==="ka"){this.lastKeepAliveAt=Date.now();return}if(o==="subscribe_success"){const i=typeof a.id=="string"?a.id:"";if(!this.subscriptionChannels.has(i))return;this.acknowledgedSubscriptions.add(i),this.markReadyWhenSubscribed();return}if(o==="data"){if(this.lastKeepAliveAt=Date.now(),typeof a.event!="string")return;try{this.input.onEvent(JSON.parse(a.event))}catch{this.reportError(new Error("Team chat realtime returned an invalid event."))}return}if(o==="connection_error"||o==="subscribe_error"){const i=R7(a);if(this.reportError(i),o==="connection_error")this.failConnection(i,!1);else{const s=typeof a.id=="string"?a.id:"";this.subscriptionChannels.delete(s),this.acknowledgedSubscriptions.delete(s),this.markReadyWhenSubscribed()}}}subscribe(t){const n={Authorization:this.input.authorizationToken,host:new URL(this.input.httpUrl).host};for(const a of Array.from(new Set(this.input.channels))){const o=_7();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."))},y7)}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."))},S7)}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 w7(e){const t=Math.min(k7,500*2**Math.min(e,5));return Math.max(100,Math.floor(Math.random()*t))}function I7(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 _7(){return globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random().toString(36).slice(2)}`}function C7(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:jC}function R7(e){const n=(Array.isArray(e.errors)?e.errors:[])[0];if(n&&typeof n=="object"){const a=n,o=typeof a.errorType=="string"?a.errorType:"RealtimeError",i=typeof a.message=="string"?a.message:"Request failed";return new Error(`${o}: ${i}`)}return new Error("Team chat realtime request failed.")}function P7(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 OC({realtimeUrl:e.session.realtimeUrl,httpUrl:e.session.httpUrl,authorizationToken:e.session.token,channels:a,onEvent:o=>{const i=cw.safeParse(o);i.success&&e.onEvent(i.data)},onReady:e.onReady,onError:e.onError},t,n)}function A7(e){return e.refs.find(t=>t.refType==="message_reply")??null}function T7(e){return{id:e.id,authorType:e.authorType,authorUserId:e.authorUserId,authorAgentId:e.authorAgentId,body:e.body,deleted:!!e.deletedAt}}function MQ(e,t){const n=A7(e);if(!n)return null;const a=t.get(n.refId);return a?T7(a):M7(n)}function E7(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 jQ(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 OQ(e){return e.deleted?"Message deleted":e.body.replace(/\s+/g," ").trim()||"Attachment"}function M7(e){const t=e.preview;return{id:e.refId,authorType:j7(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 j7(e){return e==="agent"||e==="system"?e:"user"}function oS(e,t,n){return n===t.conversationId?{...e,aiThread:t}:e}function O7(e,t){return!e||e.thread.id!==t.thread.id?t:{...t,messages:vc([...e.messages,...t.messages]),hasMoreBefore:e.messages.length>t.messages.length?e.hasMoreBefore:t.hasMoreBefore}}function lf(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=ds(a,o,"message.created",!0,o.authorUserId);return{...e,thread:a,messages:vc([...e.messages,...n])}}function $7(e,t){const n=new Set(e.map(o=>o.lastMessage?.clientRequestId).filter(o=>!!o)),a=new Map;for(const o of t.values()){if(o.clientRequestId&&n.has(o.clientRequestId))continue;const i=a.get(o.threadId)??[];i.push(o),a.set(o.threadId,i)}return e.map(o=>{let i=o;for(const s of a.get(o.id)??[])i=ds(i,s,"message.created",!0,s.authorUserId);return i}).sort((o,i)=>i.lastMessageAt.localeCompare(o.lastMessageAt))}function cf(e,t,n){for(const a of e)!a.clientRequestId||a.id.startsWith("pending:")||(t.delete(a.clientRequestId),n.delete(a.clientRequestId))}function df(e,t,n){const a=e.get(t);a&&e.set(t,{...a,metadata:{...a.metadata,deliveryStatus:n}})}function rS(e,t,n){const a=e.get(t);a&&e.set(t,{...a,metadata:{...a.metadata,uploadProgress:n}})}function vc(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 $C(e){return e.type!=="message.created"&&e.type!=="message.updated"&&e.type!=="message.deleted"?null:hg.safeParse(e.payload.message).data??null}function NC(e,t,n){const a=$C(t);if(a){const o=e.selectedThreadId===a.threadId,i=e.detail?.thread.id===a.threadId?{...e.detail,thread:ds(e.detail.thread,a,t.type,o,n),messages:vc([...e.detail.messages,a])}:e.detail,l=e.threads.some(m=>m.id===a.threadId)?e.threads.map(m=>m.id===a.threadId?ds(m,a,t.type,o,n):m).sort((m,d)=>d.lastMessageAt.localeCompare(m.lastMessageAt)):e.threads;return{...e,detail:i,threads:l,error:null}}if(t.type==="read.updated"){const o=typeof t.payload.userId=="string"?t.payload.userId:null,i=Number(t.payload.sequence);if(!o||!Number.isSafeInteger(i)||i<0)return e;const s=l=>({...l,participants:l.participants.map(m=>m.userId===o?{...m,lastReadSequence:Math.max(m.lastReadSequence,i)}:m)});return{...e,threads:e.threads.map(l=>l.id===t.threadId?s(l):l),detail:e.detail?.thread.id===t.threadId?{...e.detail,thread:s(e.detail.thread)}:e.detail}}return e}function ds(e,t,n,a,o){const i=n==="message.created",s=t.sequence>=e.lastMessageSequence;return{...e,lastMessageId:s?t.id:e.lastMessageId,lastMessageSequence:Math.max(e.lastMessageSequence,t.sequence),lastMessageAt:s?t.createdAt:e.lastMessageAt,updatedAt:s?t.createdAt:e.updatedAt,lastMessage:s?t:e.lastMessage,unreadCount:a||t.authorUserId===o?0:i?e.unreadCount+1:e.unreadCount}}function N7(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:E7(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 D7(e,t){const n=e.detail?.thread.id===t.threadId?{...e.detail,thread:ds(e.detail.thread,t,"message.created",!0,t.authorUserId),messages:vc([...e.detail.messages,t])}:e.detail;return{...e,detail:n,threads:e.threads.map(a=>a.id===t.threadId?ds(a,t,"message.created",!0,t.authorUserId):a).sort((a,o)=>o.lastMessageAt.localeCompare(a.lastMessageAt)),error:null}}function iS(e,t,n){return NC(e,{teamId:t.teamId,threadId:t.threadId,type:"message.created",payload:{message:t},createdAt:t.createdAt},n)}function L7(e,t){return gh(e,t,"failed")}function gh(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 sS(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 U7(e,t){const n=e.detail?.messages.filter(i=>i.id!==t)??[],a=n.at(-1)??null,o=e.detail?{...e.detail,thread:e.detail.thread.lastMessageId===t?lS(e.detail.thread,a):e.detail.thread,messages:n}:null;return{...e,detail:o,threads:e.threads.map(i=>i.lastMessageId===t?lS(i,a):i)}}function z7(e){if(e.length>Dr.maxAttachments)return null;const t=[];for(const n of e){if(n.kind!=="image"||!H7(n.mediaType)||!n.contentsBase64||n.sizeBytes<=0||n.sizeBytes>Dr.maxAttachmentBytes)return null;t.push({...n,kind:"image",mediaType:n.mediaType,contentsBase64:n.contentsBase64})}return t}function lS(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 H7(e){return e==="image/png"||e==="image/jpeg"||e==="image/webp"||e==="image/gif"}const q7={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 B7(e){const t=e instanceof Error?e.message:String(e),n=t.trim().toLowerCase();for(const[a,o]of Object.entries(q7))if(n.includes(a))return o;return n.includes("event stream ended")?"Team chat realtime disconnected. Messages will continue to refresh automatically.":gC(t)}const DC="openpond.team-chat.notification-mode";function LC(){try{return typeof window>"u"?null:fc}catch{return null}}function cS(e=LC()){const t=e?.getItem(DC);return t==="direct_mentions"||t==="none"?t:"all"}function F7(e,t=LC()){try{t?.setItem(DC,e)}catch{}}function V7(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 K7(e){const t=e.message.authorUserId?e.members.find(s=>s.userId===e.message.authorUserId)?.name??"Team member":e.message.authorType==="agent"?"Agent":"Team",n=e.thread.title?.trim()||(e.thread.kind==="general"?"general":"conversation"),a=e.thread.kind==="dm"?t:`${t} in #${n}`,i=e.message.body.replace(/\s+/g," ").trim()||(e.message.attachments.length===1?"Sent an image":e.message.attachments.length>1?`Sent ${e.message.attachments.length} images`:"New message");return{eventId:e.eventId,threadId:e.message.threadId,title:a,body:i.length>160?`${i.slice(0,157)}…`:i}}const dS={members:[],agents:[],threads:[],selectedThreadId:null,detail:null,aiThread:null,agentConversation:null,loading:!1,busy:!1,error:null};function Qc(e,t){return e.map(n=>n.id===t&&n.unreadCount!==0?{...n,unreadCount:0}:n)}function Xc(e){return!e||e.thread.unreadCount===0?e:{...e,thread:{...e.thread,unreadCount:0}}}function W7(e){return{teamId:e.teamId,body:e.body.trim(),clientRequestId:e.clientRequestId,selectedAgentId:e.conversation.agent.id,conversationId:e.conversation.conversationId}}function G7(e){return{teamId:e.teamId,body:e.body.trim(),clientRequestId:e.clientRequestId,selectedActionKey:e.selectedActionKey,approvalId:e.approvalId??null}}async function uS(e,t=J.markTeamChatRead){return e.lastMessageSequence<=0?!1:t(e.connection,e.threadId,e.teamId,e.lastMessageSequence).then(()=>!0,()=>!1)}function Z7(e){const[t,n]=g.useState(dS),a=g.useRef(t);a.current=t;const[o,i]=g.useState(cS);pc(()=>i(cS()));const[s,l]=g.useState(null),m=g.useRef(null),d=g.useRef(null),h=g.useRef(0),v=g.useRef(new Map),y=g.useRef(new Map),w=g.useRef(0),I=g.useRef(null),R=g.useRef(0),M=g.useRef(new Set),P=g.useRef(0),N=g.useRef(!1),O=g.useRef(new Map),j=g.useRef(new Map),[k,C]=g.useState(null),[T,z]=g.useState(null),B=g.useCallback(L=>{i(L),F7(L)},[]),D=g.useCallback(L=>{l($=>$?.eventId===L?null:$)},[]),V=g.useCallback(async()=>{if(!e.connection||!e.teamId)return[];const L=await J.teamChatThreads(e.connection,e.teamId),$=$7(L.threads,O.current);return n(H=>({...H,threads:$})),$},[e.connection,e.teamId]),le=g.useCallback(async()=>{if(!e.connection||!e.teamId)return{members:[],agents:[]};const[L,$]=await Promise.all([J.teamChatMembers(e.connection,e.teamId),J.teamChatAgents(e.connection,e.teamId)]);return n(H=>({...H,members:L.members,agents:$.agents})),{members:L.members,agents:$.agents}},[e.connection,e.teamId]),te=g.useCallback(async L=>{const $=L??m.current;if(!e.connection||!e.teamId||!$)return null;const H=(y.current.get($)??0)+1;y.current.set($,H);const Q=await J.teamChatThread(e.connection,e.teamId,$);cf(Q.messages,O.current,j.current);const me=lf(Q,O.current);return y.current.get($)!==H||(n(_e=>_e.selectedThreadId===$?{..._e,threads:Qc(_e.threads,$),detail:Xc(O7(_e.detail,me))}:_e),m.current===$&&me.thread.lastMessageSequence>0&&await J.markTeamChatRead(e.connection,$,e.teamId,me.thread.lastMessageSequence).catch(()=>{})),me},[e.connection,e.teamId]),Ie=g.useCallback(async L=>{const $=L??d.current;if(!e.connection||!e.teamId||!$)return null;const H=(v.current.get($)??0)+1;v.current.set($,H);const Q=await J.teamChatAiThread(e.connection,e.teamId,$);return v.current.get($)===H&&d.current===$&&n(me=>oS(me,Q,d.current)),Q},[e.connection,e.teamId]),ke=g.useCallback(async L=>{const $=L??I.current;if(!e.connection||!e.teamId||!$)return null;const H=await J.teamChatAgentConversation(e.connection,e.teamId,$);return n(Q=>Q.agentConversation?.run.id===$?{...Q,agentConversation:H}:Q),H},[e.connection,e.teamId]);g.useEffect(()=>{m.current=t.selectedThreadId},[t.selectedThreadId]),g.useEffect(()=>{I.current=t.agentConversation?.run.id??null},[t.agentConversation?.run.id]),g.useEffect(()=>{const L=t.agentConversation?.run.status;if(!L||!["pending","queued","running"].includes(L))return;const $=window.setInterval(()=>{ke().catch(H=>{n(Q=>({...Q,error:hn(H)}))})},2500);return()=>window.clearInterval($)},[ke,t.agentConversation?.run.status]),g.useEffect(()=>{if(!e.connection||!e.teamId||!e.currentUserId){n(dS),C(null),z(null),j.current.clear(),O.current.clear(),y.current.clear(),v.current.clear(),w.current+=1,l(null),M.current.clear(),P.current=0,R.current=0;return}let L=!1;return d.current=null,h.current+=1,w.current+=1,C(null),z(null),j.current.clear(),O.current.clear(),M.current.clear(),P.current=0,n($=>({...$,aiThread:null,agentConversation:null,loading:!0,error:null})),(async()=>{try{const $=await J.teamChatEvents(e.connection,e.teamId);if(L)return;R.current=$.cursor;const H=J.teamChatMembers(e.connection,e.teamId),Q=J.teamChatAgents(e.connection,e.teamId),me=await J.teamChatGeneral(e.connection,e.teamId),[_e,$e,Xe]=await Promise.all([H,Q,J.teamChatThreads(e.connection,e.teamId)]);if(L)return;const et=m.current&&Xe.threads.some(Me=>Me.id===m.current)?m.current:me.thread.id,rt=et===me.thread.id?me:await J.teamChatThread(e.connection,e.teamId,et);if(L)return;const it=Xc(rt);n(Me=>({...Me,members:_e.members,agents:$e.agents,threads:Qc(Xe.threads,et),selectedThreadId:et,detail:it,loading:!1,error:null})),uS({connection:e.connection,teamId:e.teamId,threadId:et,lastMessageSequence:it?.thread.lastMessageSequence??0}),z(e.teamId)}catch($){if(L)return;n(H=>({...H,loading:!1,error:hn($)}))}})(),()=>{L=!0}},[e.connection,e.currentUserId,e.refreshToken,e.teamId]);const Z=g.useCallback(L=>{if(M.current.has(L.id))return;if(M.current.add(L.id),M.current.size>2e3){const H=M.current.values().next().value;typeof H=="number"&&M.current.delete(H)}const $=$C(L);if($&&L.type==="message.created"){const H=a.current,Q=H.threads.find(_e=>_e.id===$.threadId)??(H.detail?.thread.id===$.threadId?H.detail.thread:null),me=_e=>{L.id<=P.current||V7({mode:o,currentUserId:e.currentUserId,message:$,thread:_e})&&(P.current=L.id,l(K7({eventId:L.id,message:$,thread:_e,members:H.members})))};Q?me(Q):V().then(_e=>{const $e=_e.find(Xe=>Xe.id===$.threadId);$e&&me($e)}).catch(()=>{})}$?.clientRequestId&&!$.id.startsWith("pending:")&&(O.current.delete($.clientRequestId),j.current.delete($.clientRequestId)),n(H=>NC(H,L,e.currentUserId)),L.type==="thread.created"&&V().catch(H=>{n(Q=>({...Q,error:hn(H)}))}),(L.type==="ai_thread.created"||L.type==="ai_turn.updated")&&(te(L.threadId).catch(H=>{n(Q=>({...Q,error:hn(H)}))}),L.conversationId===d.current&&Ie(L.conversationId).catch(H=>{n(Q=>({...Q,error:hn(H)}))})),$&&L.type==="message.created"&&m.current===$.threadId&&$.authorUserId!==e.currentUserId&&e.connection&&e.teamId&&J.markTeamChatRead(e.connection,$.threadId,e.teamId,$.sequence).catch(()=>{})},[e.connection,e.currentUserId,e.teamId,o,Ie,te,V]),Ae=g.useCallback(async()=>{if(!(!e.connection||!e.teamId||N.current)){N.current=!0;try{let L=!0;for(;L;){const $=await J.teamChatEvents(e.connection,e.teamId,{after:R.current,limit:250});for(const H of $.events)Z(H);R.current=$.cursor,L=$.hasMore}}finally{N.current=!1}}},[Z,e.connection,e.teamId]);g.useEffect(()=>{if(!e.connection||!e.teamId||T!==e.teamId)return;let L=!1,$=null;const H=async()=>{try{const Q=await J.teamChatRealtimeSession(e.connection,e.teamId);if(L||(await Ae(),L))return;C(Q);const me=Math.max(3e4,new Date(Q.expiresAt).getTime()-Date.now()-3e4);$=window.setTimeout(()=>{H()},me)}catch{L||(Ae().catch(()=>{}),$=window.setTimeout(()=>{H()},1e4))}};return H(),()=>{L=!0,$!==null&&window.clearTimeout($),C(null)}},[Ae,e.connection,e.teamId,T]);const he=t.threads.map(L=>L.id).sort().join(",");g.useEffect(()=>{if(!k)return;const L=P7({session:k,threadIds:he?he.split(","):[],onEvent:Z,onReady:()=>{Ae().catch($=>{n(H=>({...H,error:hn($)}))})},onError:()=>{Ae().catch(()=>{})}});return()=>{L.close()}},[Z,Ae,k,he]),g.useEffect(()=>{if(!e.connection||!e.teamId||T!==e.teamId)return;const L=window.setInterval(()=>{Ae().catch(()=>{})},15e3);return()=>window.clearInterval(L)},[Ae,e.connection,e.teamId,T]);const ue=g.useCallback(async L=>{if(!e.connection||!e.teamId)return;const $=w.current+1;w.current=$;const H=m.current!==L;m.current=L,H&&(h.current+=1,d.current=null),n(Q=>({...Q,threads:Qc(Q.threads,L),selectedThreadId:L,detail:Q.detail?.thread.id===L?Xc(Q.detail):null,aiThread:H?null:Q.aiThread,agentConversation:H?null:Q.agentConversation,loading:!0,error:null}));try{const Q=await J.teamChatThread(e.connection,e.teamId,L);if(w.current!==$||m.current!==L)return;cf(Q.messages,O.current,j.current);const me=lf(Q,O.current);n(_e=>({..._e,threads:Qc(_e.threads,L),detail:Xc(me),loading:!1})),await J.markTeamChatRead(e.connection,L,e.teamId,me.thread.lastMessageSequence).catch(()=>{})}catch(Q){if(w.current!==$)return;n(me=>({...me,loading:!1,error:hn(Q)}))}},[e.connection,e.teamId]),be=g.useCallback(async L=>{if(!e.connection||!e.teamId)return null;const $=w.current+1;w.current=$,n(H=>({...H,busy:!0,error:null}));try{const H=await J.teamChatDm(e.connection,e.teamId,L);if(w.current!==$)return null;cf(H.messages,O.current,j.current);const Q=lf(H,O.current),me=m.current!==Q.thread.id;return m.current=Q.thread.id,me&&(h.current+=1,d.current=null),n(_e=>({..._e,selectedThreadId:Q.thread.id,detail:Q,aiThread:me?null:_e.aiThread,agentConversation:me?null:_e.agentConversation,busy:!1})),await uS({connection:e.connection,teamId:e.teamId,threadId:Q.thread.id,lastMessageSequence:Q.thread.lastMessageSequence}),await V(),Q}catch(H){return w.current!==$||n(Q=>({...Q,busy:!1,error:hn(H)})),null}},[e.connection,e.teamId,V]),ne=g.useCallback(async()=>{const L=t.detail,$=L?.messages[0]?.sequence;if(!e.connection||!e.teamId||!L||!L.hasMoreBefore||$==null)return!1;n(H=>({...H,loading:!0,error:null}));try{const H=await J.teamChatThread(e.connection,e.teamId,L.thread.id,{beforeSequence:$,limit:50});return n(Q=>{if(Q.detail?.thread.id!==L.thread.id)return Q;const me=[...H.messages,...Q.detail.messages];return{...Q,loading:!1,detail:{...Q.detail,messages:vc(me),hasMoreBefore:H.hasMoreBefore}}}),!0}catch(H){return n(Q=>({...Q,loading:!1,error:hn(H)})),!1}},[e.connection,e.teamId,t.detail]),ge=g.useCallback(async L=>{const $=m.current,H=z7(L.attachments??[]);if(!H)return n(_e=>({..._e,error:"Team chat supports up to 10 PNG, JPEG, WebP, or GIF images per message."})),!1;if(!e.connection||!e.teamId||!$||!L.body.trim()&&H.length===0)return!1;if(L.replyToMessage&&(L.replyToMessage.threadId!==$||L.replyToMessage.teamId!==e.teamId||L.replyToMessage.id.startsWith("pending:")||L.replyToMessage.deletedAt))return n(_e=>({..._e,error:"That message is no longer available to reply to."})),!1;if(L.useModel){if(H.length>0)return n($e=>({...$e,error:"Images can be sent to the team thread with Use model turned off."})),!1;const _e=h.current;n($e=>({...$e,busy:!0,error:null}));try{const $e=await J.createTeamChatAiThread(e.connection,$,{teamId:e.teamId,body:L.body.trim(),clientRequestId:crypto.randomUUID(),providerId:L.providerId,modelId:L.modelId}),Xe=h.current===_e&&m.current===$;return Xe&&(h.current+=1,d.current=$e.conversationId),n(et=>({...et,aiThread:Xe?$e:et.aiThread})),$e.activeTurn&&await J.executeTeamChatAiTurn(e.connection,$e.activeTurn.id,e.teamId),await Promise.all([te($),V()]),n(et=>({...et,busy:!1})),!0}catch($e){return n(Xe=>({...Xe,busy:!1,error:hn($e)})),!1}}const Q=crypto.randomUUID();if(L.selectedActionKey){if(H.length>0)return n(_e=>({..._e,error:"Agent invocations do not support image attachments yet."})),!1;n(_e=>({..._e,busy:!0,error:null}));try{return await J.createTeamChatAgentRun(e.connection,$,G7({teamId:e.teamId,body:L.body,clientRequestId:Q,selectedActionKey:L.selectedActionKey,approvalId:L.approvalId})),await Promise.all([te($),V()]),n(_e=>({..._e,busy:!1})),!0}catch(_e){return n($e=>({...$e,busy:!1,error:hn(_e)})),!1}}j.current.set(Q,{inputs:H,uploaded:null});const me=N7({clientRequestId:Q,threadId:$,teamId:e.teamId,userId:e.currentUserId,body:L.body.trim(),mentionUserIds:L.mentionUserIds??[],attachments:H,replyToMessage:L.replyToMessage,sequence:(t.detail?.thread.lastMessageSequence??0)+1});O.current.set(Q,me),n(_e=>D7(_e,me));try{const _e=[];for(const[et,rt]of H.entries())_e.push(await J.uploadTeamChatAttachment(e.connection,$,{teamId:e.teamId,attachment:rt})),rS(O.current,Q,`${et+1} of ${H.length}`),n(it=>sS(it,Q,`${et+1} of ${H.length}`));const $e=j.current.get(Q);$e&&($e.uploaded=_e);const Xe=await J.sendTeamChatMessage(e.connection,$,{teamId:e.teamId,body:L.body.trim(),clientRequestId:Q,mentionUserIds:L.mentionUserIds,attachmentIds:_e.map(et=>et.id),replyToMessageId:L.replyToMessage?.id??null});return j.current.delete(Q),O.current.delete(Q),n(et=>iS(et,Xe,e.currentUserId)),!0}catch(_e){return df(O.current,Q,"failed"),n($e=>({...L7($e,Q),error:hn(_e)})),!1}},[e.connection,e.currentUserId,e.teamId,te,V,t.detail?.thread.lastMessageSequence]),xe=g.useCallback(async L=>{if(!(!e.connection||!e.teamId)){h.current+=1,d.current=L,n($=>({...$,aiThread:$.aiThread?.conversationId===L?$.aiThread:null,busy:!0,error:null}));try{const $=await J.teamChatAiThread(e.connection,e.teamId,L);if(d.current!==L)return;n(H=>({...H,aiThread:$,busy:!1}))}catch($){if(d.current!==L)return;n(H=>({...H,busy:!1,error:hn($)}))}}},[e.connection,e.teamId]),qe=g.useCallback(async L=>{if(!(!e.connection||!e.teamId)){I.current=L,n($=>({...$,busy:!0,error:null}));try{const $=await J.teamChatAgentConversation(e.connection,e.teamId,L);n(H=>({...H,agentConversation:$,busy:!1}))}catch($){n(H=>({...H,busy:!1,error:hn($)}))}}},[e.connection,e.teamId]),Se=g.useCallback(()=>{I.current=null,n(L=>({...L,agentConversation:null}))},[]),se=g.useCallback(async L=>{const $=m.current,H=t.agentConversation;if(!e.connection||!e.teamId||!$||!H||!L.body.trim())return!1;n(Q=>({...Q,busy:!0,error:null}));try{const Q=await J.createTeamChatAgentRun(e.connection,$,W7({teamId:e.teamId,body:L.body,clientRequestId:L.clientRequestId,conversation:H}));I.current=Q.run.id;const[me]=await Promise.all([J.teamChatAgentConversation(e.connection,e.teamId,Q.run.id),te($),V()]);return n(_e=>({..._e,agentConversation:me,busy:!1})),!0}catch(Q){return n(me=>({...me,busy:!1,error:hn(Q)})),!1}},[e.connection,e.teamId,te,V,t.agentConversation]),we=g.useCallback(()=>{h.current+=1,d.current=null,n(L=>({...L,aiThread:null}))},[]),Oe=g.useCallback(async L=>{const $=d.current;if(!e.connection||!e.teamId||!$||!L.body.trim())return!1;n(H=>({...H,busy:!0,error:null}));try{const H=await J.sendTeamChatAiTurn(e.connection,$,{teamId:e.teamId,body:L.body.trim(),clientRequestId:crypto.randomUUID(),providerId:L.providerId,modelId:L.modelId});return n(Q=>({...oS(Q,H,d.current),busy:!1})),H.activeTurn&&await J.executeTeamChatAiTurn(e.connection,H.activeTurn.id,e.teamId),!0}catch(H){return n(Q=>({...Q,busy:!1,error:hn(H)})),!1}},[e.connection,e.teamId]),Qe=g.useCallback(async()=>{const L=t.aiThread?.activeTurn?.id;return!e.connection||!e.teamId||!L?!1:(await J.cancelTeamChatAiTurnExecution(e.connection,L,e.teamId)).cancelled},[e.connection,e.teamId,t.aiThread?.activeTurn?.id]),Ge=g.useCallback(async(L,$)=>{if(!e.connection||!e.teamId)return!1;try{return await J.editTeamChatMessage(e.connection,L.threadId,L.id,{teamId:e.teamId,body:$}),await te(L.threadId),!0}catch(H){return n(Q=>({...Q,error:hn(H)})),!1}},[e.connection,e.teamId,te]),st=g.useCallback(async L=>{if(!e.connection||!e.teamId)return!1;try{return await J.deleteTeamChatMessage(e.connection,L.threadId,L.id,e.teamId),await te(L.threadId),!0}catch($){return n(H=>({...H,error:hn($)})),!1}},[e.connection,e.teamId,te]),Le=g.useCallback(async L=>{if(!e.connection||!e.teamId||!L.clientRequestId||!L.id.startsWith("pending:"))return!1;const $=Array.isArray(L.metadata.mentionUserIds)?L.metadata.mentionUserIds.filter(me=>typeof me=="string"):[],H=j.current.get(L.clientRequestId),Q=L.refs.find(me=>me.refType==="message_reply");df(O.current,L.clientRequestId,"sending"),n(me=>gh(me,L.clientRequestId,"sending"));try{let me=H?.uploaded??[];if(H&&!H.uploaded){me=[];for(const[$e,Xe]of H.inputs.entries())me.push(await J.uploadTeamChatAttachment(e.connection,L.threadId,{teamId:e.teamId,attachment:Xe})),rS(O.current,L.clientRequestId,`${$e+1} of ${H.inputs.length}`),n(et=>sS(et,L.clientRequestId,`${$e+1} of ${H.inputs.length}`));H.uploaded=me}const _e=await J.sendTeamChatMessage(e.connection,L.threadId,{teamId:e.teamId,body:L.body,clientRequestId:L.clientRequestId,mentionUserIds:$,attachmentIds:me.map($e=>$e.id),replyToMessageId:Q?.refId??null});return j.current.delete(L.clientRequestId),O.current.delete(L.clientRequestId),n($e=>iS($e,_e,e.currentUserId)),!0}catch(me){return df(O.current,L.clientRequestId,"failed"),n(_e=>({...gh(_e,L.clientRequestId,"failed"),error:hn(me)})),!1}},[e.connection,e.currentUserId,e.teamId]),Fe=g.useCallback(L=>{L.id.startsWith("pending:")&&(L.clientRequestId&&j.current.delete(L.clientRequestId),L.clientRequestId&&O.current.delete(L.clientRequestId),n($=>U7($,L.id)))},[]),De=g.useCallback(async(L,$)=>{if(!e.connection||!e.teamId)return!1;try{const H=await J.setTeamChatThreadMuted(e.connection,L,e.teamId,$),Q=me=>me.id===H.threadId?{...me,mutedAt:H.mutedAt}:me;return n(me=>({...me,threads:me.threads.map(Q),detail:me.detail?.thread.id===H.threadId?{...me.detail,thread:Q(me.detail.thread)}:me.detail,error:null})),!0}catch(H){return n(Q=>({...Q,error:hn(H)})),!1}},[e.connection,e.teamId]);return{...t,currentUserId:e.currentUserId,notificationMode:o,incomingNotification:s,setNotificationMode:B,dismissIncomingNotification:D,setThreadMuted:De,selectThread:ue,openDm:be,loadMoreMessages:ne,sendMessage:ge,openAiThread:xe,openAgentConversation:qe,closeAgentConversation:Se,sendAgentTurn:se,closeAiThread:we,sendAiTurn:Oe,stopAiTurn:Qe,editMessage:Ge,deleteMessage:st,retryMessage:Le,dismissFailedMessage:Fe,refreshDirectory:le,refresh:async()=>{await Promise.all([le(),V(),te(),Ie(),ke()])}}}function hn(e){return B7(e)}const UC="local-profile-agent";function $Q(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?[]:[jr(l.agentName),jr(s.name),jr(s.label)].filter(Boolean)})),a=t.hosted?.teamId===e.teamId?t.hosted.hostedSourceMaterialization:null,o=new Set(e.hostedActions.map(s=>s.implementation?.agentId).filter(s=>typeof s=="string")),i=t.agents.flatMap(s=>s.enabled?a?.agentId===s.id&&!!(a.runtimeAgentId&&o.has(a.runtimeAgentId))||n.has(jr(s.name))||n.has(jr(s.id))?[]:[Q7(t,s)]:[]);return[...e.hostedActions,...i]}function NQ(e){return e?.implementation?.type===UC}function DQ(e){const t=e.implementation?.profileAgentId;return typeof t=="string"&&t.trim()?t.trim():null}function J7(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 Y7(e,t){const n=t.runtimeAgentId?.trim()??"",a=t.profileName?.trim()??"",o=jr(t.agentName);return e.find(i=>{const s=i.implementation;return s?.type!=="openpond-agent"?!1:n&&typeof s.agentId=="string"&&s.agentId===n?!0:!!(a&&s.profileName===a&&o&&[s.agentName,i.name,i.label].some(l=>jr(l)===o))})??null}function Q7(e,t){return{id:`local-profile:${e.activeProfile??"default"}:${t.id}:chat`,name:t.name,label:t.name,description:X7(e),approvalPolicy:{required:!1,risk:"write"},setupRequirements:e.setupGate.blockingRequirements,invokesModel:!0,implementation:{type:UC,profileAgentId:t.id,profileName:e.activeProfile??"default"}}}function X7(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 jr(e){return typeof e=="string"?e.trim().toLowerCase().replace(/[^a-z0-9]+/g,""):""}const mS=5;function eZ(e){return g.useCallback(async t=>{if(!e.connection||!e.teamId)throw new Error("Connect OpenPond to a Team before publishing an agent.");const n=await J.profileCheck(e.connection,{kind:"all"}),a=J7(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 J.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 J.bootstrap(e.connection));let m=null;for(let d=0;d<mS;d+=1){const h=await e.refreshDirectory();if(m=Y7(h.agents,{runtimeAgentId:l,profileName:n.activeProfile,agentName:o.name}),m)break;d<mS-1&&await tZ(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 tZ(e){return new Promise(t=>{setTimeout(t,e)})}function nZ(e){g.useEffect(()=>{if(!e.notification)return;const{eventId:t,threadId:n,title:a,body:o}=e.notification;e.showToast(`${a}: ${o}`,"info",{actionLabel:"Open",onAction:()=>{e.setView("team"),e.selectThread(n)},dismissible:!0,durationMs:6500,placement:"top-right"}),e.dismiss(t)},[e.dismiss,e.notification,e.selectThread,e.setView,e.showToast])}function aZ(e){const{connection:t,refreshToken:n=null}=e,[a,o]=g.useState([]),[i,s]=g.useState(null),[l,m]=g.useState(null),[d,h]=g.useState(null),[v,y]=g.useState(!1),[w,I]=g.useState(!1),[R,M]=g.useState(!1),[P,N]=g.useState(null),[O,j]=g.useState(null),[k,C]=g.useState(null),[T,z]=g.useState(0),B=g.useRef(0),D=g.useMemo(()=>a.find(ne=>ne.id===l)??null,[a,l]),V=g.useCallback(async()=>{if(!t)return!1;y(!0),N(null);try{const ne=await J.communities(t);return o(ne.items),s(ne.nextCursor),m(ge=>ge&&ne.items.some(xe=>xe.id===ge)?ge:null),!0}catch(ne){return N(Sd(ne)),!1}finally{y(!1)}},[t]),le=g.useCallback(async()=>{if(!t||!i||v)return!1;y(!0),N(null);try{const ne=await J.communities(t,i);return o(ge=>oZ(ge,ne.items)),s(ne.nextCursor),!0}catch(ne){return N(Sd(ne)),!1}finally{y(!1)}},[t,v,i]),te=g.useCallback(async ne=>{if(!t)return null;const ge=++B.current;I(!0),j(null);try{const xe=await J.communityPreview(t,ne.slug);return B.current===ge&&h(xe),xe}catch(xe){return B.current===ge&&j(Sd(xe)),null}finally{B.current===ge&&I(!1)}},[t]),Ie=g.useCallback(ne=>{const ge=a.find(xe=>xe.id===ne);ge&&(m(ge.id),h(xe=>xe?.id===ge.id?xe:null),C(null),te(ge))},[a,te]),ke=g.useCallback(()=>{B.current+=1,m(null),h(null),j(null),C(null)},[]);g.useEffect(()=>{if(!t){o([]),h(null),m(null);return}V()},[t,V,n]),g.useEffect(()=>{!D||d?.id===D.id||w||te(D)},[te,d?.id,w,D]);const Z=g.useCallback(async()=>{const ne=D;await V(),ne&&await te(ne)},[te,V,D]),Ae=g.useCallback(async()=>{if(!t||!d?.currentRules||R)return!1;M(!0),C(null);try{return await J.joinCommunity(t,d.id,d.currentRules.id),z(ne=>ne+1),await Z(),!0}catch(ne){const ge=ed(ne);return C(ge),ge.kind==="rules_stale"&&await Z(),!1}finally{M(!1)}},[t,R,d,Z]),he=g.useCallback(async()=>{if(!t||!d?.currentRules||R)return!1;M(!0),C(null);try{return await J.acceptCommunityRules(t,d.id,d.currentRules.id),z(ne=>ne+1),await Z(),!0}catch(ne){const ge=ed(ne);return C(ge),ge.kind==="rules_stale"&&await Z(),!1}finally{M(!1)}},[t,R,d,Z]),ue=g.useCallback(async()=>{if(!t||!d||R)return!1;M(!0),C(null);try{return await J.leaveCommunity(t,d.id),z(ne=>ne+1),await Z(),!0}catch(ne){return C(ed(ne)),!1}finally{M(!1)}},[t,R,d,Z]),be=g.useCallback(async ne=>{if(!t||!d||R)return!1;M(!0),C(null);try{return await J.updateCommunityNotifications(t,d.id,ne),o(ge=>ge.map(xe=>xe.id===d.id&&xe.membership?{...xe,membership:{...xe.membership,notificationMode:ne}}:xe)),h(ge=>ge?.id===d.id&&ge.membership?{...ge,membership:{...ge.membership,notificationMode:ne}}:ge),!0}catch(ge){return C(ed(ge)),!1}finally{M(!1)}},[t,R,d]);return{items:a,nextCursor:i,selectedCommunityId:l,selectedSummary:D,preview:d,discoveryLoading:v,previewLoading:w,membershipBusy:R,discoveryError:P,previewError:O,membershipError:k,membershipVersion:T,refresh:V,loadMore:le,showDiscovery:ke,selectCommunity:Ie,join:Ae,acceptRules:he,leave:ue,updateNotifications:be,clearMembershipError:()=>C(null)}}function oZ(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 Sd(e){return e instanceof Error?e.message:String(e)}function ed(e){const t=Sd(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 rZ(e,t,n){return OC({realtimeUrl:e.session.realtimeUrl,httpUrl:e.session.httpUrl,authorizationToken:e.session.token,channels:[e.session.channel],onEvent:a=>{const o=bw.safeParse(a);o.success&&e.onEvent(o.data)},onReady:e.onReady,onError:e.onError},t,n)}function iZ(e){const{connection:t,preview:n,currentUserId:a,membershipVersion:o}=e,i=n?.id??null,s=n?.membership?.status==="active",l=!n?.capabilities.requiresRulesAcceptance,[m,d]=g.useState([]),[h,v]=g.useState(null),[y,w]=g.useState({}),[I,R]=g.useState([]),[M,P]=g.useState(!1),[N,O]=g.useState(!1),[j,k]=g.useState(!1),[C,T]=g.useState(!1),[z,B]=g.useState(null),[D,V]=g.useState(null),[le,te]=g.useState(null),[Ie,ke]=g.useState(null),[Z,Ae]=g.useState(!1),[he,ue]=g.useState(null),[be,ne]=g.useState(null),ge=g.useRef(null),xe=g.useRef([]),qe=g.useRef("mentions"),Se=g.useRef(0),se=g.useRef({}),we=g.useRef(new Set),Oe=g.useMemo(()=>m.find(Me=>Me.id===h)??null,[m,h]),Qe=h?y[h]??null:null;g.useEffect(()=>{ge.current=h},[h]),g.useEffect(()=>{xe.current=m},[m]),g.useEffect(()=>{qe.current=n?.membership?.notificationMode??"mentions"},[n?.membership?.notificationMode]);const Ge=g.useCallback(async()=>{if(!t||!i)return!1;P(!0),B(null);try{const Me=await J.communityChannels(t,i);return d(Me.channels),v(Be=>Be&&Me.channels.some(p=>p.id===Be)?Be:Me.channels.find(p=>p.isDefault)?.id??Me.channels[0]?.id??null),Ae(!1),!0}catch(Me){const Be=sa(Me);return B(Be),ml(Be)&&Ae(!0),!1}finally{P(!1)}},[i,t]),st=g.useCallback(async Me=>{if(!t||!i)return!1;const Be=++Se.current;O(!0),V(null);try{const p=await J.communityMessages(t,i,Me,{limit:50});return Be!==Se.current?!1:(w(U=>({...U,[Me]:{items:p.messages,hasMoreBefore:p.hasMoreBefore,preview:p.preview}})),Ae(!1),!0)}catch(p){if(Be!==Se.current)return!1;const U=sa(p);return V(U),ml(U)&&Ae(!0),!1}finally{Be===Se.current&&O(!1)}},[i,t]);g.useEffect(()=>{d(n?.channels??[]),w({}),v(n?.channels.find(Me=>Me.isDefault)?.id??n?.channels[0]?.id??null),B(null),V(null),te(null),Ae(!1),we.current.clear(),i&&Ge()},[i,Ge,o]),g.useEffect(()=>{h&&st(h)},[st,h]);const Le=g.useCallback(async(Me,Be)=>{if(!t||!i||!s||!l||Be<=0)return!1;if((se.current[Me]??0)>=Be)return!0;se.current[Me]=Be;try{const p=await J.markCommunityRead(t,i,Me,Be);return d(U=>U.map(K=>K.id===Me?{...K,unreadCount:0,readState:K.readState?{...K.readState,lastReadSequence:p.sequence,lastReadAt:new Date().toISOString()}:{lastReadSequence:p.sequence,lastReadAt:new Date().toISOString(),mutedAt:null,pinnedAt:null}}:K)),!0}catch(p){const U=sa(p);return ml(U)&&Ae(!0),!1}},[i,t,s,l]);g.useEffect(()=>{const Me=Qe?.items.at(-1)?.sequence??0;h&&Me>0&&Le(h,Me)},[Le,h,Qe?.items]);const Fe=g.useCallback(Me=>{if(Me.communityId!==i||we.current.has(Me.id))return;we.current.add(Me.id);const Be=vw.safeParse(Me.payload.message);if(Be.success&&Me.type!=="read.updated"){const p=Be.data;if(w(U=>{const K=U[Me.channelId];if(!K)return U;const re=K.items.some(F=>F.id===p.id)?K.items.map(F=>F.id===p.id?p:F):[...K.items,p].sort((F,_)=>F.sequence-_.sequence);return{...U,[Me.channelId]:{...K,items:re}}}),d(U=>U.map(K=>K.id===Me.channelId?{...K,lastMessageSequence:Math.max(K.lastMessageSequence,p.sequence),unreadCount:ge.current===Me.channelId||p.authorUserId===a?0:Math.max(K.unreadCount+(Me.type==="message.created"?1:0),0)}:K)),Me.type==="message.created"&&p.authorUserId!==a){const U=xe.current.find(re=>re.id===Me.channelId),K=sZ(p).includes(a??""),de=qe.current;!U?.readState?.mutedAt&&(de==="all"||de==="mentions"&&K)&&ne({communityId:Me.communityId,channelId:Me.channelId,message:p})}ge.current===Me.channelId&&Le(Me.channelId,p.sequence);return}Me.type==="read.updated"&&Me.payload.userId===a&&Ge()},[i,a,Ge,Le]);g.useEffect(()=>{if(!t||!i||!s||!l)return;let Me=!1,Be=null;return te(null),Promise.all([J.communityRealtimeSession(t,i),J.communityEvents(t,i)]).then(async([p,U])=>{if(Me)return;const K=async()=>{let re=U.cursor;for(;;){const F=await J.communityEvents(t,i,{after:re,limit:200});if(Me)return;for(const _ of F.events)Fe(_);if(re=F.cursor,!F.hasMore)return}},de=rZ({session:p,onEvent:Fe,onReady:()=>{te(null),K().catch(re=>te(sa(re)))},onError:re=>te(sa(re))});Be=()=>de.close(),await K()}).catch(p=>{if(!Me){const U=sa(p);te(U),ml(U)&&Ae(!0)}}),()=>{Me=!0,Be?.()}},[Fe,i,t,s,o,l]);const De=g.useCallback(async()=>{if(!t||!i||!h||j)return!1;const Me=y[h],Be=Me?.items[0]?.sequence;if(!Me?.hasMoreBefore||Be==null)return!1;k(!0),V(null);try{const p=await J.communityMessages(t,i,h,{beforeSequence:Be,limit:50});return w(U=>{const K=U[h]??Me,de=new Set(K.items.map(re=>re.id));return{...U,[h]:{...K,items:[...p.messages.filter(re=>!de.has(re.id)),...K.items],hasMoreBefore:p.hasMoreBefore}}}),!0}catch(p){return V(sa(p)),!1}finally{k(!1)}},[i,t,y,j,h]),L=g.useCallback(async Me=>{if(!t||!i||!h||C)return!1;T(!0),ke(null),ue(null);try{const Be=await Promise.all(Me.attachments.map(U=>J.uploadCommunityAttachment(t,i,h,U))),p=await J.sendCommunityMessage(t,i,h,{body:Me.body,clientRequestId:Me.clientRequestId,mentionUserIds:Me.mentionUserIds,attachmentIds:Be.map(U=>U.id),replyToMessageId:Me.replyToMessageId});return w(U=>{const K=U[h]??{items:[],hasMoreBefore:!1,preview:!1};return K.items.some(de=>de.id===p.id)?U:{...U,[h]:{...K,items:[...K.items,p]}}}),await Le(h,p.sequence),!0}catch(Be){const p=sa(Be);return ke(p),ue({...Me,message:p}),ml(p)&&Ae(!0),!1}finally{T(!1)}},[i,t,Le,h,C]),$=g.useCallback(Me=>L({body:Me.body,clientRequestId:crypto.randomUUID(),mentionUserIds:Me.mentionUserIds??[],attachments:Me.attachments??[],replyToMessageId:Me.replyToMessageId??null}),[L]),H=g.useCallback(async(Me,Be)=>{if(!t||!i||!h)return!1;ke(null);try{const p=await J.editCommunityMessage(t,i,h,Me,Be);return pS(w,h,p),!0}catch(p){return ke(sa(p)),!1}},[i,t,h]),Q=g.useCallback(async Me=>{if(!t||!i||!h)return!1;ke(null);try{const Be=await J.deleteCommunityMessage(t,i,h,Me);return pS(w,h,Be),!0}catch(Be){return ke(sa(Be)),!1}},[i,t,h]),me=g.useCallback(async(Me,Be)=>{if(!t||!i)return!1;ke(null);try{const p=await J.setCommunityChannelMuted(t,i,Me,Be);return d(U=>U.map(K=>K.id===Me&&K.readState?{...K,readState:{...K.readState,mutedAt:p.mutedAt}}:K)),!0}catch(p){return ke(sa(p)),!1}},[i,t]),_e=g.useCallback(async(Me="")=>{if(!t||!i||!s)return[];try{const Be=await J.searchCommunityMembers(t,i,{query:Me,limit:50});return R(p=>lZ(p,Be.items)),Be.items}catch(Be){return ke(sa(Be)),[]}},[i,t,s]);g.useEffect(()=>{s&&l?_e():R([])},[s,l,_e]);const $e=g.useCallback(async Me=>{if(!t||!i||!h)return!1;try{const Be=await J.communityAttachmentDownload(t,i,h,Me);return window.open(Be.url,"_blank","noopener,noreferrer"),!0}catch(Be){return ke(sa(Be)),!1}},[i,t,h]),Xe=g.useCallback(()=>h?st(h):Promise.resolve(!1),[st,h]),et=g.useCallback(()=>he?L(he):Promise.resolve(!1),[he,L]),rt=g.useCallback(()=>ue(null),[]),it=g.useCallback(()=>ne(null),[]);return{channels:m,selectedChannelId:h,selectedChannel:Oe,messages:Qe?.items??[],hasMoreBefore:Qe?.hasMoreBefore??!1,previewMode:Qe?.preview??!s,members:I,channelsLoading:M,messagesLoading:N,olderMessagesLoading:j,sending:C,channelsError:z,messagesError:D,realtimeError:le,actionError:Ie,lostMembership:Z,failedSend:he,incomingNotification:be,selectChannel:v,loadChannels:Ge,loadMessages:Xe,loadOlder:De,sendMessage:$,retrySend:et,dismissFailedSend:rt,editMessage:H,deleteMessage:Q,setMuted:me,searchMembers:_e,downloadAttachment:$e,dismissIncomingNotification:it}}function pS(e,t,n){e(a=>{const o=a[t];return o?{...a,[t]:{...o,items:o.items.map(i=>i.id===n.id?n:i)}}:a})}function sZ(e){const t=e.metadata.mentionUserIds;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function lZ(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 ml(e){return e.includes("community_membership_required")||e.includes("community_rules")}function sa(e){return e instanceof Error?e.message:String(e)}function cZ(e){const t=aZ({connection:e.connection,refreshToken:e.refreshToken}),n=iZ({connection:e.connection,preview:t.preview,currentUserId:e.currentUserId,membershipVersion:t.membershipVersion}),a=n.incomingNotification,o=t.items,i=n.channels,s=t.selectCommunity,l=n.selectChannel,m=n.dismissIncomingNotification,{setView:d,showToast:h}=e,v=g.useCallback(()=>{t.showDiscovery(),d("community")},[t.showDiscovery,d]),y=g.useCallback(I=>{t.selectCommunity(I),d("community")},[t.selectCommunity,d]),w=g.useCallback(I=>{n.selectChannel(I),d("community")},[n.selectChannel,d]);return g.useEffect(()=>{if(!a)return;const I=o.find(M=>M.id===a.communityId),R=i.find(M=>M.id===a.channelId);h(`${I?.displayName??"Community"} · #${R?.displayName??"channel"}: ${a.message.body.slice(0,120)||"New message"}`,"info",{actionLabel:"View",onAction:()=>{s(a.communityId),l(a.channelId),d("community")},placement:"top-right"}),m()},[i,o,m,a,l,s,d,h]),{communities:t,chat:n,sidebar:{communityItems:t.items,communityChannels:n.channels,communityLoading:t.discoveryLoading,communityError:t.discoveryError,selectedCommunityId:t.selectedCommunityId,selectedCommunityChannelId:n.selectedChannelId,discoverCommunities:v,selectCommunity:y,selectCommunityChannel:w},view:{communities:t,chat:n,currentUserId:e.currentUserId}}}const dZ=[];function uZ(e){const t=g.useCallback(a=>UK(e,a),[e]),n=g.useCallback(()=>DK(e)??dZ,[e]);return g.useSyncExternalStore(t,n,n)}function mZ(e){const[t,n]=g.useState(()=>Rp());return g.useEffect(()=>{let a=!0;return e?(J.connectedAppStatus(e,{status:"all"}).then(o=>{a&&n(o.apps)}).catch(o=>{console.warn("Unable to load connected app mention status.",o),a&&n(Rp())}),()=>{a=!1}):(n(Rp()),()=>{a=!1})},[e]),t}function pZ(){const{composerDraftStore:e,dispatch:t,setters:n,state:a}=PG(),[o,i]=g.useState(null),[s,l]=g.useState([]),[m,d]=g.useState(null),[h,v]=g.useState(null),[y,w]=g.useState([]),[I,R]=g.useState(null),[M,P]=g.useState(null),[N,O]=g.useState(F_),[j,k]=g.useState({}),[C,T]=g.useState(()=>new Set),z=g.useCallback((at,Xt)=>{T(Wt=>{if(Wt.has(at)===Xt)return Wt;const Gt=new Set(Wt);return Xt?Gt.add(at):Gt.delete(at),Gt})},[]),[B,D]=g.useState(0),[V,le]=g.useState(null),te=g.useRef(null),{confirmProjectAction:Ie,projectConfirmDialog:ke,resolveProjectConfirmDialog:Z}=PV(),{query:Ae,searchOpen:he,archivedChatsOpen:ue,sectionMenuOpen:be,projectsExpanded:ne,cloudProjectsExpanded:ge,chatRowsVisibleCount:xe,sidebarOpen:qe,view:Se,selectedAppId:se,selectedProjectId:we,selectedSessionId:Oe,draftProvider:Qe,draftModel:Ge,draftExperience:st,codexPermissionMode:Le,codexReasoningEffort:Fe,openPondCommandAccessMode:De,busy:L,diffPanelOpen:$,diffPanelExpanded:H,rightPanelMode:Q,rightChatPanels:me,terminalOpen:_e,settingsSection:$e,newProjectDialogOpen:Xe,newProjectMode:et,newProjectName:rt,newProjectPath:it,newProjectBusy:Me,commitDialogOpen:Be,commitMessage:p,commitIncludeUnstaged:U,commitNextStep:K,commitDraft:de,branchDialogOpen:re,branchDialogName:F,toast:_,error:W}=a,X=jG(Se==="labs"),{setQuery:oe,setSearchOpen:G,setArchivedChatsOpen:pe,setSectionMenuOpen:fe,setProjectsExpanded:je,setCloudProjectsExpanded:Ee,setChatRowsVisibleCount:Ne,setSidebarOpen:Ve,setView:Ue,setSelectedAppId:ut,setSelectedProjectId:Qt,setSelectedSessionId:zt,setPrompt:Mn,setDraftProvider:xn,setDraftModel:nn,setDraftExperience:bt,setCodexPermissionMode:sn,setCodexReasoningEffort:Lt,setOpenPondCommandAccessMode:yt,setDiffPanelOpen:ln,setDiffPanelExpanded:Ht,setRightPanelMode:pn,setRightChatPanels:Ln,setTerminalOpen:vn,setSyncingWorkspaceAppId:Ba,setSettingsSection:ua,setNewProjectDialogOpen:Bt,setNewProjectMode:Kn,setNewProjectName:ot,setNewProjectPath:wn,setNewProjectBusy:Fa,setCommitDialogOpen:Va,setCommitMessage:ma,setCommitIncludeUnstaged:Ka,setCommitNextStep:ae,setCommitDraft:Ke,setBranchDialogOpen:ze,setBranchDialogName:Ze,setError:kt}=n,{connectionRef:gt,setError:lt,showToast:Ct}=yG({appDispatch:t,error:W,setErrorState:kt}),{appPreferences:pa,applyBootstrapPayload:Wn,bootstrap:tt,codexHistorySessions:Rn,connection:St,events:In,runtimeEventStore:Un,approvals:jn,sessions:Wa,startup:Pa,setAppPreferences:yo,setBootstrap:Ga,setCodexHistorySessions:oa,setEvents:xt,setSessions:Za}=gG({setDraftModel:nn,setDraftProvider:xn,setCodexPermissionMode:sn,setCodexReasoningEffort:Lt,setOpenPondCommandAccessMode:yt,setError:lt,setSelectedAppId:ut,setSelectedProjectId:Qt,setSelectedSessionId:zt});gt.current=St,g.useEffect(()=>{tt&&w(tt.sidebarFileBookmarks??[])},[tt?.sidebarFileBookmarks]);const fa=g.useMemo(()=>[...In].reverse().find(at=>at.name==="tool.completed"&&at.action==="manage_sidebar_file")??null,[In]),ni=g.useRef(null);g.useEffect(()=>{!St||!fa||ni.current===fa.id||(ni.current=fa.id,J.sidebarFiles(St).then(at=>w(at.items)).catch(at=>lt(at instanceof Error?at.message:String(at))))},[St,fa,lt]);const Sr=g.useCallback(async(at,Xt)=>{if(!St)return;const Wt=y;w(Gt=>Xt==="none"?Gt.filter(Ea=>Ea.id!==at.id):Gt.some(Ea=>Ea.id===at.id)?Gt.map(Ea=>Ea.id===at.id?{...Ea,status:Xt}:Ea):[...Gt,{...at,status:Xt}]);try{const Gt=await J.patchSidebarFile(St,{workspaceKind:at.workspaceKind,workspaceId:at.workspaceId,workspaceName:at.workspaceName,path:at.path,status:Xt,sourceSessionId:at.sourceSessionId});w(Gt.items)}catch(Gt){w(Wt),lt(Gt instanceof Error?Gt.message:String(Gt))}},[St,lt,y]),kr=mZ(St),So=qG({connection:St,profileId:tt?.profile?.activeProfile??"default"}),{pinnedCollapsed:ai,projectsCollapsed:oi,cloudProjectsCollapsed:ri,chatsCollapsed:ii,savedForLaterCollapsed:ks,sidebarWidth:xs,sidebarResizing:Ja,diffPanelWidth:ws,diffPanelResizing:si,togglePinnedCollapsed:li,toggleProjectsCollapsed:ci,toggleCloudProjectsCollapsed:Is,toggleChatsCollapsed:ra,toggleSavedForLaterCollapsed:_s,startSidebarResize:Cs,startDiffPanelResize:Rs}=EG({connection:St,preferences:tt?.preferences,sidebarOpen:qe,diffPanelExpanded:H,setBootstrap:Ga,setError:lt}),{cloudProjectById:di,linkedProjectByAppId:ui,localProjectById:mi,mentionableSandboxApps:Ps,selectedApp:Ya,selectedCloudProject:ko,selectedProject:Gn,selectedProjectLinkedApp:As,selectedProjectLinkedOpenPondApp:Ts,selectedSession:bn,selectedSessionLinkedProject:pi,sidebarSessions:Zn}=n9({bootstrap:tt,codexHistorySessions:Rn,selectedAppId:se,selectedProjectId:we,selectedSessionId:Oe,sessions:Wa}),Aa=bn?.experience??st;g.useEffect(()=>{AK(Aa)},[Aa]);const xo=g.useMemo(()=>R3(Zn,Aa),[Aa,Zn]),Qa=YG(In,jn),{chatMentionApps:Es,connectedAppMentions:Ms,pendingApproval:wo}=k9({bootstrap:tt,connectedAppRows:kr,mentionableSandboxApps:Ps,runtimeIndexes:Qa,selectedApp:Ya,selectedCloudProject:ko,selectedProject:Gn,selectedSession:bn,selectedSessionId:Oe}),{codexHistoryEvents:xr,setCodexHistoryEvents:fi}=z9({connection:St,selectedSessionId:Oe,selectedSessionLocallyActive:!!(Oe&&C.has(Oe)),selectedSessionStatus:bn?.status,setCodexHistorySessions:oa,setError:lt}),{account:wr,accountPending:hi,accountSignedOut:Ir,activeModel:gi,activeProvider:ha,activeWorkspaceAppId:Qo,activeWorkspaceId:_r,activeWorkspaceKind:Io,activeWorkspaceLocation:vi,appDefaults:Xa,cloudLinked:bi,selectedCodexHistoryPending:js,selectedSessionProjectId:Cr,startMessage:yi,workspaceName:Si}=YK({bootstrap:tt,draftModel:Ge,draftProvider:Qe,selectedApp:Ya,selectedAppId:se,selectedCloudProject:ko,selectedProject:Gn,selectedSession:bn,selectedSessionId:Oe,selectedSessionLinkedProject:pi}),ki=g.useMemo(()=>qK(tt?.account??null),[tt?.account]),Os=g.useMemo(()=>rh(tt?.account??null),[tt?.account]),Rr=uZ(Os),xi=g.useMemo(()=>VK(Rr,Xa.defaultTeamId),[Xa.defaultTeamId,Rr]),Xo=xi?.teamId??null,eo=Z7({connection:St,teamId:Xo,currentUserId:wr?.profile?.id??null,refreshToken:tt?.accountMeta.asOf??null}),$s=eZ({connection:St,teamId:Xo,applyBootstrapPayload:Wn,refreshDirectory:eo.refreshDirectory});nZ({notification:eo.incomingNotification,dismiss:eo.dismissIncomingNotification,selectThread:eo.selectThread,setView:Ue,showToast:Ct});const{communities:Ns,sidebar:Ds,view:Ls}=cZ({connection:St,currentUserId:wr?.profile?.id??null,refreshToken:tt?.accountMeta.asOf??null,setView:Ue,showToast:Ct}),Ta=eo.aiThread?.conversationId??null,wi=Se==="team"&&!!Ta&&$&&Q==="chat";g.useEffect(()=>{if(Se==="team"){if(Ta){pn("chat"),ln(!0);return}Q==="chat"&&ln(!1)}},[Q,ln,pn,Ta,Se]);const Pr=g.useCallback(()=>{if(Ta){if(wi){ln(!1);return}pn("chat"),ln(!0)}},[ln,pn,wi,Ta]),Us=g.useMemo(()=>_a(Gn,tt?.cloudProjects??[]),[tt?.cloudProjects,Gn]),_o=bn?.provider==="codex"?De:bn?.openPondCommandAccessMode??De,zn=Qo,zs=_r,Hs=Io,qs=Si,{openPondActionCatalog:Bs,selectedActionCatalog:mt}=m7({cloudProjectById:di,cloudProjects:tt?.cloudProjects??[],connection:St,defaultTeamId:Xa.defaultTeamId,accountScopeKey:ki,localProjects:tt?.localProjects??[],profile:tt?.profile,selectedCloudProject:ko,selectedProject:Gn,reportError:lt}),{expandedProjectIds:Ft,expandProject:Jn,toggleProjectExpanded:fn,setExpandedProjectIds:ia}=p7({selectedProjectId:we});c9({activeWorkspaceId:_r,activeWorkspaceKind:Io,appDispatch:t,connection:St,expandProject:Jn,linkedProjectByAppId:ui,providerSettings:tt?.providers??null,selectedAppId:se,selectedSession:bn,selectedSessionId:Oe,selectedSessionProjectId:Cr,setDiffPanelExpanded:Ht,setDraftModel:nn,setDraftProvider:xn,setError:lt,setSelectedAppId:ut,setSelectedProjectId:Qt,setSessions:Za,setTerminalOpen:vn,toast:_});const{changeCodexPermissionMode:On,changeCodexReasoningEffort:Ku}=x9({connection:St,setBootstrap:Ga,setCodexPermissionMode:sn,setCodexReasoningEffort:Lt,setError:lt}),{changeOpenPondCommandAccessMode:Wu}=_8({connection:St,selectedSession:bn,setBootstrap:Ga,setError:lt,setOpenPondCommandAccessMode:yt,setSessions:Za}),Gu=d9({connection:St,setError:lt}),Fs=g.useCallback(()=>{D(at=>at+1)},[]),bc=m9({appDispatch:t,expandProject:Jn,linkedProjectByAppId:ui,requestComposerFocus:Fs,onBeginNewChat:()=>{cn({kind:"chat",sessionId:null}),le(null),bt(at=>at==="development"?"work":at)},setMentionedAppId:v}),Zu=g.useCallback(at=>{const Xt=vt("local",at);t({type:"selectProject",projectId:Xt}),Jn(Xt)},[t,Jn]),{advanceAfterTurn:Ju,begin:Yu,bindSession:Qu,dismiss:Xu,handoff:em,prepareTurn:tm,selectTask:nm}=GG({activeModel:gi,activeProvider:ha,applyBootstrapPayload:Wn,beginNewChat:bc,composerDraftStore:e,connection:St,requestComposerFocus:Fs,selectedLocalProjectId:Gn?.id??null,selectedSessionId:Oe,selectLocalProject:Zu,setDraftModel:nn,setDraftProvider:xn,setError:lt,view:Se});TG({connection:St,events:In,showToast:Ct}),j8({searchOpen:he,sectionMenuOpen:be,setSectionMenuOpen:fe,setSearchOpen:G,setQuery:oe}),g.useEffect(()=>{k({})},[tt?.server.id]);const{chatHistoryLoadStates:am,loadMoreSelectedChatHistory:yc,selectedPagedSessionEvents:om,selectedRuntimeIndexes:Sc}=ZG({approvals:jn,codexHistoryEvents:xr,connection:St,latestServerSequence:tt?.eventWindow?.latestSequence,runtimeIndexes:Qa,runtimeEventStore:Un,selectedSessionId:Oe,serverId:tt?.server.id,setCodexHistoryEvents:fi,setCodexHistorySessions:oa,setError:lt}),{activeSessions:rm,archivedSessions:im,pinnedProjects:sm,pinnedSessions:kc,savedForLaterSessions:Vs,pinnedFiles:lm,savedForLaterFiles:cm,pinnedItems:xc,projectRows:wc,localProjectRows:Ic,visibleProjectRows:Ks,cloudProjectRows:dm,projectSessionRowsByProjectId:_c,childSessionRowsByParentId:um,sidebarProjectIdBySessionId:Ws,chatRows:mm,visibleChatRows:Cc,sessionEvents:pm,chatMessages:Rc,contextUsage:fm,goalRuntime:hm,subagentRuntime:Pc}=C8({localProjects:tt?.localProjects??[],cloudProjects:tt?.cloudProjects??[],sessions:xo,runtimeIndexes:Sc,appPreferences:pa,selectedSessionId:Oe,selectedProjectId:we,archivedChatsOpen:ue,projectsExpanded:ne,chatRowsVisibleCount:xe,sidebarFileBookmarks:y}),gm=g.useCallback(at=>{bt(at);const Xt=[...xo].filter(Wt=>at==="work"?Wt.experience==="work"||Wt.experience==="development":Wt.experience===at).sort((Wt,Gt)=>Gt.updatedAt.localeCompare(Wt.updatedAt))[0]??[...Zn].filter(Wt=>Wt.experience===at).sort((Wt,Gt)=>Gt.updatedAt.localeCompare(Wt.updatedAt))[0]??null;if(Xt)t({type:"selectSession",sessionId:Xt.id,appId:at!=="chat"?Xt.appId:null,projectId:at!=="chat"?Ws[Xt.id]??null:null});else if(t({type:"beginNewChat",appId:null}),at==="chat"&&ha==="codex"){const Wt=Xf(tt?.providers,{enabledOnly:!0}).find(Gt=>Gt.value!=="codex")?.value??Fr;xn(Wt),nn(Hd(Wt,tt?.providers)??Ml)}at==="chat"&&(vn(!1),Ht(!1),pn("home")),Ue("chat")},[t,ha,tt?.providers,xo,Ht,bt,nn,xn,pn,vn,Ue,Ws,Zn]),vm=g.useCallback(at=>{const Xt=e.getSnapshot();if(bt(at),(Oe||se||we)&&(t({type:"beginNewChat",appId:null}),Xt&&e.set(Xt)),at==="chat"&&ha==="codex"){const Wt=Xf(tt?.providers,{enabledOnly:!0}).find(Gt=>Gt.value!=="codex")?.value??Fr;xn(Wt),nn(Hd(Wt,tt?.providers)??Ml)}at==="chat"&&(vn(!1),Ht(!1),pn("home")),Ue("chat")},[ha,t,tt?.providers,e,se,we,Oe,Ht,bt,nn,xn,pn,vn,Ue]),{pendingChatUserMessages:Gs,recordPendingChatUserMessage:bm,visibleChatMessages:ym}=I8({chatMessages:Rc,runtimeIndexes:Sc,selectedSessionId:Oe}),er=g.useMemo(()=>z3({selectedAppId:se,selectedProjectId:we,selectedSessionId:Oe}),[se,we,Oe]),Ac=g.useRef(null);g.useEffect(()=>{const at=Ac.current;Ac.current=er,!(!at||at.kind!=="draft"||er.kind!=="session")&&(Vl(at,er)||l(Xt=>{const Wt=H3({tabs:Xt,previousScope:at,activeScope:er});return Wt.some((Ea,Wm)=>Ea!==Xt[Wm])?Wt:Xt}))},[er]);const Sm=g.useMemo(()=>q3(s),[s]),{goalRuntime:km,runningSessionIds:xm,selectedSessionRunning:wm,sidebarGoalRuntimeBySessionId:Im,sidebarSubagentRuntimeBySessionId:_m}=M8({codexHistoryEvents:xr,codexHistorySessions:Rn,connection:St,expandedProjectIds:Ft,goalRuntime:hm,locallyActiveCodexHistorySessionIds:C,pinnedSessions:kc,savedForLaterSessions:Vs,projectSessionRowsByProjectId:_c,rightChatHistoryEvents:j,runtimeIndexes:Qa,selectedSession:bn,selectedSessionId:Oe,serverId:tt?.server.id,setCodexHistorySessions:oa,sidebarSessions:Zn,subagentRuntime:Pc,visibleChatRows:Cc,visibleProjectRows:Ks}),{dragItem:Cm,pinnedPreviewKeys:Tc,startPinnedDrag:Rm,clearSidebarDrag:Ii,previewPinnedDrop:Pm,commitPinnedDrop:Am,commitPinnedPreviewDrop:Tm}=H9({connection:St,appPreferences:pa,sessions:Zn,pinnedItems:xc,setAppPreferences:yo,setCodexHistorySessions:oa,setSessions:Za,sidebarFileBookmarks:y,setSidebarFileBookmarks:w,setError:lt}),{clearTaskDrag:Zs,commitTaskDrop:Em,commitTaskPreviewDrop:Mm,previewTaskDrop:Js,startTaskDrag:Ys,taskDragSessionId:Qs,taskPreviewSessionIds:Xs}=q9({connection:St,sessions:Zn,setCodexHistorySessions:oa,setError:lt,setSessions:Za}),{commandProjectRows:jm,contextWindowStatus:el,pinnedRows:tl,sidebarWorkspaceAppIds:nl}=u9({activeProvider:ha,contextCompaction:Xa.contextCompaction,contextUsage:fm,pinnedItems:xc,pinnedPreviewKeys:Tc??[],pinnedProjects:sm,projectRows:wc,visibleProjectRows:Ks}),to=!!(zn&&(Se==="chat"||Se==="labs")&&(Be||$&&(Q==="changes"||Q==="goal"))),{workspaceStates:al,workspaceBusy:Mc,diffBusy:Om,visibleWorkspaceState:ol,visibleWorkspaceDiff:$m,rememberWorkspaceState:jc,refreshWorkspace:Nm,refreshWorkspaceDiff:Ar,setWorkspaceBusy:Dm}=g7({connection:St,activeWorkspaceAppId:zn,view:Se,shouldLoadWorkspaceDiff:to,sidebarWorkspaceAppIds:nl,setError:lt});te.current=jc;const Lm=g.useCallback((at=zn)=>!at||at!==zn||!to?Promise.resolve(null):Ar(at),[Ar,to,zn]),Um=g.useCallback(async(at={})=>{!zn||!to||await Ar(zn,at)},[Ar,to,zn]),zm=!1,Hm=!!(bn?.provider==="codex"&&bn.cwd&&!go(bn.workspaceKind)),qm=!!(ol&&!ol.initialized&&Io!=="local_project"&&ha!=="codex"&&!Hm&&!js),rl=Io==="local_project"&&!!Gn?.sandboxTemplate?.detected&&!Gn?.linkedOpenPondApp?.appId,[Oc,il]=g.useState(null),[Bm,Fm]=g.useState(null),{projectTarget:Vm,workspaceTarget:Km}=QK({accountPending:hi,accountSignedOut:Ir,activeWorkspaceLocation:vi,bootstrap:tt,busy:L,cloudLinked:bi,selectedCloudProject:ko,selectedProject:Gn,selectedSession:bn,pendingWorkspaceTarget:Oc,workspaceStates:al,workspaceBusy:Mc});return g.useEffect(()=>{il(null)},[bn?.id]),{composerDraftStore:e,appDispatch:t,pendingTerminalCommand:o,setPendingTerminalCommand:i,terminalTabs:s,setTerminalTabs:l,trainingDetailTasksetId:m,setTrainingDetailTasksetId:d,mentionedAppId:h,setMentionedAppId:v,cloudSetupDialog:I,setCloudSetupDialog:R,rightPanelTabRequest:M,setRightPanelTabRequest:P,workspaceDiffPanelViewState:N,setWorkspaceDiffPanelViewState:O,rightChatHistoryEvents:j,setRightChatHistoryEvents:k,locallyActiveCodexHistorySessionIds:C,setCodexHistoryTurnLocallyActive:z,mainComposerFocusRequestId:B,requestMainComposerFocus:Fs,draftSubagentDelegationMode:V,setDraftSubagentDelegationMode:le,confirmProjectAction:Ie,projectConfirmDialog:ke,resolveProjectConfirmDialog:Z,query:Ae,searchOpen:he,archivedChatsOpen:ue,sectionMenuOpen:be,projectsExpanded:ne,cloudProjectsExpanded:ge,sidebarOpen:qe,view:Se,selectedAppId:se,selectedProjectId:we,selectedSessionId:Oe,draftProvider:Qe,draftModel:Ge,draftExperience:st,activeExperience:Aa,changeExperience:gm,changeNewExperience:vm,codexPermissionMode:Le,codexReasoningEffort:Fe,openPondCommandAccessMode:De,busy:L,diffPanelOpen:$,diffPanelExpanded:H,rightPanelMode:Q,rightChatPanels:me,terminalOpen:_e,settingsSection:$e,newProjectDialogOpen:Xe,newProjectMode:et,newProjectName:rt,newProjectPath:it,newProjectBusy:Me,commitDialogOpen:Be,commitMessage:p,commitIncludeUnstaged:U,commitNextStep:K,commitDraft:de,branchDialogOpen:re,branchDialogName:F,toast:_,error:W,labDetailNavigation:X,setQuery:oe,setSearchOpen:G,setArchivedChatsOpen:pe,setSectionMenuOpen:fe,setProjectsExpanded:je,setCloudProjectsExpanded:Ee,setChatRowsVisibleCount:Ne,setSidebarOpen:Ve,setView:Ue,setSelectedAppId:ut,setSelectedProjectId:Qt,setSelectedSessionId:zt,setPrompt:Mn,setDraftProvider:xn,setDraftModel:nn,setDraftExperience:bt,setDiffPanelOpen:ln,setDiffPanelExpanded:Ht,setRightPanelMode:pn,setRightChatPanels:Ln,setTerminalOpen:vn,setSyncingWorkspaceAppId:Ba,setSettingsSection:ua,setNewProjectDialogOpen:Bt,setNewProjectMode:Kn,setNewProjectName:ot,setNewProjectPath:wn,setNewProjectBusy:Fa,setCommitDialogOpen:Va,setCommitMessage:ma,setCommitIncludeUnstaged:Ka,setCommitNextStep:ae,setCommitDraft:Ke,setBranchDialogOpen:ze,setBranchDialogName:Ze,setError:lt,showToast:Ct,appPreferences:pa,applyBootstrapPayload:Wn,approvals:jn,bootstrap:tt,connection:St,events:In,runtimeEventStore:Un,sessions:Wa,startup:Pa,setAppPreferences:yo,setCodexHistorySessions:oa,setEvents:xt,setSessions:Za,training:So,pinnedCollapsed:ai,projectsCollapsed:oi,cloudProjectsCollapsed:ri,chatsCollapsed:ii,savedForLaterCollapsed:ks,sidebarWidth:xs,sidebarResizing:Ja,diffPanelWidth:ws,diffPanelResizing:si,togglePinnedCollapsed:li,toggleProjectsCollapsed:ci,toggleCloudProjectsCollapsed:Is,toggleChatsCollapsed:ra,toggleSavedForLaterCollapsed:_s,startSidebarResize:Cs,startDiffPanelResize:Rs,cloudProjectById:di,localProjectById:mi,selectedApp:Ya,selectedCloudProject:ko,selectedProject:Gn,selectedProjectLinkedApp:As,selectedProjectLinkedOpenPondApp:Ts,selectedSession:bn,sidebarSessions:Zn,runtimeIndexes:Qa,chatMentionApps:Es,connectedAppMentions:Ms,pendingApproval:wo,codexHistoryEvents:xr,setCodexHistoryEvents:fi,account:wr,accountPending:hi,accountSignedOut:Ir,activeModel:gi,activeProvider:ha,activeWorkspaceAppId:Qo,activeWorkspaceId:_r,activeWorkspaceKind:Io,activeWorkspaceLocation:vi,appDefaults:Xa,selectedSessionProjectId:Cr,startMessage:yi,workspaceName:Si,accountScopeKey:ki,organizations:Rr,teamChatOrganization:xi,teamChatTeamId:Xo,teamChat:eo,publishTeamProfileAgent:$s,communities:Ns,communitySidebar:Ds,communityView:Ls,teamAiThreadId:Ta,toggleTeamAiSidebar:Pr,selectedProjectConfirmedCloudProject:Us,activeOpenPondCommandAccessMode:_o,viewWorkspaceAppId:zn,viewWorkspaceId:zs,viewWorkspaceKind:Hs,viewWorkspaceName:qs,openPondActionCatalog:Bs,selectedActionCatalog:mt,expandedProjectIds:Ft,expandProject:Jn,toggleProjectExpanded:fn,setExpandedProjectIds:ia,changeCodexPermissionMode:On,changeCodexReasoningEffort:Ku,changeOpenPondCommandAccessMode:Wu,resolveApproval:Gu,beginNewChat:bc,advanceTrainingModelChatAfterTurn:Ju,beginNewChatWithTrainingModel:Yu,bindTrainingModelChatSession:Qu,dismissTrainingChatHandoff:Xu,trainingChatHandoff:em,prepareTrainingModelChatTurn:tm,selectTrainingChatTaskForComposer:nm,chatHistoryLoadStates:am,loadMoreSelectedChatHistory:yc,selectedPagedSessionEvents:om,activeSessions:rm,archivedSessions:im,pinnedSessions:kc,savedForLaterSessions:Vs,pinnedFiles:lm,savedForLaterFiles:cm,sidebarFileBookmarks:y,setSidebarFileStatus:Sr,projectRows:wc,localProjectRows:Ic,visibleProjectRows:Ks,cloudProjectRows:dm,projectSessionRowsByProjectId:_c,childSessionRowsByParentId:um,sidebarProjectIdBySessionId:Ws,chatRows:mm,visibleChatRows:Cc,chatRowsVisibleCount:xe,sessionEvents:pm,chatMessages:Rc,goalRuntime:km,subagentRuntime:Pc,pendingChatUserMessages:Gs,recordPendingChatUserMessage:bm,visibleChatMessages:ym,activeTerminalScope:er,terminalSummaries:Sm,runningSessionIds:xm,selectedSessionRunning:wm,sidebarGoalRuntimeBySessionId:Im,sidebarSubagentRuntimeBySessionId:_m,taskDragSessionId:Qs,taskPreviewSessionIds:Xs,startTaskDrag:Ys,clearTaskDrag:Zs,previewTaskDrop:Js,commitTaskDrop:Em,commitTaskPreviewDrop:Mm,dragItem:Cm,startPinnedDrag:Rm,clearSidebarDrag:Ii,previewPinnedDrop:Pm,commitPinnedDrop:Am,commitPinnedPreviewDrop:Tm,commandProjectRows:jm,contextWindowStatus:el,pinnedRows:tl,workspaceStates:al,workspaceBusy:Mc,diffBusy:Om,visibleWorkspaceState:ol,visibleWorkspaceDiff:$m,rememberWorkspaceState:jc,refreshWorkspace:Nm,refreshWorkspaceDiff:Ar,setWorkspaceBusy:Dm,refreshWorkspaceDiffWhenNeeded:Lm,refreshVisibleWorkspaceDiff:Um,managedWorkspace:zm,canSyncActiveWorkspace:qm,canPublishOpenPondProject:rl,pendingWorkspaceTarget:Oc,setPendingWorkspaceTarget:il,pendingSidebarWorkspaceTarget:Bm,setPendingSidebarWorkspaceTarget:Fm,projectTarget:Vm,workspaceTarget:Km}}const fZ=/^(localhost|\[::1\]|127(?:\.\d{1,3}){3})(?::\d+)?(?:[/?#].*)?$/i,hZ=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+(?:[:/?#].*)?$/i;function gZ(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)?td(n,new Set(["http:","https:"])):/^file:\/\//i.test(n)?t.explicitFile?td(n,new Set(["file:"])):null:fZ.test(n)?td(`http://${n}`,new Set(["http:"])):hZ.test(n)?td(`https://${n}`,new Set(["https:"])):null}function td(e,t){try{const n=new URL(e);return t.has(n.protocol)?n.toString():null}catch{return null}}async function vZ(e){const t=gZ(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 bZ="openpond-coding-core-v1",yZ="feature";function vh(e){const t=new URL("/sandboxes",Ev(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",yZ),t.searchParams.set("runtimeProfileId",bZ),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 LQ(e){const t=e.organizationSlug?.trim(),n=t?`/sandboxes/${encodeURIComponent(t)}/billing`:"/sandboxes/billing",a=new URL(n,Ev(e.accountBaseUrl));return!t&&e.teamId?.trim()&&a.searchParams.set("teamId",e.teamId.trim()),a.toString()}function fS(e){const t=e.organizationSlug?.trim(),n=e.projectSlug?.trim();return!t||!n?null:new URL(`/${encodeURIComponent(t)}/${encodeURIComponent(n)}`,Ev(e.accountBaseUrl)).toString()}function Ev(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 SZ({account:e,browserConversationId:t,cloudProjectById:n,cloudProjects:a,diffPanelOpen:o,rightPanelMode:i,selectedProjectId:s,setDiffPanelOpen:l,setNewProjectDialogOpen:m,setNewProjectMode:d,setNewProjectName:h,setRightPanelMode:v}){const y=g.useCallback(()=>{v("changes"),l(!0)},[l,v]),w=g.useCallback(()=>{if(o&&i==="changes"){l(!1);return}y()},[o,i,l,y]),I=g.useCallback(()=>{v("browser"),l(!0)},[l,v]),R=g.useCallback(()=>{v("goal"),l(!0)},[l,v]),M=g.useCallback((j,k)=>{vZ({conversationId:t,href:j,explicitFile:k?.explicitFile,newTab:k?.newTab}).then(C=>{C&&I()})},[t,I]),P=g.useCallback(()=>{d("cloud"),h(""),m(!0)},[m,d,h]),N=g.useCallback(j=>{const k=n.get(j);k&&M(vh({accountBaseUrl:e?.baseUrl??e?.activeProfile?.baseUrl??null,teamId:k.teamId,projectId:k.id,projectName:k.name,baseBranch:k.defaultBranch,source:"openpond-app"}),{newTab:!0})},[e,n,M]);return{createCloudEnvironmentFromSidebar:g.useCallback(()=>{const j=s?.startsWith("cloud:")?s.slice(6):a[0]?.id??null;if(j){N(j);return}P()},[a,P,s,N]),openCloudProjectDialog:P,openUrlInBrowserPanel:M,showBrowserPanel:I,showChangesPanel:y,showGoalSidebarTab:R,toggleChangesPanel:w}}function kZ(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 xZ({browserConversationId:e,sessionIds:t,onOpenSession:n,onShowBrowserPanel:a}){g.useEffect(()=>window.openpond?.browser?.onRevealRequest?.(i=>{const s=kZ({currentConversationId:e,requestConversationId:i.conversationId,sessionIds:t});s.reveal&&(s.sessionIdToOpen&&n(s.sessionIdToOpen),a())}),[e,n,a,t])}const wZ="chat",IZ=["help me","please","can you","could you","make","create","build"],_Z=new Set(["a","an","and","for","from","i","me","my","of","our","please","produce","summary","the","to","with"]);function hS(e){const t=uf(e.label);if(t&&!bh(t))return gS(t);const n=uf(e.name);if(n&&!bh(n))return gS(n);const a=uf(e.actionId)?.replace(/\.chat$/i,"")??"";return CZ(a||t||"Profile Agent")}function bh(e){return e.trim().toLowerCase()===wZ}function CZ(e){const t=RZ(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&&!_Z.has(o)).slice(0,3);return zC(a.length?a.join(" "):t||e)}function gS(e){return zC(e).split(/\s+/).slice(0,4).join(" ")}function RZ(e){let t=e.trim();for(const n of IZ)if(t.toLowerCase().startsWith(`${n} `)){t=t.slice(n.length).trim();break}return t}function uf(e){return typeof e=="string"&&e.trim()?e.trim():null}function zC(e){return e.replace(/[._-]+/g," ").replace(/\s+/g," ").trim().replace(/\b[a-z0-9]/gi,t=>t.toUpperCase())}const PZ="openpond-profile-action";function AZ(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function nd(e){return typeof e=="string"&&e.trim()?e.trim():null}function TZ(e){const t=AZ(e.implementation);if(t?.type!==PZ)return null;const n=nd(t.actionId)??e.id;if(e.sourceActionId!=="chat"&&n!=="chat"&&!n.endsWith(".chat"))return null;const a=nd(e.label);if(a&&!bh(a))return hS({label:a,description:e.description});const o=nd(t.agentName)??nd(e.name);return hS({actionId:n,description:e.description,name:o})}function EZ(e){const t=TZ(e);return t||e.label?.trim()||e.name?.trim()||e.id}function HC(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 MZ=new Set(["action","agent","chat","customer","default","filter","items","open","openpond","profile","run","summarize","track","workflow"]);function qC(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function us(e){return typeof e=="string"&&e.trim()?e.trim():null}function Vi(e,t,n={}){const a=us(t)?Dn(String(t)):"";a&&(!n.generic&&MZ.has(a)||e.add(a))}function ad(e,t){const n=us(t);if(n)for(const a of n.split(/[.:/\\\s]+/g))Vi(e,a)}function jZ(e,t){const n=us(t);if(n)for(const a of n.split(/[^A-Za-z0-9_-]+/g))a.length<4||Vi(e,a)}function BC(e){const t=new Set,n=qC(e.implementation),a=us(n?.actionId);return Vi(t,e.id,{generic:!0}),ad(t,e.id),Vi(t,a,{generic:!0}),ad(t,a),Vi(t,e.name,{generic:!0}),ad(t,e.name),Vi(t,e.label,{generic:!0}),ad(t,e.label),jZ(t,e.description),t}function OZ(e){const t=qC(e.implementation);return[e.id,e.name??"",e.label??"",e.description??"",us(t?.actionId)??"",us(t?.agentName)??"",HC(e),...Array.from(BC(e))].join(" ").toLowerCase()}function UQ(e,t,n=8){const a=Dn(t);return e.length===0?[]:e.filter(o=>a?OZ(o).includes(a):!0).slice(0,n)}function $Z(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>Dn(t[1]??"")).filter(Boolean)}function NZ(e,t){const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return e.replace(new RegExp(`(^|\\s)@${n}(?=\\s|$)`,"g"),"$1").replace(/\s+/g," ").trim()}function DZ(e,t){const n=$Z(e);if(n.length===0||t.length===0)return null;const a=new Map;for(const i of n)for(const s of t)BC(s).has(i)&&a.set(s.id,{action:s,mention:i});if(a.size!==1)return null;const o=Array.from(a.values())[0];return{action:o.action,mention:o.mention,prompt:NZ(e,o.mention)}}function zQ(e){return EZ(e)}function HQ(e){return e.description||HC(e)}const Mv=[{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 LZ(e){return Mv.filter(t=>t.id!=="goal"||e==="codex")}function FC(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 qQ(e,t){return LZ(e).filter(n=>FC(n,t))}const UZ=new Set(Mv.map(e=>e.id));function BQ(e){return e.subcommands?.length?e.subcommands.join(", "):e.description}function zZ(e){return[e.id,e.command,e.label,e.description].join(" ")}function HZ(e){return(e.subcommands??[]).flatMap(t=>[t,`${e.id} ${t}`,`${e.command} ${t}`]).join(" ")}function qZ(e){const t=/^\/([a-z][a-z0-9_-]*)(?:\s+([\s\S]*))?$/.exec(e.trim());if(!t)return null;const n=t[1];return UZ.has(n)?{command:n,args:t[2]?.trim()??""}:null}function BZ(e){const t=e.trim();if(!t.startsWith("!"))return null;const n=t.slice(1).trim();return n?{command:n}:null}function FQ({commands:e=Mv,prompt:t,limit:n=10}){if(!t.startsWith("/"))return[];const a=t.slice(1).trim().toLowerCase();if(!a)return e.slice(0,n);const o=e.filter(l=>l.id.startsWith(a));if(o.length>0)return o.slice(0,n);const i=e.filter(l=>zZ(l).toLowerCase().includes(a));return(i.length>0?i:e.filter(l=>HZ(l).toLowerCase().includes(a))).slice(0,n)}function VQ(e){return e==="owner"?"Owner":e==="admin"?"Admin":"Member"}function Fu(e){return e?.role==="owner"||e?.role==="admin"}function KQ(e){const t=Vu(e.organizations,e.defaultTeamId),n=Fu(t),a=e.localProject??null;if(!a)return FZ("Open a local project to set up an Agent.");const o=VZ(a,e.projects),i=KZ(a,o,e.agents),s=!!a.sandboxTemplate?.detected,l=t&&!n?"Ask an owner or admin to connect this project.":null;return s?o?WZ(a,o)?od({state:"needs_sync",actionLabel:"Sync Project",project:o,agent:i,canManage:n,actionBlockedReason:l}):i?{state:"ready",actionLabel:"Run Agent",canAct:!0,reason:null,project:o,agent:i}:od({state:"needs_agent",actionLabel:"Create Agent",project:o,agent:null,canManage:n,actionBlockedReason:l}):od({state:"needs_project",actionLabel:"Connect Project",project:null,agent:null,canManage:n,actionBlockedReason:l}):od({state:"missing_config",actionLabel:"Add Agent config",project:o,agent:i,canManage:n,actionBlockedReason:l})}function od(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 FZ(e){return{state:"blocked",actionLabel:"Ask admin",canAct:!1,reason:e,project:null,agent:null}}function Vu(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 VZ(e,t){const n=e.linkedSandboxProject;return n?.projectId?t.find(a=>a.id===n.projectId)??null:null}function KZ(e,t,n){if(!t)return null;const a=e.preferredSandboxAgentId;if(a){const o=n.find(i=>i.id===a&&i.projectId===t.id);if(o)return o}return n.find(o=>o.projectId===t.id)??null}function WZ(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 Tr=e=>e.slice(0,2e4);function GZ({model:e,provider:t,providerSettings:n}){return{model:mv(t,e,n),modelRef:ja(t,e,n)}}function ZZ(e,t){return e.some(n=>n.id===t.id)?e:[...e,t]}function JZ(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 YZ(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 vS({action:e,prompt:t,runPayload:n,sessionId:a}){const o=new Date().toISOString(),i=`openpond_action_${n.run.id}`,s=n.run.status==="failed"?"failed":n.run.status==="succeeded"?"completed":"started";return[{id:`${i}_user`,sessionId:a,turnId:i,name:"turn.started",timestamp:o,source:"chat_action",args:{prompt:t}},{id:`${i}_result`,sessionId:a,turnId:i,name:"workspace_action_result",timestamp:n.run.updatedAt??o,source:"chat_action",action:"sandbox_run_action",appId:null,status:s,output:s==="completed"?`Ran ${e.label??e.name??e.id}`:`Started ${e.label??e.name??e.id}`,data:{openPondActionRun:!0,action:{name:e.id,label:e.label??e.name??e.id,implementation:e.implementation},agent:n.agent,run:n.run,sandbox:n.sandbox??null,actionSummary:n.run.actionSummary??null,responseSummary:n.run.responseSummary??null,traceSummary:n.run.traceSummary??null,evalSummary:n.run.evalSummary??null,sourceSummary:n.run.sourceSummary??null}}]}function QZ({applyBootstrapPayload:e,connection:t,codexPermissionMode:n,codexReasoningEffort:a,openPondCommandAccessMode:o,draftModel:i,draftProvider:s,experience:l,expandProject:m,ensureCloudSessionReady:d,getPrompt:h,bootstrap:v,chatMessages:y,apps:w,connectedAppMentions:I,mentionedAppId:R,refreshWorkspace:M,refreshWorkspaceDiff:P,selectedApp:N,selectedActionCatalog:O,openPondActionCatalog:j,cloudProjects:k,accountScopeKey:C,selectedCloudProject:T,selectedProject:z,selectedProjectLinkedOpenPondApp:B,selectedSession:D,workspaceTarget:V,subagentDelegationMode:le,setDraftModel:te,setDraftProvider:Ie,setError:ke,setPrompt:Z,setMentionedAppId:Ae,setCodexHistoryEvents:he,setCodexHistorySessions:ue,onCodexHistoryTurnActivityChange:be,onCodexHistoryTurnPayload:ne,onPendingUserMessage:ge,setEvents:xe,setSelectedAppId:qe,setSelectedProjectId:Se,setSelectedSessionId:se,setSessions:we,setView:Oe,setWorkspaceBusy:Qe}){function Ge(F){J.bootstrap(F).then(e).catch(_=>{console.warn("[chat] Message was accepted, but the post-send bootstrap refresh failed.",_);const W=_ instanceof Error?_.message:String(_);ke(`Message sent, but the chat list could not refresh: ${W}`)})}const st=g.useRef(new Set),Le=v?.providers??null;function Fe(F,_){return F==="codex"?void 0:_}function De(F){return!!(F&&F.provider!=="codex"&&(F.workspaceKind==="local_project"&&F.cwd?.trim()||(F.workspaceKind==="sandbox"||F.workspaceKind==="sandbox_template"||F.workspaceKind==="sandbox_app")&&F.workspaceId))}function L(F){Ie(F),te(_=>br(F,_,Le)),Oe("chat")}async function $(F,_){return(IC(_,C)??await _v({teamId:_,accountKey:C,fetchAgents:async oe=>(await J.listSandboxAgents(t,{teamId:oe})).agents})).find(oe=>oe.projectId===F)??null}async function H(){if(!t)throw new Error("OpenPond App server is not connected.");if(v?.account.state!=="signed_in")throw new Error("Add an OpenPond account before syncing a Project to Cloud.");const F=await J.organizations(t),_=Vu(F.organizations.map(Uu).filter(W=>!!W).filter(W=>W.status==="active"),v?.preferences.defaultTeamId??null);if(!_)throw new Error("Add an OpenPond account before syncing a Project to Cloud.");if(!Fu(_))throw new Error(`You need owner or admin access to create projects in ${_.displayName}.`);return _}async function Q(F){if(!t)return!1;const _=z;if(!_)throw new Error("Select a local Project before using /sync-cloud.");const W=await H(),X=_.linkedSandboxProject?.defaultBranch?.trim()||"main",oe=vt("local",_.id),G=_a(_,k),pe=await J.createSession(t,{provider:"openpond",modelRef:ja("openpond",es,Le),openPondCommandAccessMode:Fe("openpond",o),appId:null,appName:null,workspaceKind:"local_project",workspaceId:_.id,workspaceName:_.name,localProjectId:_.id,cloudProjectId:G?.id??null,cloudTeamId:G?.teamId??null,cwd:_.workspacePath,title:`Sync ${_.name} to Cloud`});we(fe=>[pe,...fe]),F.onSessionCreated?.(pe),F.selectSession&&(se(pe.id),Se(oe),qe(null),Oe("chat"),m(oe)),F.clearPromptForTurn(),Qe(!0);try{const fe=await J.uploadLocalProjectCloudSource(t,_.id,{teamId:W.teamId,projectName:_.name,branch:X,chatSessionId:pe.id,displayPrompt:F.displayPrompt});return e(fe.bootstrap),m(oe),m(vt("cloud",fe.project.id)),!0}catch(fe){const je=await J.bootstrap(t).catch(()=>null);throw je&&e(je),fe}finally{Qe(!1)}}async function me(F){if(!t||F.providerForTurn==="codex"||F.selectedSessionForTurn?.provider==="codex")return!1;let _=De(F.selectedSessionForTurn)?F.selectedSessionForTurn:null;if(!_&&F.selectedSessionForTurn)throw new Error("Select a project to use this.");if(!_)if(T){const X=vt("cloud",T.id),oe=F.providerForTurn;_=await J.createSession(t,{provider:oe,modelRef:ja(oe,F.modelForTurnValue,Le),openPondCommandAccessMode:Fe(oe,F.openPondCommandAccessModeForTurn),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:T.id,workspaceName:T.name,localProjectId:null,cloudProjectId:T.id,cloudTeamId:T.teamId,cwd:null,autoTitlePrompt:Tr(F.command)}),we(G=>[_,...G]),F.onSessionCreated?.(_),F.selectSession&&(se(_.id),Se(X),qe(null),Oe("chat"),m(X))}else{const X=z;if(!X)throw new Error("Select a project to use this.");const oe=_a(X,k),G=vt("local",X.id),pe=F.providerForTurn;_=await J.createSession(t,{provider:pe,modelRef:ja(pe,F.modelForTurnValue,Le),openPondCommandAccessMode:Fe(pe,F.openPondCommandAccessModeForTurn),appId:null,appName:null,workspaceKind:"local_project",workspaceId:X.id,workspaceName:X.name,localProjectId:X.id,cloudProjectId:oe?.id??null,cloudTeamId:oe?.teamId??null,cwd:X.workspacePath,autoTitlePrompt:Tr(F.command)}),we(fe=>[_,...fe]),F.onSessionCreated?.(_),F.selectSession&&(se(_.id),Se(G),qe(null),Oe("chat"),m(G))}if(!_)throw new Error("Select a project to use this.");F.clearPromptForTurn();const W=await J.runSessionCommand(t,_.id,{command:F.command,cwd:_.cwd});return we(X=>bl(X,W.session)),xe(X=>Mo(X,W.events)),!0}async function _e(F=[],_=null,W,X={}){const oe=W??h();let G=oe.trim()||(F.length>0?"Please review the attached files.":"");if(!t||!G)return!1;const pe=X.displayPrompt?.trim()||G,fe=X.provider??s,je=X.model??i,Ee=X.openPondCommandAccessMode??o,Ne=X.session!==void 0,Ve=Ne?X.session??null:D,Ue=X.experience??Ve?.experience??l,ut=Ue==="development"||Ue==="work"&&(Ve?.workspaceKind==="local_project"||!!Ve?.localProjectId||!!Ve?.cloudProjectId||!Ne&&!!(z||T||N||V==="hybrid"||V==="local")),Qt=Ne||!ut?null:N,zt=Ne||!ut?null:z,Mn=Ne||!ut?null:T,xn=Ne||!ut?null:B,nn=!Ne&&ut&&V==="hybrid",bt=X.selectSession??!0,sn=X.chatMessages??y,Lt=X.session!==void 0?null:R,yt=X.clearPrompt===void 0?()=>{Z(""),Ae(null)}:X.clearPrompt,ln=_?null:DZ(G,O),Ht=_??ln?.action??null,pn=ln?.prompt||G,Ln=ut&&!Ht?BZ(G):null,vn=Ht||Ln?null:qZ(G),Ba=vn&&!FC({id:vn.command},Ue)?vn:null,ua=X.usageAttribution??(vn?{surface:"chat",workflowKind:"slash_command",commandName:`/${vn.command}`,commandSource:"prompt_parse"}:void 0);ke(null);let Bt=null,Kn=null;try{if(!ut&&fe==="codex")throw new Error("The Codex provider requires repository-aware Work.");if(Ba)throw new Error(`/${Ba.command} isn't available in ${Ue}.`);if(Ln&&fe!=="codex"&&Ve?.provider!=="codex"){if(F.length>0)throw new Error("Direct commands do not accept attachments.");return await me({command:Ln.command,clearPromptForTurn:yt,modelForTurnValue:je,onSessionCreated:X.onSessionCreated,openPondCommandAccessModeForTurn:Ee,providerForTurn:fe,selectedSessionForTurn:Ve,selectSession:bt})}if(!Ne&&vn?.command==="sync-cloud")return await Q({clearPromptForTurn:yt,displayPrompt:pe,onSessionCreated:X.onSessionCreated,selectSession:bt});if(Ht){const Ze=a7(Ht);if(Ze){let tt=Ve;if(!tt||tt.cloudProjectId!==Ze.projectId){tt=await J.createSession(t,{provider:"openpond",modelRef:ja("openpond",je,Le),openPondCommandAccessMode:Fe("openpond",Ee),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:Ze.projectId,workspaceName:Ze.projectName??Ze.agentName,localProjectId:null,cloudProjectId:Ze.projectId,cloudTeamId:Ze.teamId,cwd:null,autoTitlePrompt:Tr(pe)}),we(Un=>[tt,...Un]),X.onSessionCreated?.(tt),bt&&se(tt.id);const In=vt("cloud",Ze.projectId);bt&&Se(In),bt&&m(In)}const Rn=await J.runSandboxAgent(t,Ze.agentId,l7({agent:Ze,attachments:F,displayPrompt:pe,prompt:pn})),St=await J.bootstrap(t);return e(St),yt(),xe(In=>Mo(In,vS({action:Ht,prompt:pe,runPayload:Rn,sessionId:tt.id}))),!0}const kt=Av(Ht);if(kt){let tt=Ve;(!tt||tt.provider!=="openpond")&&(tt=await J.createSession(t,{provider:"openpond",modelRef:ja("openpond",je,Le),openPondCommandAccessMode:Fe("openpond",Ee),appId:null,appName:null,workspaceId:null,workspaceName:"OpenPond profile",localProjectId:null,cloudProjectId:null,cloudTeamId:null,cwd:null,autoTitlePrompt:Tr(pe)}),we(St=>[tt,...St]),X.onSessionCreated?.(tt),bt&&se(tt.id)),await J.runProfileAction(t,i7({action:kt,attachments:F,displayPrompt:pe,prompt:pn,sessionId:tt.id}));const Rn=await J.bootstrap(t);return e(Rn),yt(),!0}const gt=TC({cloudProjects:k,selectedCloudProject:T,selectedProject:z});if(!gt)throw new Error("Select a Project linked to an OpenPond Cloud Project before running an action.");let lt=Ve;(!lt||lt.cloudProjectId!==gt.id)&&(lt=await J.createSession(t,{provider:"openpond",modelRef:ja("openpond",je,Le),openPondCommandAccessMode:Fe("openpond",Ee),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:gt.id,workspaceName:gt.name,localProjectId:gt.localProjectId,cloudProjectId:gt.id,cloudTeamId:gt.teamId,cwd:null,autoTitlePrompt:Tr(pe)}),we(tt=>[lt,...tt]),X.onSessionCreated?.(lt),bt&&(se(lt.id),Se(gt.selectionKey),m(gt.selectionKey)));const Ct=await $(gt.id,gt.teamId);if(!Ct)throw new Error("No OpenPond Agent is available for this Project.");yt();const pa=await J.runSandboxAgent(t,Ct.id,s7({action:Ht,attachments:F,displayPrompt:pe,prompt:pn,teamId:gt.teamId})),Wn=await J.bootstrap(t);return e(Wn),xe(tt=>Mo(tt,vS({action:Ht,prompt:pe,runPayload:pa,sessionId:lt.id}))),!0}let ot=Ve;if(ot&&qt(ot.id)){Kn=P0({afterMessageId:sn.at(-1)?.id??null,attachments:F,content:G,sessionId:ot.id}),yt(),Bt=ot.id,st.current.add(Bt),ge?.(Kn),be?.(Bt,!0);const Ze=JZ(ot.id,G),kt=lt=>{(!Ne||D?.id===ot.id)&&he(Ct=>ZZ(Ct,lt)),X.onCodexHistoryOptimisticEvent?.(lt)};kt(Ze),ue(lt=>lt.map(Ct=>Ct.id===ot.id?{...Ct,status:"active"}:Ct));const gt=await J.sendCodexHistoryTurn(t,ot.id,{prompt:G,attachments:F.length>0?F:void 0,model:mv("codex",je,Le),modelRef:ja("codex",je,Le),...Fy(n),codexPermissionMode:n,codexReasoningEffort:a}).catch(lt=>{throw kt(YZ(Ze,lt)),lt});return(!Ne||D?.id===ot.id)&&he(lt=>Mo(lt,gt.events)),ue(lt=>bl(lt,gt.session)),ne?.(gt),Ge(t),!0}const Fa=(Lt?w.find(Ze=>Ze.id===Lt&&XK(oe,Ze)&&Ze.sandbox)??null:null)??e9(oe,G_(w)),Va=Ue==="chat"?[]:h9(oe,I).map(Ze=>Ze.ref);if(!ot){const Ze=xn?.appId??Qt?.id??null,kt=xn?.appName??Qt?.name??null,gt=Mn,lt=Ne?null:_a(zt,k),Ct=nn?q_({cloudProjects:k,selectedCloudProject:gt,selectedProject:zt}):null;if(Ct?.kind==="missing_cloud_project")throw new Error(Ct.message);const pa=Ct?.kind==="ready",Wn=pa?fe:gt?"openpond":fe,tt=ja(Wn,je,Le),Rn=Fe(Wn,Ee),St=pa?B_({modelRef:tt,provider:Wn,target:Ct,title:G.slice(0,64)}):null;ot=await J.createSession(t,St?{...St,subagentDelegationMode:le,metadata:{...St.metadata,...X.sessionMetadata??{}},...Rn?{openPondCommandAccessMode:Rn}:{},autoTitlePrompt:Tr(G)}:{experience:Ue,provider:Wn,modelRef:tt,subagentDelegationMode:le,...Rn?{openPondCommandAccessMode:Rn}:{},appId:Ze,appName:kt,workspaceKind:gt?"sandbox":zt?"local_project":Qt?"sandbox_app":void 0,workspaceId:zt?.id??(Qt?Ze:void 0),workspaceName:gt?.name??zt?.name??kt,localProjectId:zt?.id??null,cloudProjectId:gt?.id??lt?.id??null,cloudTeamId:gt?.teamId??lt?.teamId??null,...!gt&&!zt&&!Qt&&V==="local"?{metadata:{...MK(),...X.sessionMetadata??{}}}:{cwd:zt?zt.workspacePath:null,...X.sessionMetadata?{metadata:X.sessionMetadata}:{}},autoTitlePrompt:Tr(G)}),we(In=>[ot,...In]),X.onSessionCreated?.(ot),bt&&(se(ot.id),gt&&Se(vt("cloud",gt.id)),ot.workspaceKind==="local_project"&&ot.workspaceId&&m(vt("local",ot.workspaceId)),gt&&m(vt("cloud",gt.id)))}if(bS(ot)&&go(ot.workspaceKind)&&ot.provider!=="openpond"&&!vo(ot))throw new Error("Cloud workspaces use OpenPond Chat. Switch to Local to use local providers.");if(bS(ot)&&go(ot.workspaceKind)&&d)try{ot=await d(ot)}catch(Ze){const kt=Ze instanceof Error?Ze.message:String(Ze);throw await J.recordPreflightTurnFailure(t,ot.id,{prompt:G,error:kt,target:vo(ot)?"hybrid_sandbox":"cloud_workspace"}).then(e).catch(()=>{}),Ze}Kn=P0({afterMessageId:sn.at(-1)?.id??null,attachments:F,content:G,sessionId:ot.id}),yt(),Bt=ot.id,st.current.add(Bt),ge?.(Kn),we(Ze=>Ze.map(kt=>kt.id===Bt?{...kt,status:"active"}:kt));const ma=fe,Ka=GZ({provider:ma,model:je,providerSettings:Le}),ae=C3(ma,Ka.model??je,Le),Ke=ma==="codex"?Fy(n):{approvalPolicy:"on-request",sandbox:"workspace-write"};await J.sendTurn(t,ot.id,{prompt:G,metadata:X.turnMetadata,attachments:F.length>0?F:void 0,mentionedAppIds:Fa?[Fa.id]:void 0,mentionedConnectedApps:Va.length>0?Va:void 0,openPondActionCatalog:j.length>0?j:void 0,usageAttribution:ua,...Ka,...Ke,codexPermissionMode:ma==="codex"?n:"default",codexReasoningEffort:ae?a:void 0}),Ge(t);const ze=ot.workspaceId??ot.appId;return ze&&ot.workspaceKind!=="sandbox"&&ot.workspaceKind!=="sandbox_template"&&M(ze,!1).then(Ze=>{Ze?.initialized&&P(ze)}),!0}catch(ot){return ke(ot instanceof Error?ot.message:String(ot)),!1}finally{Bt&&st.current.delete(Bt),Bt&&qt(Bt)&&be?.(Bt,!1),Bt&&(qt(Bt)?ue(ot=>ot.map(wn=>wn.id===Bt&&wn.status==="active"?{...wn,status:"idle"}:wn)):we(ot=>ot.map(wn=>wn.id===Bt&&wn.status==="active"?{...wn,status:"idle"}:wn)))}}async function $e(F,_){const W=st.current.values().next().value??null,X=F??D?.id??W;if(!t||!X)return!1;if(ke(null),qt(X))try{const oe=await J.interruptCodexHistoryTurn(t,X);if(!oe.interrupted){if(oe.reason==="no_active_openpond_turn"){const pe=await J.codexHistoryThread(t,X,{tail:!0}),fe={...pe.session,status:"idle"};return D?.id===X&&he(je=>Mo(je,pe.events)),ue(je=>bl(je,fe)),ke("OpenPond no longer has a live interrupt handle for this Codex history turn. The chat was marked idle so you can send again."),!0}return ke("This Codex history turn is still starting. Try stopping it again in a moment."),!1}const G=await J.codexHistoryThread(t,X,{tail:!0});return D?.id===X&&he(pe=>Mo(pe,G.events)),ue(pe=>bl(pe,G.session)),!0}catch(oe){const G=oe instanceof Error?oe.message:String(oe);return ke(G==="Not found"?"OpenPond could not find this Codex history session, so it cannot interrupt it here.":G),!1}try{await J.interruptTurn(t,X,_);const oe=await J.bootstrap(t);return e(oe),!0}catch(oe){return ke(oe instanceof Error?oe.message:String(oe)),!1}}async function Xe(F,_){if(!t){ke("OpenPond App server is not connected.");return}ke(null),await J.applyCreateImproveAction(t,F.id,{..._,runId:F.id,expectedRevision:F.revision,actionId:`web:${_.type}:${crypto.randomUUID()}`});const W=await J.bootstrap(t);e(W)}async function et(F){await Xe(F.run,{type:"approve_plan"})}async function rt(F){await Xe(F.run,{type:"cancel",reason:null})}async function it(F,_){await Xe(F.run,{type:"revise_plan",revision:_})}async function Me(F,_,W){await Xe(F.run,{type:"answer_question",questionId:_,value:W})}async function Be(F){await Xe(F.run,{type:"pause"})}async function p(F){await Xe(F.run,{type:"resume"})}async function U(F,_){await Xe(F.run,{type:"open_pull_request",candidateId:_})}async function K(F,_){await Xe(F.run,{type:"apply_candidate",candidateId:_})}async function de(F,_){await Xe(F.run,{type:"reject_candidate",candidateId:_,reason:null})}async function re(F,_){await Xe(F.run,{type:"reconcile_pull_request",candidateId:_})}return{answerCreateImproveQuestion:Me,approveCreateImproveRun:et,applyCreateImproveCandidate:K,cancelCreateImproveRun:rt,changeDraftProvider:L,openCreateImprovePullRequest:U,pauseCreateImproveRun:Be,reconcileCreateImprovePullRequest:re,rejectCreateImproveCandidate:de,resumeCreateImproveRun:p,reviseCreateImproveRun:it,sendPrompt:_e,stopTurn:$e}}function bS(e){return e.experience==="development"||e.experience==="work"&&(e.workspaceKind==="local_project"||!!e.localProjectId||!!e.cloudProjectId||e.metadata?.workspaceTarget==="local")}async function XZ({branch:e,connection:t,session:n}){if(!go(n.workspaceKind))return{sandbox:null,session:n,status:"already_running"};const a=await J.ensureCloudWorkspaceReady(t,n.id,{branch:e,surface:"desktop"});return{bootstrap:await J.bootstrap(t),output:a.output,sandbox:null,session:a.session,status:a.status}}function eJ(e){return vo(e)?"Preparing Hybrid sandbox...":"Starting Cloud workspace..."}function tJ(e,t){if(e==="already_running")return null;const n=vo(t)?"Hybrid sandbox":"Cloud workspace";return e==="waited_for_creating"?`${n} is ready.`:e==="started"?`Started ${n}.`:e==="resumed"?`Resumed ${n}.`:e==="restored"?`Restored ${n}.`:`Recreated ${n}.`}function nJ(e,t){return!e.cloudProjectId||!e.cloudTeamId?!0:t.some(n=>n.id===e.cloudProjectId&&n.teamId===e.cloudTeamId)}function aJ({applyBootstrapPayload:e,cloudProjects:t,connection:n,localProjectById:a,selectedCloudProject:o,selectedProject:i,setWorkspaceBusy:s,showToast:l,visibleWorkspaceState:m}){return g.useCallback(async d=>{if(!n)throw new Error("OpenPond App server is not connected.");const h=i??(d.localProjectId?a.get(d.localProjectId)??null:null);if(d.cloudProjectId&&d.cloudTeamId&&!nJ(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(eJ(d),"info"),s(!0);try{const v=await XZ({branch:i?.linkedSandboxProject?.defaultBranch??o?.defaultBranch??m?.currentBranch??null,connection:n,localProject:h,session:d,source:vo(d)?"openpond-app-hybrid-chat-preflight":"openpond-app-cloud-chat-preflight"});v.bootstrap&&e(v.bootstrap);const y=tJ(v.status,d);return y&&l(y,"success"),v.session}finally{s(!1)}},[e,t,n,a,o,i,s,l,m?.currentBranch])}function oJ(){return{diffPanelOpen:!1,diffPanelExpanded:!1,rightPanelMode:"changes",rightChatPanels:[]}}function rJ(e){return{diffPanelOpen:e.diffPanelOpen,diffPanelExpanded:e.diffPanelExpanded,rightPanelMode:e.rightPanelMode,rightChatPanels:e.rightChatPanels}}function yS(e){return{...e,rightChatPanels:e.rightChatPanels.map(t=>({...t}))}}function iJ(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 sJ(e){return`${e.conversationId}\0${e.workspaceSourceKey||"none"}`}function lJ(e){const{appDispatch:t,diffPanelExpanded:n,diffPanelOpen:a,rightChatPanels:o,rightPanelMode:i,selectedAppId:s,selectedCloudProject:l,selectedProjectId:m,selectedSession:d,selectedSessionId:h,setWorkspaceDiffPanelViewState:v,view:y,viewWorkspaceAppId:w,viewWorkspaceId:I,viewWorkspaceKind:R,workspaceDiffPanelViewState:M}=e,P=g.useRef(new Map),N=g.useRef(new Map),O=g.useRef(null),j=g.useRef(null),k=h??`draft:${m??s??l?.id??"general"}`,C=g.useMemo(()=>I?`${R??"workspace"}:${I}`:w?`app:${w}`:d?.cwd&&!go(d.workspaceKind)?`cwd:${d.cwd}`:"none",[d?.cwd,d?.workspaceKind,y,w,I,R]),T=sJ({conversationId:k,workspaceSourceKey:C}),z=g.useMemo(()=>rJ({diffPanelExpanded:n,diffPanelOpen:a,rightChatPanels:o,rightPanelMode:i}),[n,a,o,i]);g.useEffect(()=>{const D=O.current;D&&P.current.set(D,yS(z))},[k,z]),g.useEffect(()=>{if(O.current===k)return;O.current=k;const V=P.current.get(k)??oJ();iJ(z,V)||t({type:"patch",patch:yS(V)})},[k,z]),g.useEffect(()=>{const D=j.current;D&&N.current.set(D,Wp(M))},[T,M]),g.useEffect(()=>{if(j.current===T)return;j.current=T;const V=N.current.get(T)??F_();v(le=>g0(le,V)?le:Wp(V))},[T]);const B=g.useCallback(D=>{v(V=>g0(V,D)?V:Wp(D))},[]);return{browserConversationId:k,handleWorkspaceDiffPanelViewStateChange:B}}function cJ({account:e,accountPending:t,accountSignedOut:n,activeWorkspaceKind:a,activeWorkspaceLocation:o,appDispatch:i,applyBootstrapPayload:s,busy:l,cloudSetupDialog:m,cloudProjects:d,connection:h,defaultTeamId:v,expandProject:y,localProjectById:w,selectedCloudProject:I,selectedProject:R,selectedSession:M,selectedSessionProjectId:P,setCloudSetupDialog:N,setDiffPanelOpen:O,setError:j,setSessions:k,setWorkspaceBusy:C,showToast:T,visibleWorkspaceState:z,workspaceBusy:B}){const D=e?.baseUrl??e?.activeProfile?.baseUrl??null,V=g.useCallback(async(Z,Ae)=>{if(h)try{const he=await J.previewLocalProjectCloudSource(h,Z.id,{branch:Ae});N(ue=>!ue||ue.status!=="confirm"||ue.localProjectId!==Z.id||ue.branch!==Ae?ue:{...ue,branch:he.preview.branch,cloudProjectId:he.preview.targetProjectId,preview:he.preview,previewLoading:!1,previewError:null})}catch(he){const ue=he instanceof Error?he.message:String(he);N(be=>!be||be.status!=="confirm"||be.localProjectId!==Z.id||be.branch!==Ae?be:{...be,preview:null,previewLoading:!1,previewError:ue})}},[h,N]),le=g.useCallback(async()=>{const Z=m;if(!Z||Z.status==="uploading")return;if(Z.projectKind==="cloud"){N(be=>be&&{...be,status:"ready",error:null});return}if(!h){N(be=>be&&{...be,status:"error",error:"OpenPond App server is not connected."});return}const Ae=Z.localProjectId??"",he=w.get(Ae);if(!he){N(be=>be&&{...be,status:"error",error:"Project is no longer available."});return}C(!0);const ue=_a(he,d);N(be=>be&&{...be,status:"uploading",error:null,previewLoading:!1});try{const be=await J.organizations(h),ne=Vu(be.organizations.map(Uu).filter(Oe=>!!Oe).filter(Oe=>Oe.status==="active"),v);if(!ne)throw new Error("Add an OpenPond account before creating a Cloud environment.");if(!Fu(ne))throw new Error(`You need owner or admin access to create projects in ${ne.displayName}.`);const ge=Z.branch||he.linkedSandboxProject?.defaultBranch||"main",xe=vt("local",he.id),qe=await J.createSession(h,{provider:"openpond",appId:null,appName:null,workspaceKind:"local_project",workspaceId:he.id,workspaceName:he.name,localProjectId:he.id,cloudProjectId:ue?.id??null,cloudTeamId:ue?.teamId??null,cwd:he.workspacePath,title:`Sync ${he.name} to Cloud`});k(Oe=>[qe,...Oe]),i({type:"selectSession",sessionId:qe.id,projectId:xe}),y(xe);const Se=await J.uploadLocalProjectCloudSource(h,he.id,{teamId:ne.teamId,projectName:he.name,branch:ge,chatSessionId:qe.id,displayPrompt:`/sync-cloud ${he.name}`});s(Se.bootstrap),y(xe),y(vt("cloud",Se.project.id));const se=vh({accountBaseUrl:D,teamId:Se.project.teamId,projectId:Se.project.id,projectName:Se.project.name,baseBranch:Se.upload.branch,localProjectId:he.id,source:"openpond-app"}),we=fS({accountBaseUrl:D,organizationSlug:Se.project.organizationSlug,projectSlug:Se.project.slug});N({status:"ready",localProjectId:he.id,cloudProjectId:Se.project.id,teamId:Se.project.teamId,projectName:Se.project.name,projectKind:"local",projectUrl:we,setupUrl:se,branch:Se.upload.branch,preview:Z.preview??null,previewLoading:!1,previewError:null,upload:{branch:Se.upload.branch,headCommit:Se.upload.headCommit,fileCount:Se.upload.fileCount,byteCount:Se.upload.byteCount,skippedCount:Se.upload.skippedCount,initializedEmptyProject:Se.upload.initializedEmptyProject},error:null}),T("Source uploaded to OpenPond Git. Cloud setup link is ready.","success")}catch(be){const ne=be instanceof Error?be.message:String(be),ge=h?await J.bootstrap(h).catch(()=>null):null;ge&&s(ge),j(ne),N(xe=>xe&&{...xe,status:"error",error:ne})}finally{C(!1)}},[D,i,s,m,d,h,v,y,w,N,j,k,C,T]),te=g.useCallback((Z,Ae)=>{if(!h){T("OpenPond App server is not connected.","error");return}if(t){T("Checking OpenPond account. Try again in a moment.","info");return}if(n){T("Add an OpenPond account before using Cloud.","error");return}const he=Ae||Z.linkedSandboxProject?.defaultBranch||"main";N({status:"confirm",localProjectId:Z.id,projectName:Z.name,projectKind:"local",projectUrl:null,setupUrl:null,branch:he,preview:null,previewLoading:!0,previewError:null,upload:null,error:null}),V(Z,he)},[t,n,h,V,N,T]),Ie=g.useCallback(async Z=>{if(Z===o||B||l)return;if(j(null),Z==="upload_cloud"){if(!R){T("Select a local Project before uploading source.","error");return}te(R,z?.currentBranch??null);return}if(Z==="local"){const ue=M?.localProjectId??R?.id??P??null,be=ue?w.get(ue)??null:null;if(!be){T("No linked local workspace for this Cloud chat.","error");return}if(go(a)&&!window.confirm("Switch to Local? Cloud changes will stay in the hosted workspace until you preserve or export them."))return;const ne=vt("local",be.id);i({type:"selectProject",projectId:ne}),y(ne),O(!1),T(`Switched to Local: ${be.name}`,"info");return}if(!h){T("OpenPond App server is not connected.","error");return}if(t){T("Checking OpenPond account. Try again in a moment.","info");return}if(n){T("Add an OpenPond account before using Cloud.","error");return}if(I){N({status:"ready",cloudProjectId:I.id,teamId:I.teamId,projectName:I.name,projectKind:"cloud",projectUrl:fS({accountBaseUrl:D,organizationSlug:I.organizationSlug,projectSlug:I.slug}),setupUrl:vh({accountBaseUrl:D,teamId:I.teamId,projectId:I.id,projectName:I.name,baseBranch:I.defaultBranch,source:"openpond-app"}),branch:I.defaultBranch??"main",preview:null,previewLoading:!1,previewError:null,upload:null,error:null});return}const Ae=R;if(!Ae){T("Select a Project before Cloud coding.","error");return}const he=z?.currentBranch||Ae.linkedSandboxProject?.defaultBranch||"main";te(Ae,he)},[D,t,n,a,o,i,l,h,d,y,w,te,I,R,M,P,N,O,j,T,z?.currentBranch,B]),ke=g.useCallback(Z=>{dv(Z)&&te(Z.project)},[te]);return{changeWorkspaceTarget:Ie,moveProjectToCloud:ke,openCloudSetupForLocalProject:te,startCloudSetupUpload:le}}function dJ({advanceTrainingTurn:e,bindTrainingSession:t,composerDraftStore:n,onSessionCreated:a,onSubmitted:o,prepareTrainingTurn:i,sendPrompt:s,setMentionedAppId:l,showToast:m}){return g.useCallback(async(d=[],h=null,v,y={})=>{const w=v??n.getSnapshot(),I=i(w);if(I.active&&w.trim()&&!I.metadata)return m(I.error??"Load the selected generated Taskset question before sending, or close the generated-question handoff to write a normal prompt.","error"),!1;const R=await s(d,h,v,{clearPrompt:y.preservePrompt?()=>{}:void 0,displayPrompt:y.displayPrompt,onSessionCreated:M=>{a(M),I.metadata&&t(M.id)},turnMetadata:I.metadata||y.turnMetadata?{...I.metadata??{},...y.turnMetadata??{}}:void 0,sessionMetadata:I.metadata?{trainingTasksetId:I.metadata.trainingTasksetId,trainingTasksetName:I.metadata.trainingTasksetName}:void 0});return R&&await o?.(),R&&I.metadata&&e(),R},[e,t,n,a,o,i,s,l,m])}function uJ({appDispatch:e,connection:t,sessions:n,setDiffPanelOpen:a,setRightPanelMode:o,setSessions:i,setView:s}){return g.useCallback(async l=>{if(!t)return;const m=n.find(v=>!v.archived&&v.workspaceKind==="sandbox"&&v.workspaceId===l.sandboxId);if(m){e({type:"selectSession",sessionId:m.id,appId:null,projectId:null}),o("changes"),a(!0),s("chat");return}const d=l.name??`Sandbox ${l.sandboxId.slice(0,8)}`,h=await J.createSession(t,{provider:"openpond",appId:null,appName:null,workspaceKind:"sandbox",workspaceId:l.sandboxId,workspaceName:d,cwd:null,title:d});i(v=>[h,...v]),e({type:"selectSession",sessionId:h.id,appId:null,projectId:null}),o("changes"),a(!0),s("chat")},[e,t,n,a,o,i,s])}function mJ({connection:e,defaultTeamId:t,sessions:n,selectedProjectId:a,confirmProjectAction:o,openExistingProjectDialog:i,applyBootstrapPayload:s,expandProject:l,setExpandedProjectIds:m,setSelectedAppId:d,setSelectedProjectId:h,setSelectedSessionId:v,setError:y,setView:w,showToast:I}){function R(k){const C=vt("local",k.id);d(null),h(C),v(null),w("chat"),l(C)}async function M(k){if(!e)return!1;y(null);const C=k.trim();if(!C)return!1;try{const T=await J.createLocalProject(e,{path:C});return s(T.bootstrap),R(T.project),I(T.created===!1?`Opened ${T.project.name}`:`Added ${T.project.name}`,"success"),!0}catch(T){return y(T instanceof Error?T.message:String(T)),I("Project folder could not be added","error"),!1}}async function P(){if(e){if(y(null),window.openpond?.selectFolder){const k=await window.openpond.selectFolder();if(k.canceled||!k.path)return;await M(k.path);return}i()}}async function N(k){if(!e)return!1;const C=k.trim();if(!C)return!1;y(null);try{const T=await J.createLocalProject(e,{createNew:!0,name:C});return s(T.bootstrap),R(T.project),I(`Created ${T.project.name}`,"success"),!0}catch(T){return y(T instanceof Error?T.message:String(T)),I("Project could not be created","error"),!1}}async function O(k){if(!e)return!1;const C=k.trim();if(!C)return!1;y(null);try{const T=await J.organizations(e),z=Vu(T.organizations.map(Uu).filter(te=>!!te).filter(te=>te.status==="active"),t);if(!z)throw new Error("Add an OpenPond account before creating a Cloud Project.");if(!Fu(z))throw new Error(`You need owner or admin access to create projects in ${z.displayName}.`);const B=`${V_(C)}-${Date.now().toString(36)}`;let D=(await J.upsertSandboxProject(e,{teamId:z.teamId,name:C,sourceType:"internal_repo",normalizedSourceIdentity:B,internalRepoPath:B,defaultBranch:"main",sourceConfig:{sourceType:"internal_repo",sourceValue:B},metadata:{source:"openpond-app-new-cloud-project"}})).project;D=(await J.uploadSandboxProjectSource(e,D.id,{teamId:z.teamId,branch:"main",commitMessage:"Initialize cloud project",entries:[{path:"README.md",type:"file",contentsBase64:BK(`# ${C}
|
|
211
|
+
|
|
212
|
+
Created in OpenPond Cloud.
|
|
213
|
+
`)}]})).project;const V=await J.bootstrap(e);s(V);const le=vt("cloud",D.id);return d(null),h(le),v(null),w("chat"),l(le),I(`Created Cloud Project: ${D.name}`,"success"),!0}catch(T){const z=T instanceof Error?T.message:String(T);return y(z),I(z,"error"),!1}}async function j(k){if(!e)return;if(k3(k)){const B=`Archive ${k.project.name} in OpenPond Cloud?`;if(!(o?await o({title:"Archive Cloud Project",body:`${k.project.name} will be archived in OpenPond Cloud. Existing task history stays available through Cloud history.`,confirmLabel:"Archive project"}):window.confirm(B)))return;y(null);try{await J.archiveSandboxProject(e,k.project.id,{teamId:k.project.teamId}),s(await J.bootstrap(e)),m(V=>{const le=new Set(V);return le.delete(k.id),le}),a===k.id&&(h(null),v(null)),I(`Archived ${k.project.name}`,"success")}catch(V){y(V instanceof Error?V.message:String(V)),I("Cloud Project could not be archived","error")}return}if(!dv(k))return;const C=k.project,T=`Remove ${C.name} from Projects? The folder will not be deleted.`;if(o?await o({title:"Remove Project",body:`${C.name} will be removed from the sidebar. The folder and files on disk will not be deleted.`,confirmLabel:"Remove project"}):window.confirm(T)){y(null);try{const B=await J.deleteLocalProject(e,C.id);s(B),m(D=>{const V=new Set(D);return V.delete(k.id),V}),a===k.id&&(h(null),v(D=>{const V=n.find(le=>le.id===D);return V?.workspaceKind==="local_project"&&V.workspaceId===C.id?null:D})),I(`Removed ${C.name}`,"success")}catch(B){y(B instanceof Error?B.message:String(B)),I("Project could not be removed","error")}}}return{addProjectFolder:P,addProjectFolderPath:M,createCloudProjectFromScratch:O,createProjectFromScratch:N,removeProject:j}}function pJ({addProjectFolder:e,addProjectFolderPath:t,appDispatch:n,busy:a,cloudProjectById:o,createCloudProjectFromScratch:i,createProjectFromScratch:s,expandProject:l,localProjectById:m,onCreateCloudEnvironment:d,onNewCloudProject:h,onNewLocalProject:v,onUseExistingFolderPath:y,newProjectBusy:w,newProjectMode:I,newProjectName:R,newProjectPath:M,projectTargetValue:P,setDiffPanelOpen:N,setDraftModel:O,setDraftProvider:j,setError:k,setNewProjectBusy:C,setNewProjectDialogOpen:T,setNewProjectName:z,setNewProjectPath:B,showToast:D,workspaceBusy:V}){const le=g.useCallback(Ie=>{if(Ie===P||a||V)return;if(k(null),Ie==="action:new-local-project"){v();return}if(Ie==="action:add-local-project"){e();return}if(Ie==="action:add-local-project-path"){y();return}if(Ie==="action:new-cloud-project"){h();return}if(Ie==="action:create-cloud-environment"){d();return}if(Ie==="none"){n({type:"selectProject",projectId:null}),N(!1),D("Started a chat without project files.","info");return}const ke=Ie.indexOf(":"),Z=ke>=0?Ie.slice(0,ke):"",Ae=ke>=0?Ie.slice(ke+1):"";if(Z==="local"){const he=m.get(Ae);if(!he){D("Project is no longer available.","error");return}const ue=vt("local",he.id);n({type:"selectProject",projectId:ue}),l(ue),N(!1);return}if(Z==="cloud"){const he=o.get(Ae);if(!he){D("Cloud Project is no longer available.","error");return}const ue=vt("cloud",he.id);n({type:"selectProject",projectId:ue}),l(ue),j("openpond"),O(be=>br("openpond",be)),N(!1)}},[e,n,a,o,l,m,d,h,v,y,P,N,O,j,k,D,V]),te=g.useCallback(async()=>{const Ie=R.trim(),ke=M.trim();if(!w&&!(I==="existing-local"?!ke:!Ie)){C(!0);try{(I==="cloud"?await i(Ie):I==="existing-local"?await t(ke):await s(Ie))&&(T(!1),z(""),B(""))}finally{C(!1)}}},[t,i,s,w,I,R,M,C,T,z,B]);return{changeProjectTarget:le,submitNewProjectDialog:te}}function fJ(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 WQ(e){return e.reduce((t,n)=>!t||n.activationVersion>=t.activationVersion?n:t,null)}function hJ(e,t){const n=Math.max(0,...e.map(i=>i.activationVersion))+1;let a=!1;const o=e.map(i=>i.id!==t?i:(a=!0,{...i,activationVersion:n}));return a?o:[...e]}function gJ(e,t){const n=Math.max(0,...e.map(i=>i.activationVersion))+1;let a=!1;const o=e.map(i=>i.sessionId!==t.sessionId?i:(a=!0,{...i,activationVersion:n,prompt:t.prompt??i.prompt}));return a?o:[...e]}function VC(e){return!!(e.parentSessionId&&e.subagentRunId)}function vJ(e){const t=e.sessions.filter(VC);return{knownSessionIds:new Set(t.map(n=>n.id)),newSessions:t.filter(n=>!e.knownSessionIds.has(n.id))}}function bJ(e,t){const n=new Set(e.map(o=>o.sessionId).filter(Boolean)),a=t.filter(VC).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 SS="openpond/openpond",yJ="github.issue.write";function SJ(e){return e.some(t=>t.provider==="github"&&(t.ref.capabilities??[]).includes(yJ))}function GQ(e){return[`Title: ${e.title.trim()}`,"","Description:",e.description.trim()].join(`
|
|
214
|
+
`)}function kJ(e){const t=e.trim();return[`@github Submit this request as a new GitHub issue in ${SS}.`,`Use the GitHub connected app write operation github.issue.create with input.repo set to ${SS}, a concise title, and a complete issue body that preserves the request.`,"This slash command is the user's explicit intent to create the issue.","Before creating, search open issues in the repository for an obvious duplicate. If a clear duplicate exists, do not create a new issue; report the existing issue instead.","",`Issue request:
|
|
215
|
+
${t}`].join(`
|
|
216
|
+
`)}function xJ(e,t){const n=t.trim();switch(e.id){case"agent":return{kind:"send_prompt",prompt:`/agent ${n}`,requiresInstructions:!0};case"skill":return{kind:"send_prompt",prompt:`/skill ${n}`,requiresInstructions:!1};case"goal":return{kind:"send_prompt",prompt:`/goal ${n}`,requiresInstructions:!0};case"workflow":return{kind:"send_prompt",prompt:["Create a scheduled workflow attached to this chat.","Use the schedule_work tool after resolving the exact cadence, local date/time, and timezone from my request. Ask a concise clarification only if a required scheduling detail is genuinely missing.",`Workflow request: ${n}`].join(`
|
|
217
|
+
|
|
218
|
+
`),requiresInstructions:!0};case"train":return{kind:"open_training",objective:n||null};case"submit-issue":return{kind:"send_prompt",prompt:kJ(n),requiresInstructions:!0};case"sync-cloud":return{kind:"send_prompt",prompt:`/sync-cloud ${n}`,requiresInstructions:!1}}}const kS=[];function wJ(e){const{approvals:t,codexHistoryEvents:n,contextCompaction:a,pendingChatUserMessages:o,rightChatHistoryEvents:i,rightChatPanels:s,runningSessionIds:l,selectedSessionId:m,sidebarSessions:d}=e;return g.useMemo(()=>{const h=new Map(d.map(y=>[y.id,y])),v=IJ(t);return s.map(y=>{const w=y.sessionId?h.get(y.sessionId)??null:null,I=qt(y.sessionId),R=I?(y.sessionId?i[y.sessionId]:void 0)??(y.sessionId===m?n:kS):kS,M=oh(R,[]),P=y.sessionId?v.get(y.sessionId)??null:null,N=!!(w&&l.has(w.id)),O=I?YV({events:R}):null,j=w?.cwd??null,k=w?.appId??w?.localProjectId??(w?.workspaceKind==="local_project"?w.workspaceId??null:null)??(w?.cwd&&!go(w.workspaceKind)?Qk(w.cwd):null),C=y.sessionId?o[y.sessionId]??null:null;return{...y,session:w,title:QV(O,w?.title??"New task"),messages:I?aC(qu(R),C):[],createImproveRun:O,contextWindowStatus:k_({provider:y.provider,snapshot:D_(M,y.sessionId),preferences:a}),goalRuntime:L_(M,y.sessionId),pendingApproval:P,running:N,workspaceRootPath:j,activeWorkspaceAppId:k,pendingUserMessage:C,runtimeSource:I?"history":"live"}})},[t,n,a,o,i,s,l,m,d])}function IJ(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 _J(e){const{applyPayload:t,connection:n,locallyActiveSessionIds:a,panels:o,sessions:i,setError:s}=e,l=g.useMemo(()=>{const h=new Set,v=[];for(const y of o)!qt(y.sessionId)||!y.sessionId||h.has(y.sessionId)||(h.add(y.sessionId),v.push(y.sessionId));return v.join(`
|
|
219
|
+
`)},[o]),m=g.useMemo(()=>{if(!l)return"";const h=new Set(l.split(`
|
|
220
|
+
`).filter(Boolean));return i.filter(v=>h.has(v.id)&&v.status==="active").map(v=>v.id).join(`
|
|
221
|
+
`)},[l,i]),d=g.useMemo(()=>l?l.split(`
|
|
222
|
+
`).filter(h=>a.has(h)).join(`
|
|
223
|
+
`):"",[a,l]);g.useEffect(()=>{if(!n||!l)return;const h=l.split(`
|
|
224
|
+
`).filter(Boolean),v=new Set(m.split(`
|
|
225
|
+
`).filter(Boolean)),y=new Set(d.split(`
|
|
226
|
+
`).filter(Boolean)),w=h.map(I=>xv({connection:n,locallyActive:y.has(I),onError:R=>s(R instanceof Error?R.message:String(R)),onPayload:R=>t(kv(R,y.has(I))),reportedActive:v.has(I),sessionId:I,surface:"thread"}));return()=>w.forEach(I=>I())},[m,t,n,d,l,s])}const xS=[];function CJ(e){const{activeModel:t,activeProvider:n,approvals:a,applyRightCodexHistoryPayload:o,codexHistoryEvents:i,connectedAppMentions:s,connection:l,contextCompaction:m,openLabTraining:d,locallyActiveCodexHistorySessionIds:h,openPondCommandAccessMode:v,pendingChatUserMessages:y,providerSettings:w,rightChatHistoryEvents:I,rightChatPanels:R,rightPanelMode:M,runtimeIndexes:P,runtimeEventStore:N,runningSessionIds:O,selectedSession:j,selectedSessionId:k,sendPrompt:C,setDiffPanelOpen:T,setError:z,setRightChatHistoryEvents:B,setRightChatPanels:D,setRightPanelMode:V,setRightPanelTabRequest:le,setView:te,showChangesPanel:Ie,showToast:ke,sidebarSessions:Z,startupReady:Ae}=e,he=g.useRef(null),ue=g.useRef(new Map),be=g.useRef(new Set);g.useEffect(()=>{if(!l)return;const Le=R.flatMap(Fe=>Fe.sessionId&&!qt(Fe.sessionId)?[Fe.sessionId]:[]);for(const Fe of Le)Object.hasOwn(I,Fe)||be.current.has(Fe)||(be.current.add(Fe),J.runtimeEventsPage(l,{sessionId:Fe,beforeSequence:Number.MAX_SAFE_INTEGER,limit:500}).then(De=>{const L=De.events.map($=>$.event);B($=>({...$,[Fe]:Oo($[Fe]??xS,L)}))}).catch(De=>{z(De instanceof Error?De.message:String(De))}).finally(()=>{be.current.delete(Fe)}))},[l,I,R,z,B]);const ne=g.useCallback(Le=>{le(Fe=>({id:(Fe?.id??0)+1,tab:Le})),Ie()},[Ie]),ge=g.useCallback((Le=null,Fe={})=>{const De=Le?.id?R.find($=>$.sessionId===Le.id)??null:null;if(De)return D($=>gJ($,{sessionId:Le.id,prompt:Fe.prompt})),T(!0),V("chat"),Fe.preserveView||te("chat"),De.id;const L=fJ({sessionId:Le?.id??null,provider:Le?.provider??n,model:Le?.modelRef?.modelId??t,prompt:Fe.prompt});return D($=>[...$,L]),T(!0),V("chat"),Fe.preserveView||te("chat"),L.id},[t,n,R,T,D,V,te]);g.useEffect(()=>{if(!Ae)return;const Le=he.current;if(!Le){he.current=new Set(Z.filter($=>!!($.parentSessionId&&$.subagentRunId)).map($=>$.id));return}const Fe=vJ({sessions:Z,knownSessionIds:Le});he.current=Fe.knownSessionIds;for(const $ of Fe.newSessions)ue.current.set($.id,$);const De=j?.parentSessionId??j?.id??null;if(!De)return;const L=[...ue.current.values()].filter($=>$.parentSessionId===De);if(L.length!==0){for(const $ of L)ue.current.delete($.id);D($=>bJ($,L)),T(!0),V("chat")}},[j?.id,j?.parentSessionId,T,D,V,Z,Ae]);const xe=g.useCallback(()=>{if(R.length===0){ge(null);return}T(!0),V("chat"),te("chat")},[ge,R.length,T,V,te]),qe=g.useCallback(Le=>{const Fe=R.length<=1&&R.some(L=>L.id===Le),De=()=>{D(L=>L.filter($=>$.id!==Le))};if(Fe&&M==="chat"){if(ne("files"),typeof window>"u"){De();return}window.requestAnimationFrame(De);return}De()},[R,M,D,ne]),Se=g.useCallback((Le,Fe)=>{D(De=>De.map(L=>L.id===Le?{...L,prompt:Fe}:L))},[D]),se=g.useCallback(Le=>{D(Fe=>hJ(Fe,Le))},[D]),we=g.useCallback((Le,Fe)=>{D(De=>De.map(L=>L.id===Le?{...L,...Fe}:L))},[D]),Oe=g.useCallback((Le,Fe)=>{D(De=>De.map(L=>L.id===Le?{...L,model:Fe}:L))},[D]),Qe=g.useCallback((Le,Fe)=>{D(De=>De.map(L=>L.id===Le?{...L,provider:Fe,model:br(Fe,L.model,w)}:L))},[w,D]);_J({applyPayload:o,connection:l,locallyActiveSessionIds:h,panels:R,sessions:Z,setError:z});const Ge=wJ({approvals:a,codexHistoryEvents:i,contextCompaction:m,pendingChatUserMessages:y,rightChatHistoryEvents:I,rightChatPanels:R,runningSessionIds:O,selectedSessionId:k,sidebarSessions:Z}),st=g.useCallback(async(Le,Fe=[],De=null,L=null,$={})=>{const H=R.find(it=>it.id===Le);if(!H)return!1;const Q=$.promptOverride??H.prompt,me=L?xJ(L,Q):null;if(me?.kind==="open_training")return Fe.length>0?(ke("/train uses this chat; add other chats from Models.","error"),!1):(d({objective:me.objective,sessionId:H.sessionId}),$.preservePrompt||Se(Le,""),!0);if(L&&me?.kind==="send_prompt"&&me.requiresInstructions&&!Q.trim())return ke(`Add instructions after ${L.command}.`,"info"),!1;if(L&&Fe.length>0)return ke(`${L.command} tasks do not accept attachments yet. Add file context in the task thread.`,"error"),!1;if(L?.id==="submit-issue"&&!SJ(s))return ke("Connect the GitHub app before using /submit-issue.","error"),!1;const _e=H.sessionId?Z.find(it=>it.id===H.sessionId)??null:null,$e=H.provider==="codex"?v:_e?.openPondCommandAccessMode??v,Xe=me?.kind==="send_prompt"?me.prompt:Q,et=qt(H.sessionId)?(H.sessionId?I[H.sessionId]:void 0)??(H.sessionId===k?i:xS):N.getSessionEvents(H.sessionId),rt=qt(H.sessionId)&&H.sessionId?it=>{const Me=H.sessionId;B(Be=>({...Be,[Me]:Oo(Be[Me]??et,[it])}))}:void 0;return C(Fe,De,Xe,{session:_e,selectSession:!1,provider:H.provider,model:H.model,openPondCommandAccessMode:$e,chatMessages:qu(et),displayPrompt:$.displayPrompt,turnMetadata:$.turnMetadata,usageAttribution:L?.id==="submit-issue"?{surface:"chat",workflowKind:"slash_command",commandName:L.command,commandSource:"composer_selection"}:void 0,onCodexHistoryOptimisticEvent:rt,clearPrompt:$.preservePrompt?()=>{}:()=>Se(Le,""),onSessionCreated:it=>{D(Me=>Me.map(Be=>Be.id===Le?{...Be,sessionId:it.id,provider:it.provider,model:it.modelRef?.modelId??Be.model}:Be))}})},[i,s,I,R,P,N,k,d,v,C,D,te,Z,ke,Se]);return{activateRightChatPanel:se,closeRightChatPanel:qe,openRightChatPanel:ge,rightChatPanelViews:Ge,showRightChatPanel:xe,showRightPanelDiffTab:ne,submitRightChatPrompt:st,updateRightChatModel:Oe,updateRightChatPrompt:Se,updateRightChatProvider:Qe,updateRightChatScrollState:we}}function RJ(e){const{appPreferences:t,connection:n,selectedSessionId:a,setAppPreferences:o,setCodexHistorySessions:i,setError:s,setSelectedSessionId:l,setSessions:m}=e;async function d(P,N){if(!n)return;const O=t[P]??{},j={...O,...N,archived:N.pinned?!1:N.archived??O.archived};o(k=>({...k,[P]:j}));try{const k=await J.patchSidebarAppPreference(n,P,N);o(C=>({...C,[P]:k}))}catch(k){s(k instanceof Error?k.message:String(k)),o(C=>({...C,[P]:O}))}}function h(P){d(P.id,{pinned:!P.pinned,archived:!1})}async function v(P,N){if(!n)return;const O=qt(P.id)?i:m,j={...P,...N};O(k=>k.some(C=>C.id===P.id)?k.map(C=>C.id===P.id?j:C):[j,...k]);try{const k=await J.patchSession(n,P.id,N);O(C=>C.some(T=>T.id===k.id)?C.map(T=>T.id===k.id?k:T):[k,...C])}catch(k){s(k instanceof Error?k.message:String(k)),O(C=>C.map(T=>T.id===P.id?P:T))}}function y(P){v(P,{pinned:!1,savedForLater:!P.savedForLater,archived:!1})}function w(P){v(P,{pinned:!P.pinned,savedForLater:!1,archived:!1})}function I(P){v(P,{pinned:!1,savedForLater:!1,archived:!0}),a===P.id&&l(null)}function R(P){v(P,{archived:!1})}function M(P,N){const O=N.trim();!O||O===P.title||v(P,{title:O})}return{archiveSession:I,renameSession:M,restoreSession:R,toggleProjectPinned:h,toggleSessionPinned:w,toggleSessionSavedForLater:y}}function PJ(e){return e.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,72)||"new-branch"}function AJ({connection:e,activeWorkspaceAppId:t,appDefaults:n,bootstrap:a,branchDialogName:o,commitIncludeUnstaged:i,commitMessage:s,commitNextStep:l,draftModel:m,draftProvider:d,cloudProjects:h,selectedApp:v,selectedProject:y,selectedProjectLinkedOpenPondApp:w,selectedSession:I,sessions:R,title:M,visibleWorkspaceDiff:P,visibleWorkspaceState:N,workspaceBusy:O,workspaceName:j,appDispatch:k,applyBootstrapPayload:C,expandProject:T,refreshWorkspace:z,refreshWorkspaceDiff:B,rememberWorkspaceState:D,setBranchDialogOpen:V,setCommitDialogOpen:le,setError:te,setSessions:Ie,setSettingsSection:ke,setSyncingWorkspaceAppId:Z,setView:Ae,setWorkspaceBusy:he,showToast:ue}){function be(){return`${XI(n.defaultBranchPrefix)}${PJ(j??M??"new-branch")}`}function ne(){return j?`Update ${j}`:(P?.filesChanged??N?.changedFilesCount??0)===1?"Update workspace file":"Update workspace files"}function ge(De="commit"){k({type:"openCommitDialog",nextStep:De})}function xe(){k({type:"openBranchDialog",branchName:be()})}function qe(){O||V(!1),ke("configuration"),Ae("settings"),cn({kind:"settings",section:"configuration"})}async function Se(De){if(!(!e||!t)){he(!0),te(null);try{const L=await J.checkoutWorkspaceBranch(e,t,{branch:De});D(L),L.initialized&&B(t)}catch(L){te(L instanceof Error?L.message:String(L))}finally{he(!1)}}}async function se(){if(!e||!t)return;const De=o.trim();if(De){he(!0),te(null);try{const L=await J.createWorkspaceBranch(e,t,{branch:De});D(L),L.initialized&&B(t),V(!1),ue(`Checked out ${De}`,"success")}catch(L){te(L instanceof Error?L.message:String(L))}finally{he(!1)}}}async function we(De){Z(De);const L=a?.apps.find($=>$.id===De)?.name??a?.localProjects.find($=>$.id===De)?.name??"Workspace";try{const $=await z(De,!0);$?.initialized&&De===t&&B(De),$?.initialized&&!$.error?ue(`${L} synced locally`,"success"):$?.error&&ue("Workspace sync failed","error")}finally{Z($=>$===De?null:$)}}async function Oe(){t&&await we(t)}async function Qe(De,L,$={}){if(!e)return null;const H=I&&!qt(I.id)?I:null;if(jJ(L,H,$)||H&&TJ(H,y,v))return H;const Q=H?await Ge(H):null;if(Q)return Q;const me=EJ(R,y,v);if(me){const et=me.workspaceKind==="local_project"&&me.workspaceId?vt("local",me.workspaceId):null;return k({type:"selectSession",sessionId:me.id,appId:me.appId,projectId:et}),me.workspaceKind==="local_project"&&me.workspaceId&&T(vt("local",me.workspaceId)),me}const _e=_a(y,h),$e=await J.createSession(e,{provider:d,modelRef:ja(d,m,a?.providers??null),appId:w?.appId??v?.id??null,appName:w?.appName??v?.name??null,workspaceKind:y?"local_project":v?"sandbox_app":void 0,workspaceId:y?.id??v?.id??null,workspaceName:y?.name??v?.name??null,localProjectId:y?.id??null,cloudProjectId:_e?.id??null,cloudTeamId:_e?.teamId??null,cwd:y?y.workspacePath:null,title:De});Ie(et=>[$e,...et]);const Xe=$e.workspaceKind==="local_project"&&$e.workspaceId?vt("local",$e.workspaceId):null;return k({type:"selectSession",sessionId:$e.id,appId:$e.appId,projectId:Xe}),$e.workspaceKind==="local_project"&&$e.workspaceId&&T(vt("local",$e.workspaceId)),$e}async function Ge(De){if(!e||!y||!w?.appId||qt(De.id)||De.workspaceKind==="local_project"||De.appId!==w.appId)return null;const L=_a(y,h),$=await J.patchSession(e,De.id,{appId:w.appId,appName:w.appName,workspaceKind:"local_project",workspaceId:y.id,workspaceName:y.name,localProjectId:y.id,cloudProjectId:L?.id??null,cloudTeamId:L?.teamId??null,cwd:y.workspacePath});return Ie(H=>H.map(Q=>Q.id===$.id?$:Q)),k({type:"selectSession",sessionId:$.id,appId:$.appId,projectId:vt("local",y.id)}),T(vt("local",y.id)),$}async function st(De,L={}){if(!e)return null;const $=await Qe(j?`${j} workspace`:"Workspace action",De,L);if(!$)return null;const H=await J.workspaceTool(e,$.id,{action:De,args:L,source:"ui_button"});ue(H.output,H.ok?"success":"error"),C(await J.bootstrap(e));const Q=H.appId??MJ($);return Q&&(await z(Q,!1))?.initialized&&await B(Q),H}async function Le(De,L={}){if(De==="git_commit"&&typeof L.message!="string")return ge("commit"),null;he(!0),te(null);try{return await st(De,L)}catch($){return te($ instanceof Error?$.message:String($)),null}finally{he(!1)}}async function Fe(){const De=s.trim()||ne(),L=l==="commit_publish",$=L&&!!N?.remoteUrl;if(!($&&!window.confirm("Replace the current origin remote with the new OpenPond repo after committing?"))){he(!0),te(null);try{if(!(await st("git_commit",{message:De,includeUnstaged:i}))?.ok||l==="commit_push"&&!(await st("git_push",{runChecks:!1}))?.ok||L&&!(await st("publish_openpond_repo",{replaceOrigin:$}))?.ok)return;le(!1)}catch(H){te(H instanceof Error?H.message:String(H))}finally{he(!1)}}}return{changeWorkspaceBranch:Se,openCommitDialog:ge,openCreateWorkspaceBranchDialog:xe,openDefaultsSettingsFromBranchDialog:qe,runWorkspaceTool:Le,submitCommitDialog:Fe,submitCreateWorkspaceBranch:se,syncWorkspaceLocally:Oe,syncWorkspaceLocallyForApp:we}}function TJ(e,t,n){return!t&&!n?!0:KC(e,t,n)}function EJ(e,t,n){if(!t&&!n)return null;let a=null,o=Number.NEGATIVE_INFINITY;for(const i of e){if(i.archived||!KC(i,t,n))continue;const s=Date.parse(i.updatedAt),l=Number.isFinite(s)?s:0;(!a||l>o)&&(a=i,o=l)}return a}function KC(e,t,n){return t?e.workspaceKind==="local_project"&&e.workspaceId===t.id:n?e.appId===n.id||e.workspaceId===n.id:!1}function MJ(e){return e.workspaceKind==="sandbox"?e.localProjectId??null:e.workspaceId??e.appId??null}function jJ(e,t,n={}){return(OJ(e)||NJ(e,n))&&$J(t)}function OJ(e){return e.startsWith("sandbox_")?e!=="sandbox_create"&&e!=="sandbox_templates"&&e!=="sandbox_template_launch":!1}function $J(e){return e?.workspaceKind==="sandbox"||e?.workspaceKind==="sandbox_template"}function NJ(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 DJ(e,t){return e.kind==="general"?"# general":e.title?e.title:e.participants.find(a=>a.userId!==t)?.name??"Direct message"}const LJ=[];function UJ(e){const{composerDraftStore:t,appDispatch:n,mentionedAppId:a,setMentionedAppId:o,cloudSetupDialog:i,setCloudSetupDialog:s,setRightPanelTabRequest:l,workspaceDiffPanelViewState:m,setWorkspaceDiffPanelViewState:d,rightChatHistoryEvents:h,setRightChatHistoryEvents:v,locallyActiveCodexHistorySessionIds:y,setCodexHistoryTurnLocallyActive:w,draftSubagentDelegationMode:I,setDraftSubagentDelegationMode:R,confirmProjectAction:M,view:P,selectedAppId:N,selectedProjectId:O,selectedSessionId:j,draftProvider:k,draftModel:C,activeExperience:T,codexPermissionMode:z,codexReasoningEffort:B,openPondCommandAccessMode:D,busy:V,diffPanelOpen:le,diffPanelExpanded:te,rightPanelMode:Ie,rightChatPanels:ke,newProjectMode:Z,newProjectName:Ae,newProjectPath:he,newProjectBusy:ue,commitMessage:be,commitIncludeUnstaged:ne,commitNextStep:ge,branchDialogName:xe,setSectionMenuOpen:qe,setView:Se,setSelectedAppId:se,setSelectedProjectId:we,setSelectedSessionId:Oe,setPrompt:Qe,setDraftProvider:Ge,setDraftModel:st,setDiffPanelOpen:Le,setRightPanelMode:Fe,setRightChatPanels:De,setSyncingWorkspaceAppId:L,setSettingsSection:$,setNewProjectDialogOpen:H,setNewProjectMode:Q,setNewProjectName:me,setNewProjectPath:_e,setNewProjectBusy:$e,setCommitDialogOpen:Xe,setBranchDialogOpen:et,setError:rt,showToast:it,appPreferences:Me,applyBootstrapPayload:Be,approvals:p,bootstrap:U,connection:K,events:de,runtimeEventStore:re,sessions:F,startup:_,setAppPreferences:W,setCodexHistorySessions:X,setEvents:oe,setSessions:G,cloudProjectById:pe,localProjectById:fe,selectedApp:je,selectedCloudProject:Ee,selectedProject:Ne,selectedProjectLinkedOpenPondApp:Ve,selectedSession:Ue,sidebarSessions:ut,runtimeIndexes:Qt,connectedAppMentions:zt,codexHistoryEvents:Mn,setCodexHistoryEvents:xn,account:nn,accountPending:bt,accountSignedOut:sn,activeModel:Lt,activeProvider:yt,activeWorkspaceAppId:ln,activeWorkspaceKind:Ht,activeWorkspaceLocation:pn,appDefaults:Ln,selectedSessionProjectId:vn,workspaceName:Ba,accountScopeKey:ua,teamChat:Bt,communities:Kn,selectedProjectConfirmedCloudProject:ot,activeOpenPondCommandAccessMode:wn,viewWorkspaceAppId:Fa,viewWorkspaceId:Va,viewWorkspaceKind:ma,openPondActionCatalog:Ka,selectedActionCatalog:ae,expandProject:Ke,setExpandedProjectIds:ze,advanceTrainingModelChatAfterTurn:Ze,bindTrainingModelChatSession:kt,prepareTrainingModelChatTurn:gt,chatMessages:lt,pendingChatUserMessages:Ct,recordPendingChatUserMessage:pa,runningSessionIds:Wn,workspaceBusy:tt,visibleWorkspaceState:Rn,visibleWorkspaceDiff:St,rememberWorkspaceState:In,refreshWorkspace:Un,setWorkspaceBusy:jn,refreshWorkspaceDiffWhenNeeded:Wa,setPendingWorkspaceTarget:Pa,pendingSidebarWorkspaceTarget:yo,setPendingSidebarWorkspaceTarget:Ga,projectTarget:oa,workspaceTarget:xt}=e,Za=P==="apps"?"Apps":P==="get-started"?"Walkthroughs":P==="labs"?"Models":P==="scheduled"?"Workflows":P==="outputs"?"Outputs":P==="projects"?"Projects":P==="team"?Bt.detail?DJ(Bt.detail.thread,Bt.currentUserId):"Team Chat":P==="community"?Kn.preview?.displayName??"Communities":Ue?.title??zI(T),{browserConversationId:fa,handleWorkspaceDiffPanelViewStateChange:ni}=lJ({appDispatch:n,diffPanelExpanded:te,diffPanelOpen:le,rightChatPanels:ke,rightPanelMode:Ie,selectedAppId:N,selectedCloudProject:Ee,selectedProjectId:O,selectedSession:Ue,selectedSessionId:j,setWorkspaceDiffPanelViewState:d,view:P,viewWorkspaceAppId:Fa,viewWorkspaceId:Va,viewWorkspaceKind:ma,workspaceDiffPanelViewState:m}),Sr=g.useCallback(mt=>{cn({kind:"chat",sessionId:mt}),Oe(mt),se(null),we(null),Se("chat")},[se,we,Oe,Se]),kr=g.useCallback(()=>{Q("existing-local"),me(""),_e(""),H(!0)},[H,Q,me,_e]),So=g.useCallback(()=>{Q("local"),me(""),_e(""),H(!0)},[H,Q,me,_e]),{addProjectFolder:ai,addProjectFolderPath:oi,createCloudProjectFromScratch:ri,createProjectFromScratch:ii,removeProject:ks}=mJ({connection:K,defaultTeamId:Ln.defaultTeamId,sessions:F,selectedProjectId:O,confirmProjectAction:M,openExistingProjectDialog:kr,applyBootstrapPayload:Be,expandProject:Ke,setExpandedProjectIds:ze,setSelectedAppId:se,setSelectedProjectId:we,setSelectedSessionId:Oe,setError:rt,setView:Se,showToast:it}),{changeWorkspaceBranch:xs,openCommitDialog:Ja,openCreateWorkspaceBranchDialog:ws,openDefaultsSettingsFromBranchDialog:si,runWorkspaceTool:li,submitCommitDialog:ci,submitCreateWorkspaceBranch:Is,syncWorkspaceLocally:ra}=AJ({connection:K,activeWorkspaceAppId:ln,appDefaults:Ln,bootstrap:U,branchDialogName:xe,commitIncludeUnstaged:ne,commitMessage:be,commitNextStep:ge,draftModel:C,draftProvider:k,cloudProjects:U?.cloudProjects??[],selectedApp:je,selectedProject:Ne,selectedProjectLinkedOpenPondApp:Ve,selectedSession:Ue,sessions:F,title:Za,visibleWorkspaceDiff:St,visibleWorkspaceState:Rn,workspaceBusy:tt,workspaceName:Ba,appDispatch:n,applyBootstrapPayload:Be,expandProject:Ke,refreshWorkspace:Un,refreshWorkspaceDiff:Wa,rememberWorkspaceState:In,setBranchDialogOpen:et,setCommitDialogOpen:Xe,setError:rt,setSessions:G,setSettingsSection:$,setSyncingWorkspaceAppId:L,setView:Se,setWorkspaceBusy:jn,showToast:it}),_s=aJ({applyBootstrapPayload:Be,cloudProjects:U?.cloudProjects??[],connection:K,localProjectById:fe,selectedCloudProject:Ee,selectedProject:Ne,setWorkspaceBusy:jn,showToast:it,visibleWorkspaceState:Rn}),Cs=U?.preferences.subagents.delegationMode??"manual",Rs=Ue?.subagentDelegationMode??I,di=!!(T==="development"&&U?.preferences.subagents.enabled&&yt!=="codex"&&!qt(j)&&!Ue?.subagentRunId),ui=g.useCallback(mt=>{if(!Ue){R(mt);return}if(!K||qt(Ue.id)||Ue.subagentRunId)return;const Ft=Ue.id,Jn=Ue.subagentDelegationMode??null;G(fn=>fn.map(ia=>ia.id===Ft?{...ia,subagentDelegationMode:mt}:ia)),J.patchSession(K,Ft,{subagentDelegationMode:mt}).then(fn=>{G(ia=>ia.map(On=>On.id===fn.id?fn:On))}).catch(fn=>{G(ia=>ia.map(On=>On.id===Ft?{...On,subagentDelegationMode:Jn}:On)),rt(fn instanceof Error?fn.message:String(fn))})},[K,Ue,rt,G]),mi=g.useCallback(mt=>{v(Ft=>Ft[mt.session.id]===mt.events?Ft:{...Ft,[mt.session.id]:mt.events}),X(Ft=>zu(Ft,mt.session))},[X]),{answerCreateImproveQuestion:Ps,applyCreateImproveCandidate:Ya,approveCreateImproveRun:ko,cancelCreateImproveRun:Gn,changeDraftProvider:As,openCreateImprovePullRequest:Ts,reconcileCreateImprovePullRequest:bn,rejectCreateImproveCandidate:pi,pauseCreateImproveRun:Zn,resumeCreateImproveRun:Aa,reviseCreateImproveRun:xo,sendPrompt:Qa,stopTurn:Es}=QZ({applyBootstrapPayload:Be,bootstrap:U,chatMessages:lt,connection:K,codexPermissionMode:z,codexReasoningEffort:B,openPondCommandAccessMode:wn,draftModel:C,draftProvider:k,experience:T,expandProject:Ke,getPrompt:t.getSnapshot,apps:U?.apps??[],connectedAppMentions:zt,mentionedAppId:a,ensureCloudSessionReady:_s,refreshWorkspace:Un,refreshWorkspaceDiff:Wa,selectedApp:je,selectedActionCatalog:ae,openPondActionCatalog:Ka,cloudProjects:U?.cloudProjects??[],accountScopeKey:ua,selectedCloudProject:Ee,selectedProject:Ne,selectedProjectLinkedOpenPondApp:Ve,selectedSession:Ue,sessions:F,workspaceTarget:xt.value,subagentDelegationMode:Ue?.subagentDelegationMode??I,setDraftModel:st,setDraftProvider:Ge,setError:rt,setPrompt:Qe,setMentionedAppId:o,setCodexHistoryEvents:xn,setCodexHistorySessions:X,onCodexHistoryTurnActivityChange:w,onCodexHistoryTurnPayload:mi,onPendingUserMessage:pa,setEvents:oe,setSelectedAppId:se,setSelectedProjectId:we,setSelectedSessionId:Oe,setSessions:G,setView:Se,setWorkspaceBusy:jn}),{archiveSession:Ms,restoreSession:wo,renameSession:xr,toggleProjectPinned:fi,toggleSessionPinned:wr,toggleSessionSavedForLater:hi}=RJ({appPreferences:Me,connection:K,selectedSessionId:j,setAppPreferences:W,setCodexHistorySessions:X,setError:rt,setSelectedSessionId:Oe,setSessions:G}),{changeWorkspaceTarget:Ir,moveProjectToCloud:gi,startCloudSetupUpload:ha}=cJ({account:nn,accountPending:bt,accountSignedOut:sn,activeWorkspaceKind:Ht,activeWorkspaceLocation:pn,appDispatch:n,applyBootstrapPayload:Be,busy:V,cloudSetupDialog:i,cloudProjects:U?.cloudProjects??[],connection:K,defaultTeamId:Ln.defaultTeamId,expandProject:Ke,localProjectById:fe,selectedCloudProject:Ee,selectedProject:Ne,selectedSession:Ue,selectedSessionProjectId:vn,setCloudSetupDialog:s,setDiffPanelOpen:Le,setError:rt,setSessions:G,setWorkspaceBusy:jn,showToast:it,visibleWorkspaceState:Rn,workspaceBusy:tt}),Qo=g.useCallback(async mt=>{if(T==="work"&&!Ue){if(mt==="local"){Pa("local"),it(Ne?`Next task will use the local ${Ne.name} checkout.`:"Next task will use an app-managed local workspace.","info");return}if(mt==="cloud"&&!Ne&&!Ee){if(bt){it("Checking OpenPond account. Try again in a moment.","info");return}if(sn){it("Add an OpenPond account before using Hosted.","error");return}Pa("cloud"),it("Next task will use Hosted without a Project.","info");return}}if(mt==="hybrid"){const Ft=Ee?.id??ot?.id??Ue?.cloudProjectId??null,Jn=Ee?.teamId??ot?.teamId??Ue?.cloudTeamId??null;if(bt){it("Checking OpenPond account. Try again in a moment.","info");return}if(sn){it("Add an OpenPond account before using Hybrid.","error");return}if(!Ft||!Jn){Pa(null),it("Upload/sync this Project to Cloud before using Hybrid.","error");return}if(Ue&&!qt(Ue.id)){if(vo(Ue))return;if(!K){it("OpenPond App server is not connected.","error");return}const fn=await J.patchSession(K,Ue.id,{provider:k,modelRef:ja(k,C,U?.providers??null),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:null,workspaceName:Ee?.name??ot?.name??Ne?.name??Ue.workspaceName??"Hybrid workspace",localProjectId:Ne?.id??Ue.localProjectId??null,cloudProjectId:Ft,cloudTeamId:Jn,metadata:H_(Ue.metadata),cwd:Ne?.workspacePath??Ue.cwd??null});G(ia=>ia.map(On=>On.id===fn.id?fn:On)),Pa(null),it("Hybrid will use your selected model with hosted sandbox edits.","info");return}Pa("hybrid"),it("Next message will use Hybrid with a hosted sandbox.","info");return}Pa(null),await Ir(mt)},[bt,sn,T,U?.providers,Ir,K,C,k,Ee?.id,Ee?.name,Ee?.teamId,Ne?.id,ot?.id,ot?.name,ot?.teamId,Ne?.name,Ne?.workspacePath,Ue,Pa,G,it]),_r=g.useCallback((mt,Ft)=>{se(null),we(mt),Oe(null),Se("chat"),Ke(mt),Ga({projectId:mt,target:Ft})},[Ke,se,we,Oe,Se]);g.useEffect(()=>{if(!yo||P!=="chat"||O!==yo.projectId||j!==null)return;const mt=yo.target;Ga(null),Qo(mt)},[Qo,yo,O,j,P]);const Io=dJ({advanceTrainingTurn:Ze,bindTrainingSession:kt,composerDraftStore:t,onSessionCreated:mt=>{Oe(mt.id),Se("chat"),cn({kind:"chat",sessionId:mt.id}),R(null)},onSubmitted:async()=>{const mt=Ue;if(!(!K||!mt||!Fl(mt)))try{const Ft=await J.patchSession(K,mt.id,{metadata:T3(mt.metadata)});G(Jn=>Jn.map(fn=>fn.id===Ft.id?Ft:fn))}catch(Ft){it(Ft instanceof Error?`Task started, but its Draft label could not be cleared: ${Ft.message}`:"Task started, but its Draft label could not be cleared.","error")}},prepareTrainingTurn:gt,sendPrompt:Qa,setMentionedAppId:o,showToast:it}),vi=uJ({appDispatch:n,connection:K,sessions:F,setDiffPanelOpen:Le,setRightPanelMode:Fe,setSessions:G,setView:Se}),{createCloudEnvironmentFromSidebar:Xa,openCloudProjectDialog:bi,openUrlInBrowserPanel:js,showBrowserPanel:Cr,showChangesPanel:yi,showGoalSidebarTab:Si}=SZ({account:nn,browserConversationId:fa,cloudProjectById:pe,cloudProjects:U?.cloudProjects??[],diffPanelOpen:le,rightPanelMode:Ie,selectedProjectId:O,setDiffPanelOpen:Le,setNewProjectDialogOpen:H,setNewProjectMode:Q,setNewProjectName:me,setRightPanelMode:Fe}),{changeProjectTarget:ki,submitNewProjectDialog:Os}=pJ({addProjectFolder:ai,addProjectFolderPath:oi,appDispatch:n,busy:V,cloudProjectById:pe,createCloudProjectFromScratch:ri,createProjectFromScratch:ii,expandProject:Ke,localProjectById:fe,newProjectBusy:ue,newProjectMode:Z,newProjectName:Ae,newProjectPath:he,onCreateCloudEnvironment:Xa,onNewCloudProject:bi,onNewLocalProject:So,onUseExistingFolderPath:kr,projectTargetValue:oa.value,setDiffPanelOpen:Le,setDraftModel:st,setDraftProvider:Ge,setError:rt,setNewProjectBusy:$e,setNewProjectDialogOpen:H,setNewProjectName:me,setNewProjectPath:_e,showToast:it,workspaceBusy:tt}),Rr=g.useMemo(()=>F.map(mt=>mt.id),[F]);xZ({browserConversationId:fa,sessionIds:Rr,onOpenSession:Sr,onShowBrowserPanel:Cr});const[xi,Xo]=g.useState(null),eo=g.useCallback(mt=>{Xo({id:Date.now(),objective:mt.objective,initialSessionIds:mt.sessionId?[mt.sessionId]:[]}),Gi(po()),Se("labs")},[Se]),{activateRightChatPanel:$s,closeRightChatPanel:Ns,openRightChatPanel:Ds,rightChatPanelViews:Ls,showRightChatPanel:Ta,showRightPanelDiffTab:wi,submitRightChatPrompt:Pr,updateRightChatModel:Us,updateRightChatPrompt:_o,updateRightChatProvider:zn,updateRightChatScrollState:zs}=CJ({activeModel:Lt,activeProvider:yt,approvals:p,applyRightCodexHistoryPayload:mi,codexHistoryEvents:Mn,connectedAppMentions:zt,connection:K,contextCompaction:Ln.contextCompaction,openLabTraining:eo,locallyActiveCodexHistorySessionIds:y,openPondCommandAccessMode:D,pendingChatUserMessages:Ct,providerSettings:U?.providers??null,rightChatHistoryEvents:h,rightChatPanels:ke,rightPanelMode:Ie,runtimeIndexes:Qt,runtimeEventStore:re,runningSessionIds:Wn,selectedSession:Ue,selectedSessionId:j,sendPrompt:Qa,setDiffPanelOpen:Le,setError:rt,setRightChatHistoryEvents:v,setRightChatPanels:De,setRightPanelMode:Fe,setRightPanelTabRequest:l,setView:Se,showChangesPanel:yi,showToast:it,sidebarSessions:ut,startupReady:_.ready}),Hs=g.useCallback(()=>{qe(null),$("profile"),Se("settings"),cn({kind:"settings",section:"profile"})},[qe,$,Se]),qs=g.useMemo(()=>Mo(U?.diagnostics??LJ,de.filter(mt=>mt.name==="diagnostic")),[U?.diagnostics,de]),Bs=g.useCallback(()=>{if(le){Le(!1);return}if(P==="labs"){Fe("changes"),l({id:Date.now(),tab:"summary"}),Le(!0);return}Fe("home"),Le(!0)},[le,Le,Fe,l,P]);return{title:Za,browserConversationId:fa,handleWorkspaceDiffPanelViewStateChange:ni,openSessionInChat:Sr,openExistingProjectPathDialog:kr,addProjectFolder:ai,removeProject:ks,changeProjectTarget:ki,submitNewProjectDialog:Os,changeWorkspaceBranch:xs,openCommitDialog:Ja,openCreateWorkspaceBranchDialog:ws,openDefaultsSettingsFromBranchDialog:si,runWorkspaceTool:li,submitCommitDialog:ci,submitCreateWorkspaceBranch:Is,syncWorkspaceLocally:ra,subagentDelegationDefaultMode:Cs,subagentDelegationMode:Rs,subagentDelegationAvailable:di,changeSubagentDelegationMode:ui,answerCreateImproveQuestion:Ps,applyCreateImproveCandidate:Ya,approveCreateImproveRun:ko,cancelCreateImproveRun:Gn,changeDraftProvider:As,openCreateImprovePullRequest:Ts,reconcileCreateImprovePullRequest:bn,rejectCreateImproveCandidate:pi,pauseCreateImproveRun:Zn,resumeCreateImproveRun:Aa,reviseCreateImproveRun:xo,sendPrompt:Qa,stopTurn:Es,archiveSession:Ms,restoreSession:wo,renameSession:xr,toggleProjectPinned:fi,toggleSessionPinned:wr,toggleSessionSavedForLater:hi,moveProjectToCloud:gi,startCloudSetupUpload:ha,changeWorkspaceTarget:Qo,switchProjectWorkspaceTarget:_r,sendPromptFromMainComposer:Io,openSandboxWorkspace:vi,createCloudEnvironmentFromSidebar:Xa,openCloudProjectDialog:bi,openUrlInBrowserPanel:js,showBrowserPanel:Cr,showChangesPanel:yi,showGoalSidebarTab:Si,rightChatTrainingLaunchRequest:xi,setRightChatTrainingLaunchRequest:Xo,closeRightChatPanel:Ns,openRightChatPanel:Ds,rightChatPanelViews:Ls,showRightChatPanel:Ta,showRightPanelDiffTab:wi,submitRightChatPrompt:Pr,activateRightChatPanel:$s,updateRightChatModel:Us,updateRightChatPrompt:_o,updateRightChatProvider:zn,updateRightChatScrollState:zs,openProfileSettings:Hs,diagnosticEvents:qs,toggleRightSidebar:Bs}}const zJ=OR();function HJ(){return x.jsx(ZC,{client:zJ,children:x.jsx(qJ,{})})}function qJ(){const e=pZ(),t=UJ(e);return x.jsx(NK,{primary:e,secondary:t})}const ZQ=Object.freeze(Object.defineProperty({__proto__:null,App:HJ},Symbol.toStringTag,{value:"Module"}));export{GQ as $,b4 as A,Uy as B,Go as C,e3 as D,UI as E,OI as F,Bl as G,Hd as H,w5 as I,SS as J,Dr as K,Mv as L,Dn as M,UQ as N,F6 as O,z5 as P,K_ as Q,vQ as R,G5 as S,FQ as T,br as U,qQ as V,Xf as W,Ss as X,FY as Y,hQ as Z,XK as _,Fy as a,Bf as a$,qZ as a0,fQ as a1,gQ as a2,EQ as a3,IQ as a4,EV as a5,ja as a6,YV as a7,ji as a8,qt as a9,NY as aA,s0 as aB,Xg as aC,CV as aD,rh as aE,FK as aF,VQ as aG,DK as aH,h0 as aI,Uu as aJ,$p as aK,RV as aL,_v as aM,XI as aN,l5 as aO,p5 as aP,HY as aQ,qY as aR,qM as aS,wK as aT,xK as aU,$I as aV,NI as aW,T5 as aX,jh as aY,BY as aZ,VY as a_,Oo as aa,aC as ab,oQ as ac,IK as ad,r7 as ae,aQ as af,yK as ag,TQ as ah,o7 as ai,ba as aj,go as ak,FC as al,SJ as am,kJ as an,vZ as ao,rQ as ap,F5 as aq,$u as ar,k3 as as,Yg as at,EI as au,ju as av,SQ as aw,dv as ax,g3 as ay,q as az,v8 as b,wu as b$,q5 as b0,jI as b1,iY as b2,Bh as b3,eh as b4,xV as b5,DY as b6,Nu as b7,ev as b8,cn as b9,lQ as bA,g0 as bB,iQ as bC,Et as bD,wO as bE,lY as bF,F_ as bG,dY as bH,MY as bI,Rp as bJ,sY as bK,ea as bL,JY as bM,YY as bN,QY as bO,XY as bP,v3 as bQ,GY as bR,ZY as bS,Mg as bT,fY as bU,Jo as bV,Mz as bW,g1 as bX,mY as bY,rn as bZ,c as b_,Ff as ba,X5 as bb,k5 as bc,rY as bd,Nh as be,Dh as bf,Op as bg,oY as bh,V4 as bi,KQ as bj,Vu as bk,M5 as bl,cY as bm,au as bn,Qg as bo,MI as bp,Ou as bq,sQ as br,mQ as bs,pQ as bt,v0 as bu,cQ as bv,Wp as bw,uQ as bx,dQ as by,rC as bz,dt as c,bY as c$,Iu as c0,wt as c1,f as c2,Vt as c3,r as c4,xu as c5,S as c6,Pe as c7,Y as c8,E as c9,qz as cA,Uz as cB,k1 as cC,jg as cD,S1 as cE,_u as cF,Cu as cG,Fz as cH,Oz as cI,He as cJ,uE as cK,Zo as cL,gu as cM,OY as cN,Na as cO,vY as cP,tH as cQ,Pg as cR,rz as cS,kY as cT,_Y as cU,IY as cV,wY as cW,nQ as cX,_Q as cY,CQ as cZ,RQ as c_,u as ca,b as cb,zz as cc,Rt as cd,lc as ce,xz as cf,Dt as cg,w1 as ch,Vz as ci,x1 as cj,Pz as ck,b1 as cl,wz as cm,Ez as cn,Lz as co,$z as cp,ee as cq,A as cr,y1 as cs,gY as ct,hY as cu,uY as cv,Iz as cw,Rz as cx,Ww as cy,Bz as cz,$G as d,$Y as d$,pY as d0,M1 as d1,Xr as d2,mr as d3,OH as d4,iH as d5,xY as d6,OF as d7,uc as d8,CY as d9,Q0 as dA,wQ as dB,hS as dC,bh as dD,yQ as dE,iC as dF,kQ as dG,xQ as dH,LQ as dI,u5 as dJ,C5 as dK,OQ as dL,MQ as dM,jQ as dN,T7 as dO,DJ as dP,$Q as dQ,NQ as dR,DQ as dS,zy as dT,i_ as dU,KY as dV,Vl as dW,TY as dX,EY as dY,WY as dZ,qr as d_,AY as da,PY as db,RY as dc,bF as dd,L1 as de,o3 as df,Gi as dg,po as dh,u3 as di,jY as dj,yY as dk,SY as dl,Du as dm,PQ as dn,AQ as dp,tQ as dq,t5 as dr,P5 as ds,fS as dt,gZ as du,oh as dv,L_ as dw,k_ as dx,D_ as dy,WQ as dz,jR as e,ZQ as e0,Wr as f,Z4 as g,Eo as h,Mu as i,UY as j,bQ as k,eQ as l,Jg as m,EZ as n,zQ as o,BQ as p,HC as q,HQ as r,I4 as s,pc as t,IS as u,J as v,fc as w,C3 as x,LY as y,zY as z};
|